repo_name
stringlengths
7
70
file_path
stringlengths
9
215
context
list
import_statement
stringlengths
47
10.3k
token_num
int64
643
100k
cropped_code
stringlengths
62
180k
all_code
stringlengths
62
224k
next_line
stringlengths
9
1.07k
gold_snippet_index
int64
0
117
created_at
stringlengths
25
25
level
stringclasses
9 values
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/event/EventHandlerEntity.java
[ { "identifier": "DangerRPG", "path": "src/main/java/mixac1/dangerrpg/DangerRPG.java", "snippet": "@Mod(\n modid = DangerRPG.MODID,\n name = DangerRPG.MODNAME,\n version = DangerRPG.VERSION,\n acceptedMinecraftVersions = DangerRPG.ACCEPTED_VERSION,\n dependencies = \"required-after:Forge\"...
import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import mixac1.dangerrpg.DangerRPG; import mixac1.dangerrpg.api.entity.EntityAttribute.EAFloat; import mixac1.dangerrpg.api.entity.LvlEAProvider; import mixac1.dangerrpg.api.event.InitRPGEntityEvent; import mixac1.dangerrpg.api.event.ItemStackEvent.StackChangedEvent; import mixac1.dangerrpg.capability.EntityAttributes; import mixac1.dangerrpg.capability.PlayerAttributes; import mixac1.dangerrpg.capability.RPGEntityHelper; import mixac1.dangerrpg.capability.data.RPGEntityProperties; import mixac1.dangerrpg.init.RPGCapability; import mixac1.dangerrpg.init.RPGConfig.EntityConfig; import mixac1.dangerrpg.init.RPGNetwork; import mixac1.dangerrpg.network.MsgSyncEntityData; import mixac1.dangerrpg.util.IMultiplier.Multiplier; import mixac1.dangerrpg.util.RPGHelper; import mixac1.dangerrpg.util.Utils; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChunkCoordinates; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityEvent.EntityConstructing; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingJumpEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import java.util.concurrent.TimeUnit;
14,980
package mixac1.dangerrpg.event; public class EventHandlerEntity { // fix https://github.com/quentin452/DangerRPG-Continuation/issues/36 @SubscribeEvent public void onDimensionChange(cpw.mods.fml.common.gameevent.PlayerEvent.PlayerChangedDimensionEvent event) { if (event.player != null) { LvlEAProvider<Float> healthLvlProvider = RPGEntityProperties.get(event.player).getLvlProvider(PlayerAttributes.HEALTH.hash); healthLvlProvider.tryUpfixissue36(event.player, event.player, true); try { TimeUnit.MILLISECONDS.sleep(500); // Wait for 500 milliseconds = 0.5 seconde } catch (InterruptedException e) { e.printStackTrace(); } healthLvlProvider.tryUpfixissue36(event.player, event.player, false); } } @SubscribeEvent public void onEntityConstructing(EntityConstructing e) { if (e.entity instanceof EntityLivingBase && RPGEntityHelper.isRPGable((EntityLivingBase) e.entity)) { RPGEntityProperties.register((EntityLivingBase) e.entity); } } @SubscribeEvent public void onEntityJoinWorld(EntityJoinWorldEvent e) { if (e.entity instanceof EntityLivingBase && RPGEntityHelper.isRPGable((EntityLivingBase) e.entity)) { if (e.entity.worldObj.isRemote) { RPGNetwork.net.sendToServer(new MsgSyncEntityData((EntityLivingBase) e.entity)); } else { RPGEntityProperties.get((EntityLivingBase) e.entity) .serverInit(); } } } @SubscribeEvent public void onPlayerCloned(PlayerEvent.Clone e) { if (e.wasDeath) { RPGEntityProperties.get(e.original) .rebuildOnDeath(); } NBTTagCompound nbt = new NBTTagCompound(); RPGEntityProperties.get(e.original) .saveNBTData(nbt); RPGEntityProperties.get(e.entityPlayer) .loadNBTData(nbt); } @SubscribeEvent public void onInitRPGEntity(InitRPGEntityEvent e) { ChunkCoordinates spawn = e.entity.worldObj.getSpawnPoint(); double distance = Utils.getDiagonal(e.entity.posX - spawn.posX, e.entity.posZ - spawn.posZ); int lvl = (int) (distance / EntityConfig.d.entityLvlUpFrequency); if (EntityAttributes.LVL.hasIt(e.entity)) { EntityAttributes.LVL.setValue(lvl + 1, e.entity); } Multiplier mul; if (EntityAttributes.HEALTH.hasIt(e.entity)) { float health = e.entity.getHealth(); mul = RPGCapability.rpgEntityRegistr.get(e.entity).attributes.get(EntityAttributes.HEALTH).mulValue;
package mixac1.dangerrpg.event; public class EventHandlerEntity { // fix https://github.com/quentin452/DangerRPG-Continuation/issues/36 @SubscribeEvent public void onDimensionChange(cpw.mods.fml.common.gameevent.PlayerEvent.PlayerChangedDimensionEvent event) { if (event.player != null) { LvlEAProvider<Float> healthLvlProvider = RPGEntityProperties.get(event.player).getLvlProvider(PlayerAttributes.HEALTH.hash); healthLvlProvider.tryUpfixissue36(event.player, event.player, true); try { TimeUnit.MILLISECONDS.sleep(500); // Wait for 500 milliseconds = 0.5 seconde } catch (InterruptedException e) { e.printStackTrace(); } healthLvlProvider.tryUpfixissue36(event.player, event.player, false); } } @SubscribeEvent public void onEntityConstructing(EntityConstructing e) { if (e.entity instanceof EntityLivingBase && RPGEntityHelper.isRPGable((EntityLivingBase) e.entity)) { RPGEntityProperties.register((EntityLivingBase) e.entity); } } @SubscribeEvent public void onEntityJoinWorld(EntityJoinWorldEvent e) { if (e.entity instanceof EntityLivingBase && RPGEntityHelper.isRPGable((EntityLivingBase) e.entity)) { if (e.entity.worldObj.isRemote) { RPGNetwork.net.sendToServer(new MsgSyncEntityData((EntityLivingBase) e.entity)); } else { RPGEntityProperties.get((EntityLivingBase) e.entity) .serverInit(); } } } @SubscribeEvent public void onPlayerCloned(PlayerEvent.Clone e) { if (e.wasDeath) { RPGEntityProperties.get(e.original) .rebuildOnDeath(); } NBTTagCompound nbt = new NBTTagCompound(); RPGEntityProperties.get(e.original) .saveNBTData(nbt); RPGEntityProperties.get(e.entityPlayer) .loadNBTData(nbt); } @SubscribeEvent public void onInitRPGEntity(InitRPGEntityEvent e) { ChunkCoordinates spawn = e.entity.worldObj.getSpawnPoint(); double distance = Utils.getDiagonal(e.entity.posX - spawn.posX, e.entity.posZ - spawn.posZ); int lvl = (int) (distance / EntityConfig.d.entityLvlUpFrequency); if (EntityAttributes.LVL.hasIt(e.entity)) { EntityAttributes.LVL.setValue(lvl + 1, e.entity); } Multiplier mul; if (EntityAttributes.HEALTH.hasIt(e.entity)) { float health = e.entity.getHealth(); mul = RPGCapability.rpgEntityRegistr.get(e.entity).attributes.get(EntityAttributes.HEALTH).mulValue;
EntityAttributes.HEALTH.setValue(RPGHelper.multyMul(health, lvl, mul), e.entity);
14
2023-10-31 21:00:14+00:00
24k
llllllxy/tiny-jdbc-boot-starter
src/main/java/org/tinycloud/jdbc/support/AbstractSqlSupport.java
[ { "identifier": "Criteria", "path": "src/main/java/org/tinycloud/jdbc/criteria/Criteria.java", "snippet": "public class Criteria extends AbstractCriteria {\n\n public <R> Criteria lt(String field, R value) {\n String condition = \" AND \" + field + \" < \" + \"?\";\n conditions.add(cond...
import org.springframework.jdbc.core.*; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.tinycloud.jdbc.criteria.Criteria; import org.tinycloud.jdbc.criteria.LambdaCriteria; import org.tinycloud.jdbc.exception.JdbcException; import org.tinycloud.jdbc.page.IPageHandle; import org.tinycloud.jdbc.page.Page; import org.tinycloud.jdbc.sql.SqlGenerator; import org.tinycloud.jdbc.sql.SqlProvider; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.*;
16,162
String selectSql = getPageHandle().handlerPagingSQL(sql, page.getPageNum(), page.getPageSize()); String countSql = getPageHandle().handlerCountSQL(sql); // 查询数据列表 List<T> resultList = getJdbcTemplate().query(selectSql, params, rowMapper); // 查询总共数量 int totalSize = getJdbcTemplate().queryForObject(countSql, params, Integer.class); page.setRecords(resultList); page.setTotal(totalSize); return page; } /** * 分页查询(带参数) * * @param sql 要执行的SQL * @param clazz 实体类型 * @param page 分页参数 * @param params ?参数 * @return Page<F> */ @Override public <F> Page<F> paginate(String sql, Class<F> clazz, Page<F> page, final Object... params) { if (page == null || page.getPageNum() == null || page.getPageSize() == null) { throw new JdbcException("paginate page cannot be null"); } if (page.getPageNum() <= 0) { throw new JdbcException("当前页数必须大于1"); } if (page.getPageSize() <= 0) { throw new JdbcException("每页大小必须大于1"); } String selectSql = getPageHandle().handlerPagingSQL(sql, page.getPageNum(), page.getPageSize()); String countSql = getPageHandle().handlerCountSQL(sql); // 查询数据列表 List<F> resultList = getJdbcTemplate().query(selectSql, params, new BeanPropertyRowMapper<>(clazz)); // 查询总共数量 int totalSize = getJdbcTemplate().queryForObject(countSql, params, Integer.class); page.setRecords(resultList); page.setTotal(totalSize); return page; } /** * 执行删除,插入,更新操作 * * @param sql 要执行的SQL * @param params 要绑定到SQL的参数 * @return 成功的条数 */ @Override public int execute(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int insert(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int update(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int delete(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } /** * 使用 in 进行批量操作,比如批量启用,批量禁用,批量删除等 -- 更灵活的就需要自己写了 * * @param sql 示例: update s_url_map set del_flag = '1' where id in (:idList) * @param idList 一般为 List<String> 或 List<Integer> * @return 执行的结果条数 */ @Override public int batchOpera(String sql, List<Object> idList) { if (idList == null || idList.size() == 0) { throw new JdbcException("batchOpera idList cannot be null or empty"); } NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate()); Map<String, Object> param = new HashMap<>(); param.put("idList", idList); return namedJdbcTemplate.update(sql, param); } // ---------------------------------ISqlSupport结束--------------------------------- // ---------------------------------IObjectSupport开始--------------------------------- @Override public T selectById(ID id) { if (id == null) { throw new JdbcException("selectById id cannot be null"); }
package org.tinycloud.jdbc.support; /** * jdbc抽象类,给出默认的支持 * * @author liuxingyu01 * @since 2022-03-11-16:49 **/ public abstract class AbstractSqlSupport<T, ID> implements ISqlSupport<T, ID>, IObjectSupport<T, ID> { protected abstract JdbcTemplate getJdbcTemplate(); protected abstract IPageHandle getPageHandle(); /** * 泛型 */ private final Class<T> entityClass; /** * bean转换器 */ private final RowMapper<T> rowMapper; @SuppressWarnings("unchecked") public AbstractSqlSupport() { ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); entityClass = (Class<T>) type.getActualTypeArguments()[0]; rowMapper = BeanPropertyRowMapper.newInstance(entityClass); } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param params 要绑定到查询的参数 ,可以不传 * @return 查询结果 */ @Override public List<T> select(String sql, Object... params) { List<T> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, rowMapper); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, rowMapper); } return resultList; } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param clazz 实体类 * @param params 要绑定到查询的参数 ,可以不传 * @param <F> 泛型 * @return 查询结果 */ @Override public <F> List<F> select(String sql, Class<F> clazz, Object... params) { List<F> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, new BeanPropertyRowMapper<>(clazz)); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, new BeanPropertyRowMapper<>(clazz)); } return resultList; } /** * 执行查询sql,有查询条件,(固定返回List<Map<String, Object>>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public List<Map<String, Object>> selectMap(String sql, Object... params) { return getJdbcTemplate().queryForList(sql, params); } /** * 执行查询sql,有查询条件,结果返回第一条(固定返回Map<String, Object>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public Map<String, Object> selectOneMap(String sql, final Object... params) { List<Map<String, Object>> resultList = getJdbcTemplate().queryForList(sql, params); if (!CollectionUtils.isEmpty(resultList)) { return resultList.get(0); } return null; } /** * 查询一个值(经常用于查count) * * @param sql 要执行的SQL查询 * @param clazz 实体类 * @param params 要绑定到查询的参数 * @param <F> 泛型 * @return T */ @Override public <F> F selectOneColumn(String sql, Class<F> clazz, Object... params) { F result; if (params == null || params.length == 0) { result = getJdbcTemplate().queryForObject(sql, clazz); } else { result = getJdbcTemplate().queryForObject(sql, params, clazz); } return result; } /** * 分页查询 * * @param sql 要执行的SQL查询 * @param page 分页参数 * @return T */ @Override public Page<T> paginate(String sql, Page<T> page) { if (page == null || page.getPageNum() == null || page.getPageSize() == null) { throw new JdbcException("paginate page cannot be null"); } if (page.getPageNum() <= 0) { throw new JdbcException("当前页数必须大于1"); } if (page.getPageSize() <= 0) { throw new JdbcException("每页大小必须大于1"); } String selectSql = getPageHandle().handlerPagingSQL(sql, page.getPageNum(), page.getPageSize()); String countSql = getPageHandle().handlerCountSQL(sql); // 查询数据列表 List<T> resultList = getJdbcTemplate().query(selectSql, rowMapper); // 查询总共数量 int totalSize = getJdbcTemplate().queryForObject(countSql, Integer.class); page.setRecords(resultList); page.setTotal(totalSize); return page; } /** * 分页查询(带参数) * * @param sql 要执行的SQL * @param page 分页参数 * @param params ?参数 * @return Page<T> */ @Override public Page<T> paginate(String sql, Page<T> page, final Object... params) { if (page == null || page.getPageNum() == null || page.getPageSize() == null) { throw new JdbcException("paginate page cannot be null"); } if (page.getPageNum() <= 0) { throw new JdbcException("当前页数必须大于1"); } if (page.getPageSize() <= 0) { throw new JdbcException("每页大小必须大于1"); } String selectSql = getPageHandle().handlerPagingSQL(sql, page.getPageNum(), page.getPageSize()); String countSql = getPageHandle().handlerCountSQL(sql); // 查询数据列表 List<T> resultList = getJdbcTemplate().query(selectSql, params, rowMapper); // 查询总共数量 int totalSize = getJdbcTemplate().queryForObject(countSql, params, Integer.class); page.setRecords(resultList); page.setTotal(totalSize); return page; } /** * 分页查询(带参数) * * @param sql 要执行的SQL * @param clazz 实体类型 * @param page 分页参数 * @param params ?参数 * @return Page<F> */ @Override public <F> Page<F> paginate(String sql, Class<F> clazz, Page<F> page, final Object... params) { if (page == null || page.getPageNum() == null || page.getPageSize() == null) { throw new JdbcException("paginate page cannot be null"); } if (page.getPageNum() <= 0) { throw new JdbcException("当前页数必须大于1"); } if (page.getPageSize() <= 0) { throw new JdbcException("每页大小必须大于1"); } String selectSql = getPageHandle().handlerPagingSQL(sql, page.getPageNum(), page.getPageSize()); String countSql = getPageHandle().handlerCountSQL(sql); // 查询数据列表 List<F> resultList = getJdbcTemplate().query(selectSql, params, new BeanPropertyRowMapper<>(clazz)); // 查询总共数量 int totalSize = getJdbcTemplate().queryForObject(countSql, params, Integer.class); page.setRecords(resultList); page.setTotal(totalSize); return page; } /** * 执行删除,插入,更新操作 * * @param sql 要执行的SQL * @param params 要绑定到SQL的参数 * @return 成功的条数 */ @Override public int execute(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int insert(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int update(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int delete(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } /** * 使用 in 进行批量操作,比如批量启用,批量禁用,批量删除等 -- 更灵活的就需要自己写了 * * @param sql 示例: update s_url_map set del_flag = '1' where id in (:idList) * @param idList 一般为 List<String> 或 List<Integer> * @return 执行的结果条数 */ @Override public int batchOpera(String sql, List<Object> idList) { if (idList == null || idList.size() == 0) { throw new JdbcException("batchOpera idList cannot be null or empty"); } NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate()); Map<String, Object> param = new HashMap<>(); param.put("idList", idList); return namedJdbcTemplate.update(sql, param); } // ---------------------------------ISqlSupport结束--------------------------------- // ---------------------------------IObjectSupport开始--------------------------------- @Override public T selectById(ID id) { if (id == null) { throw new JdbcException("selectById id cannot be null"); }
SqlProvider sqlProvider = SqlGenerator.selectByIdSql(id, entityClass);
5
2023-10-25 14:44:59+00:00
24k
ansforge/SAMU-Hub-Modeles
src/main/java/com/hubsante/model/cisu/Alert.java
[ { "identifier": "Attachment", "path": "src/main/java/com/hubsante/model/cisu/Attachment.java", "snippet": "@JsonPropertyOrder(\n {Attachment.JSON_PROPERTY_DESCRIPTION, Attachment.JSON_PROPERTY_MIME_TYPE,\n Attachment.JSON_PROPERTY_SIZE, Attachment.JSON_PROPERTY_U_R_I,\n Attachment.JSON_PROPER...
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.dataformat.xml.annotation.*; import com.hubsante.model.cisu.Attachment; import com.hubsante.model.cisu.CallTaker; import com.hubsante.model.cisu.Caller; import com.hubsante.model.cisu.ContactSource; import com.hubsante.model.cisu.Location; import com.hubsante.model.cisu.Qualification; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Arrays; import java.util.List; import java.util.Objects;
16,033
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.cisu; /** * Alert */ @JsonPropertyOrder( {Alert.JSON_PROPERTY_ID, Alert.JSON_PROPERTY_RECEPTION, Alert.JSON_PROPERTY_REPORTING, Alert.JSON_PROPERTY_FREETEXT, Alert.JSON_PROPERTY_CALLER, Alert.JSON_PROPERTY_ALERT_SOURCE, Alert.JSON_PROPERTY_LOCATION, Alert.JSON_PROPERTY_QUALIFICATION, Alert.JSON_PROPERTY_CALL_TAKER, Alert.JSON_PROPERTY_ATTACHMENT}) @JsonTypeName("alert") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Alert { public static final String JSON_PROPERTY_ID = "id"; private String id; public static final String JSON_PROPERTY_RECEPTION = "reception"; private OffsetDateTime reception; /** * Permet d&#39;attirer l&#39;attention des forces partenaires sur une affaire * pour le faire sortir du lot. Eventuellement automatisé en fonction des * critères saisis et de leur paramétrage, ou renseigné par l&#39;opérateur. * Prend les valeurs définies dans la nomenclature CISU : - standard : * STANDARD - signalé : ATTENTION Les systèmes peuvent proposer des * fonctionnalités faisant ressortir les dossiers avec le libellé ATTENTION */ public enum ReportingEnum { STANDARD("STANDARD"), ATTENTION("ATTENTION"); private String value; ReportingEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static ReportingEnum fromValue(String value) { for (ReportingEnum b : ReportingEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_REPORTING = "reporting"; private ReportingEnum reporting; public static final String JSON_PROPERTY_FREETEXT = "freetext"; private String freetext; public static final String JSON_PROPERTY_CALLER = "caller"; private Caller caller; public static final String JSON_PROPERTY_ALERT_SOURCE = "alertSource";
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.cisu; /** * Alert */ @JsonPropertyOrder( {Alert.JSON_PROPERTY_ID, Alert.JSON_PROPERTY_RECEPTION, Alert.JSON_PROPERTY_REPORTING, Alert.JSON_PROPERTY_FREETEXT, Alert.JSON_PROPERTY_CALLER, Alert.JSON_PROPERTY_ALERT_SOURCE, Alert.JSON_PROPERTY_LOCATION, Alert.JSON_PROPERTY_QUALIFICATION, Alert.JSON_PROPERTY_CALL_TAKER, Alert.JSON_PROPERTY_ATTACHMENT}) @JsonTypeName("alert") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Alert { public static final String JSON_PROPERTY_ID = "id"; private String id; public static final String JSON_PROPERTY_RECEPTION = "reception"; private OffsetDateTime reception; /** * Permet d&#39;attirer l&#39;attention des forces partenaires sur une affaire * pour le faire sortir du lot. Eventuellement automatisé en fonction des * critères saisis et de leur paramétrage, ou renseigné par l&#39;opérateur. * Prend les valeurs définies dans la nomenclature CISU : - standard : * STANDARD - signalé : ATTENTION Les systèmes peuvent proposer des * fonctionnalités faisant ressortir les dossiers avec le libellé ATTENTION */ public enum ReportingEnum { STANDARD("STANDARD"), ATTENTION("ATTENTION"); private String value; ReportingEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static ReportingEnum fromValue(String value) { for (ReportingEnum b : ReportingEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_REPORTING = "reporting"; private ReportingEnum reporting; public static final String JSON_PROPERTY_FREETEXT = "freetext"; private String freetext; public static final String JSON_PROPERTY_CALLER = "caller"; private Caller caller; public static final String JSON_PROPERTY_ALERT_SOURCE = "alertSource";
private ContactSource alertSource;
3
2023-10-25 14:24:31+00:00
24k
yaroslav318/shop-telegram-bot
telegram-bot/src/main/java/ua/ivanzaitsev/bot/Application.java
[ { "identifier": "ConfigReader", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/core/ConfigReader.java", "snippet": "public class ConfigReader {\n\n private static final ConfigReader INSTANCE = new ConfigReader();\n\n private final Properties properties;\n\n private ConfigReader() {\n ...
import java.util.ArrayList; import java.util.List; import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; import ua.ivanzaitsev.bot.core.ConfigReader; import ua.ivanzaitsev.bot.core.TelegramBot; import ua.ivanzaitsev.bot.handlers.ActionHandler; import ua.ivanzaitsev.bot.handlers.CommandHandler; import ua.ivanzaitsev.bot.handlers.UpdateHandler; import ua.ivanzaitsev.bot.handlers.commands.CartCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.CatalogCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderConfirmCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterAddressCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterCityCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterNameCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterPhoneNumberCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderStepCancelCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderStepPreviousCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.StartCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistry; import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistryDefault; import ua.ivanzaitsev.bot.repositories.CartRepository; import ua.ivanzaitsev.bot.repositories.CategoryRepository; import ua.ivanzaitsev.bot.repositories.ClientActionRepository; import ua.ivanzaitsev.bot.repositories.ClientCommandStateRepository; import ua.ivanzaitsev.bot.repositories.ClientOrderStateRepository; import ua.ivanzaitsev.bot.repositories.ClientRepository; import ua.ivanzaitsev.bot.repositories.OrderRepository; import ua.ivanzaitsev.bot.repositories.ProductRepository; import ua.ivanzaitsev.bot.repositories.database.CategoryRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.ClientRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.OrderRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.ProductRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.CartRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientActionRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientCommandStateRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientOrderStateRepositoryDefault; import ua.ivanzaitsev.bot.services.MessageService; import ua.ivanzaitsev.bot.services.NotificationService; import ua.ivanzaitsev.bot.services.impl.MessageServiceDefault; import ua.ivanzaitsev.bot.services.impl.NotificationServiceDefault;
18,802
package ua.ivanzaitsev.bot; public class Application { private ConfigReader configReader = ConfigReader.getInstance(); private ClientActionRepository clientActionRepository; private ClientCommandStateRepository clientCommandStateRepository; private ClientOrderStateRepository clientOrderStateRepository; private CartRepository cartRepository;
package ua.ivanzaitsev.bot; public class Application { private ConfigReader configReader = ConfigReader.getInstance(); private ClientActionRepository clientActionRepository; private ClientCommandStateRepository clientCommandStateRepository; private ClientOrderStateRepository clientOrderStateRepository; private CartRepository cartRepository;
private CategoryRepository categoryRepository;
18
2023-10-29 15:49:41+00:00
24k
LeoK99/swtw45WS21_reupload
src/main/java/com/buschmais/frontend/views/adrVote/ADRVoteView.java
[ { "identifier": "ADR", "path": "backup/java/com/buschmais/adr/ADR.java", "snippet": "@Document\n@Data\npublic final class ADR {\n\n\t@Getter(AccessLevel.PRIVATE)\n\t@Setter(AccessLevel.PRIVATE)\n\t@EqualsExclude\n\t@Id\n\tprivate String id;\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@DBRef\n\tprivate ADRConta...
import com.buschmais.backend.adr.ADR; import com.buschmais.backend.adr.dataAccess.ADRDao; import com.buschmais.backend.adr.status.ADRStatusType; import com.buschmais.backend.adrAccess.dataAccess.ADRAccessDao; import com.buschmais.backend.image.ImageDao; import com.buschmais.backend.notifications.VotingPendingNotification; import com.buschmais.backend.users.User; import com.buschmais.backend.users.dataAccess.UserDao; import com.buschmais.backend.voting.ADRReview; import com.buschmais.backend.voting.UserIsNotInvitedException; import com.buschmais.backend.voting.VoteType; import com.buschmais.frontend.broadcasting.BroadcastListener; import com.buschmais.frontend.broadcasting.Broadcaster; import com.buschmais.frontend.components.*; import com.buschmais.frontend.vars.StringConstantsFrontend; import com.buschmais.frontend.views.adrCreate.ADRRichCreateView; import com.vaadin.collaborationengine.CollaborationMessageInput; import com.vaadin.collaborationengine.CollaborationMessageList; import com.vaadin.collaborationengine.CollaborationMessagePersister; import com.vaadin.collaborationengine.UserInfo; import com.vaadin.flow.component.DetachEvent; import com.vaadin.flow.component.Key; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.icon.Icon; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextArea; import com.vaadin.flow.router.*; import com.vaadin.flow.shared.Registration; import lombok.NonNull; import org.springframework.beans.factory.annotation.Autowired; import java.time.LocalDateTime; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger;
14,515
package com.buschmais.frontend.views.adrVote; //@Route(value = "vote", layout = MainLayout.class) @CssImport(value = "./themes/adr-workbench/adrVoting/label.css") @CssImport(value = "./themes/adr-workbench/adrVoting/comment-section.css") @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @CssImport(value = "./themes/adr-workbench/adrVoting/adr-information.css") @PageTitle("ADR Details") public class ADRVoteView extends HorizontalLayout implements HasUrlParameter<String>, BroadcastListener, BeforeEnterObserver, BeforeLeaveObserver { /* ADR */ private String adrId; private final ADRDao adrDao; private final ADRAccessDao accessGroupService; private final UserDao userDao; private final ImageDao imageService; /* Components */ private ErrorNotification invalidIdNotification; private VoteResultBar voteResultBar; // overall layouts private VerticalLayout leftLayout; private VerticalLayout rightLayout; private HorizontalLayout adrInformationLayout; private HorizontalLayout adrInformationAuthorStatusLayout; private HorizontalLayout adrActionButtonsLayout; // information about adr (left side) private VerticalLayout adrTopInformationLayout; private VerticalLayout titleLayout; private VerticalLayout authorLayout; private VerticalLayout contextLayout; private VerticalLayout decisionLayout; private VerticalLayout consequencesLayout; private VerticalLayout supersedesLayout; // buttons layout private VerticalLayout adrButtonsLayout; private HorizontalLayout actionButtonsLayout; // voting and comments (right side) private VerticalLayout voteLayout; private HorizontalLayout voteTitleLayout; private VerticalLayout commentLayout; private VerticalLayout commentMessagesLayout; private HorizontalLayout sendCommentButtonLayout; private HorizontalLayout voteIconLayout; // Label private Label statusLabel; private Label titleLabel; private Label authorLabel; private RichTextEditor contextLabel; private RichTextEditor decisionLabel; private RichTextEditor consequencesLabel; private RichTextEditor supersedesLabel; private Label separatorAuthorStatus; private Label adrInformationLabel; private Label titleStringLabel; private Label authorStringLabel; private Label contextStringLabel; private Label decisionStringLabel; private Label consequencesStringLabel; private Label supersedesStringLabel; private Label voteLabel; private Label voteNotStartedYet; private Label votingSeparatorLabel; private Label votingProLabel; private Label votingContraLabel; private Label votingNotYetVotedLabel; private Label votingNotAllowedToVote; private Label commentLabel; // buttons private Button editButton; private Button accessGroupsButton; private Button sendButton; private Button startVoteButton; private Button endVoteButton; private Button inviteVoterButton; private Button proposeDirectlyButton; // text areas private TextArea sendMessageArea; // icons private Icon thumbsUpIcon; private Icon thumbsDownIcon; // divs private Div titleDiv; private Div authorDiv; private Div contextDiv; private Div decisionDiv; private Div consequencesDiv; private Div supersedesDiv; // collaboration private CollaborationMessageList collabMessageList; private CollaborationMessageInput collabMessageInput; private final CollaborationMessagePersister collaborationMessagePersister; private UserInfo userInfo; final String htmlRegEx = "<[^>]*>"; public ADRVoteView(@Autowired ADRDao adrService, @Autowired ADRAccessDao accessGroupService, @Autowired UserDao userService, @Autowired ImageDao imageService, @Autowired CollaborationMessagePersister collaborationMessagePersister) { this.adrDao = adrService; this.accessGroupService = accessGroupService; this.userDao = userService; this.imageService = imageService; this.collaborationMessagePersister = collaborationMessagePersister; Broadcaster.registerListener(this); addDetachListener((DetachEvent e) -> Broadcaster.unregisterListener(this)); } private void setupComponents(ADR adr) { User u = this.userDao.getCurrentUser(); this.userInfo = new UserInfo(u.getId(), u.getUserName()); // define components { // layouts this.leftLayout = new VerticalLayout(); this.rightLayout = new VerticalLayout(); this.adrTopInformationLayout = new VerticalLayout(); this.adrInformationLayout = new HorizontalLayout(); this.adrInformationAuthorStatusLayout = new HorizontalLayout(); this.adrActionButtonsLayout = new HorizontalLayout(); this.titleLayout = new VerticalLayout(); this.authorLayout = new VerticalLayout(); this.contextLayout = new VerticalLayout(); this.decisionLayout = new VerticalLayout(); this.consequencesLayout = new VerticalLayout(); this.supersedesLayout = new VerticalLayout(); this.adrButtonsLayout = new VerticalLayout(); this.actionButtonsLayout = new HorizontalLayout(); this.voteLayout = new VerticalLayout(); this.voteTitleLayout = new HorizontalLayout(); this.commentLayout = new VerticalLayout(); this.commentMessagesLayout = new VerticalLayout(); this.sendCommentButtonLayout = new HorizontalLayout(); this.voteIconLayout = new HorizontalLayout(); //this.adrInformationLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_ADR_INFORMATION); this.adrInformationLabel = new Label(adr.getTitle()); this.separatorAuthorStatus = new Label("\u2012"); this.titleStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_TITEL_STRING); this.authorStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_AUTHOR_STRING); this.contextStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_CONTEXT_STRING); this.decisionStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_DECISION_STRING); this.consequencesStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_CONSEQUENCES_STRING); this.supersedesStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_SUPERSEDES_STRING); this.commentLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_COMMENTS_STRING); this.voteLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_VOTE_STRING); this.voteNotStartedYet = new Label(StringConstantsFrontend.ADRVOTEVIEW_VOTING_HAS_NOT_STARTED_YET); this.votingSeparatorLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_VOTING_SEPARATOR_STRING); this.votingProLabel = new Label(); this.votingContraLabel = new Label(); this.votingNotYetVotedLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_NOT_YET_VOTED); this.votingNotAllowedToVote = new Label(StringConstantsFrontend.ADRVOTEVIEW_ADR_NOT_ALLOWED_TO_VOTE); // buttons this.sendButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_BUTTON_SEND_COMMENT); this.accessGroupsButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_BUTTON_EDIT_ACCESS_GROUPS_BUTTON); this.editButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_EDIT_STRING); this.startVoteButton = new Button( adr.getStatus().getType().equals(ADRStatusType.CREATED) ? StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_START_INTERNAL_VOTING : StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_START_VOTING); this.proposeDirectlyButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_PROPOSE_DIRECTLY); this.endVoteButton = new Button( adr.getStatus().getType().equals(ADRStatusType.INTERNALLY_PROPOSED) ? StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_END_INTERNAL_VOTING : StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_END_VOTING); this.inviteVoterButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_INVITE_VOTER); // text areas this.sendMessageArea = new TextArea(); this.sendMessageArea.setPlaceholder(StringConstantsFrontend.ADRVOTEVIEW_TEXTAREA_COMMENT_PLACEHOLDER); // icons this.thumbsUpIcon = new Icon(VaadinIcon.THUMBS_UP_O); this.thumbsDownIcon = new Icon(VaadinIcon.THUMBS_DOWN_O); // divs this.titleDiv = new Div(); this.authorDiv = new Div(); this.contextDiv = new Div(); this.decisionDiv = new Div(); this.consequencesDiv = new Div(); this.supersedesDiv = new Div(); // comments this.collabMessageList = new CollaborationMessageList(this.userInfo, "adr|" + this.adrId, this.collaborationMessagePersister); this.collabMessageInput = new CollaborationMessageInput(this.collabMessageList); } // methods addDescribingLabels(); //this.updateDescribingLabels(); setupStatusAndAuthorLabel(adr); // setup properties { this.leftLayout.setSpacing(false); this.leftLayout.addClassName("adr-vote-sub-main-layout"); this.rightLayout.addClassName("adr-vote-sub-main-layout"); this.adrInformationAuthorStatusLayout.addClassName("adr-information-layout-author-status"); this.titleLayout.addClassName("adr-vote-information-layout"); this.authorLayout.addClassName("adr-vote-information-layout"); this.contextLayout.addClassName("adr-vote-information-layout"); this.decisionLayout.addClassName("adr-vote-information-layout"); this.consequencesLayout.addClassName("adr-vote-information-layout"); this.supersedesLayout.addClassName("adr-vote-information-layout-superseded"); this.separatorAuthorStatus.addClassName("adr-vote-separator-author-status"); this.titleStringLabel.addClassName("adr-vote-small-heading"); this.authorStringLabel.addClassName("adr-vote-small-heading"); this.contextStringLabel.addClassName("adr-vote-small-heading"); this.decisionStringLabel.addClassName("adr-vote-small-heading"); this.consequencesStringLabel.addClassName("adr-vote-small-heading"); this.supersedesStringLabel.addClassName("adr-vote-small-heading"); this.titleDiv.addClassName("adr-information-div"); this.authorDiv.addClassName("adr-information-div"); this.contextDiv.addClassName("adr-information-div"); this.decisionDiv.addClassName("adr-information-div"); this.consequencesDiv.addClassName("adr-information-div"); this.supersedesDiv.addClassName("adr-information-div-superseded"); this.adrInformationLabel.addClassName("adr-vote-heading"); this.voteLabel.addClassName("adr-vote-heading"); this.voteLabel.getStyle().set("margin-bottom", "15px"); this.commentLabel.addClassName("adr-vote-heading"); this.thumbsUpIcon.setSize("35px"); this.thumbsDownIcon.setSize("35px"); this.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR); this.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR); if (!adr.getStatus().isVotable()) { this.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR_DISABLED); this.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR_DISABLED); } this.votingNotYetVotedLabel.getStyle().set("font-weight", "bold"); this.votingNotYetVotedLabel.getStyle().set("padding", "10px"); this.votingProLabel.addClassName("adr-vote-pro-label"); this.votingContraLabel.addClassName("adr-vote-contra-label"); this.votingSeparatorLabel.addClassName("adr-vote-separator-label"); this.sendButton.addClassName("confirm-button"); this.sendMessageArea.addClassName("adr-vote-message-text-area"); this.commentMessagesLayout.addClassName("adr-vote-message-layout"); this.sendCommentButtonLayout.addClassName("adr-vote-send-message-layout"); this.editButton.addClassName("confirm-button"); this.accessGroupsButton.addClassName("confirm-button"); this.startVoteButton.addClassName("confirm-button"); this.proposeDirectlyButton.addClassName("confirm-button"); this.endVoteButton.addClassName("confirm-button"); this.inviteVoterButton.addClassName("confirm-button"); } // listener //addSendButtonListener(); setMessageInputSubmitter(); addSendButtonShortcut(); addEditButtonListener(); addEditAccessGroupsButtonListener(); addInviteVoterButtonListener(); addVoteIconsListener(); addStartVoteButtonListener(); addEndVoteButtonListener(); } private void setupStatusAndAuthorLabel(ADR adr) { this.statusLabel = new Label(adr.getStatus().getType().getName()); this.statusLabel.setClassName("adr-vote-status-label-" + adr.getStatus().getType().getName().toLowerCase().replaceAll(" ", "-")); this.authorLabel.addClassName("adr-vote-information-author-label"); } private void addDescribingLabels() { adrDao.findById(adrId).ifPresent(adr -> { this.titleDiv.add(this.titleLabel = new Label(adr.getTitle())); this.authorDiv.add(this.authorLabel = new Label(adr.getAuthor().isPresent() ? adr.getAuthor().get().getUserName() : StringConstantsFrontend.GENERAL_UNKNOWN_AUTHOR)); this.contextDiv.add(this.contextLabel = new RichTextEditor(adr.getContext())); this.decisionDiv.add(this.decisionLabel = new RichTextEditor(adr.getDecision())); this.consequencesDiv.add(this.consequencesLabel = new RichTextEditor(adr.getConsequences())); List<ADR> supersededADRs = new LinkedList<>(); adr.getSupersededIds().forEach(id -> adrDao.findById(id).ifPresent(supersededADRs::add)); supersededADRs.forEach(supersededAdr -> { Span tagSpan = new Span(supersededAdr.getTitle()); tagSpan.addClassName("adr-vote-information-layout-superseded-adr-span"); this.supersedesDiv.add(tagSpan); }); }); } private void updateDescribingLabels() { adrDao.findById(adrId).ifPresent(adr -> getUI().ifPresent(ui -> ui.access(() -> { this.titleDiv.remove(this.titleLabel); this.adrInformationAuthorStatusLayout.remove(this.statusLabel); this.adrInformationAuthorStatusLayout.remove(this.authorLabel); this.contextDiv.remove(this.contextLabel); this.decisionDiv.remove(this.decisionLabel); this.consequencesDiv.remove(this.consequencesLabel); this.supersedesLayout.remove(this.supersedesDiv); this.titleLabel.setText(adr.getTitle()); this.statusLabel.setText(adr.getStatus().getType().getName()); this.authorLabel.setText(adr.getAuthor().isPresent() ? adr.getAuthor().get().getUserName() : StringConstantsFrontend.GENERAL_UNKNOWN_AUTHOR); this.contextLabel = new RichTextEditor(adr.getContext()); this.decisionLabel = new RichTextEditor(adr.getDecision()); this.consequencesLabel = new RichTextEditor(adr.getConsequences()); this.supersedesDiv = new Div(); List<ADR> supersededADRs = new LinkedList<>(); adr.getSupersededIds().forEach(id -> adrDao.findById(id).ifPresent(supersededADRs::add)); supersededADRs.forEach(supersededAdr -> { Span tagSpan = new Span(supersededAdr.getTitle()); tagSpan.addClassName("adr-vote-information-layout-superseded-adr-span"); this.supersedesDiv.add(tagSpan); }); this.titleDiv.add(this.titleLabel); this.adrInformationAuthorStatusLayout.add(this.statusLabel); this.adrInformationAuthorStatusLayout.addComponentAsFirst(this.authorLabel); this.contextDiv.add(this.contextLabel); this.decisionDiv.add(this.decisionLabel); this.consequencesDiv.add(this.consequencesLabel); this.supersedesLayout.add(this.supersedesDiv); }))); } private void setMessageInputSubmitter() { this.collabMessageList.setSubmitter(activationContext -> { Registration registration = this.sendButton.addClickListener(event -> { String tempValue = this.sendMessageArea.getValue().trim(); if (!tempValue.isEmpty()) { activationContext.appendMessage(tempValue); this.sendMessageArea.clear(); } }); return () -> { registration.remove(); this.sendButton.setEnabled(false); }; }); } private synchronized void addComponentsToLayouts(@NonNull final ADR adr) { // setup setupComponents(adr); // add titles to main right and left side layout this.adrTopInformationLayout.add(this.adrInformationLayout, this.adrInformationAuthorStatusLayout, this.adrActionButtonsLayout); this.adrInformationLayout.add(this.adrInformationLabel); /* if (adr.canWrite(this.userDao.getCurrentUser())) { this.adrActionButtonsLayout.add(this.editButton); } if(adr.canEditAccessGroups(this.userDao.getCurrentUser())){ this.adrActionButtonsLayout.add(this.accessGroupsButton); } */ this.leftLayout.add(this.adrTopInformationLayout); /* Left side (ADR Information) */ // adding components to vertical adr information layouts this.titleLayout.add(this.titleStringLabel, this.titleDiv); this.authorLayout.add(this.authorStringLabel, this.authorDiv); this.contextLayout.add(this.contextStringLabel, this.contextDiv); this.decisionLayout.add(this.decisionStringLabel, this.decisionDiv); this.consequencesLayout.add(this.consequencesStringLabel, this.consequencesDiv); // add only if not empty if (!adr.getSupersededIds().isEmpty()) { this.supersedesLayout.add(this.supersedesStringLabel, this.supersedesDiv); } // add vertical adr information layouts to main left layout - leftLayout //this.leftLayout.add(this.titleLayout, this.authorLayout, this.contextLayout, this.decisionLayout, this.consequencesLayout, this.supersedesLayout, this.adrButtonsLayout); this.leftLayout.add(this.contextLayout, this.decisionLayout, this.consequencesLayout, this.supersedesLayout, this.adrButtonsLayout); this.adrButtonsLayout.add(this.actionButtonsLayout); /* Right side (voting and comments) */ this.voteTitleLayout.add(this.voteLabel); this.voteLayout.add(this.voteTitleLayout); this.commentLayout.add(this.commentLabel); this.voteLayout.add(this.voteIconLayout); this.voteResultBar = new VoteResultBar(); this.voteLayout.add(this.voteResultBar); this.setVariableVotingSectionElements(); this.commentMessagesLayout.add(this.collabMessageList); this.commentLayout.add(this.commentMessagesLayout); this.sendCommentButtonLayout.add(this.sendMessageArea, this.sendButton); this.commentLayout.add(this.sendCommentButtonLayout); this.rightLayout.add(this.voteLayout); this.rightLayout.add(this.commentLayout); // adding main side layouts to overall main layout this.add(this.leftLayout); this.add(this.rightLayout); } private void addSendButtonShortcut() { this.sendButton.addClickShortcut(Key.ENTER); } private void addEditButtonListener() { this.editButton.addClickListener(event -> { String route = RouteConfiguration.forSessionScope().getUrl(ADRRichCreateView.class, adrId); this.getUI().ifPresent((ui) -> ui.getPage().setLocation(route)); }); } private void addEditAccessGroupsButtonListener() { this.accessGroupsButton.addClickListener(event -> { AccessGroupDialog dialog = new AccessGroupDialog(this.accessGroupService, this.adrDao, this.adrId); //dialog.addDetachListener(event2 -> Broadcaster.broadcastMessage(Event.ADR_ACCESS_GROUPS_CHANGED, adrId, this)); dialog.open(); }); } private void addInviteVoterButtonListener() { this.inviteVoterButton.addClickListener(event -> adrDao.findById(adrId).ifPresent(adr -> adr.getStatus().adrReviewAsOpt().ifElse(review -> { InviteVoterDialog dialog = new InviteVoterDialog(this.userDao, this.adrDao, adr); dialog.addDetachListener(event2 -> { Broadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this); setVariableVotingSectionElements(); }); dialog.open(); }, () -> new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_USERS_CURRENTLY_NOT_INVITABLE).open()))); } private void addStartVoteButtonListener() { this.startVoteButton.addClickListener(event -> { synchronized (adrDao) { adrDao.findById(adrId).ifPresent((adr) -> { if (!adr.canStartVoting(userDao.getCurrentUser())) return; adr.propose(); this.adrDao.save(adr); adr.getStatus().adrReviewAsOpt().ifPresent(review -> userDao .getCurrentUser() .pushNotification(new VotingPendingNotification(review, LocalDateTime.now()))); }); //this.getUI().ifPresent((ui) -> ui.getPage().reload()); } Broadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this); this.setVariableVotingSectionElements(); }); this.proposeDirectlyButton.addClickListener(event -> { synchronized (adrDao) { adrDao.findById(adrId).ifPresent((adr) -> { if (!adr.canPropose(userDao.getCurrentUser())) return; adr.propose(); if (adr.canPropose(userDao.getCurrentUser())) adr.propose(); this.adrDao.save(adr); adr.getStatus().adrReviewAsOpt().ifPresent(review -> userDao .getCurrentUser() .pushNotification(new VotingPendingNotification(review, LocalDateTime.now()))); }); this.getUI().ifPresent((ui) -> ui.getPage().reload()); } Broadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this); //this.setVariableVotingSectionElements(); }); } private void addEndVoteButtonListener() { this.endVoteButton.addClickListener(event -> { synchronized (adrDao) { adrDao.findById(adrId).ifPresent((adr) -> { ADR.VoteResult res = adr.endVoting(adrDao); if (res.equals(ADR.VoteResult.INTERNALLY_APPROVED)) { adr.getStatus().adrReviewAsOpt().ifPresent(review -> userDao .getCurrentUser() .pushNotification(new VotingPendingNotification(review, LocalDateTime.now()))); } this.adrDao.save(adr); Broadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this); this.setVariableVotingSectionElements(); }); } }); } static private final class VoteSts { static final int ADR_NOT_PROPOSED = -2, USER_NOT_PERMITTED_TO_VOTE = -1, VOTE_WITHDRAWN = 0, VOTE_GIVEN = 1; } private void addVoteIconsListener() { this.thumbsUpIcon.addClickListener(event -> { AtomicInteger voteSuccess = new AtomicInteger(VoteSts.ADR_NOT_PROPOSED); synchronized (adrDao) { adrDao.findById(adrId).ifPresent((adr) -> adr.getStatus().adrReviewAsOpt().ifPresent(adrReview -> { if (adrReview.getUserVote(this.userDao.getCurrentUser()).isEmpty() || !adrReview.getUserVote(this.userDao.getCurrentUser()).get().equals(VoteType.FOR)) { try { if (adr.getStatus().isVotable()) { adrReview.putVote(this.userDao.getCurrentUser(), VoteType.FOR); this.adrDao.save(adr); voteSuccess.set(VoteSts.VOTE_GIVEN); } } catch (UserIsNotInvitedException e) { voteSuccess.set(VoteSts.USER_NOT_PERMITTED_TO_VOTE); } } else if (adr.getStatus().isVotable()) { try { adrReview.removeVote(this.userDao.getCurrentUser()); this.adrDao.save(adr); voteSuccess.set(VoteSts.VOTE_WITHDRAWN); } catch (UserIsNotInvitedException e) { voteSuccess.set(VoteSts.USER_NOT_PERMITTED_TO_VOTE); } } })); } switch (voteSuccess.get()) { case VoteSts.VOTE_GIVEN: Broadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this); new SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_SUCCESSFULLY_VOTED).open(); setVariableVotingSectionElements(); break; case VoteSts.VOTE_WITHDRAWN: Broadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this); new SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_VOTE_REFUSED).open(); setVariableVotingSectionElements(); break; case VoteSts.USER_NOT_PERMITTED_TO_VOTE: new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NOT_ALLOWED_TO_VOTE).open(); default: new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NO_LONGER_PROPOSED).open(); } }); this.thumbsDownIcon.addClickListener(event -> { AtomicInteger voteSuccess = new AtomicInteger(VoteSts.ADR_NOT_PROPOSED); //-2 = ADR not proposed; -1 = user not permitted to vote; 0 = vote successfully withdrawn; 1 = vote successfully given synchronized (adrDao) { adrDao.findById(adrId).ifPresent((adr) -> adr.getStatus().adrReviewAsOpt().ifPresent(adrReview -> { if (adrReview.getUserVote(this.userDao.getCurrentUser()).isEmpty() || !adrReview.getUserVote(this.userDao.getCurrentUser()).get().equals(VoteType.AGAINST)) { try { if (adr.getStatus().isVotable()) { adrReview.putVote(this.userDao.getCurrentUser(), VoteType.AGAINST); this.adrDao.save(adr); voteSuccess.set(VoteSts.VOTE_GIVEN); } } catch (UserIsNotInvitedException e) { voteSuccess.set(-1); } } // voted else if (adr.getStatus().isVotable()) { try { adrReview.removeVote(this.userDao.getCurrentUser()); this.adrDao.save(adr); voteSuccess.set(VoteSts.VOTE_WITHDRAWN); } catch (UserIsNotInvitedException e) { voteSuccess.set(VoteSts.USER_NOT_PERMITTED_TO_VOTE); } } }) ); } switch (voteSuccess.get()) { case VoteSts.VOTE_GIVEN: Broadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this); new SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_SUCCESSFULLY_VOTED).open(); setVariableVotingSectionElements(); break; case VoteSts.VOTE_WITHDRAWN: Broadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this); new SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_VOTE_REFUSED).open(); setVariableVotingSectionElements(); break; case VoteSts.USER_NOT_PERMITTED_TO_VOTE: new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NOT_ALLOWED_TO_VOTE).open(); default: new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NO_LONGER_PROPOSED).open(); } }); } private void updateVotingResults() { VoteResultBar newBar = new VoteResultBar(); this.voteLayout.replace(this.voteResultBar, newBar); this.voteResultBar = newBar; }
package com.buschmais.frontend.views.adrVote; //@Route(value = "vote", layout = MainLayout.class) @CssImport(value = "./themes/adr-workbench/adrVoting/label.css") @CssImport(value = "./themes/adr-workbench/adrVoting/comment-section.css") @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @CssImport(value = "./themes/adr-workbench/adrVoting/adr-information.css") @PageTitle("ADR Details") public class ADRVoteView extends HorizontalLayout implements HasUrlParameter<String>, BroadcastListener, BeforeEnterObserver, BeforeLeaveObserver { /* ADR */ private String adrId; private final ADRDao adrDao; private final ADRAccessDao accessGroupService; private final UserDao userDao; private final ImageDao imageService; /* Components */ private ErrorNotification invalidIdNotification; private VoteResultBar voteResultBar; // overall layouts private VerticalLayout leftLayout; private VerticalLayout rightLayout; private HorizontalLayout adrInformationLayout; private HorizontalLayout adrInformationAuthorStatusLayout; private HorizontalLayout adrActionButtonsLayout; // information about adr (left side) private VerticalLayout adrTopInformationLayout; private VerticalLayout titleLayout; private VerticalLayout authorLayout; private VerticalLayout contextLayout; private VerticalLayout decisionLayout; private VerticalLayout consequencesLayout; private VerticalLayout supersedesLayout; // buttons layout private VerticalLayout adrButtonsLayout; private HorizontalLayout actionButtonsLayout; // voting and comments (right side) private VerticalLayout voteLayout; private HorizontalLayout voteTitleLayout; private VerticalLayout commentLayout; private VerticalLayout commentMessagesLayout; private HorizontalLayout sendCommentButtonLayout; private HorizontalLayout voteIconLayout; // Label private Label statusLabel; private Label titleLabel; private Label authorLabel; private RichTextEditor contextLabel; private RichTextEditor decisionLabel; private RichTextEditor consequencesLabel; private RichTextEditor supersedesLabel; private Label separatorAuthorStatus; private Label adrInformationLabel; private Label titleStringLabel; private Label authorStringLabel; private Label contextStringLabel; private Label decisionStringLabel; private Label consequencesStringLabel; private Label supersedesStringLabel; private Label voteLabel; private Label voteNotStartedYet; private Label votingSeparatorLabel; private Label votingProLabel; private Label votingContraLabel; private Label votingNotYetVotedLabel; private Label votingNotAllowedToVote; private Label commentLabel; // buttons private Button editButton; private Button accessGroupsButton; private Button sendButton; private Button startVoteButton; private Button endVoteButton; private Button inviteVoterButton; private Button proposeDirectlyButton; // text areas private TextArea sendMessageArea; // icons private Icon thumbsUpIcon; private Icon thumbsDownIcon; // divs private Div titleDiv; private Div authorDiv; private Div contextDiv; private Div decisionDiv; private Div consequencesDiv; private Div supersedesDiv; // collaboration private CollaborationMessageList collabMessageList; private CollaborationMessageInput collabMessageInput; private final CollaborationMessagePersister collaborationMessagePersister; private UserInfo userInfo; final String htmlRegEx = "<[^>]*>"; public ADRVoteView(@Autowired ADRDao adrService, @Autowired ADRAccessDao accessGroupService, @Autowired UserDao userService, @Autowired ImageDao imageService, @Autowired CollaborationMessagePersister collaborationMessagePersister) { this.adrDao = adrService; this.accessGroupService = accessGroupService; this.userDao = userService; this.imageService = imageService; this.collaborationMessagePersister = collaborationMessagePersister; Broadcaster.registerListener(this); addDetachListener((DetachEvent e) -> Broadcaster.unregisterListener(this)); } private void setupComponents(ADR adr) { User u = this.userDao.getCurrentUser(); this.userInfo = new UserInfo(u.getId(), u.getUserName()); // define components { // layouts this.leftLayout = new VerticalLayout(); this.rightLayout = new VerticalLayout(); this.adrTopInformationLayout = new VerticalLayout(); this.adrInformationLayout = new HorizontalLayout(); this.adrInformationAuthorStatusLayout = new HorizontalLayout(); this.adrActionButtonsLayout = new HorizontalLayout(); this.titleLayout = new VerticalLayout(); this.authorLayout = new VerticalLayout(); this.contextLayout = new VerticalLayout(); this.decisionLayout = new VerticalLayout(); this.consequencesLayout = new VerticalLayout(); this.supersedesLayout = new VerticalLayout(); this.adrButtonsLayout = new VerticalLayout(); this.actionButtonsLayout = new HorizontalLayout(); this.voteLayout = new VerticalLayout(); this.voteTitleLayout = new HorizontalLayout(); this.commentLayout = new VerticalLayout(); this.commentMessagesLayout = new VerticalLayout(); this.sendCommentButtonLayout = new HorizontalLayout(); this.voteIconLayout = new HorizontalLayout(); //this.adrInformationLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_ADR_INFORMATION); this.adrInformationLabel = new Label(adr.getTitle()); this.separatorAuthorStatus = new Label("\u2012"); this.titleStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_TITEL_STRING); this.authorStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_AUTHOR_STRING); this.contextStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_CONTEXT_STRING); this.decisionStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_DECISION_STRING); this.consequencesStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_CONSEQUENCES_STRING); this.supersedesStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_SUPERSEDES_STRING); this.commentLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_COMMENTS_STRING); this.voteLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_VOTE_STRING); this.voteNotStartedYet = new Label(StringConstantsFrontend.ADRVOTEVIEW_VOTING_HAS_NOT_STARTED_YET); this.votingSeparatorLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_VOTING_SEPARATOR_STRING); this.votingProLabel = new Label(); this.votingContraLabel = new Label(); this.votingNotYetVotedLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_NOT_YET_VOTED); this.votingNotAllowedToVote = new Label(StringConstantsFrontend.ADRVOTEVIEW_ADR_NOT_ALLOWED_TO_VOTE); // buttons this.sendButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_BUTTON_SEND_COMMENT); this.accessGroupsButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_BUTTON_EDIT_ACCESS_GROUPS_BUTTON); this.editButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_EDIT_STRING); this.startVoteButton = new Button( adr.getStatus().getType().equals(ADRStatusType.CREATED) ? StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_START_INTERNAL_VOTING : StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_START_VOTING); this.proposeDirectlyButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_PROPOSE_DIRECTLY); this.endVoteButton = new Button( adr.getStatus().getType().equals(ADRStatusType.INTERNALLY_PROPOSED) ? StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_END_INTERNAL_VOTING : StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_END_VOTING); this.inviteVoterButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_INVITE_VOTER); // text areas this.sendMessageArea = new TextArea(); this.sendMessageArea.setPlaceholder(StringConstantsFrontend.ADRVOTEVIEW_TEXTAREA_COMMENT_PLACEHOLDER); // icons this.thumbsUpIcon = new Icon(VaadinIcon.THUMBS_UP_O); this.thumbsDownIcon = new Icon(VaadinIcon.THUMBS_DOWN_O); // divs this.titleDiv = new Div(); this.authorDiv = new Div(); this.contextDiv = new Div(); this.decisionDiv = new Div(); this.consequencesDiv = new Div(); this.supersedesDiv = new Div(); // comments this.collabMessageList = new CollaborationMessageList(this.userInfo, "adr|" + this.adrId, this.collaborationMessagePersister); this.collabMessageInput = new CollaborationMessageInput(this.collabMessageList); } // methods addDescribingLabels(); //this.updateDescribingLabels(); setupStatusAndAuthorLabel(adr); // setup properties { this.leftLayout.setSpacing(false); this.leftLayout.addClassName("adr-vote-sub-main-layout"); this.rightLayout.addClassName("adr-vote-sub-main-layout"); this.adrInformationAuthorStatusLayout.addClassName("adr-information-layout-author-status"); this.titleLayout.addClassName("adr-vote-information-layout"); this.authorLayout.addClassName("adr-vote-information-layout"); this.contextLayout.addClassName("adr-vote-information-layout"); this.decisionLayout.addClassName("adr-vote-information-layout"); this.consequencesLayout.addClassName("adr-vote-information-layout"); this.supersedesLayout.addClassName("adr-vote-information-layout-superseded"); this.separatorAuthorStatus.addClassName("adr-vote-separator-author-status"); this.titleStringLabel.addClassName("adr-vote-small-heading"); this.authorStringLabel.addClassName("adr-vote-small-heading"); this.contextStringLabel.addClassName("adr-vote-small-heading"); this.decisionStringLabel.addClassName("adr-vote-small-heading"); this.consequencesStringLabel.addClassName("adr-vote-small-heading"); this.supersedesStringLabel.addClassName("adr-vote-small-heading"); this.titleDiv.addClassName("adr-information-div"); this.authorDiv.addClassName("adr-information-div"); this.contextDiv.addClassName("adr-information-div"); this.decisionDiv.addClassName("adr-information-div"); this.consequencesDiv.addClassName("adr-information-div"); this.supersedesDiv.addClassName("adr-information-div-superseded"); this.adrInformationLabel.addClassName("adr-vote-heading"); this.voteLabel.addClassName("adr-vote-heading"); this.voteLabel.getStyle().set("margin-bottom", "15px"); this.commentLabel.addClassName("adr-vote-heading"); this.thumbsUpIcon.setSize("35px"); this.thumbsDownIcon.setSize("35px"); this.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR); this.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR); if (!adr.getStatus().isVotable()) { this.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR_DISABLED); this.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR_DISABLED); } this.votingNotYetVotedLabel.getStyle().set("font-weight", "bold"); this.votingNotYetVotedLabel.getStyle().set("padding", "10px"); this.votingProLabel.addClassName("adr-vote-pro-label"); this.votingContraLabel.addClassName("adr-vote-contra-label"); this.votingSeparatorLabel.addClassName("adr-vote-separator-label"); this.sendButton.addClassName("confirm-button"); this.sendMessageArea.addClassName("adr-vote-message-text-area"); this.commentMessagesLayout.addClassName("adr-vote-message-layout"); this.sendCommentButtonLayout.addClassName("adr-vote-send-message-layout"); this.editButton.addClassName("confirm-button"); this.accessGroupsButton.addClassName("confirm-button"); this.startVoteButton.addClassName("confirm-button"); this.proposeDirectlyButton.addClassName("confirm-button"); this.endVoteButton.addClassName("confirm-button"); this.inviteVoterButton.addClassName("confirm-button"); } // listener //addSendButtonListener(); setMessageInputSubmitter(); addSendButtonShortcut(); addEditButtonListener(); addEditAccessGroupsButtonListener(); addInviteVoterButtonListener(); addVoteIconsListener(); addStartVoteButtonListener(); addEndVoteButtonListener(); } private void setupStatusAndAuthorLabel(ADR adr) { this.statusLabel = new Label(adr.getStatus().getType().getName()); this.statusLabel.setClassName("adr-vote-status-label-" + adr.getStatus().getType().getName().toLowerCase().replaceAll(" ", "-")); this.authorLabel.addClassName("adr-vote-information-author-label"); } private void addDescribingLabels() { adrDao.findById(adrId).ifPresent(adr -> { this.titleDiv.add(this.titleLabel = new Label(adr.getTitle())); this.authorDiv.add(this.authorLabel = new Label(adr.getAuthor().isPresent() ? adr.getAuthor().get().getUserName() : StringConstantsFrontend.GENERAL_UNKNOWN_AUTHOR)); this.contextDiv.add(this.contextLabel = new RichTextEditor(adr.getContext())); this.decisionDiv.add(this.decisionLabel = new RichTextEditor(adr.getDecision())); this.consequencesDiv.add(this.consequencesLabel = new RichTextEditor(adr.getConsequences())); List<ADR> supersededADRs = new LinkedList<>(); adr.getSupersededIds().forEach(id -> adrDao.findById(id).ifPresent(supersededADRs::add)); supersededADRs.forEach(supersededAdr -> { Span tagSpan = new Span(supersededAdr.getTitle()); tagSpan.addClassName("adr-vote-information-layout-superseded-adr-span"); this.supersedesDiv.add(tagSpan); }); }); } private void updateDescribingLabels() { adrDao.findById(adrId).ifPresent(adr -> getUI().ifPresent(ui -> ui.access(() -> { this.titleDiv.remove(this.titleLabel); this.adrInformationAuthorStatusLayout.remove(this.statusLabel); this.adrInformationAuthorStatusLayout.remove(this.authorLabel); this.contextDiv.remove(this.contextLabel); this.decisionDiv.remove(this.decisionLabel); this.consequencesDiv.remove(this.consequencesLabel); this.supersedesLayout.remove(this.supersedesDiv); this.titleLabel.setText(adr.getTitle()); this.statusLabel.setText(adr.getStatus().getType().getName()); this.authorLabel.setText(adr.getAuthor().isPresent() ? adr.getAuthor().get().getUserName() : StringConstantsFrontend.GENERAL_UNKNOWN_AUTHOR); this.contextLabel = new RichTextEditor(adr.getContext()); this.decisionLabel = new RichTextEditor(adr.getDecision()); this.consequencesLabel = new RichTextEditor(adr.getConsequences()); this.supersedesDiv = new Div(); List<ADR> supersededADRs = new LinkedList<>(); adr.getSupersededIds().forEach(id -> adrDao.findById(id).ifPresent(supersededADRs::add)); supersededADRs.forEach(supersededAdr -> { Span tagSpan = new Span(supersededAdr.getTitle()); tagSpan.addClassName("adr-vote-information-layout-superseded-adr-span"); this.supersedesDiv.add(tagSpan); }); this.titleDiv.add(this.titleLabel); this.adrInformationAuthorStatusLayout.add(this.statusLabel); this.adrInformationAuthorStatusLayout.addComponentAsFirst(this.authorLabel); this.contextDiv.add(this.contextLabel); this.decisionDiv.add(this.decisionLabel); this.consequencesDiv.add(this.consequencesLabel); this.supersedesLayout.add(this.supersedesDiv); }))); } private void setMessageInputSubmitter() { this.collabMessageList.setSubmitter(activationContext -> { Registration registration = this.sendButton.addClickListener(event -> { String tempValue = this.sendMessageArea.getValue().trim(); if (!tempValue.isEmpty()) { activationContext.appendMessage(tempValue); this.sendMessageArea.clear(); } }); return () -> { registration.remove(); this.sendButton.setEnabled(false); }; }); } private synchronized void addComponentsToLayouts(@NonNull final ADR adr) { // setup setupComponents(adr); // add titles to main right and left side layout this.adrTopInformationLayout.add(this.adrInformationLayout, this.adrInformationAuthorStatusLayout, this.adrActionButtonsLayout); this.adrInformationLayout.add(this.adrInformationLabel); /* if (adr.canWrite(this.userDao.getCurrentUser())) { this.adrActionButtonsLayout.add(this.editButton); } if(adr.canEditAccessGroups(this.userDao.getCurrentUser())){ this.adrActionButtonsLayout.add(this.accessGroupsButton); } */ this.leftLayout.add(this.adrTopInformationLayout); /* Left side (ADR Information) */ // adding components to vertical adr information layouts this.titleLayout.add(this.titleStringLabel, this.titleDiv); this.authorLayout.add(this.authorStringLabel, this.authorDiv); this.contextLayout.add(this.contextStringLabel, this.contextDiv); this.decisionLayout.add(this.decisionStringLabel, this.decisionDiv); this.consequencesLayout.add(this.consequencesStringLabel, this.consequencesDiv); // add only if not empty if (!adr.getSupersededIds().isEmpty()) { this.supersedesLayout.add(this.supersedesStringLabel, this.supersedesDiv); } // add vertical adr information layouts to main left layout - leftLayout //this.leftLayout.add(this.titleLayout, this.authorLayout, this.contextLayout, this.decisionLayout, this.consequencesLayout, this.supersedesLayout, this.adrButtonsLayout); this.leftLayout.add(this.contextLayout, this.decisionLayout, this.consequencesLayout, this.supersedesLayout, this.adrButtonsLayout); this.adrButtonsLayout.add(this.actionButtonsLayout); /* Right side (voting and comments) */ this.voteTitleLayout.add(this.voteLabel); this.voteLayout.add(this.voteTitleLayout); this.commentLayout.add(this.commentLabel); this.voteLayout.add(this.voteIconLayout); this.voteResultBar = new VoteResultBar(); this.voteLayout.add(this.voteResultBar); this.setVariableVotingSectionElements(); this.commentMessagesLayout.add(this.collabMessageList); this.commentLayout.add(this.commentMessagesLayout); this.sendCommentButtonLayout.add(this.sendMessageArea, this.sendButton); this.commentLayout.add(this.sendCommentButtonLayout); this.rightLayout.add(this.voteLayout); this.rightLayout.add(this.commentLayout); // adding main side layouts to overall main layout this.add(this.leftLayout); this.add(this.rightLayout); } private void addSendButtonShortcut() { this.sendButton.addClickShortcut(Key.ENTER); } private void addEditButtonListener() { this.editButton.addClickListener(event -> { String route = RouteConfiguration.forSessionScope().getUrl(ADRRichCreateView.class, adrId); this.getUI().ifPresent((ui) -> ui.getPage().setLocation(route)); }); } private void addEditAccessGroupsButtonListener() { this.accessGroupsButton.addClickListener(event -> { AccessGroupDialog dialog = new AccessGroupDialog(this.accessGroupService, this.adrDao, this.adrId); //dialog.addDetachListener(event2 -> Broadcaster.broadcastMessage(Event.ADR_ACCESS_GROUPS_CHANGED, adrId, this)); dialog.open(); }); } private void addInviteVoterButtonListener() { this.inviteVoterButton.addClickListener(event -> adrDao.findById(adrId).ifPresent(adr -> adr.getStatus().adrReviewAsOpt().ifElse(review -> { InviteVoterDialog dialog = new InviteVoterDialog(this.userDao, this.adrDao, adr); dialog.addDetachListener(event2 -> { Broadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this); setVariableVotingSectionElements(); }); dialog.open(); }, () -> new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_USERS_CURRENTLY_NOT_INVITABLE).open()))); } private void addStartVoteButtonListener() { this.startVoteButton.addClickListener(event -> { synchronized (adrDao) { adrDao.findById(adrId).ifPresent((adr) -> { if (!adr.canStartVoting(userDao.getCurrentUser())) return; adr.propose(); this.adrDao.save(adr); adr.getStatus().adrReviewAsOpt().ifPresent(review -> userDao .getCurrentUser() .pushNotification(new VotingPendingNotification(review, LocalDateTime.now()))); }); //this.getUI().ifPresent((ui) -> ui.getPage().reload()); } Broadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this); this.setVariableVotingSectionElements(); }); this.proposeDirectlyButton.addClickListener(event -> { synchronized (adrDao) { adrDao.findById(adrId).ifPresent((adr) -> { if (!adr.canPropose(userDao.getCurrentUser())) return; adr.propose(); if (adr.canPropose(userDao.getCurrentUser())) adr.propose(); this.adrDao.save(adr); adr.getStatus().adrReviewAsOpt().ifPresent(review -> userDao .getCurrentUser() .pushNotification(new VotingPendingNotification(review, LocalDateTime.now()))); }); this.getUI().ifPresent((ui) -> ui.getPage().reload()); } Broadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this); //this.setVariableVotingSectionElements(); }); } private void addEndVoteButtonListener() { this.endVoteButton.addClickListener(event -> { synchronized (adrDao) { adrDao.findById(adrId).ifPresent((adr) -> { ADR.VoteResult res = adr.endVoting(adrDao); if (res.equals(ADR.VoteResult.INTERNALLY_APPROVED)) { adr.getStatus().adrReviewAsOpt().ifPresent(review -> userDao .getCurrentUser() .pushNotification(new VotingPendingNotification(review, LocalDateTime.now()))); } this.adrDao.save(adr); Broadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this); this.setVariableVotingSectionElements(); }); } }); } static private final class VoteSts { static final int ADR_NOT_PROPOSED = -2, USER_NOT_PERMITTED_TO_VOTE = -1, VOTE_WITHDRAWN = 0, VOTE_GIVEN = 1; } private void addVoteIconsListener() { this.thumbsUpIcon.addClickListener(event -> { AtomicInteger voteSuccess = new AtomicInteger(VoteSts.ADR_NOT_PROPOSED); synchronized (adrDao) { adrDao.findById(adrId).ifPresent((adr) -> adr.getStatus().adrReviewAsOpt().ifPresent(adrReview -> { if (adrReview.getUserVote(this.userDao.getCurrentUser()).isEmpty() || !adrReview.getUserVote(this.userDao.getCurrentUser()).get().equals(VoteType.FOR)) { try { if (adr.getStatus().isVotable()) { adrReview.putVote(this.userDao.getCurrentUser(), VoteType.FOR); this.adrDao.save(adr); voteSuccess.set(VoteSts.VOTE_GIVEN); } } catch (UserIsNotInvitedException e) { voteSuccess.set(VoteSts.USER_NOT_PERMITTED_TO_VOTE); } } else if (adr.getStatus().isVotable()) { try { adrReview.removeVote(this.userDao.getCurrentUser()); this.adrDao.save(adr); voteSuccess.set(VoteSts.VOTE_WITHDRAWN); } catch (UserIsNotInvitedException e) { voteSuccess.set(VoteSts.USER_NOT_PERMITTED_TO_VOTE); } } })); } switch (voteSuccess.get()) { case VoteSts.VOTE_GIVEN: Broadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this); new SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_SUCCESSFULLY_VOTED).open(); setVariableVotingSectionElements(); break; case VoteSts.VOTE_WITHDRAWN: Broadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this); new SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_VOTE_REFUSED).open(); setVariableVotingSectionElements(); break; case VoteSts.USER_NOT_PERMITTED_TO_VOTE: new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NOT_ALLOWED_TO_VOTE).open(); default: new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NO_LONGER_PROPOSED).open(); } }); this.thumbsDownIcon.addClickListener(event -> { AtomicInteger voteSuccess = new AtomicInteger(VoteSts.ADR_NOT_PROPOSED); //-2 = ADR not proposed; -1 = user not permitted to vote; 0 = vote successfully withdrawn; 1 = vote successfully given synchronized (adrDao) { adrDao.findById(adrId).ifPresent((adr) -> adr.getStatus().adrReviewAsOpt().ifPresent(adrReview -> { if (adrReview.getUserVote(this.userDao.getCurrentUser()).isEmpty() || !adrReview.getUserVote(this.userDao.getCurrentUser()).get().equals(VoteType.AGAINST)) { try { if (adr.getStatus().isVotable()) { adrReview.putVote(this.userDao.getCurrentUser(), VoteType.AGAINST); this.adrDao.save(adr); voteSuccess.set(VoteSts.VOTE_GIVEN); } } catch (UserIsNotInvitedException e) { voteSuccess.set(-1); } } // voted else if (adr.getStatus().isVotable()) { try { adrReview.removeVote(this.userDao.getCurrentUser()); this.adrDao.save(adr); voteSuccess.set(VoteSts.VOTE_WITHDRAWN); } catch (UserIsNotInvitedException e) { voteSuccess.set(VoteSts.USER_NOT_PERMITTED_TO_VOTE); } } }) ); } switch (voteSuccess.get()) { case VoteSts.VOTE_GIVEN: Broadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this); new SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_SUCCESSFULLY_VOTED).open(); setVariableVotingSectionElements(); break; case VoteSts.VOTE_WITHDRAWN: Broadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this); new SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_VOTE_REFUSED).open(); setVariableVotingSectionElements(); break; case VoteSts.USER_NOT_PERMITTED_TO_VOTE: new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NOT_ALLOWED_TO_VOTE).open(); default: new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NO_LONGER_PROPOSED).open(); } }); } private void updateVotingResults() { VoteResultBar newBar = new VoteResultBar(); this.voteLayout.replace(this.voteResultBar, newBar); this.voteResultBar = newBar; }
private void updateVotingResults(ADRReview adrReview) {
8
2023-10-25 15:18:06+00:00
24k
Java-Game-Engine-Merger/Libgdx-Processing
server-framework/src/main/java/pama1234/math/mat/Mat4f.java
[ { "identifier": "UtilMath", "path": "server-framework/src/main/java/pama1234/math/UtilMath.java", "snippet": "public class UtilMath{\n private static final class RandomNumberGeneratorHolder{\n static final Random randomNumberGenerator=new Random();\n }\n public static final float radDeg=(float)(18...
import pama1234.math.UtilMath; import pama1234.math.gdx.temp.ServerAffine2; import pama1234.math.gdx.temp.ServerQuaternion; import pama1234.math.vec.Vec3f;
15,697
} public Mat4f avg(Mat4f[] t,float[] w) { Vec3f tv=t[0].getScale(tmpUp); tv.scl(w[0]); tmpVec.set(tv); quat.set(t[0].getRotation(quat2).exp(w[0])); tv=t[0].getTranslation(tmpUp); tv.scl(w[0]); tmpForward.set(tv); for(int i=1;i<t.length;i++) { tv=t[i].getScale(tmpUp); tv.scl(w[i]); tmpVec.add(tv); quat.mul(t[i].getRotation(quat2).exp(w[i])); tv=t[i].getTranslation(tmpUp); tv.scl(w[i]); tmpForward.add(tv); } quat.nor(); setToScaling(tmpVec); rotate(quat); setTranslation(tmpForward); return this; } public Mat4f set(Mat3f mat) { val[0]=mat.val[0]; val[1]=mat.val[1]; val[2]=mat.val[2]; val[3]=0; val[4]=mat.val[3]; val[5]=mat.val[4]; val[6]=mat.val[5]; val[7]=0; val[8]=0; val[9]=0; val[10]=1; val[11]=0; val[12]=mat.val[6]; val[13]=mat.val[7]; val[14]=0; val[15]=mat.val[8]; return this; } public Mat4f set(ServerAffine2 affine) { val[M00]=affine.m00; val[M10]=affine.m10; val[M20]=0; val[M30]=0; val[M01]=affine.m01; val[M11]=affine.m11; val[M21]=0; val[M31]=0; val[M02]=0; val[M12]=0; val[M22]=1; val[M32]=0; val[M03]=affine.m02; val[M13]=affine.m12; val[M23]=0; val[M33]=1; return this; } public Mat4f setAsAffine(ServerAffine2 affine) { val[M00]=affine.m00; val[M10]=affine.m10; val[M01]=affine.m01; val[M11]=affine.m11; val[M03]=affine.m02; val[M13]=affine.m12; return this; } public Mat4f setAsAffine(Mat4f mat) { val[M00]=mat.val[M00]; val[M10]=mat.val[M10]; val[M01]=mat.val[M01]; val[M11]=mat.val[M11]; val[M03]=mat.val[M03]; val[M13]=mat.val[M13]; return this; } public Mat4f scl(Vec3f scale) { val[M00]*=scale.x; val[M11]*=scale.y; val[M22]*=scale.z; return this; } public Mat4f scl(float x,float y,float z) { val[M00]*=x; val[M11]*=y; val[M22]*=z; return this; } public Mat4f scl(float scale) { val[M00]*=scale; val[M11]*=scale; val[M22]*=scale; return this; } public Vec3f getTranslation(Vec3f position) { position.x=val[M03]; position.y=val[M13]; position.z=val[M23]; return position; } public ServerQuaternion getRotation(ServerQuaternion rotation,boolean normalizeAxes) { return rotation.setFromMatrix(normalizeAxes,this); } public ServerQuaternion getRotation(ServerQuaternion rotation) { return rotation.setFromMatrix(this); } public float getScaleXSquared() { return val[M00]*val[M00]+val[M01]*val[M01]+val[M02]*val[M02]; } public float getScaleYSquared() { return val[M10]*val[M10]+val[M11]*val[M11]+val[M12]*val[M12]; } public float getScaleZSquared() { return val[M20]*val[M20]+val[M21]*val[M21]+val[M22]*val[M22]; } public float getScaleX() {
package pama1234.math.mat; /** * 直接从libgdx复制过来的 */ public class Mat4f{ private static final long serialVersionUID=-2717655254359579617L; public static final int M00=0; public static final int M01=4; public static final int M02=8; public static final int M03=12; public static final int M10=1; public static final int M11=5; public static final int M12=9; public static final int M13=13; public static final int M20=2; public static final int M21=6; public static final int M22=10; public static final int M23=14; public static final int M30=3; public static final int M31=7; public static final int M32=11; public static final int M33=15; static final ServerQuaternion quat=new ServerQuaternion(); static final ServerQuaternion quat2=new ServerQuaternion(); static final Vec3f l_vez=new Vec3f(); static final Vec3f l_vex=new Vec3f(); static final Vec3f l_vey=new Vec3f(); static final Vec3f tmpVec=new Vec3f(); static final Mat4f tmpMat=new Mat4f(); static final Vec3f right=new Vec3f(); static final Vec3f tmpForward=new Vec3f(); static final Vec3f tmpUp=new Vec3f(); public final float val[]=new float[16]; public Mat4f() { val[M00]=1f; val[M11]=1f; val[M22]=1f; val[M33]=1f; } public Mat4f(Mat4f matrix) { set(matrix); } public Mat4f(float[] values) { set(values); } public Mat4f(ServerQuaternion quaternion) { set(quaternion); } public Mat4f(Vec3f position,ServerQuaternion rotation,Vec3f scale) { set(position,rotation,scale); } public Mat4f set(Mat4f matrix) { return set(matrix.val); } public Mat4f set(float[] values) { System.arraycopy(values,0,val,0,val.length); return this; } public Mat4f set(ServerQuaternion quaternion) { return set(quaternion.x,quaternion.y,quaternion.z,quaternion.w); } public Mat4f set(float quaternionX,float quaternionY,float quaternionZ,float quaternionW) { return set(0f,0f,0f,quaternionX,quaternionY,quaternionZ,quaternionW); } public Mat4f set(Vec3f position,ServerQuaternion orientation) { return set(position.x,position.y,position.z,orientation.x,orientation.y,orientation.z,orientation.w); } public Mat4f set(float translationX,float translationY,float translationZ,float quaternionX,float quaternionY, float quaternionZ,float quaternionW) { final float xs=quaternionX*2f,ys=quaternionY*2f,zs=quaternionZ*2f; final float wx=quaternionW*xs,wy=quaternionW*ys,wz=quaternionW*zs; final float xx=quaternionX*xs,xy=quaternionX*ys,xz=quaternionX*zs; final float yy=quaternionY*ys,yz=quaternionY*zs,zz=quaternionZ*zs; val[M00]=1f-(yy+zz); val[M01]=xy-wz; val[M02]=xz+wy; val[M03]=translationX; val[M10]=xy+wz; val[M11]=1f-(xx+zz); val[M12]=yz-wx; val[M13]=translationY; val[M20]=xz-wy; val[M21]=yz+wx; val[M22]=1f-(xx+yy); val[M23]=translationZ; val[M30]=0f; val[M31]=0f; val[M32]=0f; val[M33]=1f; return this; } public Mat4f set(Vec3f position,ServerQuaternion orientation,Vec3f scale) { return set(position.x,position.y,position.z,orientation.x,orientation.y,orientation.z,orientation.w,scale.x,scale.y, scale.z); } public Mat4f set(float translationX,float translationY,float translationZ,float quaternionX,float quaternionY, float quaternionZ,float quaternionW,float scaleX,float scaleY,float scaleZ) { final float xs=quaternionX*2f,ys=quaternionY*2f,zs=quaternionZ*2f; final float wx=quaternionW*xs,wy=quaternionW*ys,wz=quaternionW*zs; final float xx=quaternionX*xs,xy=quaternionX*ys,xz=quaternionX*zs; final float yy=quaternionY*ys,yz=quaternionY*zs,zz=quaternionZ*zs; val[M00]=scaleX*(1.0f-(yy+zz)); val[M01]=scaleY*(xy-wz); val[M02]=scaleZ*(xz+wy); val[M03]=translationX; val[M10]=scaleX*(xy+wz); val[M11]=scaleY*(1.0f-(xx+zz)); val[M12]=scaleZ*(yz-wx); val[M13]=translationY; val[M20]=scaleX*(xz-wy); val[M21]=scaleY*(yz+wx); val[M22]=scaleZ*(1.0f-(xx+yy)); val[M23]=translationZ; val[M30]=0f; val[M31]=0f; val[M32]=0f; val[M33]=1f; return this; } public Mat4f set(Vec3f xAxis,Vec3f yAxis,Vec3f zAxis,Vec3f pos) { val[M00]=xAxis.x; val[M01]=xAxis.y; val[M02]=xAxis.z; val[M10]=yAxis.x; val[M11]=yAxis.y; val[M12]=yAxis.z; val[M20]=zAxis.x; val[M21]=zAxis.y; val[M22]=zAxis.z; val[M03]=pos.x; val[M13]=pos.y; val[M23]=pos.z; val[M30]=0f; val[M31]=0f; val[M32]=0f; val[M33]=1f; return this; } public Mat4f cpy() { return new Mat4f(this); } public Mat4f trn(Vec3f vector) { val[M03]+=vector.x; val[M13]+=vector.y; val[M23]+=vector.z; return this; } public Mat4f trn(float x,float y,float z) { val[M03]+=x; val[M13]+=y; val[M23]+=z; return this; } public float[] getValues() { return val; } public Mat4f mul(Mat4f matrix) { mul(val,matrix.val); return this; } public Mat4f mulLeft(Mat4f matrix) { tmpMat.set(matrix); mul(tmpMat.val,val); return set(tmpMat); } public Mat4f tra() { float m01=val[M01]; float m02=val[M02]; float m03=val[M03]; float m12=val[M12]; float m13=val[M13]; float m23=val[M23]; val[M01]=val[M10]; val[M02]=val[M20]; val[M03]=val[M30]; val[M10]=m01; val[M12]=val[M21]; val[M13]=val[M31]; val[M20]=m02; val[M21]=m12; val[M23]=val[M32]; val[M30]=m03; val[M31]=m13; val[M32]=m23; return this; } public Mat4f idt() { val[M00]=1f; val[M01]=0f; val[M02]=0f; val[M03]=0f; val[M10]=0f; val[M11]=1f; val[M12]=0f; val[M13]=0f; val[M20]=0f; val[M21]=0f; val[M22]=1f; val[M23]=0f; val[M30]=0f; val[M31]=0f; val[M32]=0f; val[M33]=1f; return this; } public Mat4f inv() { float l_det=val[M30]*val[M21]*val[M12]*val[M03]-val[M20]*val[M31]*val[M12]*val[M03]-val[M30]*val[M11]*val[M22]*val[M03]+val[M10]*val[M31]*val[M22]*val[M03]+val[M20]*val[M11]*val[M32]*val[M03]-val[M10]*val[M21]*val[M32]*val[M03]-val[M30]*val[M21]*val[M02]*val[M13]+val[M20]*val[M31]*val[M02]*val[M13]+val[M30]*val[M01]*val[M22]*val[M13]-val[M00]*val[M31]*val[M22]*val[M13]-val[M20]*val[M01]*val[M32]*val[M13]+val[M00]*val[M21]*val[M32]*val[M13]+val[M30]*val[M11]*val[M02]*val[M23]-val[M10]*val[M31]*val[M02]*val[M23]-val[M30]*val[M01]*val[M12]*val[M23]+val[M00]*val[M31]*val[M12]*val[M23]+val[M10]*val[M01]*val[M32]*val[M23]-val[M00]*val[M11]*val[M32]*val[M23]-val[M20]*val[M11]*val[M02]*val[M33]+val[M10]*val[M21]*val[M02]*val[M33]+val[M20]*val[M01]*val[M12]*val[M33]-val[M00]*val[M21]*val[M12]*val[M33]-val[M10]*val[M01]*val[M22]*val[M33]+val[M00]*val[M11]*val[M22]*val[M33]; if(l_det==0f) throw new RuntimeException("non-invertible matrix"); float m00=val[M12]*val[M23]*val[M31]-val[M13]*val[M22]*val[M31]+val[M13]*val[M21]*val[M32]-val[M11]*val[M23]*val[M32]-val[M12]*val[M21]*val[M33]+val[M11]*val[M22]*val[M33]; float m01=val[M03]*val[M22]*val[M31]-val[M02]*val[M23]*val[M31]-val[M03]*val[M21]*val[M32]+val[M01]*val[M23]*val[M32]+val[M02]*val[M21]*val[M33]-val[M01]*val[M22]*val[M33]; float m02=val[M02]*val[M13]*val[M31]-val[M03]*val[M12]*val[M31]+val[M03]*val[M11]*val[M32]-val[M01]*val[M13]*val[M32]-val[M02]*val[M11]*val[M33]+val[M01]*val[M12]*val[M33]; float m03=val[M03]*val[M12]*val[M21]-val[M02]*val[M13]*val[M21]-val[M03]*val[M11]*val[M22]+val[M01]*val[M13]*val[M22]+val[M02]*val[M11]*val[M23]-val[M01]*val[M12]*val[M23]; float m10=val[M13]*val[M22]*val[M30]-val[M12]*val[M23]*val[M30]-val[M13]*val[M20]*val[M32]+val[M10]*val[M23]*val[M32]+val[M12]*val[M20]*val[M33]-val[M10]*val[M22]*val[M33]; float m11=val[M02]*val[M23]*val[M30]-val[M03]*val[M22]*val[M30]+val[M03]*val[M20]*val[M32]-val[M00]*val[M23]*val[M32]-val[M02]*val[M20]*val[M33]+val[M00]*val[M22]*val[M33]; float m12=val[M03]*val[M12]*val[M30]-val[M02]*val[M13]*val[M30]-val[M03]*val[M10]*val[M32]+val[M00]*val[M13]*val[M32]+val[M02]*val[M10]*val[M33]-val[M00]*val[M12]*val[M33]; float m13=val[M02]*val[M13]*val[M20]-val[M03]*val[M12]*val[M20]+val[M03]*val[M10]*val[M22]-val[M00]*val[M13]*val[M22]-val[M02]*val[M10]*val[M23]+val[M00]*val[M12]*val[M23]; float m20=val[M11]*val[M23]*val[M30]-val[M13]*val[M21]*val[M30]+val[M13]*val[M20]*val[M31]-val[M10]*val[M23]*val[M31]-val[M11]*val[M20]*val[M33]+val[M10]*val[M21]*val[M33]; float m21=val[M03]*val[M21]*val[M30]-val[M01]*val[M23]*val[M30]-val[M03]*val[M20]*val[M31]+val[M00]*val[M23]*val[M31]+val[M01]*val[M20]*val[M33]-val[M00]*val[M21]*val[M33]; float m22=val[M01]*val[M13]*val[M30]-val[M03]*val[M11]*val[M30]+val[M03]*val[M10]*val[M31]-val[M00]*val[M13]*val[M31]-val[M01]*val[M10]*val[M33]+val[M00]*val[M11]*val[M33]; float m23=val[M03]*val[M11]*val[M20]-val[M01]*val[M13]*val[M20]-val[M03]*val[M10]*val[M21]+val[M00]*val[M13]*val[M21]+val[M01]*val[M10]*val[M23]-val[M00]*val[M11]*val[M23]; float m30=val[M12]*val[M21]*val[M30]-val[M11]*val[M22]*val[M30]-val[M12]*val[M20]*val[M31]+val[M10]*val[M22]*val[M31]+val[M11]*val[M20]*val[M32]-val[M10]*val[M21]*val[M32]; float m31=val[M01]*val[M22]*val[M30]-val[M02]*val[M21]*val[M30]+val[M02]*val[M20]*val[M31]-val[M00]*val[M22]*val[M31]-val[M01]*val[M20]*val[M32]+val[M00]*val[M21]*val[M32]; float m32=val[M02]*val[M11]*val[M30]-val[M01]*val[M12]*val[M30]-val[M02]*val[M10]*val[M31]+val[M00]*val[M12]*val[M31]+val[M01]*val[M10]*val[M32]-val[M00]*val[M11]*val[M32]; float m33=val[M01]*val[M12]*val[M20]-val[M02]*val[M11]*val[M20]+val[M02]*val[M10]*val[M21]-val[M00]*val[M12]*val[M21]-val[M01]*val[M10]*val[M22]+val[M00]*val[M11]*val[M22]; float inv_det=1.0f/l_det; val[M00]=m00*inv_det; val[M10]=m10*inv_det; val[M20]=m20*inv_det; val[M30]=m30*inv_det; val[M01]=m01*inv_det; val[M11]=m11*inv_det; val[M21]=m21*inv_det; val[M31]=m31*inv_det; val[M02]=m02*inv_det; val[M12]=m12*inv_det; val[M22]=m22*inv_det; val[M32]=m32*inv_det; val[M03]=m03*inv_det; val[M13]=m13*inv_det; val[M23]=m23*inv_det; val[M33]=m33*inv_det; return this; } public float det() { return val[M30]*val[M21]*val[M12]*val[M03] -val[M20]*val[M31]*val[M12]*val[M03] -val[M30]*val[M11]*val[M22]*val[M03] +val[M10]*val[M31]*val[M22]*val[M03] +val[M20]*val[M11]*val[M32]*val[M03] -val[M10]*val[M21]*val[M32]*val[M03] -val[M30]*val[M21]*val[M02]*val[M13] +val[M20]*val[M31]*val[M02]*val[M13] +val[M30]*val[M01]*val[M22]*val[M13] -val[M00]*val[M31]*val[M22]*val[M13] -val[M20]*val[M01]*val[M32]*val[M13] +val[M00]*val[M21]*val[M32]*val[M13] +val[M30]*val[M11]*val[M02]*val[M23] -val[M10]*val[M31]*val[M02]*val[M23] -val[M30]*val[M01]*val[M12]*val[M23] +val[M00]*val[M31]*val[M12]*val[M23] +val[M10]*val[M01]*val[M32]*val[M23] -val[M00]*val[M11]*val[M32]*val[M23] -val[M20]*val[M11]*val[M02]*val[M33] +val[M10]*val[M21]*val[M02]*val[M33] +val[M20]*val[M01]*val[M12]*val[M33] -val[M00]*val[M21]*val[M12]*val[M33] -val[M10]*val[M01]*val[M22]*val[M33] +val[M00]*val[M11]*val[M22]*val[M33]; } public Mat4f setToProjection(float near,float far,float fovy,float aspectRatio) { idt(); float l_fd=(float)(1.0/Math.tan((fovy*(Math.PI/180))/2.0)); float l_a1=(far+near)/(near-far); float l_a2=(2*far*near)/(near-far); val[M00]=l_fd/aspectRatio; val[M10]=0; val[M20]=0; val[M30]=0; val[M01]=0; val[M11]=l_fd; val[M21]=0; val[M31]=0; val[M02]=0; val[M12]=0; val[M22]=l_a1; val[M32]=-1; val[M03]=0; val[M13]=0; val[M23]=l_a2; val[M33]=0; return this; } public Mat4f setToProjection(float left,float right,float bottom,float top,float near,float far) { float x=2.0f*near/(right-left); float y=2.0f*near/(top-bottom); float a=(right+left)/(right-left); float b=(top+bottom)/(top-bottom); float l_a1=(far+near)/(near-far); float l_a2=(2*far*near)/(near-far); val[M00]=x; val[M10]=0; val[M20]=0; val[M30]=0; val[M01]=0; val[M11]=y; val[M21]=0; val[M31]=0; val[M02]=a; val[M12]=b; val[M22]=l_a1; val[M32]=-1; val[M03]=0; val[M13]=0; val[M23]=l_a2; val[M33]=0; return this; } public Mat4f setToOrtho2D(float x,float y,float width,float height) { setToOrtho(x,x+width,y,y+height,0,1); return this; } public Mat4f setToOrtho2D(float x,float y,float width,float height,float near,float far) { setToOrtho(x,x+width,y,y+height,near,far); return this; } public Mat4f setToOrtho(float left,float right,float bottom,float top,float near,float far) { float x_orth=2/(right-left); float y_orth=2/(top-bottom); float z_orth=-2/(far-near); float tx=-(right+left)/(right-left); float ty=-(top+bottom)/(top-bottom); float tz=-(far+near)/(far-near); val[M00]=x_orth; val[M10]=0; val[M20]=0; val[M30]=0; val[M01]=0; val[M11]=y_orth; val[M21]=0; val[M31]=0; val[M02]=0; val[M12]=0; val[M22]=z_orth; val[M32]=0; val[M03]=tx; val[M13]=ty; val[M23]=tz; val[M33]=1; return this; } public Mat4f setTranslation(Vec3f vector) { val[M03]=vector.x; val[M13]=vector.y; val[M23]=vector.z; return this; } public Mat4f setTranslation(float x,float y,float z) { val[M03]=x; val[M13]=y; val[M23]=z; return this; } public Mat4f setToTranslation(Vec3f vector) { idt(); val[M03]=vector.x; val[M13]=vector.y; val[M23]=vector.z; return this; } public Mat4f setToTranslation(float x,float y,float z) { idt(); val[M03]=x; val[M13]=y; val[M23]=z; return this; } public Mat4f setToTranslationAndScaling(Vec3f translation,Vec3f scaling) { idt(); val[M03]=translation.x; val[M13]=translation.y; val[M23]=translation.z; val[M00]=scaling.x; val[M11]=scaling.y; val[M22]=scaling.z; return this; } public Mat4f setToTranslationAndScaling(float translationX,float translationY,float translationZ,float scalingX, float scalingY,float scalingZ) { idt(); val[M03]=translationX; val[M13]=translationY; val[M23]=translationZ; val[M00]=scalingX; val[M11]=scalingY; val[M22]=scalingZ; return this; } public Mat4f setToRotation(Vec3f axis,float degrees) { if(degrees==0) { idt(); return this; } return set(quat.set(axis,degrees)); } public Mat4f setToRotationRad(Vec3f axis,float radians) { if(radians==0) { idt(); return this; } return set(quat.setFromAxisRad(axis,radians)); } public Mat4f setToRotation(float axisX,float axisY,float axisZ,float degrees) { if(degrees==0) { idt(); return this; } return set(quat.setFromAxis(axisX,axisY,axisZ,degrees)); } public Mat4f setToRotationRad(float axisX,float axisY,float axisZ,float radians) { if(radians==0) { idt(); return this; } return set(quat.setFromAxisRad(axisX,axisY,axisZ,radians)); } public Mat4f setToRotation(final Vec3f v1,final Vec3f v2) { return set(quat.setFromCross(v1,v2)); } public Mat4f setToRotation(final float x1,final float y1,final float z1,final float x2,final float y2,final float z2) { return set(quat.setFromCross(x1,y1,z1,x2,y2,z2)); } public Mat4f setFromEulerAngles(float yaw,float pitch,float roll) { quat.setEulerAngles(yaw,pitch,roll); return set(quat); } public Mat4f setFromEulerAnglesRad(float yaw,float pitch,float roll) { quat.setEulerAnglesRad(yaw,pitch,roll); return set(quat); } public Mat4f setToScaling(Vec3f vector) { idt(); val[M00]=vector.x; val[M11]=vector.y; val[M22]=vector.z; return this; } public Mat4f setToScaling(float x,float y,float z) { idt(); val[M00]=x; val[M11]=y; val[M22]=z; return this; } public Mat4f setToLookAt(Vec3f direction,Vec3f up) { l_vez.set(direction); l_vez.nor(); l_vex.set(direction); l_vez.crs(up); l_vez.nor(); l_vey.set(l_vex); l_vez.crs(l_vez); l_vez.nor(); idt(); val[M00]=l_vex.x; val[M01]=l_vex.y; val[M02]=l_vex.z; val[M10]=l_vey.x; val[M11]=l_vey.y; val[M12]=l_vey.z; val[M20]=-l_vez.x; val[M21]=-l_vez.y; val[M22]=-l_vez.z; return this; } public Mat4f setToLookAt(Vec3f position,Vec3f target,Vec3f up) { tmpVec.set(target); tmpVec.sub(position); setToLookAt(tmpVec,up); mul(tmpMat.setToTranslation(-position.x,-position.y,-position.z)); return this; } public Mat4f setToWorld(Vec3f position,Vec3f forward,Vec3f up) { tmpForward.set(forward); tmpForward.nor(); right.set(tmpForward); right.crs(up); right.nor(); tmpUp.set(right); tmpUp.crs(tmpForward); tmpUp.nor(); tmpForward.scl(-1); set(right,tmpUp,tmpForward,position); return this; } public Mat4f lerp(Mat4f matrix,float alpha) { for(int i=0;i<16;i++) val[i]=val[i]*(1-alpha)+matrix.val[i]*alpha; return this; } public Mat4f avg(Mat4f other,float w) { getScale(tmpVec); other.getScale(tmpForward); getRotation(quat); other.getRotation(quat2); getTranslation(tmpUp); other.getTranslation(right); tmpVec.scl(w); tmpForward.scl(1-w); tmpVec.add(tmpForward); setToScaling(tmpVec); rotate(quat.slerp(quat2,1-w)); tmpUp.scl(w); right.scl(1-w); tmpUp.add(right); setTranslation(tmpUp); return this; } public Mat4f avg(Mat4f[] t) { final float w=1.0f/t.length; Vec3f tv=t[0].getScale(tmpUp); tv.scl(w); tmpVec.set(tv); quat.set(t[0].getRotation(quat2).exp(w)); tv=t[0].getTranslation(tmpUp); tv.scl(w); tmpForward.set(tv); for(int i=1;i<t.length;i++) { tv=t[i].getScale(tmpUp); tv.scl(w); tmpVec.add(tv); quat.mul(t[i].getRotation(quat2).exp(w)); tv=t[i].getTranslation(tmpUp); t[i].scl(w); tmpForward.add(tv); } quat.nor(); setToScaling(tmpVec); rotate(quat); setTranslation(tmpForward); return this; } public Mat4f avg(Mat4f[] t,float[] w) { Vec3f tv=t[0].getScale(tmpUp); tv.scl(w[0]); tmpVec.set(tv); quat.set(t[0].getRotation(quat2).exp(w[0])); tv=t[0].getTranslation(tmpUp); tv.scl(w[0]); tmpForward.set(tv); for(int i=1;i<t.length;i++) { tv=t[i].getScale(tmpUp); tv.scl(w[i]); tmpVec.add(tv); quat.mul(t[i].getRotation(quat2).exp(w[i])); tv=t[i].getTranslation(tmpUp); tv.scl(w[i]); tmpForward.add(tv); } quat.nor(); setToScaling(tmpVec); rotate(quat); setTranslation(tmpForward); return this; } public Mat4f set(Mat3f mat) { val[0]=mat.val[0]; val[1]=mat.val[1]; val[2]=mat.val[2]; val[3]=0; val[4]=mat.val[3]; val[5]=mat.val[4]; val[6]=mat.val[5]; val[7]=0; val[8]=0; val[9]=0; val[10]=1; val[11]=0; val[12]=mat.val[6]; val[13]=mat.val[7]; val[14]=0; val[15]=mat.val[8]; return this; } public Mat4f set(ServerAffine2 affine) { val[M00]=affine.m00; val[M10]=affine.m10; val[M20]=0; val[M30]=0; val[M01]=affine.m01; val[M11]=affine.m11; val[M21]=0; val[M31]=0; val[M02]=0; val[M12]=0; val[M22]=1; val[M32]=0; val[M03]=affine.m02; val[M13]=affine.m12; val[M23]=0; val[M33]=1; return this; } public Mat4f setAsAffine(ServerAffine2 affine) { val[M00]=affine.m00; val[M10]=affine.m10; val[M01]=affine.m01; val[M11]=affine.m11; val[M03]=affine.m02; val[M13]=affine.m12; return this; } public Mat4f setAsAffine(Mat4f mat) { val[M00]=mat.val[M00]; val[M10]=mat.val[M10]; val[M01]=mat.val[M01]; val[M11]=mat.val[M11]; val[M03]=mat.val[M03]; val[M13]=mat.val[M13]; return this; } public Mat4f scl(Vec3f scale) { val[M00]*=scale.x; val[M11]*=scale.y; val[M22]*=scale.z; return this; } public Mat4f scl(float x,float y,float z) { val[M00]*=x; val[M11]*=y; val[M22]*=z; return this; } public Mat4f scl(float scale) { val[M00]*=scale; val[M11]*=scale; val[M22]*=scale; return this; } public Vec3f getTranslation(Vec3f position) { position.x=val[M03]; position.y=val[M13]; position.z=val[M23]; return position; } public ServerQuaternion getRotation(ServerQuaternion rotation,boolean normalizeAxes) { return rotation.setFromMatrix(normalizeAxes,this); } public ServerQuaternion getRotation(ServerQuaternion rotation) { return rotation.setFromMatrix(this); } public float getScaleXSquared() { return val[M00]*val[M00]+val[M01]*val[M01]+val[M02]*val[M02]; } public float getScaleYSquared() { return val[M10]*val[M10]+val[M11]*val[M11]+val[M12]*val[M12]; } public float getScaleZSquared() { return val[M20]*val[M20]+val[M21]*val[M21]+val[M22]*val[M22]; } public float getScaleX() {
return (UtilMath.nearZero(val[M01])&&UtilMath.nearZero(val[M02]))?Math.abs(val[M00])
0
2023-10-27 05:47:39+00:00
24k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/createPacient/NuevoPaciente.java
[ { "identifier": "ApplicationContext", "path": "src/com/context/ApplicationContext.java", "snippet": "public class ApplicationContext {\r\n public static SesionUsuario sesionUsuario;\r\n public static LoadingApp loading = new LoadingApp();\r\n public static LoadingApplication loadingApplication ...
import com.context.ApplicationContext; import com.context.ChoosedPalette; import com.helper.PacienteHelper; import com.utils.CustomScrollBar; import com.utils.Styles; import com.utils.Tools; import java.util.ArrayList; import javax.swing.JPanel; import javax.swing.border.MatteBorder;
15,962
javax.swing.GroupLayout jPanel27Layout = new javax.swing.GroupLayout(jPanel27); jPanel27.setLayout(jPanel27Layout); jPanel27Layout.setHorizontalGroup( jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); jPanel27Layout.setVerticalGroup( jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 290, Short.MAX_VALUE) ); container1.add(jPanel27, java.awt.BorderLayout.LINE_START); jPanel28.setBackground(new java.awt.Color(255, 255, 255)); jPanel28.setMinimumSize(new java.awt.Dimension(14, 14)); jPanel28.setOpaque(false); javax.swing.GroupLayout jPanel28Layout = new javax.swing.GroupLayout(jPanel28); jPanel28.setLayout(jPanel28Layout); jPanel28Layout.setHorizontalGroup( jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1016, Short.MAX_VALUE) ); jPanel28Layout.setVerticalGroup( jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); container1.add(jPanel28, java.awt.BorderLayout.PAGE_END); jPanel29.setBackground(new java.awt.Color(255, 255, 255)); jPanel29.setMinimumSize(new java.awt.Dimension(14, 14)); jPanel29.setOpaque(false); javax.swing.GroupLayout jPanel29Layout = new javax.swing.GroupLayout(jPanel29); jPanel29.setLayout(jPanel29Layout); jPanel29Layout.setHorizontalGroup( jPanel29Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1016, Short.MAX_VALUE) ); jPanel29Layout.setVerticalGroup( jPanel29Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); container1.add(jPanel29, java.awt.BorderLayout.PAGE_START); scrollPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255), 0)); scrollPanel.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); dataContent.setBackground(new java.awt.Color(255, 255, 255)); dataContent.setLayout(new java.awt.GridLayout(1, 0)); scrollPanel.setViewportView(dataContent); container1.add(scrollPanel, java.awt.BorderLayout.CENTER); jPanel8.add(container1, java.awt.BorderLayout.CENTER); jPanel5.add(jPanel8, java.awt.BorderLayout.CENTER); add(jPanel5, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void datosContainerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_datosContainerMouseClicked setSelectionNavigation(containerButtons, text2, datosContainer); Tools.showPanel(dataContent, ApplicationContext.newPacienteInformation, 10, 10); }//GEN-LAST:event_datosContainerMouseClicked private void odontologiaContainerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_odontologiaContainerMouseClicked setSelectionNavigation(containerButtons, text3, odontologiaContainer); if (NewContext.isTratamientoOdontologico) { setOdontologia(ApplicationContext.nuevoPacienteOdontologia); } else { setOdontologia(ApplicationContext.noPerteneceOdontologia); } Tools.showPanel(dataContent, odontologia, 10, 10); }//GEN-LAST:event_odontologiaContainerMouseClicked private void ortodonciaContainerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ortodonciaContainerMouseClicked setSelectionNavigation(containerButtons, text4, ortodonciaContainer); if (NewContext.isTratamientoOrtodontico) { setOrtodoncia(ApplicationContext.nuevoPacienteOrtodoncia); } else { setOrtodoncia(ApplicationContext.noPerteneceOrtodoncia); } Tools.showPanel(dataContent, ortodoncia, 10, 10); }//GEN-LAST:event_ortodonciaContainerMouseClicked private void saveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveButtonMouseClicked NewContext.isTratamientoOdontologico = false; NewContext.isTratamientoOrtodontico = false; NewContext.emptyCounter = 0; NewContext.countedErrors = 0; NewContext.validarTodosLosCampos(ApplicationContext.newPacienteInformation.camposTexto, ApplicationContext.newPacienteInformation.advertenciasTexto, ApplicationContext.newPacienteInformation.containersTexto); ApplicationContext.newPacienteInformation.validarCombo(); ApplicationContext.newPacienteInformation.validarEdad(); ApplicationContext.newPacienteInformation.verifyEmpty(); ApplicationContext.newPacienteInformation.validarFechaNacimiento(); if (NewContext.countedErrors == 0) { NewContext.paciente = ApplicationContext.newPacienteInformation.devolverDatos(); if (NewContext.paciente.isTratamientoOdontologico()) { NewContext.paciente.setFichaOdontologia(ApplicationContext.nuevoPacienteOdontologia.devolverFicha()); ApplicationContext.nuevoPacienteOdontologia.verifyEmpty(); } if (NewContext.paciente.isTratamientoOrtodontico()) { NewContext.paciente.setFichaOrtodoncia(ApplicationContext.nuevoPacienteOrtodoncia.devolverFicha()); ApplicationContext.nuevoPacienteOrtodoncia.verifyEmpty(); } if (NewContext.emptyCounter != 0) { EstasSeguro estasSeguro = new EstasSeguro(); estasSeguro.setVisible(true); } else {
package com.view.createPacient; /** * * @author Daniel Batres * @version 1.0.0 * @since 24/09/22 */ public class NuevoPaciente extends Styles { private JPanel odontologia = ApplicationContext.noPerteneceOdontologia; private JPanel ortodoncia = ApplicationContext.noPerteneceOrtodoncia; private ArrayList<JPanel> containerButtons = new ArrayList<>(); /** * Creates new form NuevoPaciente */ public NuevoPaciente() { initComponents(); styleMyComponentBaby(); Tools.showPanel(dataContent, ApplicationContext.newPacienteInformation, 10, 10); } @Override public void addTitlesAndSubtitles() { TITLES_AND_SUBTITLES.add(title1); } @Override public void addPlainText() { PLAIN_TEXT.add(text1); PLAIN_TEXT.add(text2); PLAIN_TEXT.add(text3); PLAIN_TEXT.add(text4); } @Override public void addContainers() { CONTAINERS.add(container1); CONTAINERS.add(container2); } @Override public void initStyles() { Tools.setScroll(scrollPanel); addContainerButtons(); } @Override public void colorBasics() { needBorder.setBorder(new MatteBorder(0, 0, 1, 0, ChoosedPalette.getGray())); text2.setForeground(ChoosedPalette.getMidColor()); datosContainer.setBorder(new MatteBorder(0, 0, 3, 0, ChoosedPalette.getMidColor())); paintOneContainer(saveButton, ChoosedPalette.getMidColor()); paintOneContainer(containerButton, ChoosedPalette.getDarkColor()); cancel.setForeground(ChoosedPalette.getDarkColor()); dataContent.setBackground(ChoosedPalette.getPrimaryBackground()); paintTitlesAndSubtitles(); paintPlainText(); } public void showFirstPanel() { Tools.showPanel(dataContent, ApplicationContext.newPacienteInformation, 10, 10); } public void addContainerButtons() { containerButtons.add(datosContainer); containerButtons.add(odontologiaContainer); containerButtons.add(ortodonciaContainer); } public JPanel getOdontologia() { return odontologia; } public void setOdontologia(JPanel odontologia) { this.odontologia = odontologia; } public JPanel getOrtodoncia() { return ortodoncia; } public void setOrtodoncia(JPanel ortodoncia) { this.ortodoncia = ortodoncia; } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); needBorder = new javax.swing.JPanel(); jPanel15 = new javax.swing.JPanel(); datosContainer = new javax.swing.JPanel(); text2 = new javax.swing.JLabel(); odontologiaContainer = new javax.swing.JPanel(); text3 = new javax.swing.JLabel(); ortodonciaContainer = new javax.swing.JPanel(); text4 = new javax.swing.JLabel(); jPanel16 = new javax.swing.JPanel(); jPanel13 = new javax.swing.JPanel(); text1 = new javax.swing.JLabel(); title1 = new javax.swing.JLabel(); containerButton = new com.k33ptoo.components.KGradientPanel(); cancel = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); jPanel9 = new javax.swing.JPanel(); container2 = new com.k33ptoo.components.KGradientPanel(); jPanel30 = new javax.swing.JPanel(); jPanel31 = new javax.swing.JPanel(); jPanel32 = new javax.swing.JPanel(); jPanel33 = new javax.swing.JPanel(); jPanel12 = new javax.swing.JPanel(); saveButton = new com.k33ptoo.components.KGradientPanel(); jLabel3 = new javax.swing.JLabel(); jPanel8 = new javax.swing.JPanel(); jPanel10 = new javax.swing.JPanel(); jPanel11 = new javax.swing.JPanel(); container1 = new com.k33ptoo.components.KGradientPanel(); jPanel26 = new javax.swing.JPanel(); jPanel27 = new javax.swing.JPanel(); jPanel28 = new javax.swing.JPanel(); jPanel29 = new javax.swing.JPanel(); scrollPanel = new javax.swing.JScrollPane(); dataContent = new javax.swing.JPanel(); setMinimumSize(new java.awt.Dimension(1060, 569)); setOpaque(false); setPreferredSize(new java.awt.Dimension(1060, 569)); setLayout(new java.awt.BorderLayout()); jPanel1.setMaximumSize(new java.awt.Dimension(22, 32767)); jPanel1.setMinimumSize(new java.awt.Dimension(22, 100)); jPanel1.setOpaque(false); jPanel1.setPreferredSize(new java.awt.Dimension(22, 569)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 22, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 529, Short.MAX_VALUE) ); add(jPanel1, java.awt.BorderLayout.LINE_END); jPanel3.setMaximumSize(new java.awt.Dimension(22, 32767)); jPanel3.setMinimumSize(new java.awt.Dimension(22, 100)); jPanel3.setOpaque(false); jPanel3.setPreferredSize(new java.awt.Dimension(22, 569)); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 22, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 529, Short.MAX_VALUE) ); add(jPanel3, java.awt.BorderLayout.LINE_START); jPanel2.setMaximumSize(new java.awt.Dimension(32767, 20)); jPanel2.setMinimumSize(new java.awt.Dimension(20, 20)); jPanel2.setOpaque(false); jPanel2.setPreferredSize(new java.awt.Dimension(1060, 20)); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1060, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 20, Short.MAX_VALUE) ); add(jPanel2, java.awt.BorderLayout.PAGE_END); jPanel4.setMaximumSize(new java.awt.Dimension(32767, 20)); jPanel4.setMinimumSize(new java.awt.Dimension(20, 20)); jPanel4.setOpaque(false); jPanel4.setPreferredSize(new java.awt.Dimension(1060, 20)); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1060, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 20, Short.MAX_VALUE) ); add(jPanel4, java.awt.BorderLayout.PAGE_START); jPanel5.setOpaque(false); jPanel5.setLayout(new java.awt.BorderLayout()); jPanel6.setMinimumSize(new java.awt.Dimension(100, 110)); jPanel6.setOpaque(false); jPanel6.setPreferredSize(new java.awt.Dimension(1016, 110)); jPanel6.setLayout(new java.awt.BorderLayout()); needBorder.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(204, 204, 204))); needBorder.setMinimumSize(new java.awt.Dimension(100, 40)); needBorder.setOpaque(false); needBorder.setPreferredSize(new java.awt.Dimension(1016, 40)); needBorder.setLayout(new java.awt.GridLayout(1, 0)); jPanel15.setOpaque(false); jPanel15.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); datosContainer.setBackground(new java.awt.Color(255, 255, 255)); datosContainer.setOpaque(false); datosContainer.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { datosContainerMouseClicked(evt); } }); text2.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N text2.setForeground(new java.awt.Color(69, 98, 255)); text2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); text2.setText("Datos generales"); text2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout datosContainerLayout = new javax.swing.GroupLayout(datosContainer); datosContainer.setLayout(datosContainerLayout); datosContainerLayout.setHorizontalGroup( datosContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(datosContainerLayout.createSequentialGroup() .addContainerGap() .addComponent(text2, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE) .addContainerGap()) ); datosContainerLayout.setVerticalGroup( datosContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, datosContainerLayout.createSequentialGroup() .addContainerGap() .addComponent(text2, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE) .addContainerGap()) ); jPanel15.add(datosContainer, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, -1, -1, 40)); odontologiaContainer.setBackground(new java.awt.Color(255, 255, 255)); odontologiaContainer.setOpaque(false); odontologiaContainer.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { odontologiaContainerMouseClicked(evt); } }); text3.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N text3.setForeground(new java.awt.Color(69, 98, 255)); text3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); text3.setText("Ficha de odontología"); text3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout odontologiaContainerLayout = new javax.swing.GroupLayout(odontologiaContainer); odontologiaContainer.setLayout(odontologiaContainerLayout); odontologiaContainerLayout.setHorizontalGroup( odontologiaContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(odontologiaContainerLayout.createSequentialGroup() .addContainerGap() .addComponent(text3, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE) .addContainerGap()) ); odontologiaContainerLayout.setVerticalGroup( odontologiaContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, odontologiaContainerLayout.createSequentialGroup() .addContainerGap() .addComponent(text3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel15.add(odontologiaContainer, new org.netbeans.lib.awtextra.AbsoluteConstraints(116, 0, -1, 39)); ortodonciaContainer.setBackground(new java.awt.Color(255, 255, 255)); ortodonciaContainer.setOpaque(false); ortodonciaContainer.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ortodonciaContainerMouseClicked(evt); } }); text4.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N text4.setForeground(new java.awt.Color(69, 98, 255)); text4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); text4.setText("Ficha de ortodoncia"); text4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout ortodonciaContainerLayout = new javax.swing.GroupLayout(ortodonciaContainer); ortodonciaContainer.setLayout(ortodonciaContainerLayout); ortodonciaContainerLayout.setHorizontalGroup( ortodonciaContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ortodonciaContainerLayout.createSequentialGroup() .addContainerGap() .addComponent(text4, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE) .addContainerGap()) ); ortodonciaContainerLayout.setVerticalGroup( ortodonciaContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ortodonciaContainerLayout.createSequentialGroup() .addContainerGap() .addComponent(text4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel15.add(ortodonciaContainer, new org.netbeans.lib.awtextra.AbsoluteConstraints(264, 0, -1, 39)); needBorder.add(jPanel15); jPanel16.setOpaque(false); javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16); jPanel16.setLayout(jPanel16Layout); jPanel16Layout.setHorizontalGroup( jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 508, Short.MAX_VALUE) ); jPanel16Layout.setVerticalGroup( jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 39, Short.MAX_VALUE) ); needBorder.add(jPanel16); jPanel6.add(needBorder, java.awt.BorderLayout.PAGE_END); jPanel13.setOpaque(false); text1.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N text1.setForeground(new java.awt.Color(153, 153, 153)); text1.setText("Agrega la información correspondiente del paciente"); title1.setBackground(new java.awt.Color(0, 0, 0)); title1.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 18)); // NOI18N title1.setForeground(new java.awt.Color(0, 0, 0)); title1.setText("Nuevo paciente"); containerButton.setkEndColor(new java.awt.Color(0, 0, 0)); containerButton.setkFillBackground(false); containerButton.setkStartColor(new java.awt.Color(0, 0, 0)); containerButton.setOpaque(false); cancel.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N cancel.setForeground(new java.awt.Color(0, 0, 0)); cancel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); cancel.setText("Cancelar"); cancel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); cancel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { cancelMouseClicked(evt); } }); javax.swing.GroupLayout containerButtonLayout = new javax.swing.GroupLayout(containerButton); containerButton.setLayout(containerButtonLayout); containerButtonLayout.setHorizontalGroup( containerButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cancel, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) ); containerButtonLayout.setVerticalGroup( containerButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13); jPanel13.setLayout(jPanel13Layout); jPanel13Layout.setHorizontalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(text1) .addComponent(title1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(containerButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel13Layout.setVerticalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(containerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(title1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(text1))) .addContainerGap(17, Short.MAX_VALUE)) ); jPanel6.add(jPanel13, java.awt.BorderLayout.CENTER); jPanel5.add(jPanel6, java.awt.BorderLayout.PAGE_START); jPanel7.setMaximumSize(new java.awt.Dimension(32767, 80)); jPanel7.setMinimumSize(new java.awt.Dimension(100, 80)); jPanel7.setOpaque(false); jPanel7.setPreferredSize(new java.awt.Dimension(1016, 80)); jPanel7.setLayout(new java.awt.BorderLayout()); jPanel9.setMaximumSize(new java.awt.Dimension(32767, 7)); jPanel9.setMinimumSize(new java.awt.Dimension(7, 7)); jPanel9.setOpaque(false); jPanel9.setPreferredSize(new java.awt.Dimension(1060, 7)); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1016, Short.MAX_VALUE) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 7, Short.MAX_VALUE) ); jPanel7.add(jPanel9, java.awt.BorderLayout.PAGE_START); container2.setkEndColor(new java.awt.Color(204, 204, 204)); container2.setkFillBackground(false); container2.setkStartColor(new java.awt.Color(204, 204, 204)); container2.setOpaque(false); container2.setLayout(new java.awt.BorderLayout()); jPanel30.setBackground(new java.awt.Color(255, 255, 255)); jPanel30.setMinimumSize(new java.awt.Dimension(14, 100)); jPanel30.setOpaque(false); jPanel30.setPreferredSize(new java.awt.Dimension(14, 150)); javax.swing.GroupLayout jPanel30Layout = new javax.swing.GroupLayout(jPanel30); jPanel30.setLayout(jPanel30Layout); jPanel30Layout.setHorizontalGroup( jPanel30Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); jPanel30Layout.setVerticalGroup( jPanel30Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container2.add(jPanel30, java.awt.BorderLayout.LINE_END); jPanel31.setBackground(new java.awt.Color(255, 255, 255)); jPanel31.setMinimumSize(new java.awt.Dimension(14, 100)); jPanel31.setOpaque(false); jPanel31.setPreferredSize(new java.awt.Dimension(14, 150)); javax.swing.GroupLayout jPanel31Layout = new javax.swing.GroupLayout(jPanel31); jPanel31.setLayout(jPanel31Layout); jPanel31Layout.setHorizontalGroup( jPanel31Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); jPanel31Layout.setVerticalGroup( jPanel31Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); container2.add(jPanel31, java.awt.BorderLayout.LINE_START); jPanel32.setBackground(new java.awt.Color(255, 255, 255)); jPanel32.setMinimumSize(new java.awt.Dimension(14, 14)); jPanel32.setOpaque(false); javax.swing.GroupLayout jPanel32Layout = new javax.swing.GroupLayout(jPanel32); jPanel32.setLayout(jPanel32Layout); jPanel32Layout.setHorizontalGroup( jPanel32Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1016, Short.MAX_VALUE) ); jPanel32Layout.setVerticalGroup( jPanel32Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); container2.add(jPanel32, java.awt.BorderLayout.PAGE_END); jPanel33.setBackground(new java.awt.Color(255, 255, 255)); jPanel33.setMinimumSize(new java.awt.Dimension(14, 14)); jPanel33.setOpaque(false); javax.swing.GroupLayout jPanel33Layout = new javax.swing.GroupLayout(jPanel33); jPanel33.setLayout(jPanel33Layout); jPanel33Layout.setHorizontalGroup( jPanel33Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1016, Short.MAX_VALUE) ); jPanel33Layout.setVerticalGroup( jPanel33Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); container2.add(jPanel33, java.awt.BorderLayout.PAGE_START); jPanel12.setOpaque(false); saveButton.setkEndColor(new java.awt.Color(0, 0, 0)); saveButton.setkStartColor(new java.awt.Color(0, 0, 0)); saveButton.setOpaque(false); saveButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { saveButtonMouseClicked(evt); } }); jLabel3.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Guardar"); jLabel3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout saveButtonLayout = new javax.swing.GroupLayout(saveButton); saveButton.setLayout(saveButtonLayout); saveButtonLayout.setHorizontalGroup( saveButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(saveButtonLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE) .addContainerGap()) ); saveButtonLayout.setVerticalGroup( saveButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(saveButtonLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12); jPanel12.setLayout(jPanel12Layout); jPanel12Layout.setHorizontalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup() .addContainerGap(802, Short.MAX_VALUE) .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel12Layout.setVerticalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(saveButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); container2.add(jPanel12, java.awt.BorderLayout.CENTER); jPanel7.add(container2, java.awt.BorderLayout.CENTER); jPanel5.add(jPanel7, java.awt.BorderLayout.PAGE_END); jPanel8.setOpaque(false); jPanel8.setLayout(new java.awt.BorderLayout()); jPanel10.setMaximumSize(new java.awt.Dimension(32767, 7)); jPanel10.setMinimumSize(new java.awt.Dimension(7, 7)); jPanel10.setOpaque(false); jPanel10.setPreferredSize(new java.awt.Dimension(1060, 7)); javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10); jPanel10.setLayout(jPanel10Layout); jPanel10Layout.setHorizontalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1016, Short.MAX_VALUE) ); jPanel10Layout.setVerticalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 7, Short.MAX_VALUE) ); jPanel8.add(jPanel10, java.awt.BorderLayout.PAGE_END); jPanel11.setMaximumSize(new java.awt.Dimension(32767, 14)); jPanel11.setMinimumSize(new java.awt.Dimension(7, 14)); jPanel11.setOpaque(false); jPanel11.setPreferredSize(new java.awt.Dimension(1060, 14)); javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11); jPanel11.setLayout(jPanel11Layout); jPanel11Layout.setHorizontalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1016, Short.MAX_VALUE) ); jPanel11Layout.setVerticalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); jPanel8.add(jPanel11, java.awt.BorderLayout.PAGE_START); container1.setkEndColor(new java.awt.Color(204, 204, 204)); container1.setkFillBackground(false); container1.setkStartColor(new java.awt.Color(204, 204, 204)); container1.setOpaque(false); container1.setLayout(new java.awt.BorderLayout()); jPanel26.setBackground(new java.awt.Color(255, 255, 255)); jPanel26.setMinimumSize(new java.awt.Dimension(14, 100)); jPanel26.setOpaque(false); jPanel26.setPreferredSize(new java.awt.Dimension(14, 150)); javax.swing.GroupLayout jPanel26Layout = new javax.swing.GroupLayout(jPanel26); jPanel26.setLayout(jPanel26Layout); jPanel26Layout.setHorizontalGroup( jPanel26Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); jPanel26Layout.setVerticalGroup( jPanel26Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 290, Short.MAX_VALUE) ); container1.add(jPanel26, java.awt.BorderLayout.LINE_END); jPanel27.setBackground(new java.awt.Color(255, 255, 255)); jPanel27.setMinimumSize(new java.awt.Dimension(14, 100)); jPanel27.setOpaque(false); jPanel27.setPreferredSize(new java.awt.Dimension(14, 150)); javax.swing.GroupLayout jPanel27Layout = new javax.swing.GroupLayout(jPanel27); jPanel27.setLayout(jPanel27Layout); jPanel27Layout.setHorizontalGroup( jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); jPanel27Layout.setVerticalGroup( jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 290, Short.MAX_VALUE) ); container1.add(jPanel27, java.awt.BorderLayout.LINE_START); jPanel28.setBackground(new java.awt.Color(255, 255, 255)); jPanel28.setMinimumSize(new java.awt.Dimension(14, 14)); jPanel28.setOpaque(false); javax.swing.GroupLayout jPanel28Layout = new javax.swing.GroupLayout(jPanel28); jPanel28.setLayout(jPanel28Layout); jPanel28Layout.setHorizontalGroup( jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1016, Short.MAX_VALUE) ); jPanel28Layout.setVerticalGroup( jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); container1.add(jPanel28, java.awt.BorderLayout.PAGE_END); jPanel29.setBackground(new java.awt.Color(255, 255, 255)); jPanel29.setMinimumSize(new java.awt.Dimension(14, 14)); jPanel29.setOpaque(false); javax.swing.GroupLayout jPanel29Layout = new javax.swing.GroupLayout(jPanel29); jPanel29.setLayout(jPanel29Layout); jPanel29Layout.setHorizontalGroup( jPanel29Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1016, Short.MAX_VALUE) ); jPanel29Layout.setVerticalGroup( jPanel29Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 14, Short.MAX_VALUE) ); container1.add(jPanel29, java.awt.BorderLayout.PAGE_START); scrollPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255), 0)); scrollPanel.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); dataContent.setBackground(new java.awt.Color(255, 255, 255)); dataContent.setLayout(new java.awt.GridLayout(1, 0)); scrollPanel.setViewportView(dataContent); container1.add(scrollPanel, java.awt.BorderLayout.CENTER); jPanel8.add(container1, java.awt.BorderLayout.CENTER); jPanel5.add(jPanel8, java.awt.BorderLayout.CENTER); add(jPanel5, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void datosContainerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_datosContainerMouseClicked setSelectionNavigation(containerButtons, text2, datosContainer); Tools.showPanel(dataContent, ApplicationContext.newPacienteInformation, 10, 10); }//GEN-LAST:event_datosContainerMouseClicked private void odontologiaContainerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_odontologiaContainerMouseClicked setSelectionNavigation(containerButtons, text3, odontologiaContainer); if (NewContext.isTratamientoOdontologico) { setOdontologia(ApplicationContext.nuevoPacienteOdontologia); } else { setOdontologia(ApplicationContext.noPerteneceOdontologia); } Tools.showPanel(dataContent, odontologia, 10, 10); }//GEN-LAST:event_odontologiaContainerMouseClicked private void ortodonciaContainerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ortodonciaContainerMouseClicked setSelectionNavigation(containerButtons, text4, ortodonciaContainer); if (NewContext.isTratamientoOrtodontico) { setOrtodoncia(ApplicationContext.nuevoPacienteOrtodoncia); } else { setOrtodoncia(ApplicationContext.noPerteneceOrtodoncia); } Tools.showPanel(dataContent, ortodoncia, 10, 10); }//GEN-LAST:event_ortodonciaContainerMouseClicked private void saveButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveButtonMouseClicked NewContext.isTratamientoOdontologico = false; NewContext.isTratamientoOrtodontico = false; NewContext.emptyCounter = 0; NewContext.countedErrors = 0; NewContext.validarTodosLosCampos(ApplicationContext.newPacienteInformation.camposTexto, ApplicationContext.newPacienteInformation.advertenciasTexto, ApplicationContext.newPacienteInformation.containersTexto); ApplicationContext.newPacienteInformation.validarCombo(); ApplicationContext.newPacienteInformation.validarEdad(); ApplicationContext.newPacienteInformation.verifyEmpty(); ApplicationContext.newPacienteInformation.validarFechaNacimiento(); if (NewContext.countedErrors == 0) { NewContext.paciente = ApplicationContext.newPacienteInformation.devolverDatos(); if (NewContext.paciente.isTratamientoOdontologico()) { NewContext.paciente.setFichaOdontologia(ApplicationContext.nuevoPacienteOdontologia.devolverFicha()); ApplicationContext.nuevoPacienteOdontologia.verifyEmpty(); } if (NewContext.paciente.isTratamientoOrtodontico()) { NewContext.paciente.setFichaOrtodoncia(ApplicationContext.nuevoPacienteOrtodoncia.devolverFicha()); ApplicationContext.nuevoPacienteOrtodoncia.verifyEmpty(); } if (NewContext.emptyCounter != 0) { EstasSeguro estasSeguro = new EstasSeguro(); estasSeguro.setVisible(true); } else {
PacienteHelper.createNewPacient(NewContext.paciente);
2
2023-10-26 19:35:40+00:00
24k
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/transformers/UnavailabilityDocCSVTransformer.java
[ { "identifier": "DataRetrievalRuntimeException", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/exceptions/DataRetrievalRuntimeException.java", "snippet": "public class DataRetrievalRuntimeException extends RuntimeException{\n private static final Logger LOGGER = LogManager.getLogge...
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedWriter; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.PropertyException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import tech.inceptive.ai4czc.entsoedataretrieval.csv.ColumnDefinition; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalRuntimeException; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.DocumentType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.AssetRegisteredResource; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.Reason; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.ResourceIDString; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.TimeSeries; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.UnavailabilityMarketDocument;
15,043
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers; /** * * @author Andres Bel Alonso */ public class UnavailabilityDocCSVTransformer extends CSVTransformer { private static final Logger LOGGER = LogManager.getLogger(UnavailabilityDocCSVTransformer.class); private static record ReadedInfo(boolean isInTS, String nominalPower) { } ; static final String TRANSMISSION_UNAVAILABILITY_BASE_NAME = "outage_grid_"; static final String UNAVAILABILITY_SCHEDULED_BN = "scheduled_outage_"; static final String GENERATION_UNAVAILABILITY_BASE_NAME = "outage_generation_"; static final String NOMINAL_OUTAGE_POWER = "outage_gen_nominal_"; private final UnavailabilityMarketDocument doc; private final DocumentType docType; public UnavailabilityDocCSVTransformer(UnavailabilityMarketDocument doc, String csvSeparator, String csvEscapeChar) { super(csvSeparator, csvEscapeChar); this.doc = doc; docType = DocumentType.fromId(doc.getType()); } @Override public boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os) { ReadedInfo readedInfo = checkIsInOutage(timeStamp); if (readedInfo.isInTS) { boolean isScheduled = checkIsScheduled(); String content; if (isScheduled) { content = getCsvSeparator() + "1" + getCsvSeparator() + "1"; } else { content = getCsvSeparator() + "1" + getCsvSeparator() + "0"; } switch (docType) { case GENERATION_UNAVAILABILITY: String gen = readedInfo.nominalPower; if (gen == null) { throw new DataRetrievalRuntimeException("Generation unavailability without a nominal power"); } content += getCsvSeparator() + gen; break; case TRANSMISSION_UNAVAILABILITY: // nothing to do break; default: throw new UnsupportedOperationException("Not suported outage column name for type " + docType.getId() + " ; " + docType.getDescription()); } try { os.write(content); } catch (IOException ex) { throw new DataRetrievalRuntimeException("Error writing timeStamp " + timeStamp.format(DateTimeFormatter.ISO_DATE), ex); } return true; } else { return false; } } private ReadedInfo checkIsInOutage(LocalDateTime timeStamp) { for (TimeSeries curTs : doc.getTimeSeries()) { LocalDateTime startDT = LocalDateTime.of(curTs.getStartDateAndOrTimeDate().getYear(), curTs.getStartDateAndOrTimeDate().getMonth(), curTs.getStartDateAndOrTimeDate().getDay(), curTs.getStartDateAndOrTimeTime().getHour(), curTs.getStartDateAndOrTimeTime().getMinute()); LocalDateTime endDT = LocalDateTime.of(curTs.getEndDateAndOrTimeDate().getYear(), curTs.getEndDateAndOrTimeDate().getMonth(), curTs.getEndDateAndOrTimeDate().getDay(), curTs.getEndDateAndOrTimeTime().getHour(), curTs.getEndDateAndOrTimeTime().getMinute()); if ((startDT.isBefore(timeStamp) && endDT.isAfter(timeStamp)) || startDT.equals(timeStamp)) { String nominalPower = null; if (curTs.getProductionRegisteredResourcePSRTypePowerSystemResourcesNominalP() != null) { nominalPower = Float.toString(curTs.getProductionRegisteredResourcePSRTypePowerSystemResourcesNominalP().getValue()); } return new ReadedInfo(true, nominalPower); } } return new ReadedInfo(false, ""); } private boolean checkIsScheduled() { List<Reason> reasonList = doc.getReason(); if (reasonList.size() != 1) { throw new UnsupportedOperationException("Expected one reason but there are " + reasonList.size() + " reasons"); } Reason reason = reasonList.get(0); switch (reason.getCode()) { case "B19": return true; case "B20": // shutdown case "B18": // failure on generation unit case "A95": // complentary info? return false; default: printCurDoc(); throw new UnsupportedOperationException("Unknow reason code " + reason.getCode()); } } private void printCurDoc() { try { // just print th pb doucment JAXBContext jaxbContext = JAXBContext.newInstance(UnavailabilityMarketDocument.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(doc, System.out); } catch (JAXBException ex) { LOGGER.catching(ex); } } @Override protected List<ColumnDefinition> computeColumnDef() { DocumentType docType = DocumentType.fromId(doc.getType()); switch (docType) { case TRANSMISSION_UNAVAILABILITY: return doc.getTimeSeries().stream(). flatMap(ts -> { if (ts.getAssetRegisteredResource().isEmpty()) {
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers; /** * * @author Andres Bel Alonso */ public class UnavailabilityDocCSVTransformer extends CSVTransformer { private static final Logger LOGGER = LogManager.getLogger(UnavailabilityDocCSVTransformer.class); private static record ReadedInfo(boolean isInTS, String nominalPower) { } ; static final String TRANSMISSION_UNAVAILABILITY_BASE_NAME = "outage_grid_"; static final String UNAVAILABILITY_SCHEDULED_BN = "scheduled_outage_"; static final String GENERATION_UNAVAILABILITY_BASE_NAME = "outage_generation_"; static final String NOMINAL_OUTAGE_POWER = "outage_gen_nominal_"; private final UnavailabilityMarketDocument doc; private final DocumentType docType; public UnavailabilityDocCSVTransformer(UnavailabilityMarketDocument doc, String csvSeparator, String csvEscapeChar) { super(csvSeparator, csvEscapeChar); this.doc = doc; docType = DocumentType.fromId(doc.getType()); } @Override public boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os) { ReadedInfo readedInfo = checkIsInOutage(timeStamp); if (readedInfo.isInTS) { boolean isScheduled = checkIsScheduled(); String content; if (isScheduled) { content = getCsvSeparator() + "1" + getCsvSeparator() + "1"; } else { content = getCsvSeparator() + "1" + getCsvSeparator() + "0"; } switch (docType) { case GENERATION_UNAVAILABILITY: String gen = readedInfo.nominalPower; if (gen == null) { throw new DataRetrievalRuntimeException("Generation unavailability without a nominal power"); } content += getCsvSeparator() + gen; break; case TRANSMISSION_UNAVAILABILITY: // nothing to do break; default: throw new UnsupportedOperationException("Not suported outage column name for type " + docType.getId() + " ; " + docType.getDescription()); } try { os.write(content); } catch (IOException ex) { throw new DataRetrievalRuntimeException("Error writing timeStamp " + timeStamp.format(DateTimeFormatter.ISO_DATE), ex); } return true; } else { return false; } } private ReadedInfo checkIsInOutage(LocalDateTime timeStamp) { for (TimeSeries curTs : doc.getTimeSeries()) { LocalDateTime startDT = LocalDateTime.of(curTs.getStartDateAndOrTimeDate().getYear(), curTs.getStartDateAndOrTimeDate().getMonth(), curTs.getStartDateAndOrTimeDate().getDay(), curTs.getStartDateAndOrTimeTime().getHour(), curTs.getStartDateAndOrTimeTime().getMinute()); LocalDateTime endDT = LocalDateTime.of(curTs.getEndDateAndOrTimeDate().getYear(), curTs.getEndDateAndOrTimeDate().getMonth(), curTs.getEndDateAndOrTimeDate().getDay(), curTs.getEndDateAndOrTimeTime().getHour(), curTs.getEndDateAndOrTimeTime().getMinute()); if ((startDT.isBefore(timeStamp) && endDT.isAfter(timeStamp)) || startDT.equals(timeStamp)) { String nominalPower = null; if (curTs.getProductionRegisteredResourcePSRTypePowerSystemResourcesNominalP() != null) { nominalPower = Float.toString(curTs.getProductionRegisteredResourcePSRTypePowerSystemResourcesNominalP().getValue()); } return new ReadedInfo(true, nominalPower); } } return new ReadedInfo(false, ""); } private boolean checkIsScheduled() { List<Reason> reasonList = doc.getReason(); if (reasonList.size() != 1) { throw new UnsupportedOperationException("Expected one reason but there are " + reasonList.size() + " reasons"); } Reason reason = reasonList.get(0); switch (reason.getCode()) { case "B19": return true; case "B20": // shutdown case "B18": // failure on generation unit case "A95": // complentary info? return false; default: printCurDoc(); throw new UnsupportedOperationException("Unknow reason code " + reason.getCode()); } } private void printCurDoc() { try { // just print th pb doucment JAXBContext jaxbContext = JAXBContext.newInstance(UnavailabilityMarketDocument.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(doc, System.out); } catch (JAXBException ex) { LOGGER.catching(ex); } } @Override protected List<ColumnDefinition> computeColumnDef() { DocumentType docType = DocumentType.fromId(doc.getType()); switch (docType) { case TRANSMISSION_UNAVAILABILITY: return doc.getTimeSeries().stream(). flatMap(ts -> { if (ts.getAssetRegisteredResource().isEmpty()) {
AssetRegisteredResource res = new AssetRegisteredResource();
3
2023-10-30 09:09:53+00:00
24k
EricFan2002/SC2002
src/app/ui/camp/enquiriesview/OverlayCampInfoDisplayEnquiries.java
[ { "identifier": "RepositoryCollection", "path": "src/app/entity/RepositoryCollection.java", "snippet": "public class RepositoryCollection {\n\n /**\n * The repository for user objects.\n */\n private static UserList userRepository;\n\n /**\n * The repository for camp objects.\n ...
import app.entity.RepositoryCollection; import app.entity.camp.Camp; import app.entity.enquiry.Enquiry; import app.entity.enquiry.EnquiryList; import app.entity.user.Student; import app.ui.camp.infomationview.OverlayCampInfoDisplayView; import app.ui.overlayactions.OverlayChooseBox; import app.ui.overlayactions.OverlayNotification; import app.ui.overlayactions.OverlayTextInputAction; import app.ui.widgets.*; import app.ui.windows.ICallBack; import app.ui.windows.Window; import java.util.ArrayList;
14,902
package app.ui.camp.enquiriesview; /** * OverlayCampInfoDisplayEnquiries extends OverlayCampInfoDisplayView and implements ICallBack. * This class manages the display and interactions related to camp enquiries within an overlay view. */ public class OverlayCampInfoDisplayEnquiries extends OverlayCampInfoDisplayView implements ICallBack { protected WidgetLabel labelNewEnq; protected WidgetTextBox textBoxEnq; protected WidgetButton sendButton; protected Camp camp; protected Student student; protected Window mainWindow; protected WidgetPageSelection participantsView; protected ArrayList<Enquiry> enquiryList; protected Enquiry selectedEnq; protected boolean editEnq = false; public OverlayCampInfoDisplayEnquiries(int x, int y, int offsetY, int offsetX, String windowName, Camp camp, Student student, Window mainWindow) { super(x, y, offsetY, offsetX, windowName, camp); this.mainWindow = mainWindow; this.camp = camp; this.student = student; enquiryList = new ArrayList<>(); ArrayList<ArrayList<String>> enqList = new ArrayList<>(); EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp); for (Enquiry enquiry : enquires) { if(camp.getCommittees().contains(student) || enquiry.getSender().equals(student)) { ArrayList<String> tmp = new ArrayList<String>(); enquiryList.add(enquiry); if (enquiry.getSender().equals(student)) tmp.add("Question: " + enquiry.getQuestion() + " ( From You )"); else tmp.add("Question: " + enquiry.getQuestion() + " ( From " + enquiry.getSender().getName() + " )"); if (enquiry.getAnswer() == null || enquiry.getAnswer().equals("")) tmp.add(" Not Answer Yet. Our coordinators will answer soon."); else tmp.add(" : " + enquiry.getAnswer() + " ( Answered By " + enquiry.getAnsweredBy().getName() + ")"); enqList.add(tmp); } } WidgetLabel labelParticipants = new WidgetLabel(3, 15, 15, "Your Enquires:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(labelParticipants); participantsView = new WidgetPageSelection(3, 16, getLenX() - 8, getLenY() / 2, "Participants", enqList, OverlayCampInfoDisplayEnquiries.this); addWidget(participantsView); labelNewEnq = new WidgetLabel(3, 31 + getLenY() / 4, getLenX() - 8, "New Enquiry To Camp"); addWidget(labelNewEnq); textBoxEnq = new WidgetTextBox(3, 32 + getLenY() / 4, getLenX() - 8, ""); addWidget(textBoxEnq); sendButton = new WidgetButton(3, 33 + getLenY() / 4, getLenX() - 8, "Send Enquiry"); addWidget(sendButton); textBoxDescription.setSkipSelection(true); textBoxDClose.setSkipSelection(true); textBoxDStart.setSkipSelection(true); textBoxDEnd.setSkipSelection(true); textBoxDClose.setSkipSelection(true); textBoxSchool.setSkipSelection(true); textBoxLocation.setSkipSelection(true); textBoxSlots.setSkipSelection(true); textBoxSlotsC.setSkipSelection(true); textBoxVis.setSkipSelection(true); removeWidget(exitButton); addWidget(exitButton); } /** * Updates the list of camp enquiries displayed in the overlay. */ public void updateEnquiries() { ArrayList<ArrayList<String>> enqList = new ArrayList<>(); EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp); enquiryList.clear(); for (Enquiry enquiry : enquires) { if(camp.getCommittees().contains(student) || enquiry.getSender().equals(student)) { ArrayList<String> tmp = new ArrayList<String>(); enquiryList.add(enquiry); if (enquiry.getSender().equals(student)) tmp.add("Question: " + enquiry.getQuestion() + " ( From You )"); else tmp.add("Question: " + enquiry.getQuestion() + " ( From " + enquiry.getSender().getName() + " )"); if (enquiry.getAnswer() == null || enquiry.getAnswer().equals("")) tmp.add(" Not Answer Yet. Our coordinators will answer soon."); else tmp.add(" : " + enquiry.getAnswer() + " ( Answered By " + enquiry.getAnsweredBy().getName() + ")"); enqList.add(tmp); } } participantsView.updateList(enqList); } /** * The main message loop handling user interactions within the camp enquiries overlay. * Manages actions based on button presses and user selections. */ public void messageLoop() { super.messageLoop(); if (participantsView.getSelectedOption() != -1) { selectedEnq = enquiryList.get(participantsView.getSelectedOption()); if (selectedEnq != null) { if (selectedEnq.getAnswer() == null || selectedEnq.getAnswer().equals("")) { ArrayList<String> options = new ArrayList<>(); if(selectedEnq.getSender().equals(student)) { options.add("Delete Enquiry"); options.add("Edit Enquiry"); } options.add("Cancel"); WidgetButton buttonPosition = participantsView.getSelectionsButton() .get(participantsView.getSelectedOption()).get(0); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(30, buttonPosition.getY(), getX() + buttonPosition.getX() + (getLenX() / 2 - 15), "Actions", options, OverlayCampInfoDisplayEnquiries.this); mainWindow.addOverlay(overlayChooseBox); participantsView.clearSelectedOption(); } else { ArrayList<String> options = new ArrayList<>(); options.add("Answered Enquiry"); options.add("Cannot Edit Anymore."); WidgetButton buttonPosition = participantsView.getSelectionsButton() .get(participantsView.getSelectedOption()).get(0); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(30, buttonPosition.getY(), getX() + buttonPosition.getX() + (getLenX() / 2 - 15), "Actions", options, OverlayCampInfoDisplayEnquiries.this); mainWindow.addOverlay(overlayChooseBox); participantsView.clearSelectedOption(); } } } if (sendButton.getPressed()) { sendButton.clearPressed(); if (textBoxEnq.getText().equals("")) {
package app.ui.camp.enquiriesview; /** * OverlayCampInfoDisplayEnquiries extends OverlayCampInfoDisplayView and implements ICallBack. * This class manages the display and interactions related to camp enquiries within an overlay view. */ public class OverlayCampInfoDisplayEnquiries extends OverlayCampInfoDisplayView implements ICallBack { protected WidgetLabel labelNewEnq; protected WidgetTextBox textBoxEnq; protected WidgetButton sendButton; protected Camp camp; protected Student student; protected Window mainWindow; protected WidgetPageSelection participantsView; protected ArrayList<Enquiry> enquiryList; protected Enquiry selectedEnq; protected boolean editEnq = false; public OverlayCampInfoDisplayEnquiries(int x, int y, int offsetY, int offsetX, String windowName, Camp camp, Student student, Window mainWindow) { super(x, y, offsetY, offsetX, windowName, camp); this.mainWindow = mainWindow; this.camp = camp; this.student = student; enquiryList = new ArrayList<>(); ArrayList<ArrayList<String>> enqList = new ArrayList<>(); EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp); for (Enquiry enquiry : enquires) { if(camp.getCommittees().contains(student) || enquiry.getSender().equals(student)) { ArrayList<String> tmp = new ArrayList<String>(); enquiryList.add(enquiry); if (enquiry.getSender().equals(student)) tmp.add("Question: " + enquiry.getQuestion() + " ( From You )"); else tmp.add("Question: " + enquiry.getQuestion() + " ( From " + enquiry.getSender().getName() + " )"); if (enquiry.getAnswer() == null || enquiry.getAnswer().equals("")) tmp.add(" Not Answer Yet. Our coordinators will answer soon."); else tmp.add(" : " + enquiry.getAnswer() + " ( Answered By " + enquiry.getAnsweredBy().getName() + ")"); enqList.add(tmp); } } WidgetLabel labelParticipants = new WidgetLabel(3, 15, 15, "Your Enquires:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(labelParticipants); participantsView = new WidgetPageSelection(3, 16, getLenX() - 8, getLenY() / 2, "Participants", enqList, OverlayCampInfoDisplayEnquiries.this); addWidget(participantsView); labelNewEnq = new WidgetLabel(3, 31 + getLenY() / 4, getLenX() - 8, "New Enquiry To Camp"); addWidget(labelNewEnq); textBoxEnq = new WidgetTextBox(3, 32 + getLenY() / 4, getLenX() - 8, ""); addWidget(textBoxEnq); sendButton = new WidgetButton(3, 33 + getLenY() / 4, getLenX() - 8, "Send Enquiry"); addWidget(sendButton); textBoxDescription.setSkipSelection(true); textBoxDClose.setSkipSelection(true); textBoxDStart.setSkipSelection(true); textBoxDEnd.setSkipSelection(true); textBoxDClose.setSkipSelection(true); textBoxSchool.setSkipSelection(true); textBoxLocation.setSkipSelection(true); textBoxSlots.setSkipSelection(true); textBoxSlotsC.setSkipSelection(true); textBoxVis.setSkipSelection(true); removeWidget(exitButton); addWidget(exitButton); } /** * Updates the list of camp enquiries displayed in the overlay. */ public void updateEnquiries() { ArrayList<ArrayList<String>> enqList = new ArrayList<>(); EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp); enquiryList.clear(); for (Enquiry enquiry : enquires) { if(camp.getCommittees().contains(student) || enquiry.getSender().equals(student)) { ArrayList<String> tmp = new ArrayList<String>(); enquiryList.add(enquiry); if (enquiry.getSender().equals(student)) tmp.add("Question: " + enquiry.getQuestion() + " ( From You )"); else tmp.add("Question: " + enquiry.getQuestion() + " ( From " + enquiry.getSender().getName() + " )"); if (enquiry.getAnswer() == null || enquiry.getAnswer().equals("")) tmp.add(" Not Answer Yet. Our coordinators will answer soon."); else tmp.add(" : " + enquiry.getAnswer() + " ( Answered By " + enquiry.getAnsweredBy().getName() + ")"); enqList.add(tmp); } } participantsView.updateList(enqList); } /** * The main message loop handling user interactions within the camp enquiries overlay. * Manages actions based on button presses and user selections. */ public void messageLoop() { super.messageLoop(); if (participantsView.getSelectedOption() != -1) { selectedEnq = enquiryList.get(participantsView.getSelectedOption()); if (selectedEnq != null) { if (selectedEnq.getAnswer() == null || selectedEnq.getAnswer().equals("")) { ArrayList<String> options = new ArrayList<>(); if(selectedEnq.getSender().equals(student)) { options.add("Delete Enquiry"); options.add("Edit Enquiry"); } options.add("Cancel"); WidgetButton buttonPosition = participantsView.getSelectionsButton() .get(participantsView.getSelectedOption()).get(0); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(30, buttonPosition.getY(), getX() + buttonPosition.getX() + (getLenX() / 2 - 15), "Actions", options, OverlayCampInfoDisplayEnquiries.this); mainWindow.addOverlay(overlayChooseBox); participantsView.clearSelectedOption(); } else { ArrayList<String> options = new ArrayList<>(); options.add("Answered Enquiry"); options.add("Cannot Edit Anymore."); WidgetButton buttonPosition = participantsView.getSelectionsButton() .get(participantsView.getSelectedOption()).get(0); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(30, buttonPosition.getY(), getX() + buttonPosition.getX() + (getLenX() / 2 - 15), "Actions", options, OverlayCampInfoDisplayEnquiries.this); mainWindow.addOverlay(overlayChooseBox); participantsView.clearSelectedOption(); } } } if (sendButton.getPressed()) { sendButton.clearPressed(); if (textBoxEnq.getText().equals("")) {
OverlayNotification overlayNotification = new OverlayNotification(40, getY() / 2 - 8,
7
2023-11-01 05:18:29+00:00
24k
TNO/PPS
plugins/nl.esi.pps.tmsc.analysis.ui/src/nl/esi/pps/tmsc/analysis/ui/handlers/SaveScopedTmscHandler.java
[ { "identifier": "DEFAULT_LOG_SEVERITIES", "path": "plugins/nl.esi.pps.common.ide.ui/src/nl/esi/pps/common/ide/ui/jobs/StatusReportingJob.java", "snippet": "public static final Collection<Integer> DEFAULT_LOG_SEVERITIES = Collections\n\t\t.unmodifiableCollection(Arrays.asList(IStatus.WARNING, IStatus.ERR...
import static nl.esi.pps.common.ide.ui.jobs.StatusReportingJob.DEFAULT_LOG_SEVERITIES; import static nl.esi.pps.tmsc.analysis.ui.Activator.getPluginID; import static nl.esi.pps.ui.handlers.AbstractCommandHandler.DEFAULT_DIALOG_SEVERITIES; import static org.eclipse.core.runtime.IStatus.ERROR; import static org.eclipse.lsat.common.queries.QueryableIterable.from; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Named; import org.apache.commons.lang3.StringUtils; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.e4.core.di.annotations.CanExecute; import org.eclipse.e4.core.di.annotations.Evaluate; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.lsat.common.emf.common.util.URIHelper; import org.eclipse.lsat.common.emf.ecore.resource.Persistor; import org.eclipse.lsat.common.emf.ecore.resource.PersistorFactory; import org.eclipse.lsat.common.queries.QueryableIterable; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.dialogs.SaveAsDialog; import nl.esi.pps.common.core.runtime.jobs.IStatusJobFunction; import nl.esi.pps.common.core.runtime.jobs.JobUtils; import nl.esi.pps.common.ide.ui.jobs.StatusReportingJob; import nl.esi.pps.tmsc.FullScopeTMSC; import nl.esi.pps.tmsc.ScopedTMSC; import nl.esi.pps.tmsc.TmscPlugin; import nl.esi.pps.tmsc.metric.MetricModel; import nl.esi.pps.tmsc.rendering.RenderingProperties; import nl.esi.pps.tmsc.rendering.plot.ScopesRenderingStrategy; import nl.esi.pps.tmsc.util.ScopedTmscCopier;
18,748
/* * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community * * This program and the accompanying materials are made available * under the terms of the MIT License which is available at * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT */ package nl.esi.pps.tmsc.analysis.ui.handlers; public class SaveScopedTmscHandler { @Evaluate @CanExecute public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional IStructuredSelection selection) { if (selection == null || selection.isEmpty()) { return false; } // Casting required for Java generics QueryableIterable<?> queryableSelection = from((Iterable<?>) selection); // Selection should be all ScopedTMSCs that share the same full scope return queryableSelection.forAll(s -> s instanceof ScopedTMSC) && queryableSelection .objectsOfKind(ScopedTMSC.class).collectOne(ScopedTMSC::getFullScope).asSet().size() == 1; } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) IStructuredSelection selection, @Named(IServiceConstants.ACTIVE_SHELL) Shell shell) { List<ScopedTMSC> scopedTmscs = from((Iterable<?>) selection).asType(ScopedTMSC.class).asList(); ScopedTMSC firstTmsc = (ScopedTMSC) selection.getFirstElement(); URI tmscURI = firstTmsc.eResource().getURI(); IFile tmscIFile = (IFile) URIHelper.asIResource(tmscURI); String suggestFileName = StringUtils.getCommonPrefix(from(scopedTmscs).collectOne(ScopedTMSC::getName).toArray(String.class)); if (suggestFileName == null || suggestFileName.isEmpty()) { suggestFileName = scopedTmscs.size() + "_scopes"; } SaveAsDialog saveAsDialog = new SaveAsDialog(shell); saveAsDialog.setOriginalFile( tmscIFile.getParent().getFile(new Path(suggestFileName + '.' + tmscURI.fileExtension()))); if (saveAsDialog.open() != SaveAsDialog.OK) { return; } IPath saveIPath = saveAsDialog.getResult(); if (!TmscPlugin.isTmscFileExtension(saveIPath.getFileExtension())) { saveIPath.addFileExtension(TmscPlugin.TMSC_FILE_EXTENSION_BINARY_COMPRESSED); } IFile saveIFile = ResourcesPlugin.getWorkspace().getRoot().getFile(saveIPath); IStatusJobFunction jobFunction = monitor -> doJob(scopedTmscs, saveIFile, monitor); String jobName = "Save scoped TMSC"; Job job = new StatusReportingJob(jobName, jobFunction, getPluginID(), DEFAULT_DIALOG_SEVERITIES, DEFAULT_LOG_SEVERITIES); job.setUser(true); job.schedule(); } public static IStatus doJob(List<ScopedTMSC> scopedTmscs, IFile saveIFile, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 101); FullScopeTMSC fullScope = scopedTmscs.get(0).getFullScope(); subMonitor.setTaskName("Prepare to copy scoped TMSC.");
/* * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community * * This program and the accompanying materials are made available * under the terms of the MIT License which is available at * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT */ package nl.esi.pps.tmsc.analysis.ui.handlers; public class SaveScopedTmscHandler { @Evaluate @CanExecute public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional IStructuredSelection selection) { if (selection == null || selection.isEmpty()) { return false; } // Casting required for Java generics QueryableIterable<?> queryableSelection = from((Iterable<?>) selection); // Selection should be all ScopedTMSCs that share the same full scope return queryableSelection.forAll(s -> s instanceof ScopedTMSC) && queryableSelection .objectsOfKind(ScopedTMSC.class).collectOne(ScopedTMSC::getFullScope).asSet().size() == 1; } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) IStructuredSelection selection, @Named(IServiceConstants.ACTIVE_SHELL) Shell shell) { List<ScopedTMSC> scopedTmscs = from((Iterable<?>) selection).asType(ScopedTMSC.class).asList(); ScopedTMSC firstTmsc = (ScopedTMSC) selection.getFirstElement(); URI tmscURI = firstTmsc.eResource().getURI(); IFile tmscIFile = (IFile) URIHelper.asIResource(tmscURI); String suggestFileName = StringUtils.getCommonPrefix(from(scopedTmscs).collectOne(ScopedTMSC::getName).toArray(String.class)); if (suggestFileName == null || suggestFileName.isEmpty()) { suggestFileName = scopedTmscs.size() + "_scopes"; } SaveAsDialog saveAsDialog = new SaveAsDialog(shell); saveAsDialog.setOriginalFile( tmscIFile.getParent().getFile(new Path(suggestFileName + '.' + tmscURI.fileExtension()))); if (saveAsDialog.open() != SaveAsDialog.OK) { return; } IPath saveIPath = saveAsDialog.getResult(); if (!TmscPlugin.isTmscFileExtension(saveIPath.getFileExtension())) { saveIPath.addFileExtension(TmscPlugin.TMSC_FILE_EXTENSION_BINARY_COMPRESSED); } IFile saveIFile = ResourcesPlugin.getWorkspace().getRoot().getFile(saveIPath); IStatusJobFunction jobFunction = monitor -> doJob(scopedTmscs, saveIFile, monitor); String jobName = "Save scoped TMSC"; Job job = new StatusReportingJob(jobName, jobFunction, getPluginID(), DEFAULT_DIALOG_SEVERITIES, DEFAULT_LOG_SEVERITIES); job.setUser(true); job.schedule(); } public static IStatus doJob(List<ScopedTMSC> scopedTmscs, IFile saveIFile, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 101); FullScopeTMSC fullScope = scopedTmscs.get(0).getFullScope(); subMonitor.setTaskName("Prepare to copy scoped TMSC.");
EObject[] otherRootContainers = ScopedTmscCopier.findOtherRootContainersToCopy(scopedTmscs,
12
2023-10-30 16:00:25+00:00
24k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/entity/BMDEntities.java
[ { "identifier": "PauseAnimationTimer", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/animation/PauseAnimationTimer.java", "snippet": "public class PauseAnimationTimer implements IAnimationTimer {\n private final Supplier<Double> sysTimeProvider;\n private final Supplier<Boolean> isP...
import com.cerbon.bosses_of_mass_destruction.animation.PauseAnimationTimer; import com.cerbon.bosses_of_mass_destruction.client.render.*; import com.cerbon.bosses_of_mass_destruction.config.BMDConfig; import com.cerbon.bosses_of_mass_destruction.entity.custom.gauntlet.*; import com.cerbon.bosses_of_mass_destruction.entity.custom.lich.*; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithArmorRenderer; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithBoneLight; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithEntity; import com.cerbon.bosses_of_mass_destruction.entity.custom.void_blossom.*; import com.cerbon.bosses_of_mass_destruction.entity.util.SimpleLivingGeoRenderer; import com.cerbon.bosses_of_mass_destruction.item.custom.ChargedEnderPearlEntity; import com.cerbon.bosses_of_mass_destruction.item.custom.SoulStarEntity; import com.cerbon.bosses_of_mass_destruction.particle.BMDParticles; import com.cerbon.bosses_of_mass_destruction.particle.ParticleFactories; import com.cerbon.bosses_of_mass_destruction.projectile.MagicMissileProjectile; import com.cerbon.bosses_of_mass_destruction.projectile.PetalBladeProjectile; import com.cerbon.bosses_of_mass_destruction.projectile.SporeBallProjectile; import com.cerbon.bosses_of_mass_destruction.projectile.comet.CometCodeAnimations; import com.cerbon.bosses_of_mass_destruction.projectile.comet.CometProjectile; import com.cerbon.bosses_of_mass_destruction.util.BMDConstants; import com.cerbon.cerbons_api.api.general.data.WeakHashPredicate; import com.cerbon.cerbons_api.api.general.particle.ClientParticleBuilder; import com.cerbon.cerbons_api.api.static_utilities.RandomUtils; import com.cerbon.cerbons_api.api.static_utilities.Vec3Colors; import com.cerbon.cerbons_api.api.static_utilities.VecUtils; import com.mojang.blaze3d.Blaze3D; import me.shedaniel.autoconfig.AutoConfig; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.EntityRenderers; import net.minecraft.client.renderer.entity.ThrownItemRenderer; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.phys.Vec3; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.event.entity.EntityAttributeCreationEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject;
17,476
package com.cerbon.bosses_of_mass_destruction.entity; public class BMDEntities { public static final BMDConfig mobConfig = AutoConfig.getConfigHolder(BMDConfig.class).getConfig(); public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, BMDConstants.MOD_ID); public static final RegistryObject<EntityType<LichEntity>> LICH = ENTITY_TYPES.register("lich", () -> EntityType.Builder.<LichEntity>of((entityType, level) -> new LichEntity(entityType, level, mobConfig.lichConfig), MobCategory.MONSTER) .sized(1.8f, 3.0f) .updateInterval(1) .build(new ResourceLocation(BMDConstants.MOD_ID, "lich").toString())); public static final RegistryObject<EntityType<MagicMissileProjectile>> MAGIC_MISSILE = ENTITY_TYPES.register("blue_fireball", () -> EntityType.Builder.<MagicMissileProjectile>of(MagicMissileProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "blue_fireball").toString())); public static final RegistryObject<EntityType<CometProjectile>> COMET = ENTITY_TYPES.register("comet", () -> EntityType.Builder.<CometProjectile>of(CometProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "comet").toString())); public static final RegistryObject<EntityType<SoulStarEntity>> SOUL_STAR = ENTITY_TYPES.register("soul_star", () -> EntityType.Builder.<SoulStarEntity>of(SoulStarEntity::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "soul_star").toString()));
package com.cerbon.bosses_of_mass_destruction.entity; public class BMDEntities { public static final BMDConfig mobConfig = AutoConfig.getConfigHolder(BMDConfig.class).getConfig(); public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, BMDConstants.MOD_ID); public static final RegistryObject<EntityType<LichEntity>> LICH = ENTITY_TYPES.register("lich", () -> EntityType.Builder.<LichEntity>of((entityType, level) -> new LichEntity(entityType, level, mobConfig.lichConfig), MobCategory.MONSTER) .sized(1.8f, 3.0f) .updateInterval(1) .build(new ResourceLocation(BMDConstants.MOD_ID, "lich").toString())); public static final RegistryObject<EntityType<MagicMissileProjectile>> MAGIC_MISSILE = ENTITY_TYPES.register("blue_fireball", () -> EntityType.Builder.<MagicMissileProjectile>of(MagicMissileProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "blue_fireball").toString())); public static final RegistryObject<EntityType<CometProjectile>> COMET = ENTITY_TYPES.register("comet", () -> EntityType.Builder.<CometProjectile>of(CometProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "comet").toString())); public static final RegistryObject<EntityType<SoulStarEntity>> SOUL_STAR = ENTITY_TYPES.register("soul_star", () -> EntityType.Builder.<SoulStarEntity>of(SoulStarEntity::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "soul_star").toString()));
public static final RegistryObject<EntityType<ChargedEnderPearlEntity>> CHARGED_ENDER_PEARL = ENTITY_TYPES.register("charged_ender_pearl",
6
2023-10-25 16:28:17+00:00
24k
sinch/sinch-sdk-java
openapi-contracts/src/main/com/sinch/sdk/domains/sms/adapters/api/v1/BatchesApi.java
[ { "identifier": "ApiException", "path": "core/src/main/com/sinch/sdk/core/exceptions/ApiException.java", "snippet": "public class ApiException extends RuntimeException {\n\n private static final long serialVersionUID = -1L;\n private int code = 0;\n\n public ApiException() {}\n\n public ApiException...
import com.fasterxml.jackson.core.type.TypeReference; import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.core.exceptions.ApiExceptionBuilder; import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.core.http.HttpMapper; import com.sinch.sdk.core.http.HttpMethod; import com.sinch.sdk.core.http.HttpRequest; import com.sinch.sdk.core.http.HttpResponse; import com.sinch.sdk.core.http.HttpStatus; import com.sinch.sdk.core.http.URLParameter; import com.sinch.sdk.core.http.URLPathUtils; import com.sinch.sdk.core.models.ServerConfiguration; import com.sinch.sdk.domains.sms.models.dto.v1.ApiBatchListDto; import com.sinch.sdk.domains.sms.models.dto.v1.ApiDeliveryFeedbackDto; import com.sinch.sdk.domains.sms.models.dto.v1.DryRun200ResponseDto; import com.sinch.sdk.domains.sms.models.dto.v1.SendSMS201ResponseDto; import com.sinch.sdk.domains.sms.models.dto.v1.SendSMSRequestDto; import com.sinch.sdk.domains.sms.models.dto.v1.UpdateBatchMessageRequestDto; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger;
20,221
final Collection<String> localVarContentTypes = Arrays.asList("application/json"); final Collection<String> localVarAuthNames = Arrays.asList("BearerAuth"); final String serializedBody = mapper.serialize(localVarContentTypes, sendSMSRequestDto); return new HttpRequest( localVarPath, HttpMethod.POST, localVarQueryParams, serializedBody, localVarHeaderParams, localVarAccepts, localVarContentTypes, localVarAuthNames); } /** * Get a batch message This operation returns a specific batch that matches the provided batch ID. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param batchId The batch ID you received from sending a message. (required) * @return SendSMS201ResponseDto * @throws ApiException if fails to make API call */ public SendSMS201ResponseDto getBatchMessage(String servicePlanId, String batchId) throws ApiException { LOGGER.finest( "[getBatchMessage]" + " " + "servicePlanId: " + servicePlanId + ", " + "batchId: " + batchId); HttpRequest httpRequest = getBatchMessageRequestBuilder(servicePlanId, batchId); HttpResponse response = httpClient.invokeAPI( this.serverConfiguration, this.authManagersByOasSecuritySchemes, httpRequest); if (HttpStatus.isSuccessfulStatus(response.getCode())) { TypeReference<SendSMS201ResponseDto> localVarReturnType = new TypeReference<SendSMS201ResponseDto>() {}; return mapper.deserialize(response, localVarReturnType); } // fallback to default errors handling: // all error cases definition are not required from specs: will try some "hardcoded" content // parsing throw ApiExceptionBuilder.build( response.getMessage(), response.getCode(), mapper.deserialize(response, new TypeReference<HashMap<String, ?>>() {})); } private HttpRequest getBatchMessageRequestBuilder(String servicePlanId, String batchId) throws ApiException { // verify the required parameter 'servicePlanId' is set if (servicePlanId == null) { throw new ApiException( 400, "Missing the required parameter 'servicePlanId' when calling getBatchMessage"); } // verify the required parameter 'batchId' is set if (batchId == null) { throw new ApiException( 400, "Missing the required parameter 'batchId' when calling getBatchMessage"); } String localVarPath = "/xms/v1/{service_plan_id}/batches/{batch_id}" .replaceAll( "\\{" + "service_plan_id" + "\\}", URLPathUtils.encodePathSegment(servicePlanId.toString())) .replaceAll( "\\{" + "batch_id" + "\\}", URLPathUtils.encodePathSegment(batchId.toString())); List<URLParameter> localVarQueryParams = new ArrayList<>(); Map<String, String> localVarHeaderParams = new HashMap<>(); final Collection<String> localVarAccepts = Arrays.asList("application/json"); final Collection<String> localVarContentTypes = Arrays.asList(); final Collection<String> localVarAuthNames = Arrays.asList("BearerAuth"); final String serializedBody = null; return new HttpRequest( localVarPath, HttpMethod.GET, localVarQueryParams, serializedBody, localVarHeaderParams, localVarAccepts, localVarContentTypes, localVarAuthNames); } /** * List Batches With the list operation you can list batch messages created in the last 14 days * that you have created. This operation supports pagination. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param page The page number starting from 0. (optional) * @param pageSize Determines the size of a page. (optional, default to 30) * @param from Only list messages sent from this sender number. Multiple originating numbers can * be comma separated. Must be phone numbers or short code. (optional) * @param startDate Only list messages received at or after this date/time. Formatted as * [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601): &#x60;YYYY-MM-DDThh:mm:ss.SSSZ&#x60;. * Default: Now-24 (optional) * @param endDate Only list messages received before this date/time. Formatted as * [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601): &#x60;YYYY-MM-DDThh:mm:ss.SSSZ&#x60;. * (optional) * @param clientReference Client reference to include (optional) * @return ApiBatchListDto * @throws ApiException if fails to make API call */
/* * API Overview | Sinch * Sinch SMS API is one of the easiest APIs we offer and enables you to add fast and reliable global SMS to your applications. Send single messages, scheduled batch messages, use available message templates and more. * * The version of the OpenAPI document: v1 * Contact: Support@sinch.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.sinch.sdk.domains.sms.adapters.api.v1; public class BatchesApi { private static final Logger LOGGER = Logger.getLogger(BatchesApi.class.getName()); private HttpClient httpClient; private ServerConfiguration serverConfiguration; private Map<String, AuthManager> authManagersByOasSecuritySchemes; private HttpMapper mapper; public BatchesApi( HttpClient httpClient, ServerConfiguration serverConfiguration, Map<String, AuthManager> authManagersByOasSecuritySchemes, HttpMapper mapper) { this.httpClient = httpClient; this.serverConfiguration = serverConfiguration; this.authManagersByOasSecuritySchemes = authManagersByOasSecuritySchemes; this.mapper = mapper; } /** * Cancel a batch message A batch can be canceled at any point. If a batch is canceled while * it&#39;s currently being delivered some messages currently being processed might still be * delivered. The delivery report will indicate which messages were canceled and which * weren&#39;t. Canceling a batch scheduled in the future will result in an empty delivery report * while canceling an already sent batch would result in no change to the completed delivery * report. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param batchId The batch ID you received from sending a message. (required) * @return SendSMS201ResponseDto * @throws ApiException if fails to make API call */ public SendSMS201ResponseDto cancelBatchMessage(String servicePlanId, String batchId) throws ApiException { LOGGER.finest( "[cancelBatchMessage]" + " " + "servicePlanId: " + servicePlanId + ", " + "batchId: " + batchId); HttpRequest httpRequest = cancelBatchMessageRequestBuilder(servicePlanId, batchId); HttpResponse response = httpClient.invokeAPI( this.serverConfiguration, this.authManagersByOasSecuritySchemes, httpRequest); if (HttpStatus.isSuccessfulStatus(response.getCode())) { TypeReference<SendSMS201ResponseDto> localVarReturnType = new TypeReference<SendSMS201ResponseDto>() {}; return mapper.deserialize(response, localVarReturnType); } // fallback to default errors handling: // all error cases definition are not required from specs: will try some "hardcoded" content // parsing throw ApiExceptionBuilder.build( response.getMessage(), response.getCode(), mapper.deserialize(response, new TypeReference<HashMap<String, ?>>() {})); } private HttpRequest cancelBatchMessageRequestBuilder(String servicePlanId, String batchId) throws ApiException { // verify the required parameter 'servicePlanId' is set if (servicePlanId == null) { throw new ApiException( 400, "Missing the required parameter 'servicePlanId' when calling cancelBatchMessage"); } // verify the required parameter 'batchId' is set if (batchId == null) { throw new ApiException( 400, "Missing the required parameter 'batchId' when calling cancelBatchMessage"); } String localVarPath = "/xms/v1/{service_plan_id}/batches/{batch_id}" .replaceAll( "\\{" + "service_plan_id" + "\\}", URLPathUtils.encodePathSegment(servicePlanId.toString())) .replaceAll( "\\{" + "batch_id" + "\\}", URLPathUtils.encodePathSegment(batchId.toString())); List<URLParameter> localVarQueryParams = new ArrayList<>(); Map<String, String> localVarHeaderParams = new HashMap<>(); final Collection<String> localVarAccepts = Arrays.asList("application/json"); final Collection<String> localVarContentTypes = Arrays.asList(); final Collection<String> localVarAuthNames = Arrays.asList("BearerAuth"); final String serializedBody = null; return new HttpRequest( localVarPath, HttpMethod.DELETE, localVarQueryParams, serializedBody, localVarHeaderParams, localVarAccepts, localVarContentTypes, localVarAuthNames); } /** * Send delivery feedback for a message Send feedback if your system can confirm successful * message delivery. Feedback can only be provided if &#x60;feedback_enabled&#x60; was set when * batch was submitted. **Batches**: It is possible to submit feedback multiple times for the same * batch for different recipients. Feedback without specified recipients is treated as successful * message delivery to all recipients referenced in the batch. Note that the * &#x60;recipients&#x60; key is still required even if the value is empty. **Groups**: If the * batch message was creating using a group ID, at least one recipient is required. Excluding * recipients (an empty recipient list) does not work and will result in a failed request. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param batchId The batch ID you received from sending a message. (required) * @param apiDeliveryFeedbackDto A list of phone numbers (MSISDNs) that successfully received the * message. (required) * @throws ApiException if fails to make API call */ public void deliveryFeedback( String servicePlanId, String batchId, ApiDeliveryFeedbackDto apiDeliveryFeedbackDto) throws ApiException { LOGGER.finest( "[deliveryFeedback]" + " " + "servicePlanId: " + servicePlanId + ", " + "batchId: " + batchId + ", " + "apiDeliveryFeedbackDto: " + apiDeliveryFeedbackDto); HttpRequest httpRequest = deliveryFeedbackRequestBuilder(servicePlanId, batchId, apiDeliveryFeedbackDto); HttpResponse response = httpClient.invokeAPI( this.serverConfiguration, this.authManagersByOasSecuritySchemes, httpRequest); if (HttpStatus.isSuccessfulStatus(response.getCode())) { return; } // fallback to default errors handling: // all error cases definition are not required from specs: will try some "hardcoded" content // parsing throw ApiExceptionBuilder.build( response.getMessage(), response.getCode(), mapper.deserialize(response, new TypeReference<HashMap<String, ?>>() {})); } private HttpRequest deliveryFeedbackRequestBuilder( String servicePlanId, String batchId, ApiDeliveryFeedbackDto apiDeliveryFeedbackDto) throws ApiException { // verify the required parameter 'servicePlanId' is set if (servicePlanId == null) { throw new ApiException( 400, "Missing the required parameter 'servicePlanId' when calling deliveryFeedback"); } // verify the required parameter 'batchId' is set if (batchId == null) { throw new ApiException( 400, "Missing the required parameter 'batchId' when calling deliveryFeedback"); } // verify the required parameter 'apiDeliveryFeedbackDto' is set if (apiDeliveryFeedbackDto == null) { throw new ApiException( 400, "Missing the required parameter 'apiDeliveryFeedbackDto' when calling deliveryFeedback"); } String localVarPath = "/xms/v1/{service_plan_id}/batches/{batch_id}/delivery_feedback" .replaceAll( "\\{" + "service_plan_id" + "\\}", URLPathUtils.encodePathSegment(servicePlanId.toString())) .replaceAll( "\\{" + "batch_id" + "\\}", URLPathUtils.encodePathSegment(batchId.toString())); List<URLParameter> localVarQueryParams = new ArrayList<>(); Map<String, String> localVarHeaderParams = new HashMap<>(); final Collection<String> localVarAccepts = Arrays.asList(); final Collection<String> localVarContentTypes = Arrays.asList("application/json"); final Collection<String> localVarAuthNames = Arrays.asList("BearerAuth"); final String serializedBody = mapper.serialize(localVarContentTypes, apiDeliveryFeedbackDto); return new HttpRequest( localVarPath, HttpMethod.POST, localVarQueryParams, serializedBody, localVarHeaderParams, localVarAccepts, localVarContentTypes, localVarAuthNames); } /** * Dry run This operation will perform a dry run of a batch which calculates the bodies and number * of parts for all messages in the batch without actually sending any messages. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param perRecipient Whether to include per recipient details in the response (optional) * @param numberOfRecipients Max number of recipients to include per recipient details for in the * response (optional, default to 100) * @param sendSMSRequestDto (optional) * @return DryRun200ResponseDto * @throws ApiException if fails to make API call */ public DryRun200ResponseDto dryRun( String servicePlanId, Boolean perRecipient, Integer numberOfRecipients, SendSMSRequestDto sendSMSRequestDto) throws ApiException { LOGGER.finest( "[dryRun]" + " " + "servicePlanId: " + servicePlanId + ", " + "perRecipient: " + perRecipient + ", " + "numberOfRecipients: " + numberOfRecipients + ", " + "sendSMSRequestDto: " + sendSMSRequestDto); HttpRequest httpRequest = dryRunRequestBuilder(servicePlanId, perRecipient, numberOfRecipients, sendSMSRequestDto); HttpResponse response = httpClient.invokeAPI( this.serverConfiguration, this.authManagersByOasSecuritySchemes, httpRequest); if (HttpStatus.isSuccessfulStatus(response.getCode())) { TypeReference<DryRun200ResponseDto> localVarReturnType = new TypeReference<DryRun200ResponseDto>() {}; return mapper.deserialize(response, localVarReturnType); } // fallback to default errors handling: // all error cases definition are not required from specs: will try some "hardcoded" content // parsing throw ApiExceptionBuilder.build( response.getMessage(), response.getCode(), mapper.deserialize(response, new TypeReference<HashMap<String, ?>>() {})); } private HttpRequest dryRunRequestBuilder( String servicePlanId, Boolean perRecipient, Integer numberOfRecipients, SendSMSRequestDto sendSMSRequestDto) throws ApiException { // verify the required parameter 'servicePlanId' is set if (servicePlanId == null) { throw new ApiException( 400, "Missing the required parameter 'servicePlanId' when calling dryRun"); } String localVarPath = "/xms/v1/{service_plan_id}/batches/dry_run" .replaceAll( "\\{" + "service_plan_id" + "\\}", URLPathUtils.encodePathSegment(servicePlanId.toString())); List<URLParameter> localVarQueryParams = new ArrayList<>(); if (null != perRecipient) { localVarQueryParams.add( new URLParameter( "per_recipient", perRecipient, URLParameter.STYLE.valueOf("form".toUpperCase()), true)); } if (null != numberOfRecipients) { localVarQueryParams.add( new URLParameter( "number_of_recipients", numberOfRecipients, URLParameter.STYLE.valueOf("form".toUpperCase()), true)); } Map<String, String> localVarHeaderParams = new HashMap<>(); final Collection<String> localVarAccepts = Arrays.asList("application/json"); final Collection<String> localVarContentTypes = Arrays.asList("application/json"); final Collection<String> localVarAuthNames = Arrays.asList("BearerAuth"); final String serializedBody = mapper.serialize(localVarContentTypes, sendSMSRequestDto); return new HttpRequest( localVarPath, HttpMethod.POST, localVarQueryParams, serializedBody, localVarHeaderParams, localVarAccepts, localVarContentTypes, localVarAuthNames); } /** * Get a batch message This operation returns a specific batch that matches the provided batch ID. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param batchId The batch ID you received from sending a message. (required) * @return SendSMS201ResponseDto * @throws ApiException if fails to make API call */ public SendSMS201ResponseDto getBatchMessage(String servicePlanId, String batchId) throws ApiException { LOGGER.finest( "[getBatchMessage]" + " " + "servicePlanId: " + servicePlanId + ", " + "batchId: " + batchId); HttpRequest httpRequest = getBatchMessageRequestBuilder(servicePlanId, batchId); HttpResponse response = httpClient.invokeAPI( this.serverConfiguration, this.authManagersByOasSecuritySchemes, httpRequest); if (HttpStatus.isSuccessfulStatus(response.getCode())) { TypeReference<SendSMS201ResponseDto> localVarReturnType = new TypeReference<SendSMS201ResponseDto>() {}; return mapper.deserialize(response, localVarReturnType); } // fallback to default errors handling: // all error cases definition are not required from specs: will try some "hardcoded" content // parsing throw ApiExceptionBuilder.build( response.getMessage(), response.getCode(), mapper.deserialize(response, new TypeReference<HashMap<String, ?>>() {})); } private HttpRequest getBatchMessageRequestBuilder(String servicePlanId, String batchId) throws ApiException { // verify the required parameter 'servicePlanId' is set if (servicePlanId == null) { throw new ApiException( 400, "Missing the required parameter 'servicePlanId' when calling getBatchMessage"); } // verify the required parameter 'batchId' is set if (batchId == null) { throw new ApiException( 400, "Missing the required parameter 'batchId' when calling getBatchMessage"); } String localVarPath = "/xms/v1/{service_plan_id}/batches/{batch_id}" .replaceAll( "\\{" + "service_plan_id" + "\\}", URLPathUtils.encodePathSegment(servicePlanId.toString())) .replaceAll( "\\{" + "batch_id" + "\\}", URLPathUtils.encodePathSegment(batchId.toString())); List<URLParameter> localVarQueryParams = new ArrayList<>(); Map<String, String> localVarHeaderParams = new HashMap<>(); final Collection<String> localVarAccepts = Arrays.asList("application/json"); final Collection<String> localVarContentTypes = Arrays.asList(); final Collection<String> localVarAuthNames = Arrays.asList("BearerAuth"); final String serializedBody = null; return new HttpRequest( localVarPath, HttpMethod.GET, localVarQueryParams, serializedBody, localVarHeaderParams, localVarAccepts, localVarContentTypes, localVarAuthNames); } /** * List Batches With the list operation you can list batch messages created in the last 14 days * that you have created. This operation supports pagination. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param page The page number starting from 0. (optional) * @param pageSize Determines the size of a page. (optional, default to 30) * @param from Only list messages sent from this sender number. Multiple originating numbers can * be comma separated. Must be phone numbers or short code. (optional) * @param startDate Only list messages received at or after this date/time. Formatted as * [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601): &#x60;YYYY-MM-DDThh:mm:ss.SSSZ&#x60;. * Default: Now-24 (optional) * @param endDate Only list messages received before this date/time. Formatted as * [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601): &#x60;YYYY-MM-DDThh:mm:ss.SSSZ&#x60;. * (optional) * @param clientReference Client reference to include (optional) * @return ApiBatchListDto * @throws ApiException if fails to make API call */
public ApiBatchListDto listBatches(
12
2023-10-31 08:32:59+00:00
24k
SpCoGov/SpCoBot
src/main/java/top/spco/util/builder/ToStringStyle.java
[ { "identifier": "ClassUtils", "path": "src/main/java/top/spco/util/ClassUtils.java", "snippet": "public class ClassUtils {\n\n private static final Comparator<Class<?>> COMPARATOR = (o1, o2) -> Objects.compare(getName(o1), getName(o2), String::compareTo);\n\n /**\n * The package separator char...
import top.spco.util.ClassUtils; import top.spco.util.ObjectUtils; import top.spco.util.StringEscapeUtils; import top.spco.util.StringUtils; import java.io.Serializable; import java.lang.reflect.Array; import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.WeakHashMap;
18,746
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.spco.util.builder; /** * Controls {@link String} formatting for {@link ToStringBuilder}. * The main public interface is always via {@link ToStringBuilder}. * * <p>These classes are intended to be used as <em>singletons</em>. * There is no need to instantiate a new style each time. A program * will generally use one of the predefined constants on this class. * Alternatively, the {@link StandardToStringStyle} class can be used * to set the individual settings. Thus most styles can be achieved * without subclassing.</p> * * <p>If required, a subclass can override as many or as few of the * methods as it requires. Each object type (from {@code boolean} * to {@code long} to {@link Object} to {@code int[]}) has * its own methods to output it. Most have two versions, detail and summary. * * <p>For example, the detail version of the array based methods will * output the whole array, whereas the summary method will just output * the array length.</p> * * <p>If you want to format the output of certain objects, such as dates, you * must create a subclass and override a method. * </p> * <pre> * public class MyStyle extends ToStringStyle { * protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { * if (value instanceof Date) { * value = new SimpleDateFormat("yyyy-MM-dd").format(value); * } * buffer.append(value); * } * } * </pre> * * @since 0.3.1 */ @SuppressWarnings("deprecation") // StringEscapeUtils public abstract class ToStringStyle implements Serializable { /** * Serialization version ID. */ private static final long serialVersionUID = -2587890625525655916L; /** * The default toString style. Using the {@code Person} * example from {@link ToStringBuilder}, the output would look like this: * * <pre> * Person@182f0db[name=John Doe,age=33,smoker=false] * </pre> */ public static final ToStringStyle DEFAULT_STYLE = new ToStringStyle.DefaultToStringStyle(); /** * The multi line toString style. Using the {@code Person} * example from {@link ToStringBuilder}, the output would look like this: * * <pre> * Person@182f0db[ * name=John Doe * age=33 * smoker=false * ] * </pre> */ public static final ToStringStyle MULTI_LINE_STYLE = new ToStringStyle.MultiLineToStringStyle(); /** * The no field names toString style. Using the * {@code Person} example from {@link ToStringBuilder}, the output * would look like this: * * <pre> * Person@182f0db[John Doe,33,false] * </pre> */ public static final ToStringStyle NO_FIELD_NAMES_STYLE = new ToStringStyle.NoFieldNameToStringStyle(); /** * The short prefix toString style. Using the {@code Person} example * from {@link ToStringBuilder}, the output would look like this: * * <pre> * Person[name=John Doe,age=33,smoker=false] * </pre> * * @since 0.3.1 */ public static final ToStringStyle SHORT_PREFIX_STYLE = new ToStringStyle.ShortPrefixToStringStyle(); /** * The simple toString style. Using the {@code Person} * example from {@link ToStringBuilder}, the output would look like this: * * <pre> * John Doe,33,false * </pre> */ public static final ToStringStyle SIMPLE_STYLE = new ToStringStyle.SimpleToStringStyle(); /** * The no class name toString style. Using the {@code Person} * example from {@link ToStringBuilder}, the output would look like this: * * <pre> * [name=John Doe,age=33,smoker=false] * </pre> * * @since 0.3.1 */ public static final ToStringStyle NO_CLASS_NAME_STYLE = new ToStringStyle.NoClassNameToStringStyle(); /** * The JSON toString style. Using the {@code Person} example from * {@link ToStringBuilder}, the output would look like this: * * <pre> * {"name": "John Doe", "age": 33, "smoker": true} * </pre> * * <strong>Note:</strong> Since field names are mandatory in JSON, this * ToStringStyle will throw an {@link UnsupportedOperationException} if no * field name is passed in while appending. Furthermore This ToStringStyle * will only generate valid JSON if referenced objects also produce JSON * when calling {@code toString()} on them. * * @see <a href="https://www.json.org/">json.org</a> * @since 0.3.1 */ public static final ToStringStyle JSON_STYLE = new ToStringStyle.JsonToStringStyle(); /** * A registry of objects used by {@code reflectionToString} methods * to detect cyclical object references and avoid infinite loops. */ private static final ThreadLocal<WeakHashMap<Object, Object>> REGISTRY = new ThreadLocal<>(); /* * Note that objects of this class are generally shared between threads, so * an instance variable would not be suitable here. * * In normal use the registry should always be left empty, because the caller * should call toString() which will clean up. * * See LANG-792 */ /** * Returns the registry of objects being traversed by the {@code reflectionToString} * methods in the current thread. * * @return Set the registry of objects being traversed */ public static Map<Object, Object> getRegistry() { return REGISTRY.get(); } /** * Returns {@code true} if the registry contains the given object. * Used by the reflection methods to avoid infinite loops. * * @param value The object to lookup in the registry. * @return boolean {@code true} if the registry contains the given * object. */ static boolean isRegistered(final Object value) { final Map<Object, Object> m = getRegistry(); return m != null && m.containsKey(value); } /** * Registers the given object. Used by the reflection methods to avoid * infinite loops. * * @param value The object to register. */ static void register(final Object value) { if (value != null) { final Map<Object, Object> m = getRegistry(); if (m == null) { REGISTRY.set(new WeakHashMap<>()); } getRegistry().put(value, null); } } /** * Unregisters the given object. * * <p> * Used by the reflection methods to avoid infinite loops. * </p> * * @param value The object to unregister. */ static void unregister(final Object value) { if (value != null) { final Map<Object, Object> m = getRegistry(); if (m != null) { m.remove(value); if (m.isEmpty()) { REGISTRY.remove(); } } } } /** * Whether to use the field names, the default is {@code true}. */ private boolean useFieldNames = true; /** * Whether to use the class name, the default is {@code true}. */ private boolean useClassName = true; /** * Whether to use short class names, the default is {@code false}. */ private boolean useShortClassName; /** * Whether to use the identity hash code, the default is {@code true}. */ private boolean useIdentityHashCode = true; /** * The content start {@code '['}. */ private String contentStart = "["; /** * The content end {@code ']'}. */ private String contentEnd = "]"; /** * The field name value separator {@code '='}. */ private String fieldNameValueSeparator = "="; /** * Whether the field separator should be added before any other fields. */ private boolean fieldSeparatorAtStart; /** * Whether the field separator should be added after any other fields. */ private boolean fieldSeparatorAtEnd; /** * The field separator {@code ','}. */ private String fieldSeparator = ","; /** * The array start <code>'{'</code>. */ private String arrayStart = "{"; /** * The array separator {@code ','}. */ private String arraySeparator = ","; /** * The detail for array content. */ private boolean arrayContentDetail = true; /** * The array end {@code '}'}. */ private String arrayEnd = "}"; /** * The value to use when fullDetail is {@code null}, * the default value is {@code true}. */ private boolean defaultFullDetail = true; /** * The {@code null} text {@code '&lt;null&gt;'}. */ private String nullText = "<null>"; /** * The summary size text start {@code '&lt;size'}. */ private String sizeStartText = "<size="; /** * The summary size text start {@code '&gt;'}. */ private String sizeEndText = ">"; /** * The summary object text start {@code '&lt;'}. */ private String summaryObjectStartText = "<"; /** * The summary object text start {@code '&gt;'}. */ private String summaryObjectEndText = ">"; /** * Constructor. */ protected ToStringStyle() { } /** * Appends to the {@code toString} the superclass toString. * <p>NOTE: It assumes that the toString has been created from the same ToStringStyle.</p> * * <p>A {@code null} {@code superToString} is ignored.</p> * * @param buffer the {@link StringBuffer} to populate * @param superToString the {@code super.toString()} * @since 0.3.1 */ public void appendSuper(final StringBuffer buffer, final String superToString) { appendToString(buffer, superToString); } /** * Appends to the {@code toString} another toString. * <p>NOTE: It assumes that the toString has been created from the same ToStringStyle.</p> * * <p>A {@code null} {@code toString} is ignored.</p> * * @param buffer the {@link StringBuffer} to populate * @param toString the additional {@code toString} * @since 0.3.1 */ public void appendToString(final StringBuffer buffer, final String toString) { if (toString != null) { final int pos1 = toString.indexOf(contentStart) + contentStart.length(); final int pos2 = toString.lastIndexOf(contentEnd); if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) { if (fieldSeparatorAtStart) { removeLastFieldSeparator(buffer); } buffer.append(toString, pos1, pos2); appendFieldSeparator(buffer); } } } /** * Appends to the {@code toString} the start of data indicator. * * @param buffer the {@link StringBuffer} to populate * @param object the {@link Object} to build a {@code toString} for */ public void appendStart(final StringBuffer buffer, final Object object) { if (object != null) { appendClassName(buffer, object); appendIdentityHashCode(buffer, object); appendContentStart(buffer); if (fieldSeparatorAtStart) { appendFieldSeparator(buffer); } } } /** * Appends to the {@code toString} the end of data indicator. * * @param buffer the {@link StringBuffer} to populate * @param object the {@link Object} to build a * {@code toString} for. */ public void appendEnd(final StringBuffer buffer, final Object object) { if (!this.fieldSeparatorAtEnd) { removeLastFieldSeparator(buffer); } appendContentEnd(buffer); unregister(object); } /** * Remove the last field separator from the buffer. * * @param buffer the {@link StringBuffer} to populate * @since 0.3.1 */ protected void removeLastFieldSeparator(final StringBuffer buffer) {
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.spco.util.builder; /** * Controls {@link String} formatting for {@link ToStringBuilder}. * The main public interface is always via {@link ToStringBuilder}. * * <p>These classes are intended to be used as <em>singletons</em>. * There is no need to instantiate a new style each time. A program * will generally use one of the predefined constants on this class. * Alternatively, the {@link StandardToStringStyle} class can be used * to set the individual settings. Thus most styles can be achieved * without subclassing.</p> * * <p>If required, a subclass can override as many or as few of the * methods as it requires. Each object type (from {@code boolean} * to {@code long} to {@link Object} to {@code int[]}) has * its own methods to output it. Most have two versions, detail and summary. * * <p>For example, the detail version of the array based methods will * output the whole array, whereas the summary method will just output * the array length.</p> * * <p>If you want to format the output of certain objects, such as dates, you * must create a subclass and override a method. * </p> * <pre> * public class MyStyle extends ToStringStyle { * protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { * if (value instanceof Date) { * value = new SimpleDateFormat("yyyy-MM-dd").format(value); * } * buffer.append(value); * } * } * </pre> * * @since 0.3.1 */ @SuppressWarnings("deprecation") // StringEscapeUtils public abstract class ToStringStyle implements Serializable { /** * Serialization version ID. */ private static final long serialVersionUID = -2587890625525655916L; /** * The default toString style. Using the {@code Person} * example from {@link ToStringBuilder}, the output would look like this: * * <pre> * Person@182f0db[name=John Doe,age=33,smoker=false] * </pre> */ public static final ToStringStyle DEFAULT_STYLE = new ToStringStyle.DefaultToStringStyle(); /** * The multi line toString style. Using the {@code Person} * example from {@link ToStringBuilder}, the output would look like this: * * <pre> * Person@182f0db[ * name=John Doe * age=33 * smoker=false * ] * </pre> */ public static final ToStringStyle MULTI_LINE_STYLE = new ToStringStyle.MultiLineToStringStyle(); /** * The no field names toString style. Using the * {@code Person} example from {@link ToStringBuilder}, the output * would look like this: * * <pre> * Person@182f0db[John Doe,33,false] * </pre> */ public static final ToStringStyle NO_FIELD_NAMES_STYLE = new ToStringStyle.NoFieldNameToStringStyle(); /** * The short prefix toString style. Using the {@code Person} example * from {@link ToStringBuilder}, the output would look like this: * * <pre> * Person[name=John Doe,age=33,smoker=false] * </pre> * * @since 0.3.1 */ public static final ToStringStyle SHORT_PREFIX_STYLE = new ToStringStyle.ShortPrefixToStringStyle(); /** * The simple toString style. Using the {@code Person} * example from {@link ToStringBuilder}, the output would look like this: * * <pre> * John Doe,33,false * </pre> */ public static final ToStringStyle SIMPLE_STYLE = new ToStringStyle.SimpleToStringStyle(); /** * The no class name toString style. Using the {@code Person} * example from {@link ToStringBuilder}, the output would look like this: * * <pre> * [name=John Doe,age=33,smoker=false] * </pre> * * @since 0.3.1 */ public static final ToStringStyle NO_CLASS_NAME_STYLE = new ToStringStyle.NoClassNameToStringStyle(); /** * The JSON toString style. Using the {@code Person} example from * {@link ToStringBuilder}, the output would look like this: * * <pre> * {"name": "John Doe", "age": 33, "smoker": true} * </pre> * * <strong>Note:</strong> Since field names are mandatory in JSON, this * ToStringStyle will throw an {@link UnsupportedOperationException} if no * field name is passed in while appending. Furthermore This ToStringStyle * will only generate valid JSON if referenced objects also produce JSON * when calling {@code toString()} on them. * * @see <a href="https://www.json.org/">json.org</a> * @since 0.3.1 */ public static final ToStringStyle JSON_STYLE = new ToStringStyle.JsonToStringStyle(); /** * A registry of objects used by {@code reflectionToString} methods * to detect cyclical object references and avoid infinite loops. */ private static final ThreadLocal<WeakHashMap<Object, Object>> REGISTRY = new ThreadLocal<>(); /* * Note that objects of this class are generally shared between threads, so * an instance variable would not be suitable here. * * In normal use the registry should always be left empty, because the caller * should call toString() which will clean up. * * See LANG-792 */ /** * Returns the registry of objects being traversed by the {@code reflectionToString} * methods in the current thread. * * @return Set the registry of objects being traversed */ public static Map<Object, Object> getRegistry() { return REGISTRY.get(); } /** * Returns {@code true} if the registry contains the given object. * Used by the reflection methods to avoid infinite loops. * * @param value The object to lookup in the registry. * @return boolean {@code true} if the registry contains the given * object. */ static boolean isRegistered(final Object value) { final Map<Object, Object> m = getRegistry(); return m != null && m.containsKey(value); } /** * Registers the given object. Used by the reflection methods to avoid * infinite loops. * * @param value The object to register. */ static void register(final Object value) { if (value != null) { final Map<Object, Object> m = getRegistry(); if (m == null) { REGISTRY.set(new WeakHashMap<>()); } getRegistry().put(value, null); } } /** * Unregisters the given object. * * <p> * Used by the reflection methods to avoid infinite loops. * </p> * * @param value The object to unregister. */ static void unregister(final Object value) { if (value != null) { final Map<Object, Object> m = getRegistry(); if (m != null) { m.remove(value); if (m.isEmpty()) { REGISTRY.remove(); } } } } /** * Whether to use the field names, the default is {@code true}. */ private boolean useFieldNames = true; /** * Whether to use the class name, the default is {@code true}. */ private boolean useClassName = true; /** * Whether to use short class names, the default is {@code false}. */ private boolean useShortClassName; /** * Whether to use the identity hash code, the default is {@code true}. */ private boolean useIdentityHashCode = true; /** * The content start {@code '['}. */ private String contentStart = "["; /** * The content end {@code ']'}. */ private String contentEnd = "]"; /** * The field name value separator {@code '='}. */ private String fieldNameValueSeparator = "="; /** * Whether the field separator should be added before any other fields. */ private boolean fieldSeparatorAtStart; /** * Whether the field separator should be added after any other fields. */ private boolean fieldSeparatorAtEnd; /** * The field separator {@code ','}. */ private String fieldSeparator = ","; /** * The array start <code>'{'</code>. */ private String arrayStart = "{"; /** * The array separator {@code ','}. */ private String arraySeparator = ","; /** * The detail for array content. */ private boolean arrayContentDetail = true; /** * The array end {@code '}'}. */ private String arrayEnd = "}"; /** * The value to use when fullDetail is {@code null}, * the default value is {@code true}. */ private boolean defaultFullDetail = true; /** * The {@code null} text {@code '&lt;null&gt;'}. */ private String nullText = "<null>"; /** * The summary size text start {@code '&lt;size'}. */ private String sizeStartText = "<size="; /** * The summary size text start {@code '&gt;'}. */ private String sizeEndText = ">"; /** * The summary object text start {@code '&lt;'}. */ private String summaryObjectStartText = "<"; /** * The summary object text start {@code '&gt;'}. */ private String summaryObjectEndText = ">"; /** * Constructor. */ protected ToStringStyle() { } /** * Appends to the {@code toString} the superclass toString. * <p>NOTE: It assumes that the toString has been created from the same ToStringStyle.</p> * * <p>A {@code null} {@code superToString} is ignored.</p> * * @param buffer the {@link StringBuffer} to populate * @param superToString the {@code super.toString()} * @since 0.3.1 */ public void appendSuper(final StringBuffer buffer, final String superToString) { appendToString(buffer, superToString); } /** * Appends to the {@code toString} another toString. * <p>NOTE: It assumes that the toString has been created from the same ToStringStyle.</p> * * <p>A {@code null} {@code toString} is ignored.</p> * * @param buffer the {@link StringBuffer} to populate * @param toString the additional {@code toString} * @since 0.3.1 */ public void appendToString(final StringBuffer buffer, final String toString) { if (toString != null) { final int pos1 = toString.indexOf(contentStart) + contentStart.length(); final int pos2 = toString.lastIndexOf(contentEnd); if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) { if (fieldSeparatorAtStart) { removeLastFieldSeparator(buffer); } buffer.append(toString, pos1, pos2); appendFieldSeparator(buffer); } } } /** * Appends to the {@code toString} the start of data indicator. * * @param buffer the {@link StringBuffer} to populate * @param object the {@link Object} to build a {@code toString} for */ public void appendStart(final StringBuffer buffer, final Object object) { if (object != null) { appendClassName(buffer, object); appendIdentityHashCode(buffer, object); appendContentStart(buffer); if (fieldSeparatorAtStart) { appendFieldSeparator(buffer); } } } /** * Appends to the {@code toString} the end of data indicator. * * @param buffer the {@link StringBuffer} to populate * @param object the {@link Object} to build a * {@code toString} for. */ public void appendEnd(final StringBuffer buffer, final Object object) { if (!this.fieldSeparatorAtEnd) { removeLastFieldSeparator(buffer); } appendContentEnd(buffer); unregister(object); } /** * Remove the last field separator from the buffer. * * @param buffer the {@link StringBuffer} to populate * @since 0.3.1 */ protected void removeLastFieldSeparator(final StringBuffer buffer) {
if (StringUtils.endsWith(buffer, fieldSeparator)) {
3
2023-10-26 10:27:47+00:00
24k
Melledy/LunarCore
src/main/java/emu/lunarcore/server/packet/recv/HandlerEntityBindPropCsReq.java
[ { "identifier": "GameSession", "path": "src/main/java/emu/lunarcore/server/game/GameSession.java", "snippet": "@Getter\npublic class GameSession {\n private final GameServer server;\n private final Int2LongMap packetCooldown;\n private InetSocketAddress address;\n\n private Account account;\...
import emu.lunarcore.server.game.GameSession; import emu.lunarcore.server.packet.CmdId; import emu.lunarcore.server.packet.Opcodes; import emu.lunarcore.server.packet.PacketHandler;
19,894
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.EntityBindPropCsReq) public class HandlerEntityBindPropCsReq extends PacketHandler { @Override
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.EntityBindPropCsReq) public class HandlerEntityBindPropCsReq extends PacketHandler { @Override
public void handle(GameSession session, byte[] data) throws Exception {
0
2023-10-10 12:57:35+00:00
24k
jar-analyzer/jar-analyzer
src/main/java/org/sqlite/jdbc3/JDBC3Statement.java
[ { "identifier": "ExtendedCommand", "path": "src/main/java/org/sqlite/ExtendedCommand.java", "snippet": "public class ExtendedCommand {\n public static interface SQLExtension {\n public void execute(DB db) throws SQLException;\n }\n\n /**\n * Parses extended commands of \"backup\" or ...
import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLWarning; import java.sql.Statement; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sqlite.ExtendedCommand; import org.sqlite.ExtendedCommand.SQLExtension; import org.sqlite.SQLiteConnection; import org.sqlite.core.CoreStatement; import org.sqlite.core.DB; import org.sqlite.core.DB.ProgressObserver;
19,155
package org.sqlite.jdbc3; public abstract class JDBC3Statement extends CoreStatement { private int queryTimeout; // in seconds, as per the JDBC spec protected long updateCount; protected boolean exhaustedResults = false; // PUBLIC INTERFACE /////////////////////////////////////////////
package org.sqlite.jdbc3; public abstract class JDBC3Statement extends CoreStatement { private int queryTimeout; // in seconds, as per the JDBC spec protected long updateCount; protected boolean exhaustedResults = false; // PUBLIC INTERFACE /////////////////////////////////////////////
protected JDBC3Statement(SQLiteConnection conn) {
2
2023-10-07 15:42:35+00:00
24k
lunasaw/gb28181-proxy
gb28181-client/src/test/java/io/github/lunasw/gbproxy/client/test/cmd/ApplicationTest.java
[ { "identifier": "Gb28181Client", "path": "gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/Gb28181Client.java", "snippet": "@SpringBootApplication\npublic class Gb28181Client {\n\n public static void main(String[] args) {\n SpringApplication.run(Gb28181Client.class, args);\n }\...
import javax.sip.message.Request; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import io.github.lunasaw.gbproxy.client.Gb28181Client; import io.github.lunasaw.gbproxy.client.transmit.request.message.ClientMessageRequestProcessor; import io.github.lunasaw.gbproxy.client.transmit.response.register.RegisterResponseProcessor; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.layer.SipLayer; import io.github.lunasaw.sip.common.transmit.SipProcessorObserver; import io.github.lunasaw.sip.common.transmit.SipSender; import io.github.lunasaw.sip.common.transmit.event.Event; import io.github.lunasaw.sip.common.transmit.event.EventResult; import io.github.lunasaw.sip.common.transmit.request.SipRequestProvider; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import lombok.SneakyThrows;
16,307
package io.github.lunasw.gbproxy.client.test.cmd; /** * @author luna * @date 2023/10/13 */ @SpringBootTest(classes = Gb28181Client.class) public class ApplicationTest { static String localIp = "172.19.128.100";
package io.github.lunasw.gbproxy.client.test.cmd; /** * @author luna * @date 2023/10/13 */ @SpringBootTest(classes = Gb28181Client.class) public class ApplicationTest { static String localIp = "172.19.128.100";
FromDevice fromDevice;
3
2023-10-11 06:56:28+00:00
24k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/loader/LoaderUtils.java
[ { "identifier": "CorruptedWorldException", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/exceptions/CorruptedWorldException.java", "snippet": "public class CorruptedWorldException extends SlimeException {\n\n public CorruptedWorldException(String world) {\n this(world, null)...
import com.flowpowered.nbt.CompoundMap; import com.flowpowered.nbt.CompoundTag; import com.flowpowered.nbt.DoubleTag; import com.flowpowered.nbt.IntArrayTag; import com.flowpowered.nbt.IntTag; import com.flowpowered.nbt.ListTag; import com.flowpowered.nbt.stream.NBTInputStream; import com.github.luben.zstd.Zstd; import net.swofty.swm.api.exceptions.CorruptedWorldException; import net.swofty.swm.api.exceptions.NewerFormatException; import net.swofty.swm.api.loaders.SlimeLoader; import net.swofty.swm.api.utils.NibbleArray; import net.swofty.swm.api.utils.SlimeFormat; import net.swofty.swm.api.world.SlimeChunk; import net.swofty.swm.api.world.SlimeChunkSection; import net.swofty.swm.api.world.properties.SlimePropertyMap; import net.swofty.swm.nms.craft.CraftSlimeChunk; import net.swofty.swm.nms.craft.CraftSlimeChunkSection; import net.swofty.swm.nms.craft.CraftSlimeWorld; import net.swofty.swm.plugin.config.ConfigManager; import net.swofty.swm.plugin.config.DatasourcesConfig; import net.swofty.swm.plugin.loader.loaders.FileLoader; import net.swofty.swm.plugin.loader.loaders.MongoLoader; import net.swofty.swm.plugin.loader.loaders.MysqlLoader; import net.swofty.swm.plugin.log.Logging; import com.mongodb.MongoException; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.sql.SQLException; import java.util.*;
15,710
Zstd.decompress(tileEntities, compressedTileEntities); Zstd.decompress(entities, compressedEntities); Zstd.decompress(extraTag, compressedExtraTag); Zstd.decompress(mapsTag, compressedMapsTag); // Chunk deserialization Map<Long, SlimeChunk> chunks = readChunks(version, worldName, minX, minZ, width, depth, chunkBitset, chunkData); // Entity deserialization CompoundTag entitiesCompound = readCompoundTag(entities); if (entitiesCompound != null) { ListTag<CompoundTag> entitiesList = (ListTag<CompoundTag>) entitiesCompound.getValue().get("entities"); for (CompoundTag entityCompound : entitiesList.getValue()) { ListTag<DoubleTag> listTag = (ListTag<DoubleTag>) entityCompound.getAsListTag("Pos").get(); int chunkX = floor(listTag.getValue().get(0).getValue()) >> 4; int chunkZ = floor(listTag.getValue().get(2).getValue()) >> 4; long chunkKey = ((long) chunkZ) * Integer.MAX_VALUE + ((long) chunkX); SlimeChunk chunk = chunks.get(chunkKey); if (chunk == null) { throw new CorruptedWorldException(worldName); } chunk.getEntities().add(entityCompound); } } // Tile Entity deserialization CompoundTag tileEntitiesCompound = readCompoundTag(tileEntities); if (tileEntitiesCompound != null) { ListTag<CompoundTag> tileEntitiesList = (ListTag<CompoundTag>) tileEntitiesCompound.getValue().get("tiles"); for (CompoundTag tileEntityCompound : tileEntitiesList.getValue()) { int chunkX = ((IntTag) tileEntityCompound.getValue().get("x")).getValue() >> 4; int chunkZ = ((IntTag) tileEntityCompound.getValue().get("z")).getValue() >> 4; long chunkKey = ((long) chunkZ) * Integer.MAX_VALUE + ((long) chunkX); SlimeChunk chunk = chunks.get(chunkKey); if (chunk == null) { throw new CorruptedWorldException(worldName); } chunk.getTileEntities().add(tileEntityCompound); } } // Extra Data CompoundTag extraCompound = readCompoundTag(extraTag); if (extraCompound == null) { extraCompound = new CompoundTag("", new CompoundMap()); } // World Maps CompoundTag mapsCompound = readCompoundTag(mapsTag); List<CompoundTag> mapList; if (mapsCompound != null) { mapList = (List<CompoundTag>) mapsCompound.getAsListTag("maps").map(ListTag::getValue).orElse(new ArrayList<>()); } else { mapList = new ArrayList<>(); } // World properties SlimePropertyMap worldPropertyMap = propertyMap; Optional<CompoundTag> propertiesTag = extraCompound.getAsCompoundTag("properties"); if (propertiesTag.isPresent()) { worldPropertyMap = SlimePropertyMap.fromCompound(propertiesTag.get()); worldPropertyMap.merge(propertyMap); // Override world properties } else if (propertyMap == null) { // Make sure the property map is never null worldPropertyMap = new SlimePropertyMap(); } return new CraftSlimeWorld(loader, worldName, chunks, extraCompound, mapList, worldPropertyMap, readOnly, !readOnly); } catch (EOFException ex) { throw new CorruptedWorldException(worldName, ex); } } private static int floor(double num) { final int floor = (int) num; return floor == num ? floor : floor - (int) (Double.doubleToRawLongBits(num) >>> 63); } private static Map<Long, SlimeChunk> readChunks(int version, String worldName, int minX, int minZ, int width, int depth, BitSet chunkBitset, byte[] chunkData) throws IOException { DataInputStream dataStream = new DataInputStream(new ByteArrayInputStream(chunkData)); Map<Long, SlimeChunk> chunkMap = new HashMap<>(); for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { int bitsetIndex = z * width + x; if (chunkBitset.get(bitsetIndex)) { // Height Maps CompoundTag heightMaps; int[] heightMap = new int[256]; for (int i = 0; i < 256; i++) { heightMap[i] = dataStream.readInt(); } CompoundMap map = new CompoundMap(); map.put("heightMap", new IntArrayTag("heightMap", heightMap)); heightMaps = new CompoundTag("", map); // Biome array int[] biomes; byte[] byteBiomes = new byte[256]; dataStream.read(byteBiomes); biomes = toIntArray(byteBiomes); // Chunk Sections
package net.swofty.swm.plugin.loader; public class LoaderUtils { public static final long MAX_LOCK_TIME = 300000L; // Max time difference between current time millis and world lock public static final long LOCK_INTERVAL = 60000L; private static Map<String, SlimeLoader> loaderMap = new HashMap<>(); public static void registerLoaders() { DatasourcesConfig config = ConfigManager.getDatasourcesConfig(); // File loader DatasourcesConfig.FileConfig fileConfig = config.getFileConfig(); registerLoader("file", new FileLoader(new File(fileConfig.getPath()))); // Mysql loader DatasourcesConfig.MysqlConfig mysqlConfig = config.getMysqlConfig(); if (mysqlConfig.isEnabled()) { try { registerLoader("mysql", new MysqlLoader(mysqlConfig)); } catch (SQLException ex) { Logging.error("Failed to establish connection to the MySQL server:"); ex.printStackTrace(); } } // MongoDB loader DatasourcesConfig.MongoDBConfig mongoConfig = config.getMongoDbConfig(); if (mongoConfig.isEnabled()) { try { registerLoader("mongodb", new MongoLoader(mongoConfig)); } catch (MongoException ex) { Logging.error("Failed to establish connection to the MongoDB server:"); ex.printStackTrace(); } } } public static List<String> getAvailableLoadersNames() { return new LinkedList<>(loaderMap.keySet()); } public static SlimeLoader getLoader(String dataSource) { return loaderMap.get(dataSource); } public static void registerLoader(String dataSource, SlimeLoader loader) { if (loaderMap.containsKey(dataSource)) { throw new IllegalArgumentException("Data source " + dataSource + " already has a declared loader!"); } if (loader instanceof UpdatableLoader) { try { ((UpdatableLoader) loader).update(); } catch (UpdatableLoader.NewerDatabaseException e) { Logging.error("Data source " + dataSource + " version is " + e.getDatabaseVersion() + ", while" + " this SWM version only supports up to version " + e.getCurrentVersion() + "."); return; } catch (IOException ex) { Logging.error("Failed to check if data source " + dataSource + " is updated:"); ex.printStackTrace(); return; } } loaderMap.put(dataSource, loader); } public static CraftSlimeWorld deserializeWorld(SlimeLoader loader, String worldName, byte[] serializedWorld, SlimePropertyMap propertyMap, boolean readOnly) throws IOException, CorruptedWorldException, NewerFormatException { DataInputStream dataStream = new DataInputStream(new ByteArrayInputStream(serializedWorld)); try { byte[] fileHeader = new byte[SlimeFormat.SLIME_HEADER.length]; dataStream.read(fileHeader); if (!Arrays.equals(SlimeFormat.SLIME_HEADER, fileHeader)) { throw new CorruptedWorldException(worldName); } // File version byte version = dataStream.readByte(); if (version > SlimeFormat.SLIME_VERSION) { throw new NewerFormatException(version); } // Chunk short minX = dataStream.readShort(); short minZ = dataStream.readShort(); int width = dataStream.readShort(); int depth = dataStream.readShort(); if (width <= 0 || depth <= 0) { throw new CorruptedWorldException(worldName); } int bitmaskSize = (int) Math.ceil((width * depth) / 8.0D); byte[] chunkBitmask = new byte[bitmaskSize]; dataStream.read(chunkBitmask); BitSet chunkBitset = BitSet.valueOf(chunkBitmask); int compressedChunkDataLength = dataStream.readInt(); int chunkDataLength = dataStream.readInt(); byte[] compressedChunkData = new byte[compressedChunkDataLength]; byte[] chunkData = new byte[chunkDataLength]; dataStream.read(compressedChunkData); // Tile Entities int compressedTileEntitiesLength = dataStream.readInt(); int tileEntitiesLength = dataStream.readInt(); byte[] compressedTileEntities = new byte[compressedTileEntitiesLength]; byte[] tileEntities = new byte[tileEntitiesLength]; dataStream.read(compressedTileEntities); // Entities byte[] compressedEntities = new byte[0]; byte[] entities = new byte[0]; if (version >= 3) { boolean hasEntities = dataStream.readBoolean(); if (hasEntities) { int compressedEntitiesLength = dataStream.readInt(); int entitiesLength = dataStream.readInt(); compressedEntities = new byte[compressedEntitiesLength]; entities = new byte[entitiesLength]; dataStream.read(compressedEntities); } } // Extra NBT tag byte[] compressedExtraTag = new byte[0]; byte[] extraTag = new byte[0]; if (version >= 2) { int compressedExtraTagLength = dataStream.readInt(); int extraTagLength = dataStream.readInt(); compressedExtraTag = new byte[compressedExtraTagLength]; extraTag = new byte[extraTagLength]; dataStream.read(compressedExtraTag); } // World Map NBT tag byte[] compressedMapsTag = new byte[0]; byte[] mapsTag = new byte[0]; if (version >= 7) { int compressedMapsTagLength = dataStream.readInt(); int mapsTagLength = dataStream.readInt(); compressedMapsTag = new byte[compressedMapsTagLength]; mapsTag = new byte[mapsTagLength]; dataStream.read(compressedMapsTag); } if (dataStream.read() != -1) { throw new CorruptedWorldException(worldName); } // Data decompression Zstd.decompress(chunkData, compressedChunkData); Zstd.decompress(tileEntities, compressedTileEntities); Zstd.decompress(entities, compressedEntities); Zstd.decompress(extraTag, compressedExtraTag); Zstd.decompress(mapsTag, compressedMapsTag); // Chunk deserialization Map<Long, SlimeChunk> chunks = readChunks(version, worldName, minX, minZ, width, depth, chunkBitset, chunkData); // Entity deserialization CompoundTag entitiesCompound = readCompoundTag(entities); if (entitiesCompound != null) { ListTag<CompoundTag> entitiesList = (ListTag<CompoundTag>) entitiesCompound.getValue().get("entities"); for (CompoundTag entityCompound : entitiesList.getValue()) { ListTag<DoubleTag> listTag = (ListTag<DoubleTag>) entityCompound.getAsListTag("Pos").get(); int chunkX = floor(listTag.getValue().get(0).getValue()) >> 4; int chunkZ = floor(listTag.getValue().get(2).getValue()) >> 4; long chunkKey = ((long) chunkZ) * Integer.MAX_VALUE + ((long) chunkX); SlimeChunk chunk = chunks.get(chunkKey); if (chunk == null) { throw new CorruptedWorldException(worldName); } chunk.getEntities().add(entityCompound); } } // Tile Entity deserialization CompoundTag tileEntitiesCompound = readCompoundTag(tileEntities); if (tileEntitiesCompound != null) { ListTag<CompoundTag> tileEntitiesList = (ListTag<CompoundTag>) tileEntitiesCompound.getValue().get("tiles"); for (CompoundTag tileEntityCompound : tileEntitiesList.getValue()) { int chunkX = ((IntTag) tileEntityCompound.getValue().get("x")).getValue() >> 4; int chunkZ = ((IntTag) tileEntityCompound.getValue().get("z")).getValue() >> 4; long chunkKey = ((long) chunkZ) * Integer.MAX_VALUE + ((long) chunkX); SlimeChunk chunk = chunks.get(chunkKey); if (chunk == null) { throw new CorruptedWorldException(worldName); } chunk.getTileEntities().add(tileEntityCompound); } } // Extra Data CompoundTag extraCompound = readCompoundTag(extraTag); if (extraCompound == null) { extraCompound = new CompoundTag("", new CompoundMap()); } // World Maps CompoundTag mapsCompound = readCompoundTag(mapsTag); List<CompoundTag> mapList; if (mapsCompound != null) { mapList = (List<CompoundTag>) mapsCompound.getAsListTag("maps").map(ListTag::getValue).orElse(new ArrayList<>()); } else { mapList = new ArrayList<>(); } // World properties SlimePropertyMap worldPropertyMap = propertyMap; Optional<CompoundTag> propertiesTag = extraCompound.getAsCompoundTag("properties"); if (propertiesTag.isPresent()) { worldPropertyMap = SlimePropertyMap.fromCompound(propertiesTag.get()); worldPropertyMap.merge(propertyMap); // Override world properties } else if (propertyMap == null) { // Make sure the property map is never null worldPropertyMap = new SlimePropertyMap(); } return new CraftSlimeWorld(loader, worldName, chunks, extraCompound, mapList, worldPropertyMap, readOnly, !readOnly); } catch (EOFException ex) { throw new CorruptedWorldException(worldName, ex); } } private static int floor(double num) { final int floor = (int) num; return floor == num ? floor : floor - (int) (Double.doubleToRawLongBits(num) >>> 63); } private static Map<Long, SlimeChunk> readChunks(int version, String worldName, int minX, int minZ, int width, int depth, BitSet chunkBitset, byte[] chunkData) throws IOException { DataInputStream dataStream = new DataInputStream(new ByteArrayInputStream(chunkData)); Map<Long, SlimeChunk> chunkMap = new HashMap<>(); for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { int bitsetIndex = z * width + x; if (chunkBitset.get(bitsetIndex)) { // Height Maps CompoundTag heightMaps; int[] heightMap = new int[256]; for (int i = 0; i < 256; i++) { heightMap[i] = dataStream.readInt(); } CompoundMap map = new CompoundMap(); map.put("heightMap", new IntArrayTag("heightMap", heightMap)); heightMaps = new CompoundTag("", map); // Biome array int[] biomes; byte[] byteBiomes = new byte[256]; dataStream.read(byteBiomes); biomes = toIntArray(byteBiomes); // Chunk Sections
SlimeChunkSection[] sections = readChunkSections(dataStream, version);
6
2023-10-08 10:54:28+00:00
24k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/api/impl/PromptConstructorImpl.java
[ { "identifier": "PromptConstructor", "path": "src/main/java/zju/cst/aces/api/PromptConstructor.java", "snippet": "public interface PromptConstructor {\n\n List<Message> generate();\n\n}" }, { "identifier": "Config", "path": "src/main/java/zju/cst/aces/api/config/Config.java", "snippet...
import com.google.j2objc.annotations.ObjectiveCName; import lombok.Data; import zju.cst.aces.api.PromptConstructor; import zju.cst.aces.api.config.Config; import zju.cst.aces.dto.ClassInfo; import zju.cst.aces.dto.Message; import zju.cst.aces.dto.MethodInfo; import zju.cst.aces.dto.PromptInfo; import zju.cst.aces.prompt.PromptGenerator; import zju.cst.aces.runner.AbstractRunner; import zju.cst.aces.util.TokenCounter; import java.io.IOException; import java.util.List; import zju.cst.aces.api.PromptConstructor;
18,074
package zju.cst.aces.api.impl; @Data public class PromptConstructorImpl implements PromptConstructor { Config config; PromptInfo promptInfo; List<Message> messages; int tokenCount = 0; String testName; String fullTestName; static final String separator = "_"; public PromptConstructorImpl(Config config) { this.config = config; } @Override public List<Message> generate() { try { if (promptInfo == null) { throw new RuntimeException("PromptInfo is null, you need to initialize it first."); } this.messages = new PromptGenerator(config).generateMessages(promptInfo); countToken(); return this.messages; } catch (IOException e) { throw new RuntimeException(e); } } public void setPromptInfoWithDep(ClassInfo classInfo, MethodInfo methodInfo) throws IOException { this.promptInfo = AbstractRunner.generatePromptInfoWithDep(config, classInfo, methodInfo); } public void setPromptInfoWithoutDep(ClassInfo classInfo, MethodInfo methodInfo) throws IOException { this.promptInfo = AbstractRunner.generatePromptInfoWithoutDep(config, classInfo, methodInfo); } public void setFullTestName(String fullTestName) { this.fullTestName = fullTestName; this.testName = fullTestName.substring(fullTestName.lastIndexOf(".") + 1); this.promptInfo.setFullTestName(this.fullTestName); } public void setTestName(String testName) { this.testName = testName; } public void countToken() { for (Message p : messages) {
package zju.cst.aces.api.impl; @Data public class PromptConstructorImpl implements PromptConstructor { Config config; PromptInfo promptInfo; List<Message> messages; int tokenCount = 0; String testName; String fullTestName; static final String separator = "_"; public PromptConstructorImpl(Config config) { this.config = config; } @Override public List<Message> generate() { try { if (promptInfo == null) { throw new RuntimeException("PromptInfo is null, you need to initialize it first."); } this.messages = new PromptGenerator(config).generateMessages(promptInfo); countToken(); return this.messages; } catch (IOException e) { throw new RuntimeException(e); } } public void setPromptInfoWithDep(ClassInfo classInfo, MethodInfo methodInfo) throws IOException { this.promptInfo = AbstractRunner.generatePromptInfoWithDep(config, classInfo, methodInfo); } public void setPromptInfoWithoutDep(ClassInfo classInfo, MethodInfo methodInfo) throws IOException { this.promptInfo = AbstractRunner.generatePromptInfoWithoutDep(config, classInfo, methodInfo); } public void setFullTestName(String fullTestName) { this.fullTestName = fullTestName; this.testName = fullTestName.substring(fullTestName.lastIndexOf(".") + 1); this.promptInfo.setFullTestName(this.fullTestName); } public void setTestName(String testName) { this.testName = testName; } public void countToken() { for (Message p : messages) {
this.tokenCount += TokenCounter.countToken(p.getContent());
8
2023-10-14 07:15:10+00:00
24k
PfauMC/CyanWorld
cyanworld-cyanuniverse/src/main/java/ru/cyanworld/cyanuniverse/MainListener.java
[ { "identifier": "Cyan1dex", "path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/Cyan1dex.java", "snippet": "public class Cyan1dex extends JavaPlugin {\n public static Server server;\n public static Cyan1dex instance;\n public static File dataFolder;\n public static Random random;...
import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.*; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.*; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import ru.cyanworld.cyan1dex.Cyan1dex; import ru.cyanworld.cyan1dex.CyanEcoManager; import ru.cyanworld.cyan1dex.Utils; import ru.cyanworld.cyan1dex.api.CustomItem; import ru.cyanworld.cyan1dex.api.ItemBuilder; import ru.cyanworld.cyanuniverse.commands.CmdNbt; import ru.cyanworld.cyanuniverse.commands.MainCommand; import ru.cyanworld.cyanuniverse.menus.MyWorlds; import ru.cyanworld.cyanuniverse.menus.coding.*; import ru.cyanworld.cyanuniverse.menus.coding.variables.EffectMenu; import ru.cyanworld.cyanuniverse.menus.coding.variables.VariableMenu; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static ru.cyanworld.cyanuniverse.Coding.cancelEvent; import static ru.cyanworld.cyanuniverse.Coding.codeMap; import static ru.cyanworld.cyanuniverse.CyanUniverse.*;
15,161
} case RIGHT_CLICK_BLOCK: { if (event.getHand() == EquipmentSlot.OFF_HAND) { codeEventHandler.runCode("СобытиеИгрока_ПравыйКлик", eventid, player, null); cancelEvent(event, eventid); } break; } case RIGHT_CLICK_AIR: { codeEventHandler.runCode("СобытиеИгрока_ПравыйКлик", eventid, player, null); cancelEvent(event, eventid); break; } } break; } case "lobby": { try { if (!event.hasItem()) { if (player.isOp() != true) { event.setUseInteractedBlock(Event.Result.DENY); } } if (event.getAction().name().startsWith("RIGHT_CLICK")) { switch (itemStack.getType()) { case COMPASS: { event.setCancelled(true); player.openInventory(MenusList.worldsMenu.inventory); break; } case MAP: { event.setCancelled(true); if (world == lobby) { player.openInventory(new MyWorlds(player).getInventory()); } break; } } } else if (player.isOp() != true) { event.setUseInteractedBlock(Event.Result.DENY); } } catch (Exception ex) { ex.toString(); } } } } @EventHandler public void onInventoryOpen(InventoryOpenEvent event) { Player player = (Player) event.getPlayer(); if (event.getInventory().getType() == InventoryType.MERCHANT && canceledOpen.contains(player)) { event.setCancelled(true); } } @EventHandler public void on(PlayerItemDamageEvent event) { Player player = event.getPlayer(); World world = player.getWorld(); if (world == lobby) { if (!player.isOp()) { event.setCancelled(true); } } } @EventHandler public void entityInteract(PlayerInteractEntityEvent event) { Player player = event.getPlayer(); World world = player.getWorld(); if (world == lobby) { if (!player.isOp()) { event.setCancelled(true); } } if (world != lobby) { switch (worldscfg.getString(world.getName() + ".type")) { case "building": { if (player.getGameMode() != GameMode.CREATIVE) { switch (event.getRightClicked().getType()) { case ITEM_FRAME: case ARMOR_STAND: { event.setCancelled(true); break; } } } else { if (CmdNbt.selectmob.contains(player)) { CmdNbt.selectmob.remove(player); CmdNbt.selectedmob.put(player, event.getRightClicked()); } } break; } case "playing": { UUID eventid = UUID.randomUUID(); CodeEventHandler codeEventHandler = codeMap.get(world); if (codeEventHandler == null) return; codeEventHandler.runCode("СобытиеИгрока_КликПоМобу", eventid, player, event.getRightClicked()); if (cancelEvent(event, eventid) && event.getRightClicked().getType() == EntityType.VILLAGER) { canceledOpen.add(player); } break; } } } } @EventHandler public void onPlace(BlockPlaceEvent event) { Player player = event.getPlayer(); Block block = event.getBlockPlaced(); World world = player.getWorld(); String uuid = player.getUniqueId().toString();
package ru.cyanworld.cyanuniverse; public class MainListener implements Listener { public static List<World> unloadwithoutsave = new ArrayList<>(); public List<Player> canceledOpen = new ArrayList<>(); DecimalFormat decimalFormat = new DecimalFormat("#.##"); public MainListener() { server.getPluginManager().registerEvents(this, plugin); server.getScheduler().scheduleSyncRepeatingTask(plugin, () -> canceledOpen.removeAll(canceledOpen), 0, 1); } @EventHandler public void onInteract(PlayerInteractEvent event) { ItemStack itemStack = event.getItem(); Player player = event.getPlayer(); World world = player.getWorld(); UUID eventid = UUID.randomUUID(); String uuid = player.getUniqueId().toString(); switch (WorldManager.getWorldType(world)) { //TODO: Правирить!!1!11! case "building": { try { if (!event.hasItem()) { if (player.getGameMode() != GameMode.CREATIVE) { event.setUseInteractedBlock(Event.Result.DENY); } } if (event.getAction().name().startsWith("RIGHT_CLICK") && itemStack != null) { switch (itemStack.getType()) { case PAPER: { Location location = player.getLocation(); if (location.getX() >= 999) { player.sendTitle("§cОШИБКА!", "Нажмите ЛКМ для телепортации в мир", 5, 60, 10); Utils.playCustomSound("deny", player); } else { String loc = ("§r" + decimalFormat.format(location.getX()) + " " + decimalFormat.format(location.getY()) + " " + decimalFormat.format(location.getZ()) + " " + decimalFormat.format(location.getYaw()) + " " + decimalFormat.format(location.getPitch())).replace(",", "."); player.getInventory().getItemInMainHand().getItemMeta().setDisplayName(loc); player.sendTitle("§aУстановлено местоположение:", loc, 5, 60, 10); Utils.playCustomSound("ok", player); } break; } case COMPASS: { event.setCancelled(true); if (player.getWorld().getName().startsWith(uuid)) player.openInventory(MenusList.myWorldMenu.inventory); else player.openInventory(MenusList.worldsMenu.inventory); break; } case MAP: { event.setCancelled(true); if (world == lobby) { player.openInventory(new MyWorlds(player).getInventory()); } break; } case PRISMARINE_CRYSTALS: { event.setCancelled(true); player.openInventory(MenusList.decoMain.getInventory()); break; } case MAGMA_CREAM: { event.setCancelled(true); player.chat("/lobby"); break; } } } } catch (Exception ex) { } } case "coding": { if (player.getGameMode() == GameMode.SPECTATOR) return; if (event.getAction().name().startsWith("RIGHT_CLICK")) { if (itemStack == null || itemStack.getType() == Material.AIR) return; switch (itemStack.getType()) { case IRON_INGOT: { server.getScheduler().scheduleSyncDelayedTask(plugin, () -> player.openInventory(new VariableMenu().getInventory())); break; } case GLASS_BOTTLE: { player.openInventory(new EffectMenu().getInventory()); break; } case PAPER: { Location location = player.getLocation(); if (location.getX() >= 999) { player.sendTitle("§cОШИБКА!", "Нажмите ЛКМ для телепортации в мир", 5, 60, 10); Utils.playCustomSound("deny", player); } else { String loc = ("§r" + decimalFormat.format(location.getX()) + " " + decimalFormat.format(location.getY()) + " " + decimalFormat.format(location.getZ()) + " " + decimalFormat.format(location.getYaw()) + " " + decimalFormat.format(location.getPitch())).replace(",", "."); player.sendTitle("§aУстановлено местоположение:", loc, 5, 60, 10); player.getInventory().setItemInMainHand(new ItemBuilder(itemStack).name(loc).build()); Utils.playCustomSound("ok", player); } break; } } } else if (event.getAction().name().startsWith("LEFT_CLICK")) { if (!event.hasItem()) return; switch (event.getMaterial()) { case PAPER: { event.setCancelled(true); Location location = player.getLocation(); if (location.getX() >= 999) { player.setGameMode(GameMode.CREATIVE); world.getWorldBorder().setSize(22848); player.teleport(world.getSpawnLocation()); world.getWorldBorder().setSize(100); } else { player.teleport(new Location(world, 1001.5, 3, 1000.5)); player.setGameMode(GameMode.ADVENTURE); player.setAllowFlight(true); } break; } } } if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { Block block = event.getClickedBlock(); switch (block.getType()) { case WALL_SIGN: { Sign sign = (Sign) block.getState(); String lines[] = sign.getLines(); switch (lines[0]) { case "§lСобытие игрока": { player.openInventory(new PlayerEventMenu(sign).getInventory()); break; } case "§lСделать игроку": { player.openInventory(new PlayerActionMenu(sign).getInventory()); break; } case "§lЕсли игрок": { player.openInventory(new IfPlayerMenu(sign).getInventory()); break; } case "§lПараметры игры": { player.openInventory(new GameAction(sign).getInventory()); break; } case "§lПланировщик": { player.openInventory(new SchedulerMenu(sign).getInventory()); break; } case "§lЕсли моб": { player.openInventory(new IfEntityMenu(sign).getInventory()); break; } } break; } } } break; } case "playing": { CodeEventHandler codeEventHandler = codeMap.get(world); switch (event.getAction()) { case LEFT_CLICK_BLOCK: { if (event.getHand() == EquipmentSlot.OFF_HAND) { codeEventHandler.runCode("СобытиеИгрока_ЛевыйКлик", eventid, player, null); cancelEvent(event, eventid); } break; } case LEFT_CLICK_AIR: { codeEventHandler.runCode("СобытиеИгрока_ЛевыйКлик", eventid, player, null); cancelEvent(event, eventid); break; } case RIGHT_CLICK_BLOCK: { if (event.getHand() == EquipmentSlot.OFF_HAND) { codeEventHandler.runCode("СобытиеИгрока_ПравыйКлик", eventid, player, null); cancelEvent(event, eventid); } break; } case RIGHT_CLICK_AIR: { codeEventHandler.runCode("СобытиеИгрока_ПравыйКлик", eventid, player, null); cancelEvent(event, eventid); break; } } break; } case "lobby": { try { if (!event.hasItem()) { if (player.isOp() != true) { event.setUseInteractedBlock(Event.Result.DENY); } } if (event.getAction().name().startsWith("RIGHT_CLICK")) { switch (itemStack.getType()) { case COMPASS: { event.setCancelled(true); player.openInventory(MenusList.worldsMenu.inventory); break; } case MAP: { event.setCancelled(true); if (world == lobby) { player.openInventory(new MyWorlds(player).getInventory()); } break; } } } else if (player.isOp() != true) { event.setUseInteractedBlock(Event.Result.DENY); } } catch (Exception ex) { ex.toString(); } } } } @EventHandler public void onInventoryOpen(InventoryOpenEvent event) { Player player = (Player) event.getPlayer(); if (event.getInventory().getType() == InventoryType.MERCHANT && canceledOpen.contains(player)) { event.setCancelled(true); } } @EventHandler public void on(PlayerItemDamageEvent event) { Player player = event.getPlayer(); World world = player.getWorld(); if (world == lobby) { if (!player.isOp()) { event.setCancelled(true); } } } @EventHandler public void entityInteract(PlayerInteractEntityEvent event) { Player player = event.getPlayer(); World world = player.getWorld(); if (world == lobby) { if (!player.isOp()) { event.setCancelled(true); } } if (world != lobby) { switch (worldscfg.getString(world.getName() + ".type")) { case "building": { if (player.getGameMode() != GameMode.CREATIVE) { switch (event.getRightClicked().getType()) { case ITEM_FRAME: case ARMOR_STAND: { event.setCancelled(true); break; } } } else { if (CmdNbt.selectmob.contains(player)) { CmdNbt.selectmob.remove(player); CmdNbt.selectedmob.put(player, event.getRightClicked()); } } break; } case "playing": { UUID eventid = UUID.randomUUID(); CodeEventHandler codeEventHandler = codeMap.get(world); if (codeEventHandler == null) return; codeEventHandler.runCode("СобытиеИгрока_КликПоМобу", eventid, player, event.getRightClicked()); if (cancelEvent(event, eventid) && event.getRightClicked().getType() == EntityType.VILLAGER) { canceledOpen.add(player); } break; } } } } @EventHandler public void onPlace(BlockPlaceEvent event) { Player player = event.getPlayer(); Block block = event.getBlockPlaced(); World world = player.getWorld(); String uuid = player.getUniqueId().toString();
List<String> list = Cyan1dex.cfgplayers.getStringList(uuid + ".bought");
0
2023-10-08 17:50:55+00:00
24k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/web/WomClient.java
[ { "identifier": "WomUtilsPlugin", "path": "src/main/java/net/wiseoldman/WomUtilsPlugin.java", "snippet": "@Slf4j\n@PluginDependency(XpUpdaterPlugin.class)\n@PluginDescriptor(\n\tname = \"Wise Old Man\",\n\ttags = {\"wom\", \"utils\", \"group\", \"xp\"},\n\tdescription = \"Helps you manage your wiseoldma...
import com.google.gson.Gson; import net.wiseoldman.WomUtilsPlugin; import net.wiseoldman.beans.GroupInfoWithMemberships; import net.wiseoldman.beans.NameChangeEntry; import net.wiseoldman.beans.ParticipantWithStanding; import net.wiseoldman.beans.WomStatus; import net.wiseoldman.beans.ParticipantWithCompetition; import net.wiseoldman.beans.GroupMemberAddition; import net.wiseoldman.beans.Member; import net.wiseoldman.beans.GroupMemberRemoval; import net.wiseoldman.beans.PlayerInfo; import net.wiseoldman.beans.WomPlayerUpdate; import net.wiseoldman.events.WomOngoingPlayerCompetitionsFetched; import net.wiseoldman.events.WomUpcomingPlayerCompetitionsFetched; import net.wiseoldman.ui.WomIconHandler; import net.wiseoldman.WomUtilsConfig; import net.wiseoldman.events.WomGroupMemberAdded; import net.wiseoldman.events.WomGroupMemberRemoved; import net.wiseoldman.events.WomGroupSynced; import java.awt.Color; import java.io.IOException; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.MessageNode; import net.runelite.api.events.ChatMessage; import net.runelite.client.callback.ClientThread; import net.runelite.client.chat.ChatColorType; import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.QueuedMessage; import net.runelite.client.eventbus.EventBus; import okhttp3.Callback; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response;
14,781
package net.wiseoldman.web; @Slf4j public class WomClient { @Inject private OkHttpClient okHttpClient; private Gson gson; @Inject
package net.wiseoldman.web; @Slf4j public class WomClient { @Inject private OkHttpClient okHttpClient; private Gson gson; @Inject
private WomIconHandler iconHandler;
13
2023-10-09 14:23:06+00:00
24k
PeytonPlayz595/c0.0.23a_01
src/main/java/com/mojang/minecraft/level/tile/Tile.java
[ { "identifier": "Entity", "path": "src/main/java/com/mojang/minecraft/Entity.java", "snippet": "public class Entity implements Serializable {\n\tpublic static final long serialVersionUID = 0L;\n\tprotected Level level;\n\tpublic float xo;\n\tpublic float yo;\n\tpublic float zo;\n\tpublic float x;\n\tpub...
import com.mojang.minecraft.Entity; import com.mojang.minecraft.level.Level; import com.mojang.minecraft.level.liquid.Liquid; import com.mojang.minecraft.particle.Particle; import com.mojang.minecraft.particle.ParticleEngine; import com.mojang.minecraft.phys.AABB; import com.mojang.minecraft.renderer.Tesselator; import java.util.Random;
19,140
package com.mojang.minecraft.level.tile; public class Tile { protected static Random random = new Random(); public static final Tile[] tiles = new Tile[256]; public static final boolean[] shouldTick = new boolean[256]; private static int[] tickSpeed = new int[256]; public static final Tile rock = (new Tile(1, 1)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile grass = (new GrassTile(2)).setSoundAndGravity(Tile.SoundType.grass, 0.9F, 1.0F); public static final Tile dirt = (new DirtTile(3, 2)).setSoundAndGravity(Tile.SoundType.grass, 0.8F, 1.0F); public static final Tile wood = (new Tile(4, 16)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile stoneBrick = (new Tile(5, 4)).setSoundAndGravity(Tile.SoundType.wood, 1.0F, 1.0F); public static final Tile bush = (new Bush(6, 15)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F); public static final Tile unbreakable = (new Tile(7, 17)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile water = (new LiquidTile(8, Liquid.water)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F); public static final Tile calmWater = (new CalmLiquidTile(9, Liquid.water)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F); public static final Tile lava = (new LiquidTile(10, Liquid.lava)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F); public static final Tile calmLava = (new CalmLiquidTile(11, Liquid.lava)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F); public static final Tile sand = (new FallingTile(12, 18)).setSoundAndGravity(Tile.SoundType.gravel, 0.8F, 1.0F); public static final Tile gravel = (new FallingTile(13, 19)).setSoundAndGravity(Tile.SoundType.gravel, 0.8F, 1.0F); public static final Tile oreGold = (new Tile(14, 32)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile oreIron = (new Tile(15, 33)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile oreCoal = (new Tile(16, 34)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile log = (new LogTile(17)).setSoundAndGravity(Tile.SoundType.wood, 1.0F, 1.0F); public static final Tile leaf = (new LeafTile(18, 22, true)).setSoundAndGravity(Tile.SoundType.grass, 1.0F, 0.4F); public static final Tile sponge = (new SpongeTile(19)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 0.9F); public static final Tile glass = (new GlassTile(20, 49, false)).setSoundAndGravity(Tile.SoundType.metal, 1.0F, 1.0F); public static final Tile clothRed = (new Tile(21, 64)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothOrange = (new Tile(22, 65)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothYellow = (new Tile(23, 66)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothChartreuse = (new Tile(24, 67)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothGreen = (new Tile(25, 68)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothSpringGreen = (new Tile(26, 69)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothCyan = (new Tile(27, 70)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothCapri = (new Tile(28, 71)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothUltramarine = (new Tile(29, 72)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothViolet = (new Tile(30, 73)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothPurple = (new Tile(31, 74)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothMagenta = (new Tile(32, 75)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothRose = (new Tile(33, 76)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothDarkGray = (new Tile(34, 77)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothGray = (new Tile(35, 78)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothWhite = (new Tile(36, 79)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile plantYellow = (new Bush(37, 13)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F); public static final Tile plantRed = (new Bush(38, 12)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F); public static final Tile mushroomBrown = (new Bush(39, 29)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F); public static final Tile mushroomRed = (new Bush(40, 28)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F); public static final Tile blockGold = (new Tile(41, 40)).setSoundAndGravity(Tile.SoundType.metal, 0.7F, 1.0F); public int tex; public final int id; public Tile.SoundType soundType; private float xx0; private float yy0; private float zz0; private float xx1; private float yy1; private float zz1; public float particleGravity; protected Tile(int var1) { tiles[var1] = this; this.id = var1; this.setShape(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } protected final Tile setSoundAndGravity(Tile.SoundType var1, float var2, float var3) { this.particleGravity = var3; this.soundType = var1; return this; } protected final void setTicking(boolean var1) { shouldTick[this.id] = var1; } protected final void setShape(float var1, float var2, float var3, float var4, float var5, float var6) { this.xx0 = var1; this.yy0 = var2; this.zz0 = var3; this.xx1 = var4; this.yy1 = var5; this.zz1 = var6; } protected Tile(int var1, int var2) { this(var1); this.tex = var2; } public final void setTickSpeed(int var1) { tickSpeed[this.id] = 16; }
package com.mojang.minecraft.level.tile; public class Tile { protected static Random random = new Random(); public static final Tile[] tiles = new Tile[256]; public static final boolean[] shouldTick = new boolean[256]; private static int[] tickSpeed = new int[256]; public static final Tile rock = (new Tile(1, 1)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile grass = (new GrassTile(2)).setSoundAndGravity(Tile.SoundType.grass, 0.9F, 1.0F); public static final Tile dirt = (new DirtTile(3, 2)).setSoundAndGravity(Tile.SoundType.grass, 0.8F, 1.0F); public static final Tile wood = (new Tile(4, 16)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile stoneBrick = (new Tile(5, 4)).setSoundAndGravity(Tile.SoundType.wood, 1.0F, 1.0F); public static final Tile bush = (new Bush(6, 15)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F); public static final Tile unbreakable = (new Tile(7, 17)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile water = (new LiquidTile(8, Liquid.water)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F); public static final Tile calmWater = (new CalmLiquidTile(9, Liquid.water)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F); public static final Tile lava = (new LiquidTile(10, Liquid.lava)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F); public static final Tile calmLava = (new CalmLiquidTile(11, Liquid.lava)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F); public static final Tile sand = (new FallingTile(12, 18)).setSoundAndGravity(Tile.SoundType.gravel, 0.8F, 1.0F); public static final Tile gravel = (new FallingTile(13, 19)).setSoundAndGravity(Tile.SoundType.gravel, 0.8F, 1.0F); public static final Tile oreGold = (new Tile(14, 32)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile oreIron = (new Tile(15, 33)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile oreCoal = (new Tile(16, 34)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F); public static final Tile log = (new LogTile(17)).setSoundAndGravity(Tile.SoundType.wood, 1.0F, 1.0F); public static final Tile leaf = (new LeafTile(18, 22, true)).setSoundAndGravity(Tile.SoundType.grass, 1.0F, 0.4F); public static final Tile sponge = (new SpongeTile(19)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 0.9F); public static final Tile glass = (new GlassTile(20, 49, false)).setSoundAndGravity(Tile.SoundType.metal, 1.0F, 1.0F); public static final Tile clothRed = (new Tile(21, 64)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothOrange = (new Tile(22, 65)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothYellow = (new Tile(23, 66)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothChartreuse = (new Tile(24, 67)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothGreen = (new Tile(25, 68)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothSpringGreen = (new Tile(26, 69)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothCyan = (new Tile(27, 70)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothCapri = (new Tile(28, 71)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothUltramarine = (new Tile(29, 72)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothViolet = (new Tile(30, 73)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothPurple = (new Tile(31, 74)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothMagenta = (new Tile(32, 75)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothRose = (new Tile(33, 76)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothDarkGray = (new Tile(34, 77)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothGray = (new Tile(35, 78)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile clothWhite = (new Tile(36, 79)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F); public static final Tile plantYellow = (new Bush(37, 13)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F); public static final Tile plantRed = (new Bush(38, 12)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F); public static final Tile mushroomBrown = (new Bush(39, 29)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F); public static final Tile mushroomRed = (new Bush(40, 28)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F); public static final Tile blockGold = (new Tile(41, 40)).setSoundAndGravity(Tile.SoundType.metal, 0.7F, 1.0F); public int tex; public final int id; public Tile.SoundType soundType; private float xx0; private float yy0; private float zz0; private float xx1; private float yy1; private float zz1; public float particleGravity; protected Tile(int var1) { tiles[var1] = this; this.id = var1; this.setShape(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } protected final Tile setSoundAndGravity(Tile.SoundType var1, float var2, float var3) { this.particleGravity = var3; this.soundType = var1; return this; } protected final void setTicking(boolean var1) { shouldTick[this.id] = var1; } protected final void setShape(float var1, float var2, float var3, float var4, float var5, float var6) { this.xx0 = var1; this.yy0 = var2; this.zz0 = var3; this.xx1 = var4; this.yy1 = var5; this.zz1 = var6; } protected Tile(int var1, int var2) { this(var1); this.tex = var2; } public final void setTickSpeed(int var1) { tickSpeed[this.id] = 16; }
public boolean render(Tesselator var1, Level var2, int var3, int var4, int var5, int var6) {
1
2023-10-10 17:10:45+00:00
24k
5152Alotobots/2024_Crescendo_Preseason
src/main/java/frc/robot/chargedup/commands/auto/singleelement/cone/Auto_middlebluecharge_1cone_Cmd.java
[ { "identifier": "Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj", "path": "src/main/java/frc/robot/library/drivetrains/commands/Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj.java", "snippet": "public class Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj extends CommandBase {\n /** Creates a new Cmd_SubSys_Dr...
import edu.wpi.first.wpilibj.DriverStation.Alliance; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.ParallelCommandGroup; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import frc.robot.library.drivetrains.commands.Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj; import frc.robot.chargedup.subsystems.arm.SubSys_Arm; import frc.robot.chargedup.subsystems.arm.commands.Cmd_SubSys_Arm_RotateAndExtend; import frc.robot.chargedup.subsystems.bling.SubSys_Bling; import frc.robot.chargedup.subsystems.bling.SubSys_Bling_Constants; import frc.robot.chargedup.subsystems.bling.commands.Cmd_SubSys_Bling_SetColorValue; import frc.robot.chargedup.subsystems.chargestation.commands.Cmd_SubSys_ChargeStation_Balance; import frc.robot.chargedup.subsystems.hand.SubSys_Hand; import frc.robot.library.drivetrains.SubSys_DriveTrain; import frc.robot.library.gyroscopes.pigeon2.SubSys_PigeonGyro;
17,012
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. /* __ __ _ _ _ _ \ \ / / | | /\ | | | | | | \ \ /\ / /_ _ _ _ | |_ ___ __ _ ___ / \ _ _| |_ ___ | |_ ___ __ _ _ __ ___ | | \ \/ \/ / _` | | | | | __/ _ \ / _` |/ _ \ / /\ \| | | | __/ _ \ | __/ _ \/ _` | '_ ` _ \| | \ /\ / (_| | |_| | | || (_) | | (_| | (_) | / ____ \ |_| | || (_) | | || __/ (_| | | | | | |_| \/ \/ \__,_|\__, | \__\___/ \__, |\___/ /_/ \_\__,_|\__\___/ \__\___|\__,_|_| |_| |_(_) __/ | __/ | |___/ |___/ */ package frc.robot.chargedup.commands.auto.singleelement.cone; /** * *Link For PathPlaner * * https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e65ac68f1d_0_48 */ public class Auto_middlebluecharge_1cone_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain; private final SubSys_PigeonGyro m_pigeonGyro; private final SubSys_Arm subsysArm; private final SubSys_Hand subsysHand; private final SubSys_Bling blingSubSys; /** Creates a new Auto_Challenge1_Cmd. */ public Auto_middlebluecharge_1cone_Cmd( SubSys_DriveTrain driveSubSys, SubSys_PigeonGyro pigeonGyro, SubSys_Arm arm, SubSys_Hand hand, SubSys_Bling bling) { m_DriveTrain = driveSubSys; m_pigeonGyro = pigeonGyro; subsysArm = arm; subsysHand = hand; blingSubSys = bling; /* Construct parallel command groups */ ParallelCommandGroup driveAndRetractArm = new ParallelCommandGroup( new Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj( driveSubSys, "middlecharge_1cone", true, true, Alliance.Blue), new Cmd_SubSys_Arm_RotateAndExtend(subsysArm, 10.0, true, 0.8, true).withTimeout(4)); // Add your commands in the addCommands() call, e.g. // addCommands(new FooCommand(), new BarCommand()); addCommands( new Cmd_SubSys_Arm_RotateAndExtend(subsysArm, -147.0, true, 1.54, true) .withTimeout(4), // Lift arm to high position new WaitCommand(1.5), // Add buffer time new InstantCommand(subsysHand::CloseHand, subsysHand), // Open hand (reversed) driveAndRetractArm, // Drive to charge station whilst retracting arm new Cmd_SubSys_ChargeStation_Balance(pigeonGyro, driveSubSys), // Balance on charge station
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. /* __ __ _ _ _ _ \ \ / / | | /\ | | | | | | \ \ /\ / /_ _ _ _ | |_ ___ __ _ ___ / \ _ _| |_ ___ | |_ ___ __ _ _ __ ___ | | \ \/ \/ / _` | | | | | __/ _ \ / _` |/ _ \ / /\ \| | | | __/ _ \ | __/ _ \/ _` | '_ ` _ \| | \ /\ / (_| | |_| | | || (_) | | (_| | (_) | / ____ \ |_| | || (_) | | || __/ (_| | | | | | |_| \/ \/ \__,_|\__, | \__\___/ \__, |\___/ /_/ \_\__,_|\__\___/ \__\___|\__,_|_| |_| |_(_) __/ | __/ | |___/ |___/ */ package frc.robot.chargedup.commands.auto.singleelement.cone; /** * *Link For PathPlaner * * https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e65ac68f1d_0_48 */ public class Auto_middlebluecharge_1cone_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain; private final SubSys_PigeonGyro m_pigeonGyro; private final SubSys_Arm subsysArm; private final SubSys_Hand subsysHand; private final SubSys_Bling blingSubSys; /** Creates a new Auto_Challenge1_Cmd. */ public Auto_middlebluecharge_1cone_Cmd( SubSys_DriveTrain driveSubSys, SubSys_PigeonGyro pigeonGyro, SubSys_Arm arm, SubSys_Hand hand, SubSys_Bling bling) { m_DriveTrain = driveSubSys; m_pigeonGyro = pigeonGyro; subsysArm = arm; subsysHand = hand; blingSubSys = bling; /* Construct parallel command groups */ ParallelCommandGroup driveAndRetractArm = new ParallelCommandGroup( new Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj( driveSubSys, "middlecharge_1cone", true, true, Alliance.Blue), new Cmd_SubSys_Arm_RotateAndExtend(subsysArm, 10.0, true, 0.8, true).withTimeout(4)); // Add your commands in the addCommands() call, e.g. // addCommands(new FooCommand(), new BarCommand()); addCommands( new Cmd_SubSys_Arm_RotateAndExtend(subsysArm, -147.0, true, 1.54, true) .withTimeout(4), // Lift arm to high position new WaitCommand(1.5), // Add buffer time new InstantCommand(subsysHand::CloseHand, subsysHand), // Open hand (reversed) driveAndRetractArm, // Drive to charge station whilst retracting arm new Cmd_SubSys_ChargeStation_Balance(pigeonGyro, driveSubSys), // Balance on charge station
new Cmd_SubSys_Bling_SetColorValue(
5
2023-10-09 00:27:11+00:00
24k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/agent/server/Server.java
[ { "identifier": "RootHandler", "path": "src/main/java/com/monitor/agent/server/handler/RootHandler.java", "snippet": "public class RootHandler extends DefaultResponder {\r\n\r\n @Override\r\n public NanoHTTPD.Response get(\r\n RouterNanoHTTPD.UriResource uriResource, \r\n Map...
import com.monitor.agent.server.handler.RootHandler; import com.monitor.agent.server.handler.LogRecordsHandler; import com.monitor.agent.server.handler.NotFoundHandler; import com.monitor.agent.server.handler.AckHandler; import com.fasterxml.jackson.databind.JsonMappingException; import com.monitor.agent.server.handler.ConfigHandler; import com.monitor.agent.server.handler.WatchMapHandler; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.router.RouterNanoHTTPD; import static org.apache.log4j.Level.*; import java.io.IOException; import com.monitor.agent.server.config.ConfigurationManager; import com.monitor.agent.server.config.FilesConfig; import com.monitor.agent.server.config.OneCServerConfig; import com.monitor.agent.server.handler.AccessibilityHandler; import com.monitor.agent.server.handler.ContinueServerHandler; import com.monitor.agent.server.handler.DefaultResponder; import com.monitor.agent.server.handler.ExecQueryHandler; import com.monitor.agent.server.handler.TJLogConfigHandler; import com.monitor.agent.server.handler.OneCSessionsInfoHandler; import com.monitor.agent.server.handler.PauseServerHandler; import com.monitor.agent.server.handler.PingHandler; import com.monitor.agent.server.handler.StopServerHandler; import com.monitor.agent.server.handler.VersionHandler; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.concurrent.Semaphore; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.log4j.Appender; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.RollingFileAppender; import org.apache.log4j.spi.RootLogger;
18,200
package com.monitor.agent.server; /* * Copyright 2015 Didier Fetter * Copyright 2021 Aleksei Andreev * * 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. * * Changes by Aleksei Andreev: * - almost all code except option processing was rewriten * */ public class Server { private static final Logger logger = Logger.getLogger(Server.class); private static final String AGENT_VERSION = "2.6.3"; private static final String SINCEDB = ".monitor-remote-agent"; private static final String SINCEDB_CAT = "sincedb"; private static Level logLevel = INFO; private RouterNanoHTTPD httpd; private int starterPort = 0; private int port = 8085; private int spoolSize = 1024; private String config; private ConfigurationManager configManager; private int signatureLength = 4096; private boolean tailSelected = false; private String sincedbFile = SINCEDB; private boolean debugWatcherSelected = false; private String stopRoute = "/shutdown"; private boolean stopServer = false; private String logfile = null; private String logfileSize = "10MB"; private int logfileNumber = 5; private final Semaphore pauseLock = new Semaphore(1); private final HashMap<Section, FileWatcher> watchers = new HashMap<>(); public static boolean isCaseInsensitiveFileSystem() { return System.getProperty("os.name").toLowerCase().startsWith("win"); } public static String version() { return AGENT_VERSION; } @SuppressWarnings({"UseSpecificCatch", "CallToPrintStackTrace"}) public static void main(String[] args) { try { Server server = new Server(); server.parseOptions(args); if (server.stopServer) { server.sendStop(); return; } server.setupLogging(); server.initializeFileWatchers(); server.startServer(); } catch (Exception e) { e.printStackTrace(); System.exit(3); } } public Server() { } private void startServer() throws IOException { new File(SINCEDB_CAT).mkdir(); httpd = new RouterNanoHTTPD(port); httpd.addRoute("/", RootHandler.class); httpd.addRoute("/ping", PingHandler.class); httpd.addRoute("/version", VersionHandler.class); httpd.addRoute("/pause", PauseServerHandler.class, this);
package com.monitor.agent.server; /* * Copyright 2015 Didier Fetter * Copyright 2021 Aleksei Andreev * * 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. * * Changes by Aleksei Andreev: * - almost all code except option processing was rewriten * */ public class Server { private static final Logger logger = Logger.getLogger(Server.class); private static final String AGENT_VERSION = "2.6.3"; private static final String SINCEDB = ".monitor-remote-agent"; private static final String SINCEDB_CAT = "sincedb"; private static Level logLevel = INFO; private RouterNanoHTTPD httpd; private int starterPort = 0; private int port = 8085; private int spoolSize = 1024; private String config; private ConfigurationManager configManager; private int signatureLength = 4096; private boolean tailSelected = false; private String sincedbFile = SINCEDB; private boolean debugWatcherSelected = false; private String stopRoute = "/shutdown"; private boolean stopServer = false; private String logfile = null; private String logfileSize = "10MB"; private int logfileNumber = 5; private final Semaphore pauseLock = new Semaphore(1); private final HashMap<Section, FileWatcher> watchers = new HashMap<>(); public static boolean isCaseInsensitiveFileSystem() { return System.getProperty("os.name").toLowerCase().startsWith("win"); } public static String version() { return AGENT_VERSION; } @SuppressWarnings({"UseSpecificCatch", "CallToPrintStackTrace"}) public static void main(String[] args) { try { Server server = new Server(); server.parseOptions(args); if (server.stopServer) { server.sendStop(); return; } server.setupLogging(); server.initializeFileWatchers(); server.startServer(); } catch (Exception e) { e.printStackTrace(); System.exit(3); } } public Server() { } private void startServer() throws IOException { new File(SINCEDB_CAT).mkdir(); httpd = new RouterNanoHTTPD(port); httpd.addRoute("/", RootHandler.class); httpd.addRoute("/ping", PingHandler.class); httpd.addRoute("/version", VersionHandler.class); httpd.addRoute("/pause", PauseServerHandler.class, this);
httpd.addRoute("/continue", ContinueServerHandler.class, this);
10
2023-10-11 20:25:12+00:00
24k
giteecode/bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/appllication/LibraryBookController.java
[ { "identifier": "SysUser", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/entity/SysUser.java", "snippet": "public class SysUser extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 用户ID */\n @Excel(name = \"用户序号\", cellType = ColumnType.NUMERIC, pro...
import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.nhXJH.common.core.domain.entity.SysUser; import com.nhXJH.common.core.domain.model.LoginUser; import com.nhXJH.system.service.ISysUserService; import com.nhXJH.web.domain.BaseFile; import com.nhXJH.web.domain.LibraryBook; import com.nhXJH.web.domain.dto.LibraryBookDto; import com.nhXJH.web.domain.dto.SearchBookDto; import com.nhXJH.web.domain.param.BookFileParam; import com.nhXJH.web.domain.vo.BookVO; import com.nhXJH.web.service.ILibraryBookService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.aspectj.weaver.loadtime.Aj; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.nhXJH.common.annotation.Log; import com.nhXJH.common.core.controller.BaseController; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.enums.BusinessType; import com.nhXJH.common.utils.poi.ExcelUtil; import com.nhXJH.common.core.page.TableDataInfo; import org.springframework.web.multipart.MultipartFile;
20,678
package com.nhXJH.web.controller.appllication; /** * 图书实体信息Controller * * @author xjh * @date 2022-02-07 */ @RestController @RequestMapping("/userApplication/book") @Api(tags = {"图书实体信息"}) public class LibraryBookController extends BaseController { @Autowired private ILibraryBookService libraryBookService; @Autowired
package com.nhXJH.web.controller.appllication; /** * 图书实体信息Controller * * @author xjh * @date 2022-02-07 */ @RestController @RequestMapping("/userApplication/book") @Api(tags = {"图书实体信息"}) public class LibraryBookController extends BaseController { @Autowired private ILibraryBookService libraryBookService; @Autowired
private ISysUserService userService;
2
2023-10-13 07:19:20+00:00
24k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/client/sounds/hum/ClientCreakHandler.java
[ { "identifier": "LoopingSound", "path": "src/main/java/mdteam/ait/client/sounds/LoopingSound.java", "snippet": "@Environment(EnvType.CLIENT)\npublic abstract class LoopingSound extends MovingSoundInstance {\n public LoopingSound(SoundEvent soundEvent, SoundCategory soundCategory) {\n super(sou...
import mdteam.ait.client.sounds.LoopingSound; import mdteam.ait.client.sounds.PlayerFollowingLoopingSound; import mdteam.ait.client.sounds.PlayerFollowingSound; import mdteam.ait.client.util.ClientTardisUtil; import mdteam.ait.core.AITDimensions; import mdteam.ait.registry.CreakRegistry; import mdteam.ait.registry.HumsRegistry; import mdteam.ait.tardis.Tardis; import mdteam.ait.tardis.handler.ServerHumHandler; import mdteam.ait.tardis.handler.properties.PropertiesHandler; import mdteam.ait.tardis.sound.CreakSound; import mdteam.ait.tardis.sound.HumSound; import mdteam.ait.tardis.util.AbsoluteBlockPos; import mdteam.ait.tardis.util.SoundHandler; import mdteam.ait.tardis.util.TardisUtil; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.client.sound.PositionedSoundInstance; import net.minecraft.client.sound.SoundInstance; import net.minecraft.network.PacketByteBuf; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import java.util.ArrayList; import java.util.List; import java.util.Random; import static mdteam.ait.AITMod.AIT_CONFIG;
15,104
package mdteam.ait.client.sounds.hum; public class ClientCreakHandler extends SoundHandler { private static final Random random = new Random(); protected ClientCreakHandler() {} public static ClientCreakHandler create() { if (MinecraftClient.getInstance().player == null) return null; ClientCreakHandler handler = new ClientCreakHandler(); handler.generateCreaks(); return handler; } private void generateCreaks() { this.sounds = new ArrayList<>(); this.sounds.addAll(registryToList()); } /** * Converts all the {@link CreakSound}'s in the {@link CreakRegistry} to {@link LoopingSound} so they are usable * * @return A list of {@link LoopingSound} from the {@link CreakRegistry} */ private List<LoopingSound> registryToList() { List<LoopingSound> list = new ArrayList<>(); for (CreakSound sound : CreakRegistry.REGISTRY) { list.add(new PlayerFollowingLoopingSound(sound.sound(), SoundCategory.AMBIENT, AIT_CONFIG.INTERIOR_HUM_VOLUME())); } return list; } public boolean isPlayerInATardis() { if (MinecraftClient.getInstance().world == null || MinecraftClient.getInstance().world.getRegistryKey() != AITDimensions.TARDIS_DIM_WORLD) return false; ClientPlayerEntity player = MinecraftClient.getInstance().player; Tardis found = TardisUtil.findTardisByInterior(player.getBlockPos()); return found != null; } public BlockPos randomNearConsolePos(AbsoluteBlockPos.Directed consolePos) { return consolePos.add(random.nextInt(8) - 1, 0, random.nextInt(8) - 1); } public Tardis tardis() { ClientPlayerEntity player = MinecraftClient.getInstance().player; if (player == null) return null; Tardis found = TardisUtil.findTardisByInterior(player.getBlockPos()); return found; } public void playRandomCreak() { CreakSound chosen = CreakRegistry.getRandomCreak(); if(chosen.equals(CreakRegistry.WHISPER) && ClientTardisUtil.getCurrentTardis().getDesktop().getConsolePos() != null) { startIfNotPlaying(new PositionedSoundInstance(chosen.sound(), SoundCategory.HOSTILE, 0.5f, 1.0f, net.minecraft.util.math.random.Random.create(), randomNearConsolePos(ClientTardisUtil.getCurrentTardis().getDesktop().getConsolePos()))); return; }
package mdteam.ait.client.sounds.hum; public class ClientCreakHandler extends SoundHandler { private static final Random random = new Random(); protected ClientCreakHandler() {} public static ClientCreakHandler create() { if (MinecraftClient.getInstance().player == null) return null; ClientCreakHandler handler = new ClientCreakHandler(); handler.generateCreaks(); return handler; } private void generateCreaks() { this.sounds = new ArrayList<>(); this.sounds.addAll(registryToList()); } /** * Converts all the {@link CreakSound}'s in the {@link CreakRegistry} to {@link LoopingSound} so they are usable * * @return A list of {@link LoopingSound} from the {@link CreakRegistry} */ private List<LoopingSound> registryToList() { List<LoopingSound> list = new ArrayList<>(); for (CreakSound sound : CreakRegistry.REGISTRY) { list.add(new PlayerFollowingLoopingSound(sound.sound(), SoundCategory.AMBIENT, AIT_CONFIG.INTERIOR_HUM_VOLUME())); } return list; } public boolean isPlayerInATardis() { if (MinecraftClient.getInstance().world == null || MinecraftClient.getInstance().world.getRegistryKey() != AITDimensions.TARDIS_DIM_WORLD) return false; ClientPlayerEntity player = MinecraftClient.getInstance().player; Tardis found = TardisUtil.findTardisByInterior(player.getBlockPos()); return found != null; } public BlockPos randomNearConsolePos(AbsoluteBlockPos.Directed consolePos) { return consolePos.add(random.nextInt(8) - 1, 0, random.nextInt(8) - 1); } public Tardis tardis() { ClientPlayerEntity player = MinecraftClient.getInstance().player; if (player == null) return null; Tardis found = TardisUtil.findTardisByInterior(player.getBlockPos()); return found; } public void playRandomCreak() { CreakSound chosen = CreakRegistry.getRandomCreak(); if(chosen.equals(CreakRegistry.WHISPER) && ClientTardisUtil.getCurrentTardis().getDesktop().getConsolePos() != null) { startIfNotPlaying(new PositionedSoundInstance(chosen.sound(), SoundCategory.HOSTILE, 0.5f, 1.0f, net.minecraft.util.math.random.Random.create(), randomNearConsolePos(ClientTardisUtil.getCurrentTardis().getDesktop().getConsolePos()))); return; }
PlayerFollowingSound following = new PlayerFollowingSound(chosen.sound(), SoundCategory.AMBIENT, AIT_CONFIG.INTERIOR_HUM_VOLUME());
2
2023-10-08 00:38:53+00:00
24k
jianjian3219/044_bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/appllication/LibraryMechanismController.java
[ { "identifier": "RedisCache", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/redis/RedisCache.java", "snippet": "@SuppressWarnings(value = { \"unchecked\", \"rawtypes\" })\n@Component\npublic class RedisCache {\n @Autowired\n public RedisTemplate redisTemplate;\n\n /**\n * 缓存基本的对...
import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.nhXJH.common.core.redis.RedisCache; import com.nhXJH.common.enums.application.StatusEnums; import com.nhXJH.common.enums.application.TableTypeEnums; import com.nhXJH.web.domain.BaseFile; import com.nhXJH.web.domain.LibraryMechanism; import com.nhXJH.web.domain.param.GetFileParam; import com.nhXJH.web.domain.param.MechanismParam; import com.nhXJH.web.domain.param.RefulshMechaismFileParam; import com.nhXJH.web.domain.vo.FileVo; import com.nhXJH.web.domain.vo.GetFileVO; import com.nhXJH.web.domain.vo.MechanismVO; import com.nhXJH.web.service.IBaseFileService; import com.nhXJH.web.service.ILibraryMechanismService; import com.nhXJH.web.util.tokenizer.Tokenizer; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.nhXJH.common.annotation.Log; import com.nhXJH.common.core.controller.BaseController; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.enums.BusinessType; import com.nhXJH.common.utils.poi.ExcelUtil; import com.nhXJH.common.core.page.TableDataInfo;
18,479
package com.nhXJH.web.controller.appllication; /** * 图书管理机构信息Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/mechanism") @Api(tags = {"图书管理机构信息"}) public class LibraryMechanismController extends BaseController { @Autowired private ILibraryMechanismService libraryMechanismService; @Autowired private IBaseFileService baseFileService; @Autowired private RedisCache redisCache; @Value("${redisCache.timeOut.mechanismTag:1800}") Long mechanismTagTimeOut; /** * 查询图书管理机构信息列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:list')") @GetMapping("/list") @ApiOperation(value ="查询图书管理机构信息列表",notes = "查询图书管理机构信息列表") public TableDataInfo list(MechanismParam libraryMechanism) { List<LibraryMechanism> mechanisms = libraryMechanismService.selectLibraryMechanismList(libraryMechanism); Integer total = null== mechanisms ? 0:mechanisms.size(); startPage(); List<MechanismVO> list = libraryMechanismService.selectLibraryMechanismVOList(libraryMechanism); TableDataInfo info = getDataTable(list); info.setTotal(total); return info; } /** * 导出图书管理机构信息列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:export')") @Log(title = "图书管理机构信息", businessType = BusinessType.EXPORT) @PostMapping("/export") @ApiOperation(value ="导出图书管理机构信息列表",notes = "导出图书管理机构信息列表") public void export(HttpServletResponse response, MechanismParam libraryMechanism) { List<LibraryMechanism> list = libraryMechanismService.selectLibraryMechanismList(libraryMechanism); ExcelUtil<LibraryMechanism> util = new ExcelUtil<LibraryMechanism>(LibraryMechanism.class); util.exportExcel(response, list, "图书管理机构信息数据"); } /** * 获取图书管理机构信息详细信息 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:query')") @GetMapping(value = "/{id}") @ApiOperation(value ="获取图书管理机构信息详细信息",notes = "获取图书管理机构信息详细信息") public AjaxResult getInfo(@PathVariable("id") Long id) { return AjaxResult.success(libraryMechanismService.selectLibraryMechanismById(id)); } /** * 新增图书管理机构信息 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:add')") @Log(title = "图书管理机构信息", businessType = BusinessType.INSERT) @PostMapping @ApiOperation(value ="新增图书管理机构信息",notes = "新增图书管理机构信息") public AjaxResult add(@RequestBody MechanismParam libraryMechanism) { libraryMechanism.setCreatePersonal(getUserId()); libraryMechanism.setCreateBy(getUsername()); libraryMechanism.setCreateTime(new Date()); libraryMechanism.setId(libraryMechanism.getSnowID()); return toAjax(libraryMechanismService.insertLibraryMechanism(libraryMechanism)); } /** * 修改图书管理机构信息 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:edit')") @Log(title = "图书管理机构信息", businessType = BusinessType.UPDATE) @PutMapping @ApiOperation(value ="修改图书管理机构信息",notes = "修改图书管理机构信息") public AjaxResult edit(@RequestBody LibraryMechanism libraryMechanism) { libraryMechanism.setUpdatePersonal(getUserId()); libraryMechanism.setUpdateTime(new Date()); return toAjax(libraryMechanismService.updateLibraryMechanism(libraryMechanism)); } /** * 删除图书管理机构信息 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:remove')") @Log(title = "图书管理机构信息", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") @ApiOperation(value ="删除图书管理机构信息",notes = "删除图书管理机构信息") public AjaxResult remove(@PathVariable Long[] ids) { return toAjax(libraryMechanismService.deleteLibraryMechanismByIds(ids)); } /** * 修改信息状态 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:modify')") @Log(title = "修改实体信息状态", businessType = BusinessType.UPDATE) @PutMapping("/changeStatus") @ApiOperation(value ="修改实体信息状态",notes = "修改实体信息状态") public AjaxResult changeStatus(@RequestBody LibraryMechanism mechanism){ // userService.checkUserAllowed(); mechanism.setUpdateBy(getUsername()); mechanism.setUpdatePersonal(getUserId()); return toAjax(libraryMechanismService.updateUserStatus(mechanism)); } /** * 查询附件实体对应信息列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:file:list')") @Log(title = "查询附件实体对应信息列表", businessType = BusinessType.OTHER) @GetMapping("/getFile/{id}") @ApiOperation(value ="查询附件实体对应信息列表",notes = "查询附件实体对应信息列表") public AjaxResult getFile(@PathVariable("id") Long id) { BaseFile baseFile = new BaseFile(); baseFile.setModelId(id); baseFile.setDbId(TableTypeEnums.MECHANISM.getCode());
package com.nhXJH.web.controller.appllication; /** * 图书管理机构信息Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/mechanism") @Api(tags = {"图书管理机构信息"}) public class LibraryMechanismController extends BaseController { @Autowired private ILibraryMechanismService libraryMechanismService; @Autowired private IBaseFileService baseFileService; @Autowired private RedisCache redisCache; @Value("${redisCache.timeOut.mechanismTag:1800}") Long mechanismTagTimeOut; /** * 查询图书管理机构信息列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:list')") @GetMapping("/list") @ApiOperation(value ="查询图书管理机构信息列表",notes = "查询图书管理机构信息列表") public TableDataInfo list(MechanismParam libraryMechanism) { List<LibraryMechanism> mechanisms = libraryMechanismService.selectLibraryMechanismList(libraryMechanism); Integer total = null== mechanisms ? 0:mechanisms.size(); startPage(); List<MechanismVO> list = libraryMechanismService.selectLibraryMechanismVOList(libraryMechanism); TableDataInfo info = getDataTable(list); info.setTotal(total); return info; } /** * 导出图书管理机构信息列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:export')") @Log(title = "图书管理机构信息", businessType = BusinessType.EXPORT) @PostMapping("/export") @ApiOperation(value ="导出图书管理机构信息列表",notes = "导出图书管理机构信息列表") public void export(HttpServletResponse response, MechanismParam libraryMechanism) { List<LibraryMechanism> list = libraryMechanismService.selectLibraryMechanismList(libraryMechanism); ExcelUtil<LibraryMechanism> util = new ExcelUtil<LibraryMechanism>(LibraryMechanism.class); util.exportExcel(response, list, "图书管理机构信息数据"); } /** * 获取图书管理机构信息详细信息 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:query')") @GetMapping(value = "/{id}") @ApiOperation(value ="获取图书管理机构信息详细信息",notes = "获取图书管理机构信息详细信息") public AjaxResult getInfo(@PathVariable("id") Long id) { return AjaxResult.success(libraryMechanismService.selectLibraryMechanismById(id)); } /** * 新增图书管理机构信息 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:add')") @Log(title = "图书管理机构信息", businessType = BusinessType.INSERT) @PostMapping @ApiOperation(value ="新增图书管理机构信息",notes = "新增图书管理机构信息") public AjaxResult add(@RequestBody MechanismParam libraryMechanism) { libraryMechanism.setCreatePersonal(getUserId()); libraryMechanism.setCreateBy(getUsername()); libraryMechanism.setCreateTime(new Date()); libraryMechanism.setId(libraryMechanism.getSnowID()); return toAjax(libraryMechanismService.insertLibraryMechanism(libraryMechanism)); } /** * 修改图书管理机构信息 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:edit')") @Log(title = "图书管理机构信息", businessType = BusinessType.UPDATE) @PutMapping @ApiOperation(value ="修改图书管理机构信息",notes = "修改图书管理机构信息") public AjaxResult edit(@RequestBody LibraryMechanism libraryMechanism) { libraryMechanism.setUpdatePersonal(getUserId()); libraryMechanism.setUpdateTime(new Date()); return toAjax(libraryMechanismService.updateLibraryMechanism(libraryMechanism)); } /** * 删除图书管理机构信息 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:remove')") @Log(title = "图书管理机构信息", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") @ApiOperation(value ="删除图书管理机构信息",notes = "删除图书管理机构信息") public AjaxResult remove(@PathVariable Long[] ids) { return toAjax(libraryMechanismService.deleteLibraryMechanismByIds(ids)); } /** * 修改信息状态 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:mechanism:modify')") @Log(title = "修改实体信息状态", businessType = BusinessType.UPDATE) @PutMapping("/changeStatus") @ApiOperation(value ="修改实体信息状态",notes = "修改实体信息状态") public AjaxResult changeStatus(@RequestBody LibraryMechanism mechanism){ // userService.checkUserAllowed(); mechanism.setUpdateBy(getUsername()); mechanism.setUpdatePersonal(getUserId()); return toAjax(libraryMechanismService.updateUserStatus(mechanism)); } /** * 查询附件实体对应信息列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:file:list')") @Log(title = "查询附件实体对应信息列表", businessType = BusinessType.OTHER) @GetMapping("/getFile/{id}") @ApiOperation(value ="查询附件实体对应信息列表",notes = "查询附件实体对应信息列表") public AjaxResult getFile(@PathVariable("id") Long id) { BaseFile baseFile = new BaseFile(); baseFile.setModelId(id); baseFile.setDbId(TableTypeEnums.MECHANISM.getCode());
List<FileVo> list = baseFileService.getFile(baseFile);
8
2023-10-14 04:57:42+00:00
24k
codegrits/CodeGRITS
src/main/java/actions/StartStopTrackingAction.java
[ { "identifier": "ConfigDialog", "path": "src/main/java/components/ConfigDialog.java", "snippet": "public class ConfigDialog extends DialogWrapper {\n\n private List<JCheckBox> checkBoxes;\n\n private final JPanel panel = new JPanel();\n private static List<JTextField> labelAreas = new ArrayList...
import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import components.ConfigDialog; import entity.Config; import org.jetbrains.annotations.NotNull; import trackers.EyeTracker; import trackers.IDETracker; import trackers.ScreenRecorder; import utils.AvailabilityChecker; import javax.swing.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.IOException; import java.util.Objects;
17,955
package actions; /** * This class is the action for starting/stopping tracking. */ public class StartStopTrackingAction extends AnAction { /** * This variable indicates whether the tracking is started. */ private static boolean isTracking = false; /** * This variable is the IDE tracker. */ private static IDETracker iDETracker; /** * This variable is the eye tracker. */ private static EyeTracker eyeTracker; /** * This variable is the screen recorder. */ private final ScreenRecorder screenRecorder = ScreenRecorder.getInstance(); /** * This variable is the configuration. */ Config config = new Config(); /** * Update the text of the action button. * * @param e The action event. */ @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setText(isTracking ? "Stop Tracking" : "Start Tracking"); } /** * This method is called when the action is performed. It will start/stop tracking. * * @param e The action event. */ @Override public void actionPerformed(@NotNull AnActionEvent e) { if (config.configExists()) { config.loadFromJson(); } else { Notification notification = new Notification("CodeGRITS Notification Group", "Configuration", "Please configure the plugin first.", NotificationType.WARNING); notification.notify(e.getProject()); return; } try { if (!isTracking) { if (config.getCheckBoxes().get(1)) { if (!AvailabilityChecker.checkPythonEnvironment(config.getPythonInterpreter())) { JOptionPane.showMessageDialog(null, "Python interpreter not found. Please configure the plugin first."); return; } if (config.getEyeTrackerDevice() != 0 && !AvailabilityChecker.checkEyeTracker(config.getPythonInterpreter())) { JOptionPane.showMessageDialog(null, "Eye tracker not found. Please configure the mouse simulation first."); return; } } isTracking = true; ConfigAction.setIsEnabled(false); AddLabelActionGroup.setIsEnabled(true); String projectPath = e.getProject() != null ? e.getProject().getBasePath() : "";
package actions; /** * This class is the action for starting/stopping tracking. */ public class StartStopTrackingAction extends AnAction { /** * This variable indicates whether the tracking is started. */ private static boolean isTracking = false; /** * This variable is the IDE tracker. */ private static IDETracker iDETracker; /** * This variable is the eye tracker. */ private static EyeTracker eyeTracker; /** * This variable is the screen recorder. */ private final ScreenRecorder screenRecorder = ScreenRecorder.getInstance(); /** * This variable is the configuration. */ Config config = new Config(); /** * Update the text of the action button. * * @param e The action event. */ @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setText(isTracking ? "Stop Tracking" : "Start Tracking"); } /** * This method is called when the action is performed. It will start/stop tracking. * * @param e The action event. */ @Override public void actionPerformed(@NotNull AnActionEvent e) { if (config.configExists()) { config.loadFromJson(); } else { Notification notification = new Notification("CodeGRITS Notification Group", "Configuration", "Please configure the plugin first.", NotificationType.WARNING); notification.notify(e.getProject()); return; } try { if (!isTracking) { if (config.getCheckBoxes().get(1)) { if (!AvailabilityChecker.checkPythonEnvironment(config.getPythonInterpreter())) { JOptionPane.showMessageDialog(null, "Python interpreter not found. Please configure the plugin first."); return; } if (config.getEyeTrackerDevice() != 0 && !AvailabilityChecker.checkEyeTracker(config.getPythonInterpreter())) { JOptionPane.showMessageDialog(null, "Eye tracker not found. Please configure the mouse simulation first."); return; } } isTracking = true; ConfigAction.setIsEnabled(false); AddLabelActionGroup.setIsEnabled(true); String projectPath = e.getProject() != null ? e.getProject().getBasePath() : "";
String realDataOutputPath = Objects.equals(config.getDataOutputPath(), ConfigDialog.selectDataOutputPlaceHolder)
0
2023-10-12 15:40:39+00:00
24k
giteecode/supermarket2Public
src/main/java/com/ruoyi/project/system/post/service/PostServiceImpl.java
[ { "identifier": "UserConstants", "path": "src/main/java/com/ruoyi/common/constant/UserConstants.java", "snippet": "public class UserConstants\n{\n /** 正常状态 */\n public static final String NORMAL = \"0\";\n\n /** 异常状态 */\n public static final String EXCEPTION = \"1\";\n\n /** 用户封禁状态 */\n ...
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.ShiroUtils; import com.ruoyi.common.utils.text.Convert; import com.ruoyi.project.system.post.domain.Post; import com.ruoyi.project.system.post.mapper.PostMapper; import com.ruoyi.project.system.user.mapper.UserPostMapper;
16,153
package com.ruoyi.project.system.post.service; /** * 岗位信息 服务层处理 * * @author ruoyi */ @Service public class PostServiceImpl implements IPostService { @Autowired private PostMapper postMapper; @Autowired private UserPostMapper userPostMapper; /** * 查询岗位信息集合 * * @param post 岗位信息 * @return 岗位信息集合 */ @Override public List<Post> selectPostList(Post post) { return postMapper.selectPostList(post); } /** * 查询所有岗位 * * @return 岗位列表 */ @Override public List<Post> selectPostAll() { return postMapper.selectPostAll(); } /** * 根据用户ID查询岗位 * * @param userId 用户ID * @return 岗位列表 */ @Override public List<Post> selectPostsByUserId(Long userId) { List<Post> userPosts = postMapper.selectPostsByUserId(userId); List<Post> posts = postMapper.selectPostAll(); for (Post post : posts) { for (Post userRole : userPosts) { if (post.getPostId().longValue() == userRole.getPostId().longValue()) { post.setFlag(true); break; } } } return posts; } /** * 通过岗位ID查询岗位信息 * * @param postId 岗位ID * @return 角色对象信息 */ @Override public Post selectPostById(Long postId) { return postMapper.selectPostById(postId); } /** * 批量删除岗位信息 * * @param ids 需要删除的数据ID * @return 结果 */ @Override public int deletePostByIds(String ids) {
package com.ruoyi.project.system.post.service; /** * 岗位信息 服务层处理 * * @author ruoyi */ @Service public class PostServiceImpl implements IPostService { @Autowired private PostMapper postMapper; @Autowired private UserPostMapper userPostMapper; /** * 查询岗位信息集合 * * @param post 岗位信息 * @return 岗位信息集合 */ @Override public List<Post> selectPostList(Post post) { return postMapper.selectPostList(post); } /** * 查询所有岗位 * * @return 岗位列表 */ @Override public List<Post> selectPostAll() { return postMapper.selectPostAll(); } /** * 根据用户ID查询岗位 * * @param userId 用户ID * @return 岗位列表 */ @Override public List<Post> selectPostsByUserId(Long userId) { List<Post> userPosts = postMapper.selectPostsByUserId(userId); List<Post> posts = postMapper.selectPostAll(); for (Post post : posts) { for (Post userRole : userPosts) { if (post.getPostId().longValue() == userRole.getPostId().longValue()) { post.setFlag(true); break; } } } return posts; } /** * 通过岗位ID查询岗位信息 * * @param postId 岗位ID * @return 角色对象信息 */ @Override public Post selectPostById(Long postId) { return postMapper.selectPostById(postId); } /** * 批量删除岗位信息 * * @param ids 需要删除的数据ID * @return 结果 */ @Override public int deletePostByIds(String ids) {
Long[] postIds = Convert.toLongArray(ids);
4
2023-10-14 02:27:47+00:00
24k
lukas-mb/ABAP-SQL-Beautifier
ABAP SQL Beautifier/src/com/abap/sql/beautifier/StatementProcessor.java
[ { "identifier": "PreferenceConstants", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/preferences/PreferenceConstants.java", "snippet": "public class PreferenceConstants {\n\n\tpublic static final String ALLIGN_OPERS = \"ALLIGN_OPERS\";\n\n\tpublic static final String COMBINE_CHAR_LIMIT = \"CO...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext; import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; import org.eclipse.jface.text.source.Annotation; import org.eclipse.ui.PlatformUI; import com.abap.sql.beautifier.preferences.PreferenceConstants; import com.abap.sql.beautifier.settings.AbstractSqlSetting; import com.abap.sql.beautifier.settings.CommentsAdder; import com.abap.sql.beautifier.settings.ConditionAligner; import com.abap.sql.beautifier.settings.JoinCombiner; import com.abap.sql.beautifier.settings.OperatorUnifier; import com.abap.sql.beautifier.settings.Restructor; import com.abap.sql.beautifier.settings.SelectCombiner; import com.abap.sql.beautifier.settings.SpaceAdder; import com.abap.sql.beautifier.statement.AbapSql; import com.abap.sql.beautifier.utility.BeautifierIcon; import com.abap.sql.beautifier.utility.Utility; import com.sap.adt.tools.abapsource.ui.AbapSourceUi; import com.sap.adt.tools.abapsource.ui.IAbapSourceUi; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices.Token; import com.sap.adt.tools.abapsource.ui.sources.editors.AbapSourcePage;
14,532
} catch (BadLocationException e) { e.printStackTrace(); } break; } } if (firstToken != null) { if (firstToken.equalsIgnoreCase(Abap.SELECT)) { sql = code.substring(startReplacement, end); String sqlHelper = sql.replaceAll(",", ""); sqlHelper = Utility.cleanString(sqlHelper); List<String> customTokens = Arrays.asList(sqlHelper.split(" ")); if (customTokens.size() > 2) { // check if old or new syntax String secToken = customTokens.get(1).toString().toUpperCase(); String thirdToken = customTokens.get(2).toString().toUpperCase(); if (secToken.equals(Abap.FROM) || (secToken.equals(Abap.SINGLE) && thirdToken.equals(Abap.FROM))) { this.oldSyntax = false; } } // TODO // check if second SELECT or WHEN in statement --> not working currently in this // plugin // check if it contains multiple 'select' or 'when' // when? if (sql.toUpperCase().contains(" WHEN ")) { return false; } // mult. select? int count = Utility.countKeyword(sql, Abap.SELECT); if (count <= 1) { return true; } } } } return false; } @Override public boolean canFix(Annotation annotation) { return true; } @Override public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) { List<ICompletionProposal> proposals = new ArrayList<>(); if (canAssist(invocationContext)) { int replaceLength = end - startReplacement + 1; String beautifulSql = ""; String convertedSql = ""; try { beautifulSql = beautifyStatement(sql); if (this.oldSyntax) { // convertedSql = convertToNewSyntax(beautifulSql); } } catch (Exception e) { // to avoid 'disturbing' other plugins with other proposals if there is a bug e.printStackTrace(); return null; } String descBeautify = "Beautify this SQL statement depending on the settings in your preferences."; BeautifyProposal beautifyProp = new BeautifyProposal(beautifulSql, startReplacement, replaceLength, 0, BeautifierIcon.get(), "Beautify SQL-Statement", null, descBeautify); proposals.add(beautifyProp); // if (this.oldSyntax) { // CompletionProposal conversionProp = new CompletionProposal(convertedSql, startReplacement, // replaceLength, 0, BeautifierIcon.get(), "Convert SQL-Statement", null, // "Convert this SQL statement to the new syntax depending on the settings in your preferences."); // // proposals.add(conversionProp); // } return proposals.toArray(new ICompletionProposal[proposals.size()]); } return null; } @Override public String getErrorMessage() { return null; } private List<AbstractSqlSetting> generateSettings() { List<AbstractSqlSetting> settings = new ArrayList<>(); settings.add(new Restructor()); settings.add(new OperatorUnifier()); if (this.oldSyntax) { // settings.add(new CommasAdder()); settings.add(new JoinCombiner()); settings.add(new SelectCombiner()); // settings.add(new EscapingAdder()); } settings.add(new SpaceAdder()); settings.add(new ConditionAligner());
package com.abap.sql.beautifier; public class StatementProcessor implements IQuickAssistProcessor { public IDocument document = null; public IAbapSourceScannerServices scannerServices = null; public AbapSourcePage sourcePage; public IAbapSourceUi sourceUi = null; private String sql = ""; private String code; private int diff; private int end; private int offsetCursor; private int startReplacement; private boolean oldSyntax = true; private String beautifyStatement(String inputCode) { // otherwise the whole beautifier would not work inputCode = inputCode.toUpperCase(); AbapSql abapSql = new AbapSql(inputCode, diff); System.out.println("=================================="); System.out.println("Input"); System.out.println(inputCode); List<AbstractSqlSetting> settings = generateSettings(); // apply settings for (AbstractSqlSetting setting : settings) { System.out.println("=================================="); System.out.println(setting.getClass().getSimpleName()); setting.setAbapSql(abapSql); setting.apply(); abapSql = setting.getAbapSql(); System.out.println(abapSql.toString()); } abapSql.setPoint(); String outputCode = abapSql.toString(); // delete last empty row if (outputCode.endsWith("\r\n")) { outputCode = outputCode.substring(0, outputCode.length() - "\r\n".length()); } System.out.println("=================================="); System.out.println("Output"); System.out.println(outputCode); return outputCode; } @Override public boolean canAssist(IQuickAssistInvocationContext invocationContext) { // get part of code and check if the current code part is a sql statement document = invocationContext.getSourceViewer().getDocument(); sourceUi = AbapSourceUi.getInstance(); scannerServices = sourceUi.getSourceScannerServices(); sourcePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() .getAdapter(AbapSourcePage.class); code = document.get(); // offset of current cursor offsetCursor = invocationContext.getOffset(); // get offset of last and next dot int start = scannerServices.goBackToDot(document, offsetCursor) + 1; end = scannerServices.goForwardToDot(document, offsetCursor); // all words in selected code List<Token> statementTokens = scannerServices.getStatementTokens(document, start); // check first word if (statementTokens.size() > 0) { String firstToken = null; // get first non comment token for (int i = 0; i < statementTokens.size(); i++) { Token t = statementTokens.get(i); if (!scannerServices.isComment(document, t.offset)) { firstToken = t.toString(); // offset of last dot and startReplacement could be different startReplacement = t.offset; try { int line = document.getLineOfOffset(startReplacement); int lineOffset = document.getLineOffset(line); diff = startReplacement - lineOffset; } catch (BadLocationException e) { e.printStackTrace(); } break; } } if (firstToken != null) { if (firstToken.equalsIgnoreCase(Abap.SELECT)) { sql = code.substring(startReplacement, end); String sqlHelper = sql.replaceAll(",", ""); sqlHelper = Utility.cleanString(sqlHelper); List<String> customTokens = Arrays.asList(sqlHelper.split(" ")); if (customTokens.size() > 2) { // check if old or new syntax String secToken = customTokens.get(1).toString().toUpperCase(); String thirdToken = customTokens.get(2).toString().toUpperCase(); if (secToken.equals(Abap.FROM) || (secToken.equals(Abap.SINGLE) && thirdToken.equals(Abap.FROM))) { this.oldSyntax = false; } } // TODO // check if second SELECT or WHEN in statement --> not working currently in this // plugin // check if it contains multiple 'select' or 'when' // when? if (sql.toUpperCase().contains(" WHEN ")) { return false; } // mult. select? int count = Utility.countKeyword(sql, Abap.SELECT); if (count <= 1) { return true; } } } } return false; } @Override public boolean canFix(Annotation annotation) { return true; } @Override public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) { List<ICompletionProposal> proposals = new ArrayList<>(); if (canAssist(invocationContext)) { int replaceLength = end - startReplacement + 1; String beautifulSql = ""; String convertedSql = ""; try { beautifulSql = beautifyStatement(sql); if (this.oldSyntax) { // convertedSql = convertToNewSyntax(beautifulSql); } } catch (Exception e) { // to avoid 'disturbing' other plugins with other proposals if there is a bug e.printStackTrace(); return null; } String descBeautify = "Beautify this SQL statement depending on the settings in your preferences."; BeautifyProposal beautifyProp = new BeautifyProposal(beautifulSql, startReplacement, replaceLength, 0, BeautifierIcon.get(), "Beautify SQL-Statement", null, descBeautify); proposals.add(beautifyProp); // if (this.oldSyntax) { // CompletionProposal conversionProp = new CompletionProposal(convertedSql, startReplacement, // replaceLength, 0, BeautifierIcon.get(), "Convert SQL-Statement", null, // "Convert this SQL statement to the new syntax depending on the settings in your preferences."); // // proposals.add(conversionProp); // } return proposals.toArray(new ICompletionProposal[proposals.size()]); } return null; } @Override public String getErrorMessage() { return null; } private List<AbstractSqlSetting> generateSettings() { List<AbstractSqlSetting> settings = new ArrayList<>(); settings.add(new Restructor()); settings.add(new OperatorUnifier()); if (this.oldSyntax) { // settings.add(new CommasAdder()); settings.add(new JoinCombiner()); settings.add(new SelectCombiner()); // settings.add(new EscapingAdder()); } settings.add(new SpaceAdder()); settings.add(new ConditionAligner());
settings.add(new CommentsAdder());
2
2023-10-10 18:56:27+00:00
24k
Spider-Admin/Frost
src/main/java/frost/fileTransfer/filerequest/FileRequestsManager.java
[ { "identifier": "FileSharingManager", "path": "src/main/java/frost/fileTransfer/FileSharingManager.java", "snippet": "public class FileSharingManager {\r\n\r\n private static FileListDownloadThread fileListDownloadThread = null;\r\n private static FileListUploadThread fileListUploadThread = null;\...
import frost.storage.perst.filelist.FileListStorage; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import frost.fileTransfer.FileSharingManager; import frost.fileTransfer.FileTransferManager; import frost.fileTransfer.FrostFileListFileObject; import frost.fileTransfer.download.FrostDownloadItem; import frost.fileTransfer.sharing.FrostSharedFileItem;
18,520
/* FileRequestsManager.java / Frost Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.fileTransfer.filerequest; /** * Collects the files to request from other users. * Processes incoming requests. */ public class FileRequestsManager { private static final Logger logger = LoggerFactory.getLogger(FileRequestsManager.class); private static final int MAX_SHA_PER_REQUESTFILE = 350; private static final long MIN_LAST_UPLOADED = 10; // start upload if last upload is X days back /** * @return List with SHA strings that should be requested */ public static List<String> getRequestsToSend() { // get files from downloadtable that are shared and check if we should send a request for them // sha256 = 64 bytes, send a maximum of 350 requests per file (<32kb) // Rules for send of a request: // - don't send a request if the file to request was not seen in a file index for more than 3 days // -> maybe file was already uploaded! // - must be not requested since 23h ( by us or others ) // - we DON'T have the chk OR // - we HAVE the chk, but download FAILED // - when progress did not change for X hours frost-measured trytime or FAILED. // FIXME: maybe only request FAILED if failed reason was Data_Not_Found! // But this requires that the dlitem remembers the failed reason! // We don't send requests if we have more than 3 file list files that wait for downloading, // because maybe those files contain the file key that we just want to request. // But we allow 3 files to be in the queue to prevent that requests are permanently not send // because a new file list file just arrived in the queue. if( FileSharingManager.getFileListDownloadQueueSize() > 3 ) { return Collections.emptyList(); } final long now = System.currentTimeMillis(); final long before23hours = now - 1L * 23L * 60L * 60L * 1000L; final long before3days = now - 3L * 24L * 60L * 60L * 1000L; final long time12hoursInSeconds = 12 * 60 * 60; final List<String> mustSendRequests = new LinkedList<String>(); final List<FrostDownloadItem> downloadModelItems = FileTransferManager.inst().getDownloadManager().getDownloadItemList(); for( final FrostDownloadItem dlItem : downloadModelItems ) { if( !dlItem.isSharedFile() ) { continue; } if( dlItem.isEnabled().booleanValue() == false ) { continue; } final FrostFileListFileObject sfo = dlItem.getFileListFileObject(); if( sfo.getLastReceived() < before3days ) { // sha not received for 3 days, is it still shared, or maybe already uploaded? don't request it. continue; } if( sfo.getRequestLastSent() > before23hours || sfo.getRequestLastReceived() > before23hours ) { // request received or send in last 24 hours continue; } if( dlItem.getKey() != null && dlItem.getKey().length() > 0 ) { // send request after 12 hours runtime without any progress // send request when download is in FAILED state if( dlItem.getState() != FrostDownloadItem.STATE_FAILED && dlItem.getRuntimeSecondsWithoutProgress() < time12hoursInSeconds ) { continue; } } // we MUST request this file mustSendRequests.add( sfo.getSha() ); if( mustSendRequests.size() == MAX_SHA_PER_REQUESTFILE ) { break; } } return mustSendRequests; } /** * @param requests a List of String objects with SHAs that were successfully sent within a request file */ public static void updateRequestsWereSuccessfullySent(final List<String> requests) { final long now = System.currentTimeMillis(); final List<FrostDownloadItem> downloadModelItems = FileTransferManager.inst().getDownloadManager().getDownloadItemList(); // first update filelistfiles in memory for( final String sha : requests ) { // filelist files in download table for( final FrostDownloadItem dlItem : downloadModelItems ) { if( !dlItem.isSharedFile() ) { continue; } final FrostFileListFileObject sfo = dlItem.getFileListFileObject(); if( !sfo.getSha().equals(sha) ) { continue; } sfo.setRequestsSentCount(sfo.getRequestsSentCount() + 1); sfo.setRequestLastSent(now); } } // then update same filelistfiles in database
/* FileRequestsManager.java / Frost Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.fileTransfer.filerequest; /** * Collects the files to request from other users. * Processes incoming requests. */ public class FileRequestsManager { private static final Logger logger = LoggerFactory.getLogger(FileRequestsManager.class); private static final int MAX_SHA_PER_REQUESTFILE = 350; private static final long MIN_LAST_UPLOADED = 10; // start upload if last upload is X days back /** * @return List with SHA strings that should be requested */ public static List<String> getRequestsToSend() { // get files from downloadtable that are shared and check if we should send a request for them // sha256 = 64 bytes, send a maximum of 350 requests per file (<32kb) // Rules for send of a request: // - don't send a request if the file to request was not seen in a file index for more than 3 days // -> maybe file was already uploaded! // - must be not requested since 23h ( by us or others ) // - we DON'T have the chk OR // - we HAVE the chk, but download FAILED // - when progress did not change for X hours frost-measured trytime or FAILED. // FIXME: maybe only request FAILED if failed reason was Data_Not_Found! // But this requires that the dlitem remembers the failed reason! // We don't send requests if we have more than 3 file list files that wait for downloading, // because maybe those files contain the file key that we just want to request. // But we allow 3 files to be in the queue to prevent that requests are permanently not send // because a new file list file just arrived in the queue. if( FileSharingManager.getFileListDownloadQueueSize() > 3 ) { return Collections.emptyList(); } final long now = System.currentTimeMillis(); final long before23hours = now - 1L * 23L * 60L * 60L * 1000L; final long before3days = now - 3L * 24L * 60L * 60L * 1000L; final long time12hoursInSeconds = 12 * 60 * 60; final List<String> mustSendRequests = new LinkedList<String>(); final List<FrostDownloadItem> downloadModelItems = FileTransferManager.inst().getDownloadManager().getDownloadItemList(); for( final FrostDownloadItem dlItem : downloadModelItems ) { if( !dlItem.isSharedFile() ) { continue; } if( dlItem.isEnabled().booleanValue() == false ) { continue; } final FrostFileListFileObject sfo = dlItem.getFileListFileObject(); if( sfo.getLastReceived() < before3days ) { // sha not received for 3 days, is it still shared, or maybe already uploaded? don't request it. continue; } if( sfo.getRequestLastSent() > before23hours || sfo.getRequestLastReceived() > before23hours ) { // request received or send in last 24 hours continue; } if( dlItem.getKey() != null && dlItem.getKey().length() > 0 ) { // send request after 12 hours runtime without any progress // send request when download is in FAILED state if( dlItem.getState() != FrostDownloadItem.STATE_FAILED && dlItem.getRuntimeSecondsWithoutProgress() < time12hoursInSeconds ) { continue; } } // we MUST request this file mustSendRequests.add( sfo.getSha() ); if( mustSendRequests.size() == MAX_SHA_PER_REQUESTFILE ) { break; } } return mustSendRequests; } /** * @param requests a List of String objects with SHAs that were successfully sent within a request file */ public static void updateRequestsWereSuccessfullySent(final List<String> requests) { final long now = System.currentTimeMillis(); final List<FrostDownloadItem> downloadModelItems = FileTransferManager.inst().getDownloadManager().getDownloadItemList(); // first update filelistfiles in memory for( final String sha : requests ) { // filelist files in download table for( final FrostDownloadItem dlItem : downloadModelItems ) { if( !dlItem.isSharedFile() ) { continue; } final FrostFileListFileObject sfo = dlItem.getFileListFileObject(); if( !sfo.getSha().equals(sha) ) { continue; } sfo.setRequestsSentCount(sfo.getRequestsSentCount() + 1); sfo.setRequestLastSent(now); } } // then update same filelistfiles in database
if( !FileListStorage.inst().beginExclusiveThreadTransaction() ) {
5
2023-10-07 22:25:20+00:00
24k
Gaia3D/mago-3d-tiler
tiler/src/main/java/com/gaia3d/process/postprocess/batch/Batched3DModel.java
[ { "identifier": "GaiaSet", "path": "core/src/main/java/com/gaia3d/basic/exchangable/GaiaSet.java", "snippet": "@Slf4j\n@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class GaiaSet {\n List<GaiaBufferDataSet> bufferDatas;\n List<GaiaMaterial> materials;\n\n private Matrix4d tr...
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.gaia3d.basic.exchangable.GaiaSet; import com.gaia3d.basic.geometry.GaiaBoundingBox; import com.gaia3d.basic.structure.GaiaScene; import com.gaia3d.converter.jgltf.GltfWriter; import com.gaia3d.process.ProcessOptions; import com.gaia3d.process.postprocess.TileModel; import com.gaia3d.process.postprocess.instance.GaiaFeatureTable; import com.gaia3d.process.tileprocess.tile.ContentInfo; import com.gaia3d.process.tileprocess.tile.TileInfo; import com.gaia3d.util.DecimalUtils; import com.gaia3d.util.io.LittleEndianDataInputStream; import com.gaia3d.util.io.LittleEndianDataOutputStream; import lombok.extern.slf4j.Slf4j; import org.apache.commons.cli.CommandLine; import org.lwjgl.BufferUtils; import java.io.*; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.util.List;
14,894
package com.gaia3d.process.postprocess.batch; @Slf4j public class Batched3DModel implements TileModel { private static final String MAGIC = "b3dm"; private static final int VERSION = 1; private final GltfWriter gltfWriter; private final CommandLine command; public Batched3DModel(CommandLine command) { this.gltfWriter = new GltfWriter(); this.command = command; } @Override public ContentInfo run(ContentInfo contentInfo) { GaiaSet batchedSet = contentInfo.getBatchedSet(); int featureTableJSONByteLength; int batchTableJSONByteLength; String featureTableJson; String batchTableJson; String nodeCode = contentInfo.getNodeCode();
package com.gaia3d.process.postprocess.batch; @Slf4j public class Batched3DModel implements TileModel { private static final String MAGIC = "b3dm"; private static final int VERSION = 1; private final GltfWriter gltfWriter; private final CommandLine command; public Batched3DModel(CommandLine command) { this.gltfWriter = new GltfWriter(); this.command = command; } @Override public ContentInfo run(ContentInfo contentInfo) { GaiaSet batchedSet = contentInfo.getBatchedSet(); int featureTableJSONByteLength; int batchTableJSONByteLength; String featureTableJson; String batchTableJson; String nodeCode = contentInfo.getNodeCode();
List<TileInfo> tileInfos = contentInfo.getTileInfos();
8
2023-11-30 01:59:44+00:00
24k
lidaofu-hub/j_media_server
src/main/java/com/ldf/media/context/MediaServerContext.java
[ { "identifier": "MediaServerConfig", "path": "src/main/java/com/ldf/media/config/MediaServerConfig.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"media\")\npublic class MediaServerConfig {\n\n private Integer thread_num;\n\n private Integer rtmp_port;\n\n private ...
import com.ldf.media.callback.*; import com.ldf.media.config.MediaServerConfig; import com.ldf.media.sdk.core.ZLMApi; import com.ldf.media.sdk.structure.MK_EVENTS; import com.ldf.media.sdk.structure.MK_INI; import com.sun.jna.Native; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy;
15,971
package com.ldf.media.context; /** * 流媒体上下文 * * @author lidaofu * @since 2023/11/28 **/ @Slf4j @Component public class MediaServerContext { @Autowired private MediaServerConfig config;
package com.ldf.media.context; /** * 流媒体上下文 * * @author lidaofu * @since 2023/11/28 **/ @Slf4j @Component public class MediaServerContext { @Autowired private MediaServerConfig config;
public static ZLMApi ZLM_API = null;
1
2023-11-29 07:47:56+00:00
24k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/result/AbstractResult.java
[ { "identifier": "MainController", "path": "core/src/bms/player/beatoraja/MainController.java", "snippet": "public class MainController extends ApplicationAdapter {\n\n\tprivate static final String VERSION = \"LR2oraja Endless Dream 0.1.1\";\n\n\tpublic static final boolean debug = false;\n\n\t/**\n\t * ...
import static bms.player.beatoraja.ClearType.NoPlay; import java.util.Arrays; import com.badlogic.gdx.math.MathUtils; import bms.player.beatoraja.MainController; import bms.player.beatoraja.MainState; import bms.player.beatoraja.ScoreData; import bms.player.beatoraja.input.BMSPlayerInputProcessor; import bms.player.beatoraja.ir.RankingData;
21,069
package bms.player.beatoraja.result; public abstract class AbstractResult extends MainState { /** * 状態 */ protected int state; public static final int STATE_OFFLINE = 0; /** * 状態:IR送信中 */ public static final int STATE_IR_PROCESSING = 1; /** * 状態:IR処理完了 */ public static final int STATE_IR_FINISHED = 2; /** * ランキングデータ */ protected RankingData ranking; /** * ランキング表示位置 */ protected int rankingOffset = 0; /** * 全ノーツの平均ズレ(us) */ protected long avgduration; /** * タイミング分布 */ protected TimingDistribution timingDistribution; /** * タイミング分布レンジ */ final int distRange = 150; /** * 各リプレイデータ状態 */ protected ReplayStatus[] saveReplay = new ReplayStatus[REPLAY_SIZE]; protected static final int REPLAY_SIZE = 4; public static final int SOUND_CLEAR = 0; public static final int SOUND_FAIL = 1; public static final int SOUND_CLOSE = 2; protected int gaugeType; /** * 旧スコアデータ */ protected ScoreData oldscore = new ScoreData();
package bms.player.beatoraja.result; public abstract class AbstractResult extends MainState { /** * 状態 */ protected int state; public static final int STATE_OFFLINE = 0; /** * 状態:IR送信中 */ public static final int STATE_IR_PROCESSING = 1; /** * 状態:IR処理完了 */ public static final int STATE_IR_FINISHED = 2; /** * ランキングデータ */ protected RankingData ranking; /** * ランキング表示位置 */ protected int rankingOffset = 0; /** * 全ノーツの平均ズレ(us) */ protected long avgduration; /** * タイミング分布 */ protected TimingDistribution timingDistribution; /** * タイミング分布レンジ */ final int distRange = 150; /** * 各リプレイデータ状態 */ protected ReplayStatus[] saveReplay = new ReplayStatus[REPLAY_SIZE]; protected static final int REPLAY_SIZE = 4; public static final int SOUND_CLEAR = 0; public static final int SOUND_FAIL = 1; public static final int SOUND_CLOSE = 2; protected int gaugeType; /** * 旧スコアデータ */ protected ScoreData oldscore = new ScoreData();
public AbstractResult(MainController main) {
0
2023-12-02 23:41:17+00:00
24k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/buffs/WellFed.java
[ { "identifier": "Challenges", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Challenges.java", "snippet": "public class Challenges {\n\n\t//Some of these internal IDs are outdated and don't represent what these challenges do\n\tpublic static final int NO_FOOD\t\t\t\t= 1;\n\tpublic ...
import com.shatteredpixel.shatteredpixeldungeon.Challenges; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.ui.BuffIndicator; import com.watabou.utils.Bundle;
18,972
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.actors.buffs; public class WellFed extends Buff { { type = buffType.POSITIVE; announced = true; } int left; @Override public boolean act() { left --; if (left < 0){ detach(); return true; } else if (left % 18 == 0){ target.HP = Math.min(target.HT, target.HP + 1); } spend(TICK); return true; } public void reset(){ //heals one HP every 18 turns for 450 turns //25 HP healed in total left = (int)Hunger.STARVING;
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.actors.buffs; public class WellFed extends Buff { { type = buffType.POSITIVE; announced = true; } int left; @Override public boolean act() { left --; if (left < 0){ detach(); return true; } else if (left % 18 == 0){ target.HP = Math.min(target.HT, target.HP + 1); } spend(TICK); return true; } public void reset(){ //heals one HP every 18 turns for 450 turns //25 HP healed in total left = (int)Hunger.STARVING;
if (Dungeon.isChallenged(Challenges.NO_FOOD)){
0
2023-11-27 05:56:58+00:00
24k
parttimenerd/hello-ebpf
bcc/src/main/java/me/bechberger/ebpf/samples/chapter2/ex/HelloBufferEvenOdd.java
[ { "identifier": "BPF", "path": "bcc/src/main/java/me/bechberger/ebpf/bcc/BPF.java", "snippet": "public class BPF implements AutoCloseable {\n\n static {\n try {\n System.loadLibrary(\"bcc\");\n } catch (UnsatisfiedLinkError e) {\n try {\n System.load...
import static me.bechberger.ebpf.samples.chapter2.HelloBuffer.DATA_TYPE; import me.bechberger.ebpf.bcc.BPF; import me.bechberger.ebpf.bcc.BPFTable; import me.bechberger.ebpf.samples.chapter2.HelloBuffer;
20,711
/** * HelloBuffer that outputs different trace messages for even and odd process ids */ package me.bechberger.ebpf.samples.chapter2.ex; /** * Also shows how to reuse data types from {@link HelloBuffer} */ public class HelloBufferEvenOdd { public static void main(String[] args) throws InterruptedException {
/** * HelloBuffer that outputs different trace messages for even and odd process ids */ package me.bechberger.ebpf.samples.chapter2.ex; /** * Also shows how to reuse data types from {@link HelloBuffer} */ public class HelloBufferEvenOdd { public static void main(String[] args) throws InterruptedException {
try (var b = BPF.builder("""
0
2023-12-01 20:24:28+00:00
24k
WiIIiam278/HuskClaims
common/src/main/java/net/william278/huskclaims/api/HuskClaimsAPI.java
[ { "identifier": "HuskClaims", "path": "common/src/main/java/net/william278/huskclaims/HuskClaims.java", "snippet": "public interface HuskClaims extends Task.Supplier, ConfigProvider, DatabaseProvider, GsonProvider, UserManager,\n ClaimManager, GroupManager, TrustTagManager, ListenerProvider, User...
import lombok.AccessLevel; import lombok.AllArgsConstructor; import net.william278.cloplib.operation.Operation; import net.william278.cloplib.operation.OperationType; import net.william278.huskclaims.HuskClaims; import net.william278.huskclaims.claim.Claim; import net.william278.huskclaims.claim.ClaimWorld; import net.william278.huskclaims.claim.Region; import net.william278.huskclaims.claim.ServerWorldClaim; import net.william278.huskclaims.highlighter.Highlighter; import net.william278.huskclaims.position.BlockPosition; import net.william278.huskclaims.position.Position; import net.william278.huskclaims.position.ServerWorld; import net.william278.huskclaims.position.World; import net.william278.huskclaims.trust.TrustLevel; import net.william278.huskclaims.trust.TrustTag; import net.william278.huskclaims.trust.Trustable; import net.william278.huskclaims.trust.UserGroup; import net.william278.huskclaims.user.ClaimBlocksManager; import net.william278.huskclaims.user.OnlineUser; import net.william278.huskclaims.user.SavedUser; import net.william278.huskclaims.user.User; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Unmodifiable; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors;
15,598
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * 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 net.william278.huskclaims.api; /** * The <a href="https://william278.net/docs/huskclaims/api">HuskClaims API</a>. * <p> * Get the singleton instance with {@link #getInstance()}. * * @since 1.0 */ @AllArgsConstructor(access = AccessLevel.PROTECTED) @SuppressWarnings("unused") public class HuskClaimsAPI { // Singleton API instance protected static HuskClaimsAPI instance; // Plugin instance protected final HuskClaims plugin; /** * Get a {@link SavedUser} instance for a player, by UUID. * * @param uuid the UUID of the player * @return a {@link CompletableFuture} containing an {@link Optional} of the {@link SavedUser} instance, if found. * This contains persisted (offline) player data pertinent to HuskClaims. * @since 1.0 */ public CompletableFuture<Optional<SavedUser>> getUser(@NotNull UUID uuid) { return plugin.supplyAsync(() -> plugin.getDatabase().getUser(uuid)); } /** * Get a {@link SavedUser} instance for a player, by username. * * @param name the name of the player * @return a {@link CompletableFuture} containing an {@link Optional} of the {@link SavedUser} instance, if found. * This contains persisted (offline) player data pertinent to HuskClaims. * @since 1.0 */ public CompletableFuture<Optional<SavedUser>> getUser(@NotNull String name) { return plugin.supplyAsync(() -> plugin.getDatabase().getUser(name)); } /** * Get a {@link User}'s claim blocks. * <p> * If you are checking the claim blocks of an online player, it is recommended to use * {@link #getClaimBlocks(OnlineUser)} instead. * * @param user the user * @return a {@link CompletableFuture} containing the number of claim blocks the user has. * @since 1.0 */ public CompletableFuture<Long> getClaimBlocks(@NotNull User user) { return plugin.supplyAsync(() -> plugin.getClaimBlocks(user)); } /** * Get a {@link User}'s claim blocks. * <p> * If you are checking the claim blocks of an online player, it is recommended to use * {@link #getClaimBlocks(OnlineUser)} instead. * * @param uuid the UUID of the user * @return a {@link CompletableFuture} containing the number of claim blocks the user has. * @since 1.0 */ public CompletableFuture<Long> getClaimBlocks(@NotNull UUID uuid) { return plugin.supplyAsync(() -> plugin.getClaimBlocks(uuid)); } /** * Check if a {@link User} has more than a certain amount of claim blocks. * <p> * If you are checking the claim blocks of an online player, it is recommended to use * {@link #getClaimBlocks(OnlineUser)} instead. * * @param user the user * @param amount the amount of claim blocks to check for (positive integer) * @return a {@link CompletableFuture} containing {@code true} if the user has more than the specified amount of * claim blocks, else {@code false} * @since 1.0 */ public CompletableFuture<Boolean> hasClaimBlocks(@NotNull User user, @Range(from = 0, to = Long.MAX_VALUE) long amount) { return getClaimBlocks(user).thenApply(blocks -> blocks >= amount); } /** * Get a {@link User}'s claim blocks. * * @param user the user * @return a {@link CompletableFuture} containing the number of claim blocks the user has. * @since 1.0 */
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * 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 net.william278.huskclaims.api; /** * The <a href="https://william278.net/docs/huskclaims/api">HuskClaims API</a>. * <p> * Get the singleton instance with {@link #getInstance()}. * * @since 1.0 */ @AllArgsConstructor(access = AccessLevel.PROTECTED) @SuppressWarnings("unused") public class HuskClaimsAPI { // Singleton API instance protected static HuskClaimsAPI instance; // Plugin instance protected final HuskClaims plugin; /** * Get a {@link SavedUser} instance for a player, by UUID. * * @param uuid the UUID of the player * @return a {@link CompletableFuture} containing an {@link Optional} of the {@link SavedUser} instance, if found. * This contains persisted (offline) player data pertinent to HuskClaims. * @since 1.0 */ public CompletableFuture<Optional<SavedUser>> getUser(@NotNull UUID uuid) { return plugin.supplyAsync(() -> plugin.getDatabase().getUser(uuid)); } /** * Get a {@link SavedUser} instance for a player, by username. * * @param name the name of the player * @return a {@link CompletableFuture} containing an {@link Optional} of the {@link SavedUser} instance, if found. * This contains persisted (offline) player data pertinent to HuskClaims. * @since 1.0 */ public CompletableFuture<Optional<SavedUser>> getUser(@NotNull String name) { return plugin.supplyAsync(() -> plugin.getDatabase().getUser(name)); } /** * Get a {@link User}'s claim blocks. * <p> * If you are checking the claim blocks of an online player, it is recommended to use * {@link #getClaimBlocks(OnlineUser)} instead. * * @param user the user * @return a {@link CompletableFuture} containing the number of claim blocks the user has. * @since 1.0 */ public CompletableFuture<Long> getClaimBlocks(@NotNull User user) { return plugin.supplyAsync(() -> plugin.getClaimBlocks(user)); } /** * Get a {@link User}'s claim blocks. * <p> * If you are checking the claim blocks of an online player, it is recommended to use * {@link #getClaimBlocks(OnlineUser)} instead. * * @param uuid the UUID of the user * @return a {@link CompletableFuture} containing the number of claim blocks the user has. * @since 1.0 */ public CompletableFuture<Long> getClaimBlocks(@NotNull UUID uuid) { return plugin.supplyAsync(() -> plugin.getClaimBlocks(uuid)); } /** * Check if a {@link User} has more than a certain amount of claim blocks. * <p> * If you are checking the claim blocks of an online player, it is recommended to use * {@link #getClaimBlocks(OnlineUser)} instead. * * @param user the user * @param amount the amount of claim blocks to check for (positive integer) * @return a {@link CompletableFuture} containing {@code true} if the user has more than the specified amount of * claim blocks, else {@code false} * @since 1.0 */ public CompletableFuture<Boolean> hasClaimBlocks(@NotNull User user, @Range(from = 0, to = Long.MAX_VALUE) long amount) { return getClaimBlocks(user).thenApply(blocks -> blocks >= amount); } /** * Get a {@link User}'s claim blocks. * * @param user the user * @return a {@link CompletableFuture} containing the number of claim blocks the user has. * @since 1.0 */
public long getClaimBlocks(@NotNull OnlineUser user) {
12
2023-11-28 01:09:43+00:00
24k
Manzzx/multi-channel-message-reach
metax-modules/metax-system/src/main/java/com/metax/system/controller/SysPostController.java
[ { "identifier": "ExcelUtil", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/utils/poi/ExcelUtil.java", "snippet": "public class ExcelUtil<T>\n{\n private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);\n\n public static final String FORMULA_REGEX_ST...
import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.metax.common.core.utils.poi.ExcelUtil; import com.metax.common.core.web.controller.BaseController; import com.metax.common.core.web.domain.AjaxResult; import com.metax.common.core.web.page.TableDataInfo; import com.metax.common.log.annotation.Log; import com.metax.common.log.enums.BusinessType; import com.metax.common.security.annotation.RequiresPermissions; import com.metax.common.security.utils.SecurityUtils; import com.metax.system.domain.SysPost; import com.metax.system.service.ISysPostService;
16,481
package com.metax.system.controller; /** * 岗位信息操作处理 * * @author ruoyi */ @RestController @RequestMapping("/post") public class SysPostController extends BaseController { @Autowired private ISysPostService postService; /** * 获取岗位列表 */ @RequiresPermissions("system:post:list") @GetMapping("/list")
package com.metax.system.controller; /** * 岗位信息操作处理 * * @author ruoyi */ @RestController @RequestMapping("/post") public class SysPostController extends BaseController { @Autowired private ISysPostService postService; /** * 获取岗位列表 */ @RequiresPermissions("system:post:list") @GetMapping("/list")
public TableDataInfo list(SysPost post)
6
2023-12-04 05:10:13+00:00
24k
ydb-platform/yoj-project
repository-ydb-v1/src/main/java/tech/ydb/yoj/repository/ydb/YdbRepository.java
[ { "identifier": "Entity", "path": "repository/src/main/java/tech/ydb/yoj/repository/db/Entity.java", "snippet": "public interface Entity<E extends Entity<E>> extends Table.ViewId<E> {\n @Override\n Id<E> getId();\n\n @SuppressWarnings(\"unchecked\")\n default E postLoad() {\n return (...
import com.google.common.base.Strings; import com.google.common.net.HostAndPort; import com.yandex.ydb.core.auth.AuthProvider; import com.yandex.ydb.core.auth.NopAuthProvider; import com.yandex.ydb.core.grpc.GrpcTransport; import io.grpc.ClientInterceptor; import io.grpc.netty.NettyChannelBuilder; import lombok.Getter; import lombok.NonNull; import lombok.Value; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tech.ydb.yoj.repository.db.Entity; import tech.ydb.yoj.repository.db.EntitySchema; import tech.ydb.yoj.repository.db.Repository; import tech.ydb.yoj.repository.db.RepositoryTransaction; import tech.ydb.yoj.repository.db.SchemaOperations; import tech.ydb.yoj.repository.db.TxOptions; import tech.ydb.yoj.repository.ydb.client.SessionManager; import tech.ydb.yoj.repository.ydb.client.YdbPaths; import tech.ydb.yoj.repository.ydb.client.YdbSchemaOperations; import tech.ydb.yoj.repository.ydb.client.YdbSessionManager; import tech.ydb.yoj.repository.ydb.client.YdbTableHint; import tech.ydb.yoj.repository.ydb.compatibility.YdbDataCompatibilityChecker; import tech.ydb.yoj.repository.ydb.compatibility.YdbSchemaCompatibilityChecker; import tech.ydb.yoj.repository.ydb.statement.Statement; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import static java.util.stream.Collectors.toUnmodifiableSet; import static tech.ydb.yoj.repository.ydb.client.YdbPaths.canonicalDatabase;
15,456
package tech.ydb.yoj.repository.ydb; public class YdbRepository implements Repository { private static final Logger log = LoggerFactory.getLogger(YdbRepository.class); @Getter private final YdbSchemaOperations schemaOperations; @Getter private final SessionManager sessionManager; private final GrpcTransport transport; @Getter private final String tablespace; @Getter private final YdbConfig config; private final ConcurrentMap<String, Class<? extends Entity<?>>> entityClassesByTableName; public YdbRepository(@NonNull YdbConfig config) { this(config, NopAuthProvider.INSTANCE); } public YdbRepository(@NonNull YdbConfig config, @NonNull AuthProvider authProvider) { this(config, authProvider, List.of()); } public YdbRepository(@NonNull YdbConfig config, @NonNull AuthProvider authProvider, List<ClientInterceptor> interceptors) { this.config = config; this.tablespace = YdbPaths.canonicalTablespace(config.getTablespace()); this.entityClassesByTableName = new ConcurrentHashMap<>(); this.transport = makeGrpcTransport(config, authProvider, interceptors); this.sessionManager = new YdbSessionManager(config, transport); this.schemaOperations = buildSchemaOperations(config.getTablespace(), transport, sessionManager); } @NonNull protected YdbSchemaOperations buildSchemaOperations(@NonNull String tablespace, GrpcTransport transport, SessionManager sessionManager) { return new YdbSchemaOperations(tablespace, sessionManager, transport); } public final void checkDataCompatibility(List<Class<? extends Entity>> entities) { checkDataCompatibility(entities, YdbDataCompatibilityChecker.Config.DEFAULT); } public final void checkSchemaCompatibility(List<Class<? extends Entity>> entities) { checkSchemaCompatibility(entities, YdbSchemaCompatibilityChecker.Config.DEFAULT); } public final void checkSchemaCompatibility( List<Class<? extends Entity>> entities, YdbSchemaCompatibilityChecker.Config config ) { new YdbSchemaCompatibilityChecker(entities, this, config).run(); } public final void checkDataCompatibility( List<Class<? extends Entity>> entities, YdbDataCompatibilityChecker.Config config ) { new YdbDataCompatibilityChecker(entities, this, config).run(); } private GrpcTransport makeGrpcTransport(@NonNull YdbConfig config, AuthProvider authProvider, List<ClientInterceptor> interceptors) { GrpcTransport.Builder transportBuilder; if (!Strings.isNullOrEmpty(config.getDiscoveryEndpoint())) { transportBuilder = GrpcTransport.forEndpoint(config.getDiscoveryEndpoint(), canonicalDatabase(config.getDatabase())) .withChannelInitializer(channelBuilder -> { initializeTcpKeepAlive(channelBuilder); initializeYdbMaxInboundMessageSize(channelBuilder); initializeChannelInterceptors(channelBuilder, interceptors); }); } else { List<HostAndPort> endpoints = config.getEndpoints(); if (endpoints == null || endpoints.isEmpty()) { throw new IllegalArgumentException("one of [discoveryEndpoint, endpoints] must be set"); } transportBuilder = GrpcTransport.forHosts(endpoints) .withDataBase(canonicalDatabase(config.getDatabase())) .withChannelInitializer(channelBuilder -> { initializeTcpKeepAlive(channelBuilder); initializeYdbMaxInboundMessageSize(channelBuilder); initializeChannelInterceptors(channelBuilder, interceptors); }); } if (config.isUseTLS()) { if (config.isUseTrustStore()) { transportBuilder.withSecureConnection(); } else if (config.getRootCA() != null) { transportBuilder.withSecureConnection(config.getRootCA()); } else { throw new IllegalArgumentException("you must either set useTrustStore=true or specify rootCA content"); } } return transportBuilder .withAuthProvider(authProvider) .build(); } private void initializeChannelInterceptors(NettyChannelBuilder channelBuilder, List<ClientInterceptor> interceptors) { channelBuilder.intercept(interceptors); } private void initializeTcpKeepAlive(NettyChannelBuilder channelBuilder) { channelBuilder .keepAliveTime(config.getTcpKeepaliveTime().toMillis(), TimeUnit.MILLISECONDS) .keepAliveTimeout(config.getTcpKeepaliveTimeout().toMillis(), TimeUnit.MILLISECONDS) .keepAliveWithoutCalls(true); } private void initializeYdbMaxInboundMessageSize(NettyChannelBuilder channelBuilder) { // See com.yandex.ydb.core.grpc.GrpcTransport#createChannel // This fixes incompatibility with old gRPC without recompiling ydb-sdk-core // https://github.com/grpc/grpc-java/issues/8313 channelBuilder.maxInboundMessageSize(64 << 20); // 64 MiB } @Override public boolean healthCheck() { return getSessionManager().healthCheck(); } @Override public void shutdown() { getSessionManager().shutdown(); transport.close(); } @Override public void createTablespace() { schemaOperations.createTablespace(); } @Override public Set<Class<? extends Entity<?>>> tables() { return schemaOperations.getTableNames().stream() .map(entityClassesByTableName::get) .filter(Objects::nonNull) .collect(toUnmodifiableSet()); } @Override
package tech.ydb.yoj.repository.ydb; public class YdbRepository implements Repository { private static final Logger log = LoggerFactory.getLogger(YdbRepository.class); @Getter private final YdbSchemaOperations schemaOperations; @Getter private final SessionManager sessionManager; private final GrpcTransport transport; @Getter private final String tablespace; @Getter private final YdbConfig config; private final ConcurrentMap<String, Class<? extends Entity<?>>> entityClassesByTableName; public YdbRepository(@NonNull YdbConfig config) { this(config, NopAuthProvider.INSTANCE); } public YdbRepository(@NonNull YdbConfig config, @NonNull AuthProvider authProvider) { this(config, authProvider, List.of()); } public YdbRepository(@NonNull YdbConfig config, @NonNull AuthProvider authProvider, List<ClientInterceptor> interceptors) { this.config = config; this.tablespace = YdbPaths.canonicalTablespace(config.getTablespace()); this.entityClassesByTableName = new ConcurrentHashMap<>(); this.transport = makeGrpcTransport(config, authProvider, interceptors); this.sessionManager = new YdbSessionManager(config, transport); this.schemaOperations = buildSchemaOperations(config.getTablespace(), transport, sessionManager); } @NonNull protected YdbSchemaOperations buildSchemaOperations(@NonNull String tablespace, GrpcTransport transport, SessionManager sessionManager) { return new YdbSchemaOperations(tablespace, sessionManager, transport); } public final void checkDataCompatibility(List<Class<? extends Entity>> entities) { checkDataCompatibility(entities, YdbDataCompatibilityChecker.Config.DEFAULT); } public final void checkSchemaCompatibility(List<Class<? extends Entity>> entities) { checkSchemaCompatibility(entities, YdbSchemaCompatibilityChecker.Config.DEFAULT); } public final void checkSchemaCompatibility( List<Class<? extends Entity>> entities, YdbSchemaCompatibilityChecker.Config config ) { new YdbSchemaCompatibilityChecker(entities, this, config).run(); } public final void checkDataCompatibility( List<Class<? extends Entity>> entities, YdbDataCompatibilityChecker.Config config ) { new YdbDataCompatibilityChecker(entities, this, config).run(); } private GrpcTransport makeGrpcTransport(@NonNull YdbConfig config, AuthProvider authProvider, List<ClientInterceptor> interceptors) { GrpcTransport.Builder transportBuilder; if (!Strings.isNullOrEmpty(config.getDiscoveryEndpoint())) { transportBuilder = GrpcTransport.forEndpoint(config.getDiscoveryEndpoint(), canonicalDatabase(config.getDatabase())) .withChannelInitializer(channelBuilder -> { initializeTcpKeepAlive(channelBuilder); initializeYdbMaxInboundMessageSize(channelBuilder); initializeChannelInterceptors(channelBuilder, interceptors); }); } else { List<HostAndPort> endpoints = config.getEndpoints(); if (endpoints == null || endpoints.isEmpty()) { throw new IllegalArgumentException("one of [discoveryEndpoint, endpoints] must be set"); } transportBuilder = GrpcTransport.forHosts(endpoints) .withDataBase(canonicalDatabase(config.getDatabase())) .withChannelInitializer(channelBuilder -> { initializeTcpKeepAlive(channelBuilder); initializeYdbMaxInboundMessageSize(channelBuilder); initializeChannelInterceptors(channelBuilder, interceptors); }); } if (config.isUseTLS()) { if (config.isUseTrustStore()) { transportBuilder.withSecureConnection(); } else if (config.getRootCA() != null) { transportBuilder.withSecureConnection(config.getRootCA()); } else { throw new IllegalArgumentException("you must either set useTrustStore=true or specify rootCA content"); } } return transportBuilder .withAuthProvider(authProvider) .build(); } private void initializeChannelInterceptors(NettyChannelBuilder channelBuilder, List<ClientInterceptor> interceptors) { channelBuilder.intercept(interceptors); } private void initializeTcpKeepAlive(NettyChannelBuilder channelBuilder) { channelBuilder .keepAliveTime(config.getTcpKeepaliveTime().toMillis(), TimeUnit.MILLISECONDS) .keepAliveTimeout(config.getTcpKeepaliveTimeout().toMillis(), TimeUnit.MILLISECONDS) .keepAliveWithoutCalls(true); } private void initializeYdbMaxInboundMessageSize(NettyChannelBuilder channelBuilder) { // See com.yandex.ydb.core.grpc.GrpcTransport#createChannel // This fixes incompatibility with old gRPC without recompiling ydb-sdk-core // https://github.com/grpc/grpc-java/issues/8313 channelBuilder.maxInboundMessageSize(64 << 20); // 64 MiB } @Override public boolean healthCheck() { return getSessionManager().healthCheck(); } @Override public void shutdown() { getSessionManager().shutdown(); transport.close(); } @Override public void createTablespace() { schemaOperations.createTablespace(); } @Override public Set<Class<? extends Entity<?>>> tables() { return schemaOperations.getTableNames().stream() .map(entityClassesByTableName::get) .filter(Objects::nonNull) .collect(toUnmodifiableSet()); } @Override
public RepositoryTransaction startTransaction(TxOptions options) {
5
2023-12-05 15:57:58+00:00
24k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/api/ModpackApi.java
[ { "identifier": "ProgressLayout", "path": "app_pojavlauncher/src/main/java/com/kdt/mcgui/ProgressLayout.java", "snippet": "public class ProgressLayout extends ConstraintLayout implements View.OnClickListener, TaskCountListener{\n public static final String UNPACK_RUNTIME = \"unpack_runtime\";\n pu...
import android.content.Context; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.PojavApplication; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModDetail; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModItem; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchFilters; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchResult; import java.io.IOException;
14,874
package net.kdt.pojavlaunch.modloaders.modpacks.api; /** * */ public interface ModpackApi { /** * @param searchFilters Filters * @param previousPageResult The result from the previous page * @return the list of mod items from specified offset */ SearchResult searchMod(SearchFilters searchFilters, SearchResult previousPageResult); /** * @param searchFilters Filters * @return A list of mod items */ default SearchResult searchMod(SearchFilters searchFilters) { return searchMod(searchFilters, null); } /** * Fetch the mod details * @param item The moditem that was selected * @return Detailed data about a mod(pack) */
package net.kdt.pojavlaunch.modloaders.modpacks.api; /** * */ public interface ModpackApi { /** * @param searchFilters Filters * @param previousPageResult The result from the previous page * @return the list of mod items from specified offset */ SearchResult searchMod(SearchFilters searchFilters, SearchResult previousPageResult); /** * @param searchFilters Filters * @return A list of mod items */ default SearchResult searchMod(SearchFilters searchFilters) { return searchMod(searchFilters, null); } /** * Fetch the mod details * @param item The moditem that was selected * @return Detailed data about a mod(pack) */
ModDetail getModDetails(ModItem item);
3
2023-12-01 16:16:12+00:00
24k
kawashirov/distant-horizons
common/src/main/java/com/seibel/distanthorizons/common/wrappers/WrapperFactory.java
[ { "identifier": "BiomeWrapper", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/block/BiomeWrapper.java", "snippet": "public class BiomeWrapper implements IBiomeWrapper\n{\n\tprivate static final Logger LOGGER = LogManager.getLogger();\n\t\n\t#if PRE_MC_1_18_2\n\tpublic static f...
import com.seibel.distanthorizons.api.interfaces.override.worldGenerator.IDhApiWorldGenerator; import com.seibel.distanthorizons.common.wrappers.block.BiomeWrapper; import com.seibel.distanthorizons.common.wrappers.block.BlockStateWrapper; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import com.seibel.distanthorizons.common.wrappers.world.ClientLevelWrapper; import com.seibel.distanthorizons.common.wrappers.world.ServerLevelWrapper; import com.seibel.distanthorizons.common.wrappers.worldGeneration.BatchGenerationEnvironment; import com.seibel.distanthorizons.core.level.IDhLevel; import com.seibel.distanthorizons.core.level.IDhServerLevel; import com.seibel.distanthorizons.core.wrapperInterfaces.IWrapperFactory; import com.seibel.distanthorizons.core.wrapperInterfaces.block.IBlockStateWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.chunk.IChunkWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IBiomeWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.ILevelWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.worldGeneration.AbstractBatchGenerationEnvironmentWrapper; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.chunk.ChunkAccess; import java.io.IOException; import java.util.HashSet;
17,816
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers; /** * This handles creating abstract wrapper objects. * * @author James Seibel * @version 2022-12-5 */ public class WrapperFactory implements IWrapperFactory { public static final WrapperFactory INSTANCE = new WrapperFactory(); @Override public AbstractBatchGenerationEnvironmentWrapper createBatchGenerator(IDhLevel targetLevel) { if (targetLevel instanceof IDhServerLevel) { return new BatchGenerationEnvironment((IDhServerLevel) targetLevel); } else { throw new IllegalArgumentException("The target level must be a server-side level."); } } @Override public IBiomeWrapper deserializeBiomeWrapper(String str, ILevelWrapper levelWrapper) throws IOException { return BiomeWrapper.deserialize(str, levelWrapper); } @Override
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers; /** * This handles creating abstract wrapper objects. * * @author James Seibel * @version 2022-12-5 */ public class WrapperFactory implements IWrapperFactory { public static final WrapperFactory INSTANCE = new WrapperFactory(); @Override public AbstractBatchGenerationEnvironmentWrapper createBatchGenerator(IDhLevel targetLevel) { if (targetLevel instanceof IDhServerLevel) { return new BatchGenerationEnvironment((IDhServerLevel) targetLevel); } else { throw new IllegalArgumentException("The target level must be a server-side level."); } } @Override public IBiomeWrapper deserializeBiomeWrapper(String str, ILevelWrapper levelWrapper) throws IOException { return BiomeWrapper.deserialize(str, levelWrapper); } @Override
public IBlockStateWrapper deserializeBlockStateWrapper(String str, ILevelWrapper levelWrapper) throws IOException { return BlockStateWrapper.deserialize(str, levelWrapper); }
1
2023-12-04 11:41:46+00:00
24k
hmcts/juror-sql-support-library
src/main/java/uk/gov/hmcts/juror/support/sql/service/SqlSupportService.java
[ { "identifier": "Constants", "path": "src/main/java/uk/gov/hmcts/juror/support/sql/Constants.java", "snippet": "public class Constants {\n\n public static final String PHONE_REGEX = \"^(\\\\+44|0)7\\\\d{9}$\";\n public static final String NOTES_REGEX = \"[A-Za-z0-9]{10,501}\";\n public static f...
import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StopWatch; import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromCollectionGeneratorImpl; import uk.gov.hmcts.juror.support.generation.util.RandomGenerator; import uk.gov.hmcts.juror.support.sql.Constants; import uk.gov.hmcts.juror.support.sql.Util; import uk.gov.hmcts.juror.support.sql.dto.JurorAccountDetailsDto; import uk.gov.hmcts.juror.support.sql.entity.CourtLocation; import uk.gov.hmcts.juror.support.sql.entity.Juror; import uk.gov.hmcts.juror.support.sql.entity.JurorGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorPool; import uk.gov.hmcts.juror.support.sql.entity.JurorPoolGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorStatus; import uk.gov.hmcts.juror.support.sql.entity.PoolRequest; import uk.gov.hmcts.juror.support.sql.entity.PoolRequestGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.AbstractJurorResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.AbstractJurorResponseGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.DigitalResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.DigitalResponseGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.PaperResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.PaperResponseGenerator; import uk.gov.hmcts.juror.support.sql.generators.DigitalResponseGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.JurorGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.JurorPoolGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.PaperResponseGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.PoolRequestGeneratorUtil; import uk.gov.hmcts.juror.support.sql.repository.CourtLocationRepository; import uk.gov.hmcts.juror.support.sql.repository.DigitalResponseRepository; import uk.gov.hmcts.juror.support.sql.repository.JurorPoolRepository; import uk.gov.hmcts.juror.support.sql.repository.JurorRepository; import uk.gov.hmcts.juror.support.sql.repository.PaperResponseRepository; import uk.gov.hmcts.juror.support.sql.repository.PoolRequestRepository; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors;
14,502
log.info("Clearing database: DONE"); } public void createJurorsAssociatedToPools(boolean isCourtOwned, int jurorsInPoolMinimumInclusive, int jurorsInPoolMaximumExclusive, Map<JurorStatus, Integer> jurorStatusCountMap) { final int totalCount = jurorStatusCountMap.values().stream().reduce(0, Integer::sum); log.info("Creating Jurors save dtos"); List<JurorAccountDetailsDto> jurorAccountDetailsDtos = createJurorAccountDetailsDtos(isCourtOwned, jurorStatusCountMap); assert totalCount == jurorAccountDetailsDtos.size(); log.info("Creating Pool Request's"); List<JurorPool> needRandomPool = new ArrayList<>(); List<PoolRequest> pools = new ArrayList<>(totalCount / jurorsInPoolMinimumInclusive); PoolRequestGenerator poolRequestGenerator = PoolRequestGeneratorUtil.create(isCourtOwned, Constants.POOL_REQUEST_WEIGHT_MAP); int remainingJurors = totalCount; Collections.shuffle(jurorAccountDetailsDtos); //Ensures pools get a random distribution of juror types while (remainingJurors > 0) { final int totalJurorsInPool = RandomGenerator.nextInt( jurorsInPoolMinimumInclusive, jurorsInPoolMaximumExclusive); PoolRequest poolRequest = poolRequestGenerator.generate(); poolRequest.setTotalNoRequired(RandomGenerator.nextInt(10, 16)); pools.add(poolRequest); List<JurorAccountDetailsDto> selectedJurors = jurorAccountDetailsDtos.subList( Math.max(0, remainingJurors - totalJurorsInPool), remainingJurors); selectedJurors.parallelStream().forEach(juror -> { String firstJurorPoolOwner = null; List<JurorPool> jurorPools = juror.getJurorPools(); for (JurorPool jurorPool : jurorPools) { if (firstJurorPoolOwner == null) { firstJurorPoolOwner = jurorPool.getOwner(); } //Set owner so we know which pool this juror can not be in jurorPool.setOwner(jurorPool.getOwner()); if (jurorPool.getOwner().equals(firstJurorPoolOwner)) { jurorPool.setPoolNumber(poolRequest.getPoolNumber()); jurorPool.setStartDate(poolRequest.getReturnDate()); } else { needRandomPool.add(jurorPool); } } } ); remainingJurors -= totalJurorsInPool; } reassignJurorPoolsToRandomPoolWithNewOwner(needRandomPool, pools); stopWatch.start("Saving Pool Request's"); log.info("Saving Pool Request's to database"); Util.batchSave(poolRequestRepository, pools, BATCH_SIZE); stopWatch.stop(); saveJurorAccountDetailsDtos(jurorAccountDetailsDtos); } private void saveJurorAccountDetailsDtos(List<JurorAccountDetailsDto> jurorAccountDetailsDtos) { stopWatch.start("Saving Juror's"); log.info("Saving Juror's to database"); Util.batchSave(jurorRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJuror).toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Paper Response's"); log.info("Saving Juror Paper Response's"); Util.batchSave(paperResponseRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorResponse) .filter(PaperResponse.class::isInstance) .map(PaperResponse.class::cast) .toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Digital Response's"); log.info("Saving Juror Digital Response's"); Util.batchSave(digitalResponseRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorResponse) .filter(DigitalResponse.class::isInstance) .map(DigitalResponse.class::cast) .toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Pool's"); log.info("Saving Juror Pool's to database"); Util.batchSave(jurorPoolRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorPools).flatMap(List::stream).toList(), BATCH_SIZE); stopWatch.stop(); } private void addSummonsReplyToJurorAccountDto(int digitalWeight, int paperWeight, JurorStatus jurorStatus, List<JurorAccountDetailsDto> jurors) { stopWatch.start("Creating Summons replies from jurors"); log.info("Creating {} juror responses from jurors", jurors.size()); DigitalResponseGenerator digitalResponseGenerator = DigitalResponseGeneratorUtil.create(jurorStatus); PaperResponseGenerator paperResponseGenerator = PaperResponseGeneratorUtil.create(jurorStatus); Map<AbstractJurorResponseGenerator<?>, Integer> weightMap = Map.of( digitalResponseGenerator, digitalWeight, paperResponseGenerator, paperWeight ); jurors.forEach(jurorAccountDetailsDto -> { AbstractJurorResponseGenerator<?> generator = Util.getWeightedRandomItem(weightMap); AbstractJurorResponse jurorResponse = generator.generate(); mapJurorToJurorResponse(jurorAccountDetailsDto.getJuror(), jurorResponse); jurorAccountDetailsDto.setJurorResponse(jurorResponse); }); stopWatch.stop(); }
package uk.gov.hmcts.juror.support.sql.service; @Component @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Slf4j public class SqlSupportService { private final JurorRepository jurorRepository; private final PoolRequestRepository poolRequestRepository; private final JurorPoolRepository jurorPoolRepository; private final DigitalResponseRepository digitalResponseRepository; private final PaperResponseRepository paperResponseRepository; private StopWatch stopWatch; private final CourtLocationRepository courtLocationRepository; private static final List<CourtLocation> courtLocations; private static final Set<String> courtOwners; private static final int BATCH_SIZE = 100; static { courtLocations = new ArrayList<>(); courtOwners = new HashSet<>(); } public static List<CourtLocation> getCourtLocations() { return Collections.unmodifiableList(courtLocations); } public static Set<String> getCourtOwners() { return Collections.unmodifiableSet(courtOwners); } @PostConstruct //Temporary for testing purposes public void postConstruct() { this.stopWatch = new StopWatch(); courtLocationRepository.findAll().forEach(courtLocations::add); courtOwners.add("400"); courtOwners.add("415"); //TODO add back courtLocations.forEach(courtLocation -> courtOwners.add(courtLocation.getOwner())); clearDownDatabase(); Map<JurorStatus, Integer> jurorStatusCountMapCourt = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourt.put(JurorStatus.DEFERRED, 12585); jurorStatusCountMapCourt.put(JurorStatus.DISQUALIFIED, 126); jurorStatusCountMapCourt.put(JurorStatus.EXCUSED, 15607); jurorStatusCountMapCourt.put(JurorStatus.FAILED_TO_ATTEND, 705); jurorStatusCountMapCourt.put(JurorStatus.JUROR, 3916); jurorStatusCountMapCourt.put(JurorStatus.PANEL, 472); jurorStatusCountMapCourt.put(JurorStatus.REASSIGNED, 41313); jurorStatusCountMapCourt.put(JurorStatus.RESPONDED, 208525); jurorStatusCountMapCourt.put(JurorStatus.SUMMONED, 56443); jurorStatusCountMapCourt.put(JurorStatus.TRANSFERRED, 1075); //TODO uncomment createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourt); //TODO remove Map<JurorStatus, Integer> jurorStatusCountMapCourtTmp = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourtTmp.put(JurorStatus.SUMMONED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.RESPONDED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.DEFERRED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.EXCUSED, 100); //TODO remove end createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourtTmp); log.info("DONE: " + stopWatch.prettyPrint()); } private void clearDownDatabase() { log.info("Clearing database"); stopWatch.start("Cleaning database"); jurorPoolRepository.deleteAll(); poolRequestRepository.deleteAll(); digitalResponseRepository.deleteAll(); paperResponseRepository.deleteAll(); jurorRepository.deleteAll(); stopWatch.stop(); log.info("Clearing database: DONE"); } public void createJurorsAssociatedToPools(boolean isCourtOwned, int jurorsInPoolMinimumInclusive, int jurorsInPoolMaximumExclusive, Map<JurorStatus, Integer> jurorStatusCountMap) { final int totalCount = jurorStatusCountMap.values().stream().reduce(0, Integer::sum); log.info("Creating Jurors save dtos"); List<JurorAccountDetailsDto> jurorAccountDetailsDtos = createJurorAccountDetailsDtos(isCourtOwned, jurorStatusCountMap); assert totalCount == jurorAccountDetailsDtos.size(); log.info("Creating Pool Request's"); List<JurorPool> needRandomPool = new ArrayList<>(); List<PoolRequest> pools = new ArrayList<>(totalCount / jurorsInPoolMinimumInclusive); PoolRequestGenerator poolRequestGenerator = PoolRequestGeneratorUtil.create(isCourtOwned, Constants.POOL_REQUEST_WEIGHT_MAP); int remainingJurors = totalCount; Collections.shuffle(jurorAccountDetailsDtos); //Ensures pools get a random distribution of juror types while (remainingJurors > 0) { final int totalJurorsInPool = RandomGenerator.nextInt( jurorsInPoolMinimumInclusive, jurorsInPoolMaximumExclusive); PoolRequest poolRequest = poolRequestGenerator.generate(); poolRequest.setTotalNoRequired(RandomGenerator.nextInt(10, 16)); pools.add(poolRequest); List<JurorAccountDetailsDto> selectedJurors = jurorAccountDetailsDtos.subList( Math.max(0, remainingJurors - totalJurorsInPool), remainingJurors); selectedJurors.parallelStream().forEach(juror -> { String firstJurorPoolOwner = null; List<JurorPool> jurorPools = juror.getJurorPools(); for (JurorPool jurorPool : jurorPools) { if (firstJurorPoolOwner == null) { firstJurorPoolOwner = jurorPool.getOwner(); } //Set owner so we know which pool this juror can not be in jurorPool.setOwner(jurorPool.getOwner()); if (jurorPool.getOwner().equals(firstJurorPoolOwner)) { jurorPool.setPoolNumber(poolRequest.getPoolNumber()); jurorPool.setStartDate(poolRequest.getReturnDate()); } else { needRandomPool.add(jurorPool); } } } ); remainingJurors -= totalJurorsInPool; } reassignJurorPoolsToRandomPoolWithNewOwner(needRandomPool, pools); stopWatch.start("Saving Pool Request's"); log.info("Saving Pool Request's to database"); Util.batchSave(poolRequestRepository, pools, BATCH_SIZE); stopWatch.stop(); saveJurorAccountDetailsDtos(jurorAccountDetailsDtos); } private void saveJurorAccountDetailsDtos(List<JurorAccountDetailsDto> jurorAccountDetailsDtos) { stopWatch.start("Saving Juror's"); log.info("Saving Juror's to database"); Util.batchSave(jurorRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJuror).toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Paper Response's"); log.info("Saving Juror Paper Response's"); Util.batchSave(paperResponseRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorResponse) .filter(PaperResponse.class::isInstance) .map(PaperResponse.class::cast) .toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Digital Response's"); log.info("Saving Juror Digital Response's"); Util.batchSave(digitalResponseRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorResponse) .filter(DigitalResponse.class::isInstance) .map(DigitalResponse.class::cast) .toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Pool's"); log.info("Saving Juror Pool's to database"); Util.batchSave(jurorPoolRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorPools).flatMap(List::stream).toList(), BATCH_SIZE); stopWatch.stop(); } private void addSummonsReplyToJurorAccountDto(int digitalWeight, int paperWeight, JurorStatus jurorStatus, List<JurorAccountDetailsDto> jurors) { stopWatch.start("Creating Summons replies from jurors"); log.info("Creating {} juror responses from jurors", jurors.size()); DigitalResponseGenerator digitalResponseGenerator = DigitalResponseGeneratorUtil.create(jurorStatus); PaperResponseGenerator paperResponseGenerator = PaperResponseGeneratorUtil.create(jurorStatus); Map<AbstractJurorResponseGenerator<?>, Integer> weightMap = Map.of( digitalResponseGenerator, digitalWeight, paperResponseGenerator, paperWeight ); jurors.forEach(jurorAccountDetailsDto -> { AbstractJurorResponseGenerator<?> generator = Util.getWeightedRandomItem(weightMap); AbstractJurorResponse jurorResponse = generator.generate(); mapJurorToJurorResponse(jurorAccountDetailsDto.getJuror(), jurorResponse); jurorAccountDetailsDto.setJurorResponse(jurorResponse); }); stopWatch.stop(); }
private void mapJurorToJurorResponse(final Juror juror, final AbstractJurorResponse jurorResponse) {
4
2023-12-01 11:38:42+00:00
24k
SuperRicky14/TpaPlusPlus
src/main/java/net/superricky/tpaplusplus/command/TPAPlusPlusCommand.java
[ { "identifier": "Config", "path": "src/main/java/net/superricky/tpaplusplus/util/configuration/Config.java", "snippet": "public class Config {\n public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n public static final ForgeConfigSpec SPEC;\n\n public static fin...
import com.mojang.brigadier.arguments.StringArgumentType; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.network.chat.Component; import net.minecraftforge.event.RegisterCommandsEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.superricky.tpaplusplus.util.configuration.Config; import net.superricky.tpaplusplus.Main; import net.superricky.tpaplusplus.util.configuration.Messages; import net.superricky.tpaplusplus.util.manager.DeathManager; import net.superricky.tpaplusplus.util.configuration.formatters.MessageReformatter; import net.superricky.tpaplusplus.util.manager.RequestManager; import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.literal;
14,624
package net.superricky.tpaplusplus.command; @Mod.EventBusSubscriber public class TPAPlusPlusCommand { private static final String FORCE_PARAMETER = "-force"; @SubscribeEvent public static void onRegisterCommandEvent(RegisterCommandsEvent event) { event.getDispatcher().register(literal("tpaplusplus") .executes(context -> version(context.getSource())) .then(literal("refactor") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .then(literal("messages") .then(literal("color-set") .then(argument("colors", StringArgumentType.string()) .executes(context -> refactorColorSet(context.getSource(), StringArgumentType.getString(context, "colors"))))))) .then(literal("version") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .executes(context -> version(context.getSource()))) .then(literal("reload") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .executes(context -> reloadConfig(context.getSource(), false)) .then(literal(FORCE_PARAMETER) .executes(context -> reloadConfig(context.getSource(), true))) .then(literal("config") .executes(context -> reloadConfig(context.getSource(), false)) .then(literal(FORCE_PARAMETER) .executes(context -> reloadConfig(context.getSource(), true))))) .then(literal("license") .executes(context -> printLicense(context.getSource())))); } private TPAPlusPlusCommand() { } private static int printLicense(CommandSourceStack source) { source.sendSystemMessage(Component.literal(""" §6The §cMIT §6License §c(MIT) §cCopyright §6(c) §c2023 SuperRicky §6Permission is §chereby granted§6, §cfree of charge§6, to §cany person obtaining a copy of this software §6and associated documentation files (the "Software"), to deal in the Software §cwithout restriction, §6including without limitation the rights to §cuse§6, §ccopy§6, §cmodify§6, §cmerge§6, §cpublish§6, §cdistribute§6, §csublicense§6, and/or §csell copies of the Software§6, and to permit persons to whom the Software is furnished to do so, §4§l§usubject to the following conditions§6: §4§lThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. §6§lTHE SOFTWARE IS PROVIDED "AS IS", §c§lWITHOUT WARRANTY OF ANY KIND§6§l, §c§lEXPRESS OR IMPLIED§6§l, INCLUDING BUT §c§lNOT LIMITED TO §6§lTHE §c§lWARRANTIES OF MERCHANTABILITY§6§l, §c§lFITNESS §6§lFOR A §c§lPARTICULAR PURPOSE §6§lAND §c§lNONINFRINGEMENT§6§l. IN §4§lNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """)); return 1; } private static int refactorColorSet(CommandSourceStack source, String colors) { colors = colors.replace(" ", ""); String[] colorList = colors.split(","); if (colorList.length != 6) { source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_REQUIRE_SIX_COLORS.get(), colorList.length))); return 0; } for (String color : colorList) { if (!MessageReformatter.isValidColor(color)) { source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_INVALID_COLORS.get(), color))); source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_INVALID_COLORS_EXAMPLES.get(), MessageReformatter.getRandomColorCode()))); return 0; } } String oldMainColor = colorList[0].replace("&", "§").toLowerCase(); String oldSecondaryColor = colorList[1].replace("&", "§").toLowerCase(); String oldErrorColor = colorList[2].replace("&", "§").toLowerCase(); String newMainColor = colorList[3].replace("&", "§").toLowerCase(); String newSecondaryColor = colorList[4].replace("&", "§").toLowerCase(); String newErrorColor = colorList[5].replace("&", "§").toLowerCase(); if (oldMainColor.equals(oldSecondaryColor) || newMainColor.equals(newSecondaryColor)) { source.sendSystemMessage(Component.literal(Messages.ERR_TPAPLUSPLUS_COLORS_CANNOT_BE_THE_SAME.get())); return 0; } MessageReformatter.updateColorsAndSave(MessageReformatter.loadRawConfig(), oldMainColor, newMainColor, oldSecondaryColor, newSecondaryColor, oldErrorColor, newErrorColor); source.sendSystemMessage(Component.literal(Messages.TPAPLUSPLUS_COLORS_SUCCESS.get())); return 1; } private static int version(CommandSourceStack source) { source.sendSystemMessage(Component.literal(String.format(Messages.TPAPLUSPLUS_VERSION.get(), Main.MOD_VERSION))); // send the mod's version to the command executor return 1; } private static int reloadConfig(CommandSourceStack source, boolean force) { if (force) { source.sendSystemMessage(Component.literal(Messages.TPAPLUSPLUS_FORCE_RELOADING_CONFIG.get()));
package net.superricky.tpaplusplus.command; @Mod.EventBusSubscriber public class TPAPlusPlusCommand { private static final String FORCE_PARAMETER = "-force"; @SubscribeEvent public static void onRegisterCommandEvent(RegisterCommandsEvent event) { event.getDispatcher().register(literal("tpaplusplus") .executes(context -> version(context.getSource())) .then(literal("refactor") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .then(literal("messages") .then(literal("color-set") .then(argument("colors", StringArgumentType.string()) .executes(context -> refactorColorSet(context.getSource(), StringArgumentType.getString(context, "colors"))))))) .then(literal("version") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .executes(context -> version(context.getSource()))) .then(literal("reload") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .executes(context -> reloadConfig(context.getSource(), false)) .then(literal(FORCE_PARAMETER) .executes(context -> reloadConfig(context.getSource(), true))) .then(literal("config") .executes(context -> reloadConfig(context.getSource(), false)) .then(literal(FORCE_PARAMETER) .executes(context -> reloadConfig(context.getSource(), true))))) .then(literal("license") .executes(context -> printLicense(context.getSource())))); } private TPAPlusPlusCommand() { } private static int printLicense(CommandSourceStack source) { source.sendSystemMessage(Component.literal(""" §6The §cMIT §6License §c(MIT) §cCopyright §6(c) §c2023 SuperRicky §6Permission is §chereby granted§6, §cfree of charge§6, to §cany person obtaining a copy of this software §6and associated documentation files (the "Software"), to deal in the Software §cwithout restriction, §6including without limitation the rights to §cuse§6, §ccopy§6, §cmodify§6, §cmerge§6, §cpublish§6, §cdistribute§6, §csublicense§6, and/or §csell copies of the Software§6, and to permit persons to whom the Software is furnished to do so, §4§l§usubject to the following conditions§6: §4§lThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. §6§lTHE SOFTWARE IS PROVIDED "AS IS", §c§lWITHOUT WARRANTY OF ANY KIND§6§l, §c§lEXPRESS OR IMPLIED§6§l, INCLUDING BUT §c§lNOT LIMITED TO §6§lTHE §c§lWARRANTIES OF MERCHANTABILITY§6§l, §c§lFITNESS §6§lFOR A §c§lPARTICULAR PURPOSE §6§lAND §c§lNONINFRINGEMENT§6§l. IN §4§lNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """)); return 1; } private static int refactorColorSet(CommandSourceStack source, String colors) { colors = colors.replace(" ", ""); String[] colorList = colors.split(","); if (colorList.length != 6) { source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_REQUIRE_SIX_COLORS.get(), colorList.length))); return 0; } for (String color : colorList) { if (!MessageReformatter.isValidColor(color)) { source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_INVALID_COLORS.get(), color))); source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_INVALID_COLORS_EXAMPLES.get(), MessageReformatter.getRandomColorCode()))); return 0; } } String oldMainColor = colorList[0].replace("&", "§").toLowerCase(); String oldSecondaryColor = colorList[1].replace("&", "§").toLowerCase(); String oldErrorColor = colorList[2].replace("&", "§").toLowerCase(); String newMainColor = colorList[3].replace("&", "§").toLowerCase(); String newSecondaryColor = colorList[4].replace("&", "§").toLowerCase(); String newErrorColor = colorList[5].replace("&", "§").toLowerCase(); if (oldMainColor.equals(oldSecondaryColor) || newMainColor.equals(newSecondaryColor)) { source.sendSystemMessage(Component.literal(Messages.ERR_TPAPLUSPLUS_COLORS_CANNOT_BE_THE_SAME.get())); return 0; } MessageReformatter.updateColorsAndSave(MessageReformatter.loadRawConfig(), oldMainColor, newMainColor, oldSecondaryColor, newSecondaryColor, oldErrorColor, newErrorColor); source.sendSystemMessage(Component.literal(Messages.TPAPLUSPLUS_COLORS_SUCCESS.get())); return 1; } private static int version(CommandSourceStack source) { source.sendSystemMessage(Component.literal(String.format(Messages.TPAPLUSPLUS_VERSION.get(), Main.MOD_VERSION))); // send the mod's version to the command executor return 1; } private static int reloadConfig(CommandSourceStack source, boolean force) { if (force) { source.sendSystemMessage(Component.literal(Messages.TPAPLUSPLUS_FORCE_RELOADING_CONFIG.get()));
Config.SPEC.afterReload();
0
2023-12-02 05:41:24+00:00
24k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/ui/generic/EditActivity.java
[ { "identifier": "ActivityDiaryApplication", "path": "app/src/main/java/de/rampro/activitydiary/ActivityDiaryApplication.java", "snippet": "public class ActivityDiaryApplication extends Application {\n\n private static Context context;\n\n public void onCreate() {\n SpeechUtility.createUtili...
import android.content.AsyncQueryHandler; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import androidx.annotation.ColorInt; import androidx.annotation.Nullable; import com.google.android.material.textfield.TextInputLayout; import androidx.appcompat.widget.TooltipCompat; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Toast; import com.pes.androidmaterialcolorpickerdialog.ColorPicker; import com.pes.androidmaterialcolorpickerdialog.ColorPickerCallback; import java.util.LinkedList; import de.rampro.activitydiary.ActivityDiaryApplication; import de.rampro.activitydiary.R; import de.rampro.activitydiary.db.ActivityDiaryContract; import de.rampro.activitydiary.helpers.ActivityHelper; import de.rampro.activitydiary.helpers.JaroWinkler; import de.rampro.activitydiary.helpers.GraphicsHelper; import de.rampro.activitydiary.model.DiaryActivity;
14,490
/* * ActivityDiary * * Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de * Copyright (C) 2018 Sam Partee * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.ui.generic; /* * EditActivity to add and modify activities * * */ public class EditActivity extends BaseActivity implements ActivityHelper.DataChangedListener { @Nullable private DiaryActivity currentActivity; /* null is for creating a new object */ private final int QUERY_NAMES = 1; private final int RENAME_DELETED_ACTIVITY = 2; private final int TEST_DELETED_NAME = 3; private final int SIMILAR_ACTIVITY = 4; private final String[] NAME_TEST_PROJ = new String[]{ActivityDiaryContract.DiaryActivity.NAME}; private final String COLOR_KEY = "COLOR"; private final String NAME_KEY = "NAME"; private EditText mActivityName; private TextInputLayout mActivityNameTIL; private ImageView mActivityColorImg; private int mActivityColor; private ColorPicker mCp; private int linkCol; /* accent color -> to be sued for links */ private ImageButton mQuickFixBtn1; private ImageButton mBtnRenameDeleted; private int checkState = CHECK_STATE_CHECKING; private static final int CHECK_STATE_CHECKING = 0; private static final int CHECK_STATE_OK = 1; private static final int CHECK_STATE_WARNING = 2; private static final int CHECK_STATE_ERROR = 3;
/* * ActivityDiary * * Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de * Copyright (C) 2018 Sam Partee * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.ui.generic; /* * EditActivity to add and modify activities * * */ public class EditActivity extends BaseActivity implements ActivityHelper.DataChangedListener { @Nullable private DiaryActivity currentActivity; /* null is for creating a new object */ private final int QUERY_NAMES = 1; private final int RENAME_DELETED_ACTIVITY = 2; private final int TEST_DELETED_NAME = 3; private final int SIMILAR_ACTIVITY = 4; private final String[] NAME_TEST_PROJ = new String[]{ActivityDiaryContract.DiaryActivity.NAME}; private final String COLOR_KEY = "COLOR"; private final String NAME_KEY = "NAME"; private EditText mActivityName; private TextInputLayout mActivityNameTIL; private ImageView mActivityColorImg; private int mActivityColor; private ColorPicker mCp; private int linkCol; /* accent color -> to be sued for links */ private ImageButton mQuickFixBtn1; private ImageButton mBtnRenameDeleted; private int checkState = CHECK_STATE_CHECKING; private static final int CHECK_STATE_CHECKING = 0; private static final int CHECK_STATE_OK = 1; private static final int CHECK_STATE_WARNING = 2; private static final int CHECK_STATE_ERROR = 3;
JaroWinkler mJaroWinkler = new JaroWinkler(0.8);
3
2023-12-02 12:36:40+00:00
24k
Ethylene9160/Chess
src/chess/main/WebStartPanel.java
[ { "identifier": "PanelBase", "path": "src/chess/panels/PanelBase.java", "snippet": "public abstract class PanelBase extends JPanel {\n public PanelType type;\n protected int ax=-1,ay=-1,bx=-1,by=-1;\n protected int currentPlayer, xOld, yOld;\n\n protected Point aOldPoint = new Point(0,0), aC...
import chess.panels.PanelBase; import chess.panels.WebButtons; import chess.panels.WebPanel; import chess.util.Constants; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import static chess.panels.PanelBase.FIRST;
16,394
package chess.main; public class WebStartPanel extends JPanel { private WebPanel webPanel; private WebButtons webButtons; public WebStartPanel(String IP, int port){ super(); webPanel = new WebPanel(new JLabel(FIRST), IP, port); webButtons = new WebButtons(webPanel);
package chess.main; public class WebStartPanel extends JPanel { private WebPanel webPanel; private WebButtons webButtons; public WebStartPanel(String IP, int port){ super(); webPanel = new WebPanel(new JLabel(FIRST), IP, port); webButtons = new WebButtons(webPanel);
webPanel.setBounds(0, 0, Constants.PANEL_WEIGHT, PanelBase.BOARD_HEIGHT);
3
2023-12-01 02:33:32+00:00
24k
ynewmark/vector-lang
compiler/src/main/java/org/vectorlang/compiler/App.java
[ { "identifier": "CodeBase", "path": "compiler/src/main/java/org/vectorlang/compiler/ast/CodeBase.java", "snippet": "public class CodeBase {\n \n private final FunctionStatement[] functions;\n\n public CodeBase(FunctionStatement[] functions) {\n this.functions = functions;\n }\n\n p...
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.List; import org.vectorlang.compiler.ast.CodeBase; import org.vectorlang.compiler.compiler.Chunk; import org.vectorlang.compiler.compiler.Compiler; import org.vectorlang.compiler.compiler.Linker; import org.vectorlang.compiler.compiler.Pruner; import org.vectorlang.compiler.compiler.TypeFailure; import org.vectorlang.compiler.compiler.Typer; import org.vectorlang.compiler.parser.Lexer; import org.vectorlang.compiler.parser.Parser; import org.vectorlang.compiler.parser.Token;
15,410
package org.vectorlang.compiler; public class App { public static void main(String[] args) { if (args.length < 1) { System.err.println("Provide a file to compile"); System.exit(1); } File file = new File(args[0]); FileReader reader; StringBuilder builder = new StringBuilder(); try { reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); bufferedReader.lines().forEach((String line) -> { builder.append(line).append('\n'); }); bufferedReader.close(); } catch (FileNotFoundException e) { System.err.println("File " + args[0] + " not found"); System.exit(1); } catch (IOException e) { System.err.println("Failed to close file"); System.exit(1); } String code = builder.toString(); Lexer lexer = new Lexer(code); List<Token> tokens = lexer.lex(); Parser parser = new Parser(); CodeBase codeBase = parser.parse(tokens);
package org.vectorlang.compiler; public class App { public static void main(String[] args) { if (args.length < 1) { System.err.println("Provide a file to compile"); System.exit(1); } File file = new File(args[0]); FileReader reader; StringBuilder builder = new StringBuilder(); try { reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); bufferedReader.lines().forEach((String line) -> { builder.append(line).append('\n'); }); bufferedReader.close(); } catch (FileNotFoundException e) { System.err.println("File " + args[0] + " not found"); System.exit(1); } catch (IOException e) { System.err.println("Failed to close file"); System.exit(1); } String code = builder.toString(); Lexer lexer = new Lexer(code); List<Token> tokens = lexer.lex(); Parser parser = new Parser(); CodeBase codeBase = parser.parse(tokens);
Typer typer = new Typer();
5
2023-11-30 04:22:36+00:00
24k
godheaven/klib-data-jdbc
src/main/java/cl/kanopus/jdbc/impl/AbstractDAO.java
[ { "identifier": "DAOInterface", "path": "src/main/java/cl/kanopus/jdbc/DAOInterface.java", "snippet": "public interface DAOInterface<T, I> {\r\n\r\n long generateID() throws DataException;\r\n\r\n void persist(T entity) throws DataException;\r\n\r\n int update(T entity) throws DataException;\r\...
import cl.kanopus.common.data.Paginator; import cl.kanopus.common.data.enums.SortOrder; import cl.kanopus.common.enums.EnumIdentifiable; import cl.kanopus.common.util.CryptographyUtils; import cl.kanopus.common.util.GsonUtils; import cl.kanopus.common.util.Utils; import cl.kanopus.jdbc.DAOInterface; import cl.kanopus.jdbc.entity.Mapping; import cl.kanopus.jdbc.entity.annotation.Column; import cl.kanopus.jdbc.entity.annotation.ColumnGroup; import cl.kanopus.jdbc.entity.annotation.JoinTable; import cl.kanopus.jdbc.entity.annotation.Table; import cl.kanopus.jdbc.entity.mapper.AbstractRowMapper; import cl.kanopus.jdbc.exception.DataException; import cl.kanopus.jdbc.impl.engine.CustomEngine; import cl.kanopus.jdbc.impl.engine.Engine; import cl.kanopus.jdbc.impl.engine.OracleEngine; import cl.kanopus.jdbc.impl.engine.PostgresEngine; import cl.kanopus.jdbc.impl.engine.SQLServerEngine; import cl.kanopus.jdbc.util.JdbcCache; import cl.kanopus.jdbc.util.QueryIterator; import cl.kanopus.jdbc.util.SQLQueryDynamic; import cl.kanopus.jdbc.util.parser.ByteaJsonListParser; import cl.kanopus.jdbc.util.parser.ByteaJsonParser; import cl.kanopus.jdbc.util.parser.EnumParser; import cl.kanopus.jdbc.util.parser.JsonListParser; import cl.kanopus.jdbc.util.parser.JsonParser; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.postgresql.util.PGobject; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall;
15,317
} sql.append(" WHERE "); firstElement = true; for (String key : primaryKeys) { sql.append(!firstElement ? " AND " : ""); sql.append(key).append("=:").append(key); firstElement = false; } return update(sql.toString(), params); } private Table getTableName(Class clazz) throws DataException { Table table = (Table) clazz.getAnnotation(Table.class); if (table == null) { throw new DataException("There is no annotation @Table into the class: " + clazz.getCanonicalName()); } return table; } private boolean isPrimaryKey(Table table, String field) { boolean isPrimary = false; if (table != null) { for (String key : table.keys()) { if (key.equals(field)) { isPrimary = true; break; } } } return isPrimary; } private HashMap<String, Object> prepareParams(Operation operation, Object object) throws DataException { HashMap<String, Object> params = new HashMap<>(); try { if (object != null) { Table table = object.getClass().getAnnotation(Table.class); for (Field field : object.getClass().getDeclaredFields()) { // this is for private scope field.setAccessible(true); Object value = field.get(object); Column column = field.getAnnotation(Column.class); if (column != null && ((operation == Operation.PERSIST && column.insertable()) || (operation == Operation.UPDATE && column.updatable()) || isPrimaryKey(table, column.name()))) { if (column.parser() == EnumParser.class && value instanceof EnumIdentifiable) { params.put(column.name(), ((EnumIdentifiable) value).getId()); } else if (column.parser() == EnumParser.class && value instanceof Enum) { params.put(column.name(), ((Enum) value).name()); } else if (column.parser() == JsonParser.class || column.parser() == JsonListParser.class) { PGobject jsonbObj = new PGobject(); jsonbObj.setType("json"); jsonbObj.setValue(GsonUtils.custom.toJson(value)); params.put(column.name(), jsonbObj); } else if (column.parser() == ByteaJsonParser.class || column.parser() == ByteaJsonListParser.class) { byte[] bytes = GsonUtils.custom.toJson(value).getBytes(DEFAULT_CHARSET); params.put(column.name(), bytes); } else if (value instanceof StringWriter) { //TODO: Hacer un conversor generico byte[] bytes = ((StringWriter) value).toString().getBytes(DEFAULT_CHARSET); params.put(column.name(), bytes); } else if (value instanceof String) { String text = ((String) value).trim(); text = (column.length() > 0 && text.length() > column.length()) ? text.substring(0, column.length()) : text; params.put(column.name(), column.encrypted() ? CryptographyUtils.encrypt(text) : text); } else { boolean isZeroOrNull = (value == null || (value instanceof Long && ((Long) value) == 0) || (value instanceof Integer && ((Integer) value) == 0)); if (!column.serial() || (column.serial() && !isZeroOrNull)) { params.put(column.name(), value); } } } else { ColumnGroup columnMapping = field.getAnnotation(ColumnGroup.class); if (columnMapping != null) { params.putAll(prepareParams(operation, value)); } else { JoinTable joinTable = field.getAnnotation(JoinTable.class); if (joinTable != null) { Object tableValue = field.get(object); if (tableValue != null) { params.put(joinTable.foreignKey(), extractPrimaryKey(tableValue)); } } } } } } } catch (Exception ex) { throw new DataException("Error preparing parameter of the Object", ex); } return params; } private Object extractPrimaryKey(Object entity) throws IllegalArgumentException, IllegalAccessException { Table table = entity.getClass().getAnnotation(Table.class); String key = table.keys()[0]; Object value = null; for (Field field : entity.getClass().getDeclaredFields()) { Column column = field.getAnnotation(Column.class); if (column != null && column.name().equals(key)) { // this is for private scope field.setAccessible(true); value = field.get(entity); if (column.parser() == EnumParser.class && value instanceof EnumIdentifiable) { value = ((EnumIdentifiable) value).getId(); } else if (column.parser() == EnumParser.class && value instanceof Enum) { value = ((Enum) value).name(); } break; } } return value; }
package cl.kanopus.jdbc.impl; /** * This abstract class defines methods for data access that are common, * generally, all kinds of data access DAO must implement this class.Thus it is * given safely access the Connection database. The JdbcTemplate property is * kept private and gives access to the database through the methods implemented * in this AbstractDAO. * * @param <T> * @param <ID> * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @SuppressWarnings("all") public abstract class AbstractDAO<T extends Mapping, ID> implements DAOInterface<T, ID> { enum Operation { UPDATE, PERSIST } private final Class<T> genericTypeClass; protected AbstractDAO() { Type type = getClass().getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) type; genericTypeClass = (Class<T>) paramType.getActualTypeArguments()[0]; } protected abstract NamedParameterJdbcTemplate getJdbcTemplate(); private static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; protected abstract Engine getEngine(); private String createSqlPagination2Engine(SQLQueryDynamic sqlQuery) { String sql = getCustom().prepareSQL2Engine(sqlQuery.getSQL()); if (sqlQuery.isLimited()) { return getCustom().createSqlPagination(sql, sqlQuery.getLimit(), sqlQuery.getOffset()).toString(); } else { return sql; } } private String createSqlPagination(String sql, int limit, int offset) { return getCustom().createSqlPagination(sql, limit, offset).toString(); } @Override public int deleteByID(ID id) throws DataException { return deleteByID(getGenericTypeClass(), id); } protected int deleteByID(Class clazz, ID key) throws DataException { return deleteByID(clazz, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected int deleteByID(Class clazz, Object... keys) throws DataException { Table table = getTableName(clazz); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } if (table.keys().length != keys.length) { throw new DataException("It is necessary to specify the same amount keys to remove the entity: " + table.getClass().getCanonicalName()); } StringBuilder sql = new StringBuilder(); sql.append("DELETE FROM ").append(table.name()).append(" WHERE "); HashMap<String, Object> params = new HashMap<>(); for (int i = 0; i < keys.length; i++) { params.put(table.keys()[i], keys[i]); sql.append(i == 0 ? "" : " AND "); sql.append(table.keys()[i]).append("=:").append(table.keys()[i]); } return update(sql.toString(), params); } protected <T> List<T> executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params, Class<T> returnType) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters); SqlParameterSource in = new MapSqlParameterSource().addValues(params); Map<String, Object> out = sjc.execute(in); Map.Entry<String, Object> entry = out.entrySet().iterator().next(); if (entry.getValue() instanceof List<?>) { List<?> tempList = (List<?>) entry.getValue(); if (!tempList.isEmpty() && tempList.get(0).getClass().equals(returnType)) { return (List<T>) entry.getValue(); } } return new ArrayList<>(); } protected void executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters); SqlParameterSource in = new MapSqlParameterSource().addValues(params); sjc.execute(in); } protected T executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params, Class<T> returnType) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); return sjc.executeFunction(returnType, params); } protected void executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); sjc.execute(params); } protected Map<String, Object> executeProcedureOut(String name, SqlParameter[] parameters, MapSqlParameterSource params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); Map<String, Object> out = sjc.execute(params); return out; } @Override public List<T> findAll() throws DataException { Table table = getTableName(getGenericTypeClass()); SQLQueryDynamic sqlQuery = new SQLQueryDynamic(getGenericTypeClass()); if (!"[unassigned]".equals(table.defaultOrderBy())) { sqlQuery.setOrderBy(table.defaultOrderBy(), SortOrder.ASCENDING); } return (List<T>) AbstractDAO.this.find(sqlQuery); } public List findAll(Class<? extends Mapping> aClass) throws DataException { return findAll(aClass, false); } public List findAll(Class<? extends Mapping> aClass, boolean loadAll) throws DataException { //@TODO: implementar defaultOrderBy List list; try { String sql = JdbcCache.sqlBase(aClass, loadAll); list = getJdbcTemplate().query(sql, rowMapper(aClass, loadAll)); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } catch (DataException de) { throw de; } catch (Exception ex) { throw new DataException(ex.getMessage(), ex); } return list; } @Override public List<T> findTop(int limit, SortOrder sortOrder) throws DataException { Table table = getTableName(getGenericTypeClass()); StringBuilder sql = new StringBuilder(); sql.append(JdbcCache.sqlBase(getGenericTypeClass())); if (table.keys() != null) { sql.append(" ORDER BY "); for (String s : table.keys()) { sql.append(s); } sql.append(sortOrder == SortOrder.DESCENDING ? " DESC" : " ASC"); } StringBuilder customSql = getCustom().createSqlPagination(sql.toString(), limit, 0); return AbstractDAO.this.find(customSql.toString()); } public Iterator findQueryIterator(SQLQueryDynamic sqlQuery) { int limit = Utils.defaultValue(sqlQuery.getLimit(), 2500); if (!sqlQuery.isSorted()) { throw new DataException("It is necessary to specify a sort with identifier to be able to iterate over the records."); } return new QueryIterator<Map<String, Object>>(limit) { @Override public List getData(int limit, int offset) { sqlQuery.setLimit(limit); sqlQuery.setOffset(offset); List records = null; if (sqlQuery.getClazz() != null) { records = getJdbcTemplate().query(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), rowMapper(sqlQuery.getClazz(), sqlQuery.isLoadAll())); } else { records = getJdbcTemplate().queryForList(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams()); } sqlQuery.setTotalResultCount(sqlQuery.getTotalResultCount() + records.size()); return records; } }; } protected List<T> find(String sql) throws DataException { List list; try { list = getJdbcTemplate().query(sql, rowMapper(getGenericTypeClass())); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<T> find(String sql, HashMap<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().query(sql, params, rowMapper(getGenericTypeClass())); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz) throws DataException { List list; try { list = getJdbcTemplate().query(sql, params, rowMapper(clazz)); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz, int limit, int offset) throws DataException { List list; try { String sqlPagination = createSqlPagination(sql, limit, offset); list = getJdbcTemplate().query(sqlPagination, params, rowMapper(clazz)); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<?> find(SQLQueryDynamic sqlQuery) throws DataException { return find(sqlQuery, sqlQuery.getClazz()); } protected List find(SQLQueryDynamic sqlQuery, Class<? extends Mapping> clazz) throws DataException { List records = getJdbcTemplate().query(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), rowMapper(clazz, sqlQuery.isLoadAll())); if (sqlQuery.isLimited()) { long count = getJdbcTemplate().queryForObject(getCustom().prepareSQL2Engine(sqlQuery.getSQLCount()), sqlQuery.getParams(), Long.class); sqlQuery.setTotalResultCount(count); } else { sqlQuery.setTotalResultCount(records.size()); } return records; } protected Paginator findPaginator(SQLQueryDynamic sqlQuery) throws DataException { List records = find(sqlQuery, sqlQuery.getClazz()); Paginator paginator = new Paginator(); paginator.setRecords(records); paginator.setTotalRecords(sqlQuery.getTotalResultCount()); return paginator; } protected Paginator<Map<String, Object>> findMaps(SQLQueryDynamic sqlQuery) throws DataException { Paginator paginator = new Paginator(); try { List records = getJdbcTemplate().queryForList(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams()); if (sqlQuery.isLimited()) { long count = getJdbcTemplate().queryForObject(getCustom().prepareSQL2Engine(sqlQuery.getSQLCount()), sqlQuery.getParams(), Long.class); sqlQuery.setTotalResultCount(count); } else { sqlQuery.setTotalResultCount(records.size()); } paginator.setRecords(records); paginator.setTotalRecords(sqlQuery.getTotalResultCount()); } catch (EmptyResultDataAccessException e) { paginator.setRecords(new ArrayList<>()); paginator.setTotalRecords(0); } return paginator; } protected List<Map<String, Object>> findMaps(String sql, Map<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().queryForList(sql, params); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<Map<String, Object>> findMaps(String sql, Map<String, ?> params, int limit, int offset) throws DataException { List list; try { String sqlPagination = createSqlPagination(sql, limit, offset); list = getJdbcTemplate().queryForList(sqlPagination, params); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<String> findStrings(String sql, Map<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().queryForList(sql, params, String.class); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<String> findStrings(String sql, Map<String, ?> params, int limit, int offset) throws DataException { List list; try { String sqlPagination = createSqlPagination(sql, limit, offset); list = getJdbcTemplate().queryForList(sqlPagination, params, String.class); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<Long> findLongs(String sql, Map<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().queryForList(sql, params, Long.class); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } @Override public long generateID() throws DataException { Table table = getTableName(getGenericTypeClass()); if (table.sequence() == null) { throw new DataException("It is necessary to specify the sequence related to the entity:"); } String customSql = getCustom().createSqlNextval(table.sequence()); return queryForLong(customSql); } protected long generateAnyID(Class<? extends Mapping> clazz) throws DataException { Table table = getTableName(clazz); if (table.sequence() == null) { throw new DataException("It is necessary to specify the sequence related to the entity:"); } String customSql = getCustom().createSqlNextval(table.sequence()); return queryForLong(customSql); } @Override public T getByID(ID id) throws DataException { return (T) getByID(getGenericTypeClass(), id); } @Override public T getByID(ID key, boolean loadAll) throws DataException { return (T) getByID(getGenericTypeClass(), loadAll, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected <T extends Mapping> T getByID(Class<T> clazz, ID key) throws DataException { return getByID(clazz, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected <T extends Mapping> T getByID(Class<T> clazz, Object... keys) throws DataException { return getByID(clazz, false, keys); } protected <T extends Mapping> T getByID(Class<T> clazz, boolean loadAll, Object... keys) throws DataException { Table table = getTableName(clazz); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } if (table.keys().length != keys.length) { throw new DataException("It is necessary to specify the same keys to identify the entity: " + table.getClass().getCanonicalName()); } StringBuilder sql = new StringBuilder(); sql.append(JdbcCache.sqlBase(clazz, true)).append(" WHERE "); HashMap<String, Object> params = new HashMap<>(); for (int i = 0; i < keys.length; i++) { params.put(table.keys()[i], keys[i]); sql.append(i == 0 ? "" : " AND "); sql.append(table.keys()[i]).append("=:").append(table.keys()[i]); } return (T) queryForObject(sql.toString(), params, rowMapper(clazz, loadAll)); } private Class<T> getGenericTypeClass() { return genericTypeClass; } @Override public void persist(T object) throws DataException { persistAny(object); } protected void persistAny(Mapping object) throws DataException { Table table = getTableName(object.getClass()); HashMap<String, Object> params = prepareParams(Operation.PERSIST, object); StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO ").append(table.name()); sql.append("("); boolean firstElement = true; for (String key : params.keySet()) { sql.append(!firstElement ? "," : ""); sql.append(key); firstElement = false; } sql.append(") VALUES"); sql.append("("); firstElement = true; for (String key : params.keySet()) { sql.append(!firstElement ? "," : ""); sql.append(":").append(key); firstElement = false; } sql.append(")"); update(sql.toString(), params); } protected String queryForString(String sql, HashMap<String, ?> params) throws DataException { String object; try { object = getJdbcTemplate().queryForObject(sql, params, String.class); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected byte[] queryForBytes(String sql, HashMap<String, ?> params) throws DataException { return getJdbcTemplate().queryForObject(sql, params, byte[].class); } protected Integer queryForInteger(String sql) throws DataException { return queryForInteger(sql, null); } protected Integer queryForInteger(String sql, HashMap<String, ?> params) throws DataException { Integer object; try { object = getJdbcTemplate().queryForObject(sql, params, Integer.class); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected Long queryForLong(String sql) throws DataException { return queryForLong(sql, null); } protected Long queryForLong(String sql, HashMap<String, ?> params) throws DataException { Long object; try { object = getJdbcTemplate().queryForObject(sql, params, Long.class); } catch (EmptyResultDataAccessException e) { object = null; } return object; } private T queryForObject(String sql, HashMap<String, ?> params, AbstractRowMapper<T> rowMapper) throws DataException { T mapping; try { mapping = getJdbcTemplate().queryForObject(sql, params, rowMapper); } catch (EmptyResultDataAccessException e) { mapping = null; } return mapping; } protected T queryForObject(String sql, HashMap<String, ?> params) throws DataException { return queryForObject(sql, params, true); } protected T queryForObject(String sql, HashMap<String, ?> params, boolean loadAll) throws DataException { T object; try { object = (T) queryForObject(sql, params, rowMapper(getGenericTypeClass(), loadAll)); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected <I extends Mapping> I queryForObject(SQLQueryDynamic sqlQuery) throws DataException { return queryForObject(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), (Class<I>) sqlQuery.getClazz()); } protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz) throws DataException { return queryForObject(sql, params, clazz, true); } protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz, boolean loadAll) throws DataException { Object object; try { object = getJdbcTemplate().queryForObject(sql, params, rowMapper(clazz, loadAll)); } catch (EmptyResultDataAccessException e) { object = null; } return (I) object; } private AbstractRowMapper rowMapper(final Class clazz) { return JdbcCache.rowMapper(clazz, false); } private AbstractRowMapper rowMapper(final Class clazz, boolean loadAll) { return JdbcCache.rowMapper(clazz, loadAll); } protected int update(String sql, HashMap<String, ?> params) throws DataException { return getJdbcTemplate().update(sql, params); } @Override public int update(T object) throws DataException { return updateAny(object); } protected int updateAny(Mapping object) throws DataException { Table table = getTableName(object.getClass()); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } List<String> primaryKeys = Arrays.asList(table.keys()); HashMap<String, Object> params = prepareParams(Operation.UPDATE, object); StringBuilder sql = new StringBuilder(); sql.append("UPDATE ").append(table.name()); sql.append(" SET "); boolean firstElement = true; for (String key : params.keySet()) { if (primaryKeys.contains(key)) { continue; } sql.append(!firstElement ? "," : ""); sql.append(key).append("=:").append(key); firstElement = false; } sql.append(" WHERE "); firstElement = true; for (String key : primaryKeys) { sql.append(!firstElement ? " AND " : ""); sql.append(key).append("=:").append(key); firstElement = false; } return update(sql.toString(), params); } private Table getTableName(Class clazz) throws DataException { Table table = (Table) clazz.getAnnotation(Table.class); if (table == null) { throw new DataException("There is no annotation @Table into the class: " + clazz.getCanonicalName()); } return table; } private boolean isPrimaryKey(Table table, String field) { boolean isPrimary = false; if (table != null) { for (String key : table.keys()) { if (key.equals(field)) { isPrimary = true; break; } } } return isPrimary; } private HashMap<String, Object> prepareParams(Operation operation, Object object) throws DataException { HashMap<String, Object> params = new HashMap<>(); try { if (object != null) { Table table = object.getClass().getAnnotation(Table.class); for (Field field : object.getClass().getDeclaredFields()) { // this is for private scope field.setAccessible(true); Object value = field.get(object); Column column = field.getAnnotation(Column.class); if (column != null && ((operation == Operation.PERSIST && column.insertable()) || (operation == Operation.UPDATE && column.updatable()) || isPrimaryKey(table, column.name()))) { if (column.parser() == EnumParser.class && value instanceof EnumIdentifiable) { params.put(column.name(), ((EnumIdentifiable) value).getId()); } else if (column.parser() == EnumParser.class && value instanceof Enum) { params.put(column.name(), ((Enum) value).name()); } else if (column.parser() == JsonParser.class || column.parser() == JsonListParser.class) { PGobject jsonbObj = new PGobject(); jsonbObj.setType("json"); jsonbObj.setValue(GsonUtils.custom.toJson(value)); params.put(column.name(), jsonbObj); } else if (column.parser() == ByteaJsonParser.class || column.parser() == ByteaJsonListParser.class) { byte[] bytes = GsonUtils.custom.toJson(value).getBytes(DEFAULT_CHARSET); params.put(column.name(), bytes); } else if (value instanceof StringWriter) { //TODO: Hacer un conversor generico byte[] bytes = ((StringWriter) value).toString().getBytes(DEFAULT_CHARSET); params.put(column.name(), bytes); } else if (value instanceof String) { String text = ((String) value).trim(); text = (column.length() > 0 && text.length() > column.length()) ? text.substring(0, column.length()) : text; params.put(column.name(), column.encrypted() ? CryptographyUtils.encrypt(text) : text); } else { boolean isZeroOrNull = (value == null || (value instanceof Long && ((Long) value) == 0) || (value instanceof Integer && ((Integer) value) == 0)); if (!column.serial() || (column.serial() && !isZeroOrNull)) { params.put(column.name(), value); } } } else { ColumnGroup columnMapping = field.getAnnotation(ColumnGroup.class); if (columnMapping != null) { params.putAll(prepareParams(operation, value)); } else { JoinTable joinTable = field.getAnnotation(JoinTable.class); if (joinTable != null) { Object tableValue = field.get(object); if (tableValue != null) { params.put(joinTable.foreignKey(), extractPrimaryKey(tableValue)); } } } } } } } catch (Exception ex) { throw new DataException("Error preparing parameter of the Object", ex); } return params; } private Object extractPrimaryKey(Object entity) throws IllegalArgumentException, IllegalAccessException { Table table = entity.getClass().getAnnotation(Table.class); String key = table.keys()[0]; Object value = null; for (Field field : entity.getClass().getDeclaredFields()) { Column column = field.getAnnotation(Column.class); if (column != null && column.name().equals(key)) { // this is for private scope field.setAccessible(true); value = field.get(entity); if (column.parser() == EnumParser.class && value instanceof EnumIdentifiable) { value = ((EnumIdentifiable) value).getId(); } else if (column.parser() == EnumParser.class && value instanceof Enum) { value = ((Enum) value).name(); } break; } } return value; }
private CustomEngine getCustom() {
4
2023-11-27 18:25:00+00:00
24k
aliyun/aliyun-pairec-config-java-sdk
src/main/java/com/aliyun/openservices/pairec/ExperimentClient.java
[ { "identifier": "ApiClient", "path": "src/main/java/com/aliyun/openservices/pairec/api/ApiClient.java", "snippet": "public class ApiClient {\n private Configuration configuration;\n Client client;\n\n private CrowdApi crowdApi;\n\n private SceneApi sceneApi;\n\n private ExperimentRoomApi ...
import com.aliyun.openservices.pairec.api.ApiClient; import com.aliyun.openservices.pairec.common.Constants; import com.aliyun.openservices.pairec.model.DefaultSceneParams; import com.aliyun.openservices.pairec.model.EmptySceneParams; import com.aliyun.openservices.pairec.model.Experiment; import com.aliyun.openservices.pairec.model.ExperimentContext; import com.aliyun.openservices.pairec.model.ExperimentGroup; import com.aliyun.openservices.pairec.model.ExperimentResult; import com.aliyun.openservices.pairec.model.ExperimentRoom; import com.aliyun.openservices.pairec.model.Layer; import com.aliyun.openservices.pairec.model.Param; import com.aliyun.openservices.pairec.model.Scene; import java.math.BigInteger; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.aliyun.openservices.pairec.model.SceneParams; import com.aliyun.openservices.pairec.util.FNV; import org.apache.commons.codec.digest.DigestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
18,073
package com.aliyun.openservices.pairec; public class ExperimentClient { public static Logger logger = LoggerFactory.getLogger(ExperimentClient.class); private ApiClient apiClient ; /** * cache experiment data by per scene */ Map<String, Scene> sceneMap = new HashMap<>(); /** * cache param data by per scene */ Map<String, SceneParams> sceneParamData = new HashMap<>(); ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); boolean started = false; public ExperimentClient(ApiClient apiClient) { this.apiClient = apiClient; } private static class ExperimentWorker extends Thread { ExperimentClient experimentClient; public ExperimentWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadExperimentData(); } catch (Exception e) { logger.error(e.getMessage()); } } } private static class SceneParamWorker extends Thread { ExperimentClient experimentClient; public SceneParamWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadSceneParamsData(); } catch (Exception e) { logger.error(e.getMessage()); } } } public synchronized void init() throws Exception { if (started) { return; } logger.debug("experiment client init"); loadExperimentData(); loadSceneParamsData(); ExperimentWorker worker = new ExperimentWorker(this); scheduledThreadPool.scheduleWithFixedDelay(worker, 60, 60, TimeUnit.SECONDS); SceneParamWorker sceneParamWorker = new SceneParamWorker(this); scheduledThreadPool.scheduleWithFixedDelay(sceneParamWorker, 60, 60, TimeUnit.SECONDS); started = true; } /** * load experiment data from ab server * * @throws Exception */ public void loadExperimentData() throws Exception { Map<String, Scene> sceneData = new HashMap<>(); List<Scene> scenes= apiClient.getSceneApi().listAllScenes(); for (Scene scene : scenes) { List<ExperimentRoom> experimentRooms = apiClient.getExperimentRoomApi().listExperimentRooms(apiClient.getConfiguration().getEnvironment(), scene.getSceneId(), Constants.ExpRoom_Status_Online); for (ExperimentRoom experimentRoom : experimentRooms) { if (experimentRoom.getDebugCrowdId() != null && experimentRoom.getDebugCrowdId() > 0) { List<String> expRoomDebugUsers = apiClient.getCrowdApi().listCrowdUsers(Long.valueOf(experimentRoom.getDebugCrowdId())); experimentRoom.setDebugCrowdIdUsers(expRoomDebugUsers); } experimentRoom.init(); scene.addExperimentRoom(experimentRoom); List<Layer> layers = apiClient.getLayerApi().listLayers(experimentRoom.getExpRoomId()); for (Layer layer : layers) { experimentRoom.addLayer(layer); List<ExperimentGroup> experimentGroups = apiClient.getExperimentGroupApi().listExperimentGroups(layer.getLayerId(), experimentRoom.getExpRoomId(), Constants.ExpGroup_Status_Online); for (ExperimentGroup experimentGroup : experimentGroups) { if (experimentGroup.getCrowdId() != null && experimentGroup.getCrowdId() > 0) { List<String> crowdUsers = apiClient.getCrowdApi().listCrowdUsers(experimentGroup.getCrowdId()); experimentGroup.setCrowdUsers(crowdUsers); } if (experimentGroup.getDebugCrowdId() != null && experimentGroup.getDebugCrowdId() > 0) { List<String> debugCrowdUsers = apiClient.getCrowdApi().listCrowdUsers(Long.valueOf(experimentGroup.getDebugCrowdId())); experimentGroup.setDebugCrowdUsers(debugCrowdUsers); } experimentGroup.init(); layer.addExperimentGroup(experimentGroup); List<Experiment> experiments = apiClient.getExperimentApi().listExperiments(experimentGroup.getExpGroupId(), Constants.Experiment_Status_Online); for (Experiment experiment : experiments) { if (experiment.getDebugCrowdId() != null && experiment.getDebugCrowdId() > 0) { List<String> debugCrowdUsers = apiClient.getCrowdApi().listCrowdUsers(Long.valueOf(experiment.getDebugCrowdId())); experiment.setDebugCrowdUsers(debugCrowdUsers); } experiment.init(); experimentGroup.addExperiment(experiment); } } } } sceneData.put(scene.getSceneName(), scene); } if (sceneData.size() > 0) { this.sceneMap = sceneData; } } public Map<String, Scene> getSceneMap() { return sceneMap; } /** * This method determines traffic based on the experimental context and returns the matching result * * @param sceneName scene name * @param experimentContext * @return ExperimentResult */
package com.aliyun.openservices.pairec; public class ExperimentClient { public static Logger logger = LoggerFactory.getLogger(ExperimentClient.class); private ApiClient apiClient ; /** * cache experiment data by per scene */ Map<String, Scene> sceneMap = new HashMap<>(); /** * cache param data by per scene */ Map<String, SceneParams> sceneParamData = new HashMap<>(); ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); boolean started = false; public ExperimentClient(ApiClient apiClient) { this.apiClient = apiClient; } private static class ExperimentWorker extends Thread { ExperimentClient experimentClient; public ExperimentWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadExperimentData(); } catch (Exception e) { logger.error(e.getMessage()); } } } private static class SceneParamWorker extends Thread { ExperimentClient experimentClient; public SceneParamWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadSceneParamsData(); } catch (Exception e) { logger.error(e.getMessage()); } } } public synchronized void init() throws Exception { if (started) { return; } logger.debug("experiment client init"); loadExperimentData(); loadSceneParamsData(); ExperimentWorker worker = new ExperimentWorker(this); scheduledThreadPool.scheduleWithFixedDelay(worker, 60, 60, TimeUnit.SECONDS); SceneParamWorker sceneParamWorker = new SceneParamWorker(this); scheduledThreadPool.scheduleWithFixedDelay(sceneParamWorker, 60, 60, TimeUnit.SECONDS); started = true; } /** * load experiment data from ab server * * @throws Exception */ public void loadExperimentData() throws Exception { Map<String, Scene> sceneData = new HashMap<>(); List<Scene> scenes= apiClient.getSceneApi().listAllScenes(); for (Scene scene : scenes) { List<ExperimentRoom> experimentRooms = apiClient.getExperimentRoomApi().listExperimentRooms(apiClient.getConfiguration().getEnvironment(), scene.getSceneId(), Constants.ExpRoom_Status_Online); for (ExperimentRoom experimentRoom : experimentRooms) { if (experimentRoom.getDebugCrowdId() != null && experimentRoom.getDebugCrowdId() > 0) { List<String> expRoomDebugUsers = apiClient.getCrowdApi().listCrowdUsers(Long.valueOf(experimentRoom.getDebugCrowdId())); experimentRoom.setDebugCrowdIdUsers(expRoomDebugUsers); } experimentRoom.init(); scene.addExperimentRoom(experimentRoom); List<Layer> layers = apiClient.getLayerApi().listLayers(experimentRoom.getExpRoomId()); for (Layer layer : layers) { experimentRoom.addLayer(layer); List<ExperimentGroup> experimentGroups = apiClient.getExperimentGroupApi().listExperimentGroups(layer.getLayerId(), experimentRoom.getExpRoomId(), Constants.ExpGroup_Status_Online); for (ExperimentGroup experimentGroup : experimentGroups) { if (experimentGroup.getCrowdId() != null && experimentGroup.getCrowdId() > 0) { List<String> crowdUsers = apiClient.getCrowdApi().listCrowdUsers(experimentGroup.getCrowdId()); experimentGroup.setCrowdUsers(crowdUsers); } if (experimentGroup.getDebugCrowdId() != null && experimentGroup.getDebugCrowdId() > 0) { List<String> debugCrowdUsers = apiClient.getCrowdApi().listCrowdUsers(Long.valueOf(experimentGroup.getDebugCrowdId())); experimentGroup.setDebugCrowdUsers(debugCrowdUsers); } experimentGroup.init(); layer.addExperimentGroup(experimentGroup); List<Experiment> experiments = apiClient.getExperimentApi().listExperiments(experimentGroup.getExpGroupId(), Constants.Experiment_Status_Online); for (Experiment experiment : experiments) { if (experiment.getDebugCrowdId() != null && experiment.getDebugCrowdId() > 0) { List<String> debugCrowdUsers = apiClient.getCrowdApi().listCrowdUsers(Long.valueOf(experiment.getDebugCrowdId())); experiment.setDebugCrowdUsers(debugCrowdUsers); } experiment.init(); experimentGroup.addExperiment(experiment); } } } } sceneData.put(scene.getSceneName(), scene); } if (sceneData.size() > 0) { this.sceneMap = sceneData; } } public Map<String, Scene> getSceneMap() { return sceneMap; } /** * This method determines traffic based on the experimental context and returns the matching result * * @param sceneName scene name * @param experimentContext * @return ExperimentResult */
public ExperimentResult matchExperiment(String sceneName, ExperimentContext experimentContext) {
5
2023-11-29 06:27:36+00:00
24k
tuxiaobei-scu/SCU-CCSOJ-Backend
DataBackup/src/main/java/top/hcode/hoj/manager/oj/DiscussionManager.java
[ { "identifier": "HOJAccessEnum", "path": "DataBackup/src/main/java/top/hcode/hoj/annotation/HOJAccessEnum.java", "snippet": "public enum HOJAccessEnum {\n /**\n * 公共讨论区\n */\n PUBLIC_DISCUSSION,\n\n /**\n * 团队讨论区\n */\n GROUP_DISCUSSION,\n\n /**\n * 比赛评论\n */\n ...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import top.hcode.hoj.annotation.HOJAccessEnum; import top.hcode.hoj.common.exception.StatusFailException; import top.hcode.hoj.common.exception.StatusForbiddenException; import top.hcode.hoj.common.exception.StatusNotFoundException; import top.hcode.hoj.dao.discussion.DiscussionEntityService; import top.hcode.hoj.dao.discussion.DiscussionLikeEntityService; import top.hcode.hoj.dao.discussion.DiscussionReportEntityService; import top.hcode.hoj.dao.problem.CategoryEntityService; import top.hcode.hoj.dao.problem.ProblemEntityService; import top.hcode.hoj.dao.user.UserAcproblemEntityService; import top.hcode.hoj.exception.AccessException; import top.hcode.hoj.pojo.entity.discussion.Discussion; import top.hcode.hoj.pojo.entity.discussion.DiscussionLike; import top.hcode.hoj.pojo.entity.discussion.DiscussionReport; import top.hcode.hoj.pojo.entity.problem.Category; import top.hcode.hoj.pojo.entity.problem.Problem; import top.hcode.hoj.pojo.entity.user.UserAcproblem; import top.hcode.hoj.pojo.vo.ConfigVo; import top.hcode.hoj.pojo.vo.DiscussionVo; import top.hcode.hoj.pojo.vo.UserRolesVo; import top.hcode.hoj.utils.Constants; import top.hcode.hoj.utils.RedisUtils; import top.hcode.hoj.validator.AccessValidator; import top.hcode.hoj.validator.GroupValidator; import java.util.List;
17,071
if (SecurityUtils.getSubject().hasRole("root")) { discussion.setRole("root"); } else if (SecurityUtils.getSubject().hasRole("admin") || SecurityUtils.getSubject().hasRole("problem_admin")) { discussion.setRole("admin"); } else { // 如果不是管理员角色,一律重置为不置顶 discussion.setTopPriority(false); } boolean isOk = discussionEntityService.saveOrUpdate(discussion); if (!isOk) { throw new StatusFailException("发布失败,请重新尝试!"); } } public void updateDiscussion(Discussion discussion) throws StatusFailException, StatusForbiddenException { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); if (!isRoot && !discussion.getUid().equals(userRolesVo.getUid()) && !(discussion.getGid() != null && groupValidator.isGroupAdmin(userRolesVo.getUid(), discussion.getGid()))) { throw new StatusForbiddenException("对不起,您无权限操作!"); } boolean isOk = discussionEntityService.updateById(discussion); if (!isOk) { throw new StatusFailException("修改失败"); } } public void removeDiscussion(Integer did) throws StatusFailException, StatusForbiddenException { // 获取当前登录的用户 Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); Discussion discussion = discussionEntityService.getById(did); if (!isRoot && !discussion.getUid().equals(userRolesVo.getUid()) && !(discussion.getGid() != null && groupValidator.isGroupAdmin(userRolesVo.getUid(), discussion.getGid()))) { throw new StatusForbiddenException("对不起,您无权限操作!"); } UpdateWrapper<Discussion> discussionUpdateWrapper = new UpdateWrapper<Discussion>().eq("id", did); // 如果不是是管理员,则需要附加当前用户的uid条件 if (!SecurityUtils.getSubject().hasRole("root") && !SecurityUtils.getSubject().hasRole("admin") && !SecurityUtils.getSubject().hasRole("problem_admin")) { discussionUpdateWrapper.eq("uid", userRolesVo.getUid()); } boolean isOk = discussionEntityService.remove(discussionUpdateWrapper); if (!isOk) { throw new StatusFailException("删除失败,无权限或者该讨论不存在"); } } @Transactional(rollbackFor = Exception.class) public void addDiscussionLike(Integer did, boolean toLike) throws StatusFailException, StatusForbiddenException { // 获取当前登录的用户 Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); Discussion discussion = discussionEntityService.getById(did); if (discussion.getGid() != null) { boolean isRoot = SecurityUtils.getSubject().hasRole("root"); if (!isRoot && !discussion.getUid().equals(userRolesVo.getUid()) && !groupValidator.isGroupMember(userRolesVo.getUid(), discussion.getGid())) { throw new StatusForbiddenException("对不起,您无权限操作!"); } } QueryWrapper<DiscussionLike> discussionLikeQueryWrapper = new QueryWrapper<>(); discussionLikeQueryWrapper.eq("did", did).eq("uid", userRolesVo.getUid()); DiscussionLike discussionLike = discussionLikeEntityService.getOne(discussionLikeQueryWrapper, false); if (toLike) { // 添加点赞 if (discussionLike == null) { // 如果不存在就添加 boolean isSave = discussionLikeEntityService.saveOrUpdate(new DiscussionLike().setUid(userRolesVo.getUid()).setDid(did)); if (!isSave) { throw new StatusFailException("点赞失败,请重试尝试!"); } } // 点赞+1 UpdateWrapper<Discussion> discussionUpdateWrapper = new UpdateWrapper<>(); discussionUpdateWrapper.eq("id", discussion.getId()) .setSql("like_num=like_num+1"); discussionEntityService.update(discussionUpdateWrapper); // 当前帖子要不是点赞者的 才发送点赞消息 if (!userRolesVo.getUsername().equals(discussion.getAuthor())) { discussionEntityService.updatePostLikeMsg(discussion.getUid(), userRolesVo.getUid(), did, discussion.getGid()); } } else { // 取消点赞 if (discussionLike != null) { // 如果存在就删除 boolean isDelete = discussionLikeEntityService.removeById(discussionLike.getId()); if (!isDelete) { throw new StatusFailException("取消点赞失败,请重试尝试!"); } } // 点赞-1 UpdateWrapper<Discussion> discussionUpdateWrapper = new UpdateWrapper<>(); discussionUpdateWrapper.setSql("like_num=like_num-1").eq("id", did); discussionEntityService.update(discussionUpdateWrapper); } } public List<Category> getDiscussionCategory() { return categoryEntityService.list(); }
package top.hcode.hoj.manager.oj; /** * @Author: Himit_ZH * @Date: 2022/3/11 15:21 * @Description: */ @Component public class DiscussionManager { @Autowired private DiscussionEntityService discussionEntityService; @Autowired private DiscussionLikeEntityService discussionLikeEntityService; @Autowired private CategoryEntityService categoryEntityService; @Autowired private DiscussionReportEntityService discussionReportEntityService; @Autowired private RedisUtils redisUtils; @Autowired private UserAcproblemEntityService userAcproblemEntityService; @Autowired private ProblemEntityService problemEntityService; @Autowired private GroupValidator groupValidator; @Autowired private AccessValidator accessValidator; @Autowired private ConfigVo configVo; public IPage<Discussion> getDiscussionList(Integer limit, Integer currentPage, Integer categoryId, String pid, boolean onlyMine, String keyword, boolean admin) { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); QueryWrapper<Discussion> discussionQueryWrapper = new QueryWrapper<>(); IPage<Discussion> iPage = new Page<>(currentPage, limit); if (categoryId != null) { discussionQueryWrapper.eq("category_id", categoryId); } if (!StringUtils.isEmpty(keyword)) { final String key = keyword.trim(); discussionQueryWrapper.and(wrapper -> wrapper.like("title", key).or() .like("author", key).or() .like("id", key).or() .like("description", key)); } boolean isAdmin = SecurityUtils.getSubject().hasRole("root") || SecurityUtils.getSubject().hasRole("problem_admin") || SecurityUtils.getSubject().hasRole("admin"); if (!StringUtils.isEmpty(pid)) { discussionQueryWrapper.eq("pid", pid); } if (!(admin && isAdmin)) { discussionQueryWrapper.isNull("gid"); } discussionQueryWrapper .eq(!(admin && isAdmin), "status", 0) .ne("id", 1) .orderByDesc("top_priority") .orderByDesc("gmt_create") .orderByDesc("like_num") .orderByDesc("view_num"); if (onlyMine) { discussionQueryWrapper.eq("uid", userRolesVo.getUid()); } return discussionEntityService.page(iPage, discussionQueryWrapper); } public DiscussionVo getDiscussion(Integer did) throws StatusNotFoundException, StatusForbiddenException, AccessException { // 获取当前登录的用户 Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); Discussion discussion = discussionEntityService.getById(did); if (discussion.getGid() != null) { accessValidator.validateAccess(HOJAccessEnum.GROUP_DISCUSSION); if (!isRoot && !discussion.getUid().equals(userRolesVo.getUid()) && !groupValidator.isGroupMember(userRolesVo.getUid(), discussion.getGid())) { throw new StatusForbiddenException("对不起,您无权限操作!"); } } else { accessValidator.validateAccess(HOJAccessEnum.PUBLIC_DISCUSSION); } String uid = null; if (userRolesVo != null) { uid = userRolesVo.getUid(); } DiscussionVo discussionVo = discussionEntityService.getDiscussion(did, uid); if (discussionVo == null) { throw new StatusNotFoundException("对不起,该讨论不存在!"); } if (discussionVo.getStatus() == 1) { throw new StatusForbiddenException("对不起,该讨论已被封禁!"); } // 浏览量+1 UpdateWrapper<Discussion> discussionUpdateWrapper = new UpdateWrapper<>(); discussionUpdateWrapper.setSql("view_num=view_num+1").eq("id", discussionVo.getId()); discussionEntityService.update(discussionUpdateWrapper); discussionVo.setViewNum(discussionVo.getViewNum() + 1); return discussionVo; } public void addDiscussion(Discussion discussion) throws StatusFailException, StatusForbiddenException, StatusNotFoundException { // 获取当前登录的用户 Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); boolean isProblemAdmin = SecurityUtils.getSubject().hasRole("problem_admin"); boolean isAdmin = SecurityUtils.getSubject().hasRole("admin"); String problemId = discussion.getPid(); if (problemId != null) { QueryWrapper<Problem> problemQueryWrapper = new QueryWrapper<>(); problemQueryWrapper.eq("problem_id", problemId); int problemCount = problemEntityService.count(problemQueryWrapper); if (problemCount == 0) { throw new StatusNotFoundException("对不起,该题目不存在,无法发布题解!"); } } if (discussion.getGid() != null) { if (!isRoot && !discussion.getUid().equals(userRolesVo.getUid()) && !groupValidator.isGroupMember(userRolesVo.getUid(), discussion.getGid())) { throw new StatusForbiddenException("对不起,您无权限操作!"); } } // 除管理员外 其它用户需要AC20道题目以上才可发帖,同时限制一天只能发帖5次 if (!isRoot && !isProblemAdmin && !isAdmin) { QueryWrapper<UserAcproblem> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("uid", userRolesVo.getUid()).select("distinct pid"); int userAcProblemCount = userAcproblemEntityService.count(queryWrapper); if (userAcProblemCount < configVo.getDefaultCreateDiscussionACInitValue()) { throw new StatusForbiddenException("对不起,您暂时不能评论!请先去提交题目通过" + configVo.getDefaultCreateDiscussionACInitValue() + "道以上!"); } String lockKey = Constants.Account.DISCUSSION_ADD_NUM_LOCK.getCode() + userRolesVo.getUid(); Integer num = (Integer) redisUtils.get(lockKey); if (num == null) { redisUtils.set(lockKey, 1, 3600 * 24); } else if (num >= configVo.getDefaultCreateDiscussionDailyLimit()) { throw new StatusForbiddenException("对不起,您今天发帖次数已超过" + configVo.getDefaultCreateDiscussionDailyLimit() + "次,已被限制!"); } else { redisUtils.incr(lockKey, 1); } } discussion.setAuthor(userRolesVo.getUsername()) .setAvatar(userRolesVo.getAvatar()) .setUid(userRolesVo.getUid()); if (SecurityUtils.getSubject().hasRole("root")) { discussion.setRole("root"); } else if (SecurityUtils.getSubject().hasRole("admin") || SecurityUtils.getSubject().hasRole("problem_admin")) { discussion.setRole("admin"); } else { // 如果不是管理员角色,一律重置为不置顶 discussion.setTopPriority(false); } boolean isOk = discussionEntityService.saveOrUpdate(discussion); if (!isOk) { throw new StatusFailException("发布失败,请重新尝试!"); } } public void updateDiscussion(Discussion discussion) throws StatusFailException, StatusForbiddenException { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); if (!isRoot && !discussion.getUid().equals(userRolesVo.getUid()) && !(discussion.getGid() != null && groupValidator.isGroupAdmin(userRolesVo.getUid(), discussion.getGid()))) { throw new StatusForbiddenException("对不起,您无权限操作!"); } boolean isOk = discussionEntityService.updateById(discussion); if (!isOk) { throw new StatusFailException("修改失败"); } } public void removeDiscussion(Integer did) throws StatusFailException, StatusForbiddenException { // 获取当前登录的用户 Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); Discussion discussion = discussionEntityService.getById(did); if (!isRoot && !discussion.getUid().equals(userRolesVo.getUid()) && !(discussion.getGid() != null && groupValidator.isGroupAdmin(userRolesVo.getUid(), discussion.getGid()))) { throw new StatusForbiddenException("对不起,您无权限操作!"); } UpdateWrapper<Discussion> discussionUpdateWrapper = new UpdateWrapper<Discussion>().eq("id", did); // 如果不是是管理员,则需要附加当前用户的uid条件 if (!SecurityUtils.getSubject().hasRole("root") && !SecurityUtils.getSubject().hasRole("admin") && !SecurityUtils.getSubject().hasRole("problem_admin")) { discussionUpdateWrapper.eq("uid", userRolesVo.getUid()); } boolean isOk = discussionEntityService.remove(discussionUpdateWrapper); if (!isOk) { throw new StatusFailException("删除失败,无权限或者该讨论不存在"); } } @Transactional(rollbackFor = Exception.class) public void addDiscussionLike(Integer did, boolean toLike) throws StatusFailException, StatusForbiddenException { // 获取当前登录的用户 Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); Discussion discussion = discussionEntityService.getById(did); if (discussion.getGid() != null) { boolean isRoot = SecurityUtils.getSubject().hasRole("root"); if (!isRoot && !discussion.getUid().equals(userRolesVo.getUid()) && !groupValidator.isGroupMember(userRolesVo.getUid(), discussion.getGid())) { throw new StatusForbiddenException("对不起,您无权限操作!"); } } QueryWrapper<DiscussionLike> discussionLikeQueryWrapper = new QueryWrapper<>(); discussionLikeQueryWrapper.eq("did", did).eq("uid", userRolesVo.getUid()); DiscussionLike discussionLike = discussionLikeEntityService.getOne(discussionLikeQueryWrapper, false); if (toLike) { // 添加点赞 if (discussionLike == null) { // 如果不存在就添加 boolean isSave = discussionLikeEntityService.saveOrUpdate(new DiscussionLike().setUid(userRolesVo.getUid()).setDid(did)); if (!isSave) { throw new StatusFailException("点赞失败,请重试尝试!"); } } // 点赞+1 UpdateWrapper<Discussion> discussionUpdateWrapper = new UpdateWrapper<>(); discussionUpdateWrapper.eq("id", discussion.getId()) .setSql("like_num=like_num+1"); discussionEntityService.update(discussionUpdateWrapper); // 当前帖子要不是点赞者的 才发送点赞消息 if (!userRolesVo.getUsername().equals(discussion.getAuthor())) { discussionEntityService.updatePostLikeMsg(discussion.getUid(), userRolesVo.getUid(), did, discussion.getGid()); } } else { // 取消点赞 if (discussionLike != null) { // 如果存在就删除 boolean isDelete = discussionLikeEntityService.removeById(discussionLike.getId()); if (!isDelete) { throw new StatusFailException("取消点赞失败,请重试尝试!"); } } // 点赞-1 UpdateWrapper<Discussion> discussionUpdateWrapper = new UpdateWrapper<>(); discussionUpdateWrapper.setSql("like_num=like_num-1").eq("id", did); discussionEntityService.update(discussionUpdateWrapper); } } public List<Category> getDiscussionCategory() { return categoryEntityService.list(); }
public void addDiscussionReport(DiscussionReport discussionReport) throws StatusFailException {
13
2023-12-03 14:15:51+00:00
24k
yichenhsiaonz/EscAIpe-room-final
src/main/java/nz/ac/auckland/se206/controllers/ControlRoomController.java
[ { "identifier": "App", "path": "src/main/java/nz/ac/auckland/se206/App.java", "snippet": "public class App extends Application {\n\n private static Scene scene;\n public static ControlRoomController controlRoomController;\n public static LabController labController;\n public static KitchenController...
import java.io.IOException; import javafx.animation.FadeTransition; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.shape.Circle; import javafx.util.Duration; import nz.ac.auckland.se206.App; import nz.ac.auckland.se206.GameState; import nz.ac.auckland.se206.SceneManager.AppUi; import nz.ac.auckland.se206.TextToSpeechManager; import nz.ac.auckland.se206.gpt.ChatMessage; import nz.ac.auckland.se206.gpt.GptPromptEngineering; import nz.ac.auckland.se206.gpt.openai.ApiProxyException; import nz.ac.auckland.se206.gpt.openai.ChatCompletionRequest; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult.Choice;
17,052
@FXML private void onFiveClicked() { appendNumber("5"); } @FXML private void onSixClicked() { appendNumber("6"); } @FXML private void onSevenClicked() { appendNumber("7"); } @FXML private void onEightClicked() { appendNumber("8"); } @FXML private void onNineClicked() { appendNumber("9"); } @FXML private void onZeroClicked() { appendNumber("0"); } /** Deletes the last entered digit of the code. */ @FXML private void onDeleteClicked() { if (code.length() > 0) { code = code.substring(0, code.length() - 1); codeText.setText(code); } } /** * Checks if the code is correct. * * @throws ApiProxyException if there is an error communicating with the API proxy */ @FXML private void onEnterClicked() throws ApiProxyException { System.out.println(code); System.out.println("Enter clicked"); // Check if the code is correct if (code.equals(GameState.code)) { GameState.playSound("/sounds/unlock.m4a"); // load the ai text for ending endingChatCompletionRequest = new ChatCompletionRequest().setN(1).setTemperature(0.2).setTopP(0.5).setMaxTokens(100); endingGpt(new ChatMessage("user", GptPromptEngineering.endingCongrats()), 1); codeText.setText("Unlocked"); GameState.isExitUnlocked = true; } else { codeText.setText("Incorrect"); Timeline timeline = new Timeline( new KeyFrame( Duration.seconds(1.5), event -> { codeText.setText(""); // reset the text codeText.clear(); // clear the input field })); timeline.setCycleCount(1); timeline.play(); // reset code code = ""; } } /** Returns to the control room screen when exit button clicked. */ @FXML private void onCloseKeypadClicked() throws IOException { System.out.println("Exit clicked"); keyPadAnchorPane.setVisible(false); } /** * Appends the input number to the text field if the code is less than 3 digits long. * * @param number the number to be appended */ private void appendNumber(String number) { if (code.length() < 6 && !codeText.getText().equals("Incorrect")) { codeText.appendText(number); code += number; } } /** * Runs the GPT model with a given chat message. * * @param msg the chat message to process * @return the response chat message * @throws ApiProxyException if there is an error communicating with the API proxy */ public ChatMessage endingGpt(ChatMessage msg, int iteration) throws ApiProxyException { endingChatCompletionRequest.addMessage(msg); // task for gpt chat generation Task<ChatMessage> gptTask = new Task<ChatMessage>() { @Override protected ChatMessage call() throws Exception { System.out.println("Get message: " + Thread.currentThread().getName()); try { // get response from gpt
package nz.ac.auckland.se206.controllers; /** Controller class for the Control Room. */ public class ControlRoomController { static ControlRoomController instance; @FXML private AnchorPane contentPane; @FXML private ImageView computer; @FXML private ImageView keypad; @FXML private ImageView exitDoor; @FXML private ImageView rightArrow; @FXML private ImageView rightGlowArrow; @FXML private ImageView leftArrow; @FXML private ImageView leftGlowArrow; @FXML private ImageView computerGlow; @FXML private ImageView exitGlow; @FXML private ImageView keypadGlow; @FXML private ImageView character; @FXML private ImageView running; @FXML private AnchorPane room; @FXML private HBox dialogueHorizontalBox; @FXML private Pane inventoryPane; @FXML private VBox hintVerticalBox; @FXML private VBox bottomVerticalBox; @FXML private ImageView neutralAi; @FXML private ImageView loadingAi; @FXML private ImageView talkingAi; @FXML private Circle rightDoorMarker; @FXML private Circle leftDoorMarker; @FXML private Circle computerMarker; @FXML private Circle keypadMarker; @FXML private Circle centerDoorMarker; @FXML private Button muteButton; // elements of keypad @FXML private AnchorPane keyPadAnchorPane; @FXML private TextField codeText; // elements of computer @FXML private AnchorPane computerAnchorPane; @FXML private AnchorPane computerLoginAnchorPane; @FXML private Label gptLabel; @FXML private Button enterButton; @FXML private TextField inputText; @FXML private AnchorPane computerSignedInAnchorPane; @FXML private ImageView computerDocumentIcon; @FXML private ImageView computerPrintIcon; @FXML private ImageView computerCatsIcon; @FXML private Image document = new Image("images/Computer/document.png"); @FXML private Image print = new Image("images/Computer/printer.png"); @FXML private Image cats = new Image("images/Computer/image.png"); @FXML private Image documentHover = new Image("images/Computer/document_hover.png"); @FXML private Image printHover = new Image("images/Computer/printer_hover.png"); @FXML private Image catsHover = new Image("images/Computer/image_hover.png"); @FXML private AnchorPane computerPrintWindowAnchorPane; @FXML private ImageView printIcon; @FXML private ImageView printIconComplete; @FXML private Button printButton; @FXML private Label printLabel; @FXML private AnchorPane computerTextWindowAnchorPane; @FXML private TextArea computerDoorCodeTextArea; @FXML private AnchorPane computerImageWindowAnchorPane; @FXML private Label riddleLabel; private String code = ""; private ChatCompletionRequest endingChatCompletionRequest; private ChatCompletionRequest computerChatCompletionRequest; private boolean firstOpeningTextFile; /** This method initializes the control room for when the user first enters it. */ public void initialize() { SharedElements.initialize( room, bottomVerticalBox, inventoryPane, dialogueHorizontalBox, muteButton, contentPane); // computer initialization firstOpeningTextFile = true; try { computerChatCompletionRequest = new ChatCompletionRequest().setN(1).setTemperature(0.2).setTopP(0.5).setMaxTokens(100); runGpt( new ChatMessage("user", GptPromptEngineering.getRiddle(GameState.getRiddleAnswer())), true); computerDoorCodeTextArea.setText( "TOP SECRET DOOR CODE: \n\n__" + GameState.getSecondDigits() + "__\n\n\n\n" + "(If only I could remember the other four digits)"); } catch (Exception e) { e.printStackTrace(); } GameState.goToInstant( centerDoorMarker.getLayoutX(), centerDoorMarker.getLayoutY(), character, running); instance = this; } /** * Handles the click event on the computer. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML private void clickComputer(MouseEvent event) throws IOException { System.out.println("computer clicked"); try { // move character to clicked location GameState.goTo(computerMarker.getLayoutX(), computerMarker.getLayoutY(), character, running); // flag the current puzzle as the computer puzzle for hints // set root to the computer // enable movement after delay Runnable accessComputer = () -> { GameState.setPuzzleComputer(); computerAnchorPane.setVisible(true); }; GameState.setOnMovementComplete(accessComputer); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to computer when hover @FXML private void onComputerHovered(MouseEvent event) { computerGlow.setVisible(true); } @FXML private void onComputerUnhovered(MouseEvent event) { computerGlow.setVisible(false); } /** * Handles the click event on the exit door. * * @param event the mouse event */ @FXML private void clickExit(MouseEvent event) { try { // move character to center door marker position GameState.goTo( centerDoorMarker.getLayoutX(), centerDoorMarker.getLayoutY(), character, running); Runnable leaveRoom = () -> { System.out.println("exit door clicked"); if (GameState.isExitUnlocked) { // if the exit is unlocked, fade to black for ending scene TextToSpeechManager.cutOff(); GameState.stopAllThreads(); GameState.stopSound(); GameState.playSound("/sounds/gate-open.m4a"); fadeBlack(); } else { String message = "The exit is locked and will not budge"; // otherwise, display notification in chat SharedElements.appendChat(message); SharedElements.chatBubbleSpeak(message); } }; GameState.setOnMovementComplete(leaveRoom); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to exit door when hover @FXML private void onExitHovered(MouseEvent event) { exitGlow.setVisible(true); } @FXML private void onExitUnhovered(MouseEvent event) { exitGlow.setVisible(false); } /** * Handles the click event on the keypad. * * @param event the mouse event * @throws IOException throws an exception if there is an error loading the keypad view */ @FXML private void clickKeypad(MouseEvent event) throws IOException { System.out.println("keypad clicked"); try { // check if the character is already moving to prevent multiple clicks // move character to clicked location GameState.goTo(keypadMarker.getLayoutX(), keypadMarker.getLayoutY(), character, running); // set root to the keypad after delay and enable movement Runnable accessKeypad = () -> { keyPadAnchorPane.setVisible(true); }; GameState.setOnMovementComplete(accessKeypad); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to keypad when hover @FXML private void onKeypadHovered(MouseEvent event) { keypadGlow.setVisible(true); } @FXML private void onKeypadUnhovered(MouseEvent event) { keypadGlow.setVisible(false); } /** * Handles the click event on the right arrow. * * @param event the mouse event */ @FXML private void onRightClicked(MouseEvent event) throws IOException { try { // move character to clicked location GameState.goTo( rightDoorMarker.getLayoutX(), rightDoorMarker.getLayoutY(), character, running); // set root to the kitchen after delay and enable movement Runnable leaveRoom = () -> { GameState.playSound("/sounds/door-opening.m4a"); GameState.fadeOut(room); Runnable loadKitchen = () -> { try { App.setRoot(AppUi.KITCHEN); KitchenController.instance.fadeIn(); } catch (IOException e) { e.printStackTrace(); } }; GameState.delayRun(loadKitchen, 1); }; GameState.setOnMovementComplete(leaveRoom); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to right arrow when hover @FXML private void onRightHovered(MouseEvent event) { rightGlowArrow.setVisible(true); } @FXML private void onRightUnhovered(MouseEvent event) { rightGlowArrow.setVisible(false); } /** * Handles the click event on the left arrow. * * @param event the mouse event */ @FXML private void onLeftClicked(MouseEvent event) { try { // move character to clicked location GameState.goTo(leftDoorMarker.getLayoutX(), leftDoorMarker.getLayoutY(), character, running); // set root to the lab after delay and enable movement Runnable leaveRoom = () -> { GameState.playSound("/sounds/door-opening.m4a"); GameState.fadeOut(room); Runnable loadLab = () -> { try { App.setRoot(AppUi.LAB); LabController.instance.fadeIn(); } catch (IOException e) { e.printStackTrace(); } }; GameState.delayRun(loadLab, 1); }; GameState.setOnMovementComplete(leaveRoom); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to left arrow when hover @FXML private void onLeftHovered(MouseEvent event) { leftGlowArrow.setVisible(true); } @FXML private void onLeftUnhovered(MouseEvent event) { leftGlowArrow.setVisible(false); } /** * 'Consumes' the mouse event, preventing it from being registered. * * @param event the mouse event */ @FXML private void consumeMouseEvent(MouseEvent event) { System.out.println("mouse event consumed"); System.out.println(event.getSource()); event.consume(); } /** * Handles the mouse click event on the room, moving the character to the clicked location. * * @param event the mouse event */ @FXML private void onMoveCharacter(MouseEvent event) { // check if the character is already moving to prevent multiple clicks // play click animation GameState.onCharacterMovementClick(event, room); // move character to clicked location double mouseX = event.getX(); double mouseY = event.getY(); GameState.goTo(mouseX, mouseY, character, running); GameState.startMoving(); } /** This method fades the room into black for transitions. */ public void fadeBlack() { // stop timer GameState.stopTimer(); // Create a black rectangle that covers the entire AnchorPane AnchorPane anchorPane = contentPane; AnchorPane blackRectangle = new AnchorPane(); blackRectangle.setStyle("-fx-background-color: black;"); blackRectangle.setOpacity(0.0); AnchorPane.setTopAnchor(blackRectangle, 0.0); AnchorPane.setBottomAnchor(blackRectangle, 0.0); AnchorPane.setLeftAnchor(blackRectangle, 0.0); AnchorPane.setRightAnchor(blackRectangle, 0.0); // Add the black rectangle to AnchorPane anchorPane.getChildren().add(blackRectangle); // Create a fade transition FadeTransition fadeToBlack = new FadeTransition(Duration.seconds(5), blackRectangle); fadeToBlack.setFromValue(0.0); fadeToBlack.setToValue(1.0); // Change to end scene when the fade animation is complete fadeToBlack.setOnFinished( event -> { try { App.setRoot(AppUi.ENDING); } catch (IOException e) { e.printStackTrace(); System.out.println("Error changing to ending scene"); } }); fadeToBlack.play(); } // get image of loading AI public ImageView getLoadingAi() { return loadingAi; } // get image of talking AI public ImageView getTalkingAi() { return talkingAi; } @FXML private void onBackToMenu(ActionEvent event) throws IOException { TextToSpeechManager.cutOff(); GameState.stopAllThreads(); GameState.stopSound(); App.setRoot(AppUi.MENU); } @FXML private void onMute(ActionEvent event) { GameState.toggleMuted(); } public void fadeIn() { GameState.fadeIn(room); } // keypad methods // Implement keypad functionality @FXML private void onOneClicked() { appendNumber("1"); } @FXML private void onTwoClicked() { appendNumber("2"); } @FXML private void onThreeClicked() { appendNumber("3"); } @FXML private void onFourClicked() { appendNumber("4"); } @FXML private void onFiveClicked() { appendNumber("5"); } @FXML private void onSixClicked() { appendNumber("6"); } @FXML private void onSevenClicked() { appendNumber("7"); } @FXML private void onEightClicked() { appendNumber("8"); } @FXML private void onNineClicked() { appendNumber("9"); } @FXML private void onZeroClicked() { appendNumber("0"); } /** Deletes the last entered digit of the code. */ @FXML private void onDeleteClicked() { if (code.length() > 0) { code = code.substring(0, code.length() - 1); codeText.setText(code); } } /** * Checks if the code is correct. * * @throws ApiProxyException if there is an error communicating with the API proxy */ @FXML private void onEnterClicked() throws ApiProxyException { System.out.println(code); System.out.println("Enter clicked"); // Check if the code is correct if (code.equals(GameState.code)) { GameState.playSound("/sounds/unlock.m4a"); // load the ai text for ending endingChatCompletionRequest = new ChatCompletionRequest().setN(1).setTemperature(0.2).setTopP(0.5).setMaxTokens(100); endingGpt(new ChatMessage("user", GptPromptEngineering.endingCongrats()), 1); codeText.setText("Unlocked"); GameState.isExitUnlocked = true; } else { codeText.setText("Incorrect"); Timeline timeline = new Timeline( new KeyFrame( Duration.seconds(1.5), event -> { codeText.setText(""); // reset the text codeText.clear(); // clear the input field })); timeline.setCycleCount(1); timeline.play(); // reset code code = ""; } } /** Returns to the control room screen when exit button clicked. */ @FXML private void onCloseKeypadClicked() throws IOException { System.out.println("Exit clicked"); keyPadAnchorPane.setVisible(false); } /** * Appends the input number to the text field if the code is less than 3 digits long. * * @param number the number to be appended */ private void appendNumber(String number) { if (code.length() < 6 && !codeText.getText().equals("Incorrect")) { codeText.appendText(number); code += number; } } /** * Runs the GPT model with a given chat message. * * @param msg the chat message to process * @return the response chat message * @throws ApiProxyException if there is an error communicating with the API proxy */ public ChatMessage endingGpt(ChatMessage msg, int iteration) throws ApiProxyException { endingChatCompletionRequest.addMessage(msg); // task for gpt chat generation Task<ChatMessage> gptTask = new Task<ChatMessage>() { @Override protected ChatMessage call() throws Exception { System.out.println("Get message: " + Thread.currentThread().getName()); try { // get response from gpt
ChatCompletionResult chatCompletionResult = endingChatCompletionRequest.execute();
8
2023-12-02 04:57:43+00:00
24k
nageoffer/shortlink
project/src/main/java/com/nageoffer/shortlink/project/service/impl/ShortLinkServiceImpl.java
[ { "identifier": "ClientException", "path": "project/src/main/java/com/nageoffer/shortlink/project/common/convention/exception/ClientException.java", "snippet": "public class ClientException extends AbstractException {\n\n public ClientException(IErrorCode errorCode) {\n this(null, null, errorC...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.Week; import cn.hutool.core.lang.UUID; import cn.hutool.core.text.StrBuilder; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.nageoffer.shortlink.project.common.convention.exception.ClientException; import com.nageoffer.shortlink.project.common.convention.exception.ServiceException; import com.nageoffer.shortlink.project.common.enums.VailDateTypeEnum; import com.nageoffer.shortlink.project.config.GotoDomainWhiteListConfiguration; import com.nageoffer.shortlink.project.dao.entity.LinkAccessLogsDO; import com.nageoffer.shortlink.project.dao.entity.LinkAccessStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkBrowserStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkDeviceStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkLocaleStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkNetworkStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkOsStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkStatsTodayDO; import com.nageoffer.shortlink.project.dao.entity.ShortLinkDO; import com.nageoffer.shortlink.project.dao.entity.ShortLinkGotoDO; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessLogsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkBrowserStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkDeviceStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkLocaleStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkNetworkStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkOsStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkStatsTodayMapper; import com.nageoffer.shortlink.project.dao.mapper.ShortLinkGotoMapper; import com.nageoffer.shortlink.project.dao.mapper.ShortLinkMapper; import com.nageoffer.shortlink.project.dto.biz.ShortLinkStatsRecordDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkBatchCreateReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkCreateReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkPageReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkUpdateReqDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkBaseInfoRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkBatchCreateRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkCreateRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkGroupCountQueryRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkPageRespDTO; import com.nageoffer.shortlink.project.mq.producer.DelayShortLinkStatsProducer; import com.nageoffer.shortlink.project.service.LinkStatsTodayService; import com.nageoffer.shortlink.project.service.ShortLinkService; import com.nageoffer.shortlink.project.toolkit.HashUtil; import com.nageoffer.shortlink.project.toolkit.LinkUtil; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.redisson.api.RBloomFilter; import org.redisson.api.RLock; import org.redisson.api.RReadWriteLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DuplicateKeyException; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.GOTO_IS_NULL_SHORT_LINK_KEY; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.GOTO_SHORT_LINK_KEY; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.LOCK_GID_UPDATE_KEY; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.LOCK_GOTO_SHORT_LINK_KEY; import static com.nageoffer.shortlink.project.common.constant.ShortLinkConstant.AMAP_REMOTE_URL;
15,470
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nageoffer.shortlink.project.service.impl; /** * 短链接接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class ShortLinkServiceImpl extends ServiceImpl<ShortLinkMapper, ShortLinkDO> implements ShortLinkService { private final RBloomFilter<String> shortUriCreateCachePenetrationBloomFilter; private final ShortLinkGotoMapper shortLinkGotoMapper; private final StringRedisTemplate stringRedisTemplate; private final RedissonClient redissonClient; private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nageoffer.shortlink.project.service.impl; /** * 短链接接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class ShortLinkServiceImpl extends ServiceImpl<ShortLinkMapper, ShortLinkDO> implements ShortLinkService { private final RBloomFilter<String> shortUriCreateCachePenetrationBloomFilter; private final ShortLinkGotoMapper shortLinkGotoMapper; private final StringRedisTemplate stringRedisTemplate; private final RedissonClient redissonClient; private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper;
private final LinkOsStatsMapper linkOsStatsMapper;
20
2023-11-19 16:04:32+00:00
24k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/parser/HitsResultParser.java
[ { "identifier": "Constants", "path": "src/main/java/com/ly/ckibana/constants/Constants.java", "snippet": "public class Constants {\n\n public static final String HEADER_ELASTICSEARCH = \"Elasticsearch\";\n\n public static final String HEADER_X_ELASTIC_PRODUCT = \"X-elastic-product\";\n\n public...
import com.alibaba.fastjson2.JSONObject; import com.ly.ckibana.constants.Constants; import com.ly.ckibana.constants.SqlConstants; import com.ly.ckibana.model.compute.Range; import com.ly.ckibana.model.enums.SortType; import com.ly.ckibana.model.request.CkRequest; import com.ly.ckibana.model.request.CkRequestContext; import com.ly.ckibana.model.request.SortedField; import com.ly.ckibana.model.response.DocValue; import com.ly.ckibana.model.response.Hit; import com.ly.ckibana.model.response.HitsOptimizedResult; import com.ly.ckibana.model.response.Response; import com.ly.ckibana.service.CkService; import com.ly.ckibana.util.DateUtils; import com.ly.ckibana.util.JSONUtils; import com.ly.ckibana.util.ProxyUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
15,802
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * 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.ly.ckibana.parser; /** * 封装结果类. */ @Slf4j @Service public class HitsResultParser { @Resource private CkService ckService; /** * 查询hit *. * * @param ckRequestContext ckRequestContext * @param response response * @throws Exception Exception */ public void queryHits(CkRequestContext ckRequestContext, Response response) throws Exception { if (ckRequestContext.getSize() > 0) { CkRequest hitsRequest = buildHitRequest(ckRequestContext); optimizeSearchTimeRange(hitsRequest, ckRequestContext, response); String optimizedSql = hitsRequest.buildToStr(); queryHitsFromCk(ckRequestContext, response, optimizedSql); response.getSqls().add(String.format("%s", optimizedSql)); } } /** * 查询count. * * @param ckRequestContext ckRequestContext * @param response response * @return long count * @throws Exception Exception */ public long queryTotalCount(CkRequestContext ckRequestContext, Response response) throws Exception { long result = 0; String sql = getTotalCountQuerySql(ckRequestContext); Pair<List<JSONObject>, Boolean> countResultAndStatus = ckService.queryDataWithCacheAndStatus(ckRequestContext, sql); if (!countResultAndStatus.getLeft().isEmpty()) { result = countResultAndStatus.getLeft().get(0).getLongValue(SqlConstants.DEFAULT_COUNT_NAME); } if (response == null) { return result; } response.setCache(countResultAndStatus.getRight()); response.getSqls().add(sql); return result; } /** * 构建查询总条数的sql. * * @param ckRequestContext ckRequestContext * @return sql */ public String getTotalCountQuerySql(CkRequestContext ckRequestContext) { CkRequest countRequest = ProxyUtils.buildCkRequest(ckRequestContext); countRequest.initSelect(SqlConstants.COUNT_QUERY); if (StringUtils.isNotBlank(ckRequestContext.getQuery())) { countRequest.appendWhere(ckRequestContext.getQuery()); } return countRequest.buildToStr(); } /** * 从ck中查询hits,处理后返回. * * @param ckRequestContext ckRequestContext * @param response response * @param optimizedSql optimizedSql * @throws Exception Exception */ private void queryHitsFromCk(CkRequestContext ckRequestContext, Response response, String optimizedSql) throws Exception { Pair<List<JSONObject>, Boolean> hitResultAndStatus = ckService.queryDataWithCacheAndStatus(ckRequestContext, optimizedSql); response.getHits().setHits(buildHitsResponse(ckRequestContext, hitResultAndStatus.getLeft())); response.setCache(hitResultAndStatus.getRight()); } /** * 基于核心业务逻辑条件,获取每分钟的count统计值. * 用于优化带时间排序查询明细下的区间。如用户查询1小时数据的最近10条,加入最后1分钟数据>10条。实际可用最后1分钟作为时间条件查询明细 * * @param ckRequestContext ckRequestContext * @param optimizedContext optimizedContext * @param orgTimeRange orgTimeRange * @return List count * @throws Exception Exception */ private List<JSONObject> queryCountByDivMinutes(CkRequestContext ckRequestContext, HitsOptimizedResult optimizedContext, Range orgTimeRange) throws Exception { CkRequest ckRequest = getByMinuteRequest(optimizedContext.getSortType(), ckRequestContext, orgTimeRange); String sql = orgTimeRange.toSql(true); ckRequest.appendWhere(sql); ckRequest.appendWhere(ckRequestContext.getQuerySqlWithoutTimeRange()); String countByMinutesQuerySql = ckRequest.buildToStr(); optimizedContext.setCountByMinutesQuerySql(countByMinutesQuerySql); Pair<List<JSONObject>, Boolean> resultAndStatus = ckService.queryDataWithCacheAndStatus(ckRequestContext, countByMinutesQuerySql); optimizedContext.setCache(resultAndStatus.getRight()); return resultAndStatus.getLeft(); } public CkRequest buildHitRequest(CkRequestContext ckRequestContext) { CkRequest result = ProxyUtils.buildCkRequest(ckRequestContext); result.limit(ckRequestContext.getSize()); result.orderBy(ckRequestContext.getSort()); result.appendWhere(ckRequestContext.getQuery()); return result; } /** * 封装hits结构. * 展开extention字段, * 字段名转换为es字段名 * 封装sort,fields字段 * * @param ckRequestContext ckRequestContext * @param hitResult hitResult * @return List hits结果 */ private List<Hit> buildHitsResponse(CkRequestContext ckRequestContext, List<JSONObject> hitResult) { List<Hit> result = new ArrayList<>(); for (int i = 0; i < hitResult.size(); i++) { Hit hitTemp = new Hit(); //解压扩展字段,ck field->es field JSONObject hitSource = setHitResource(hitResult, i, hitTemp); hitTemp.setIndex(generateHitsIndexValue(ckRequestContext.getTableName(), hitSource.get(ckRequestContext.getIndexPattern().getTimeField()))); hitTemp.setId(generateHitsId(i, hitTemp)); setHitFieldsResponse(ckRequestContext, hitSource, hitTemp); setHitSortResponse(ckRequestContext, hitSource, hitTemp); result.add(hitTemp); //total已经在优化中设置 } return result; } private String generateHitsId(int index, Hit hitTemp) { return hitTemp.getIndex() + "_t" + System.currentTimeMillis() + "_i" + index; } /** * 生成hits index_id,非核心功能,异常返回空. * * @param tableName tableName * @param timeValue timeValue * @return String index_id */ private String generateHitsIndexValue(String tableName, Object timeValue) { try {
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * 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.ly.ckibana.parser; /** * 封装结果类. */ @Slf4j @Service public class HitsResultParser { @Resource private CkService ckService; /** * 查询hit *. * * @param ckRequestContext ckRequestContext * @param response response * @throws Exception Exception */ public void queryHits(CkRequestContext ckRequestContext, Response response) throws Exception { if (ckRequestContext.getSize() > 0) { CkRequest hitsRequest = buildHitRequest(ckRequestContext); optimizeSearchTimeRange(hitsRequest, ckRequestContext, response); String optimizedSql = hitsRequest.buildToStr(); queryHitsFromCk(ckRequestContext, response, optimizedSql); response.getSqls().add(String.format("%s", optimizedSql)); } } /** * 查询count. * * @param ckRequestContext ckRequestContext * @param response response * @return long count * @throws Exception Exception */ public long queryTotalCount(CkRequestContext ckRequestContext, Response response) throws Exception { long result = 0; String sql = getTotalCountQuerySql(ckRequestContext); Pair<List<JSONObject>, Boolean> countResultAndStatus = ckService.queryDataWithCacheAndStatus(ckRequestContext, sql); if (!countResultAndStatus.getLeft().isEmpty()) { result = countResultAndStatus.getLeft().get(0).getLongValue(SqlConstants.DEFAULT_COUNT_NAME); } if (response == null) { return result; } response.setCache(countResultAndStatus.getRight()); response.getSqls().add(sql); return result; } /** * 构建查询总条数的sql. * * @param ckRequestContext ckRequestContext * @return sql */ public String getTotalCountQuerySql(CkRequestContext ckRequestContext) { CkRequest countRequest = ProxyUtils.buildCkRequest(ckRequestContext); countRequest.initSelect(SqlConstants.COUNT_QUERY); if (StringUtils.isNotBlank(ckRequestContext.getQuery())) { countRequest.appendWhere(ckRequestContext.getQuery()); } return countRequest.buildToStr(); } /** * 从ck中查询hits,处理后返回. * * @param ckRequestContext ckRequestContext * @param response response * @param optimizedSql optimizedSql * @throws Exception Exception */ private void queryHitsFromCk(CkRequestContext ckRequestContext, Response response, String optimizedSql) throws Exception { Pair<List<JSONObject>, Boolean> hitResultAndStatus = ckService.queryDataWithCacheAndStatus(ckRequestContext, optimizedSql); response.getHits().setHits(buildHitsResponse(ckRequestContext, hitResultAndStatus.getLeft())); response.setCache(hitResultAndStatus.getRight()); } /** * 基于核心业务逻辑条件,获取每分钟的count统计值. * 用于优化带时间排序查询明细下的区间。如用户查询1小时数据的最近10条,加入最后1分钟数据>10条。实际可用最后1分钟作为时间条件查询明细 * * @param ckRequestContext ckRequestContext * @param optimizedContext optimizedContext * @param orgTimeRange orgTimeRange * @return List count * @throws Exception Exception */ private List<JSONObject> queryCountByDivMinutes(CkRequestContext ckRequestContext, HitsOptimizedResult optimizedContext, Range orgTimeRange) throws Exception { CkRequest ckRequest = getByMinuteRequest(optimizedContext.getSortType(), ckRequestContext, orgTimeRange); String sql = orgTimeRange.toSql(true); ckRequest.appendWhere(sql); ckRequest.appendWhere(ckRequestContext.getQuerySqlWithoutTimeRange()); String countByMinutesQuerySql = ckRequest.buildToStr(); optimizedContext.setCountByMinutesQuerySql(countByMinutesQuerySql); Pair<List<JSONObject>, Boolean> resultAndStatus = ckService.queryDataWithCacheAndStatus(ckRequestContext, countByMinutesQuerySql); optimizedContext.setCache(resultAndStatus.getRight()); return resultAndStatus.getLeft(); } public CkRequest buildHitRequest(CkRequestContext ckRequestContext) { CkRequest result = ProxyUtils.buildCkRequest(ckRequestContext); result.limit(ckRequestContext.getSize()); result.orderBy(ckRequestContext.getSort()); result.appendWhere(ckRequestContext.getQuery()); return result; } /** * 封装hits结构. * 展开extention字段, * 字段名转换为es字段名 * 封装sort,fields字段 * * @param ckRequestContext ckRequestContext * @param hitResult hitResult * @return List hits结果 */ private List<Hit> buildHitsResponse(CkRequestContext ckRequestContext, List<JSONObject> hitResult) { List<Hit> result = new ArrayList<>(); for (int i = 0; i < hitResult.size(); i++) { Hit hitTemp = new Hit(); //解压扩展字段,ck field->es field JSONObject hitSource = setHitResource(hitResult, i, hitTemp); hitTemp.setIndex(generateHitsIndexValue(ckRequestContext.getTableName(), hitSource.get(ckRequestContext.getIndexPattern().getTimeField()))); hitTemp.setId(generateHitsId(i, hitTemp)); setHitFieldsResponse(ckRequestContext, hitSource, hitTemp); setHitSortResponse(ckRequestContext, hitSource, hitTemp); result.add(hitTemp); //total已经在优化中设置 } return result; } private String generateHitsId(int index, Hit hitTemp) { return hitTemp.getIndex() + "_t" + System.currentTimeMillis() + "_i" + index; } /** * 生成hits index_id,非核心功能,异常返回空. * * @param tableName tableName * @param timeValue timeValue * @return String index_id */ private String generateHitsIndexValue(String tableName, Object timeValue) { try {
return String.format("%s-%s", tableName, DateUtils.getDateStr(timeValue));
12
2023-11-21 09:12:07+00:00
24k
lidaofu-hub/j_zlm_sdk
src/main/java/com/aizuda/test/Test.java
[ { "identifier": "IMKProxyPlayCloseCallBack", "path": "src/main/java/com/aizuda/callback/IMKProxyPlayCloseCallBack.java", "snippet": "public interface IMKProxyPlayCloseCallBack extends Callback {\n /**\n * MediaSource.close()回调事件\n * 在选择关闭一个关联的MediaSource时,将会最终触发到该回调\n * 你应该通过该事件调用mk_proxy...
import com.aizuda.callback.IMKProxyPlayCloseCallBack; import com.aizuda.core.ZLMApi; import com.aizuda.structure.MK_EVENTS; import com.aizuda.structure.MK_INI; import com.aizuda.structure.MK_PROXY_PLAYER; import com.sun.jna.Native; import com.sun.jna.Pointer;
18,292
package com.aizuda.test; /** * 测试程序 展示了服务器配置 系统配置 流媒体服务启动 回调监听 拉流代理 * * @author lidaofu * @since 2023/11/23 **/ public class Test { //动态链接库放在/resource/win32-x86-64&/resource/linux-x86-64下JNA会自动查找目录 //public static ZLMApi ZLM_API = Native.load("mk_api", ZLMApi.class); //Windows环境测试 public static ZLMApi ZLM_API = Native.load("D:\\ZLMediaKit\\source\\release\\windows\\Debug\\mk_api.dll", ZLMApi.class); //Linux环境测试 //public static ZLMApi ZLM_API = Native.load("/opt/media/libmk_api.so", ZLMApi.class); public static void main(String[] args) throws InterruptedException { //初始化环境配置 MK_INI mkIni = ZLM_API.mk_ini_default(); //配置参数 全部配置参数及说明见(resources/conf.ini) 打开自动关流 对应conf.ini中配置[protocol] auto_close ZLM_API.mk_ini_set_option_int(mkIni, "protocol.auto_close", 1); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_fmp4", 0); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_hls", 0); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_ts", 0); //全局回调 全部回调见MK_EVENTS内所有的回调属性,有些需要去实现,不然流无法播放或者无法推流 MK_EVENTS mkEvents = new MK_EVENTS(); //流状态改变回调 mkEvents.on_mk_media_changed = (regist, sender) -> { System.out.println("这里是流改变回调通知:" + regist); }; //无人观看回调 mkEvents.on_mk_media_no_reader = sender -> { System.out.println("这里是无人观看回调通知"); ZLM_API.mk_media_source_close(sender, 1); }; //播放回调可做播放鉴权 mkEvents.on_mk_media_play = (url_info, invoker, sender) -> { //这里拿到访问路径后(例如http://xxxx/xxx/xxx.live.flv?token=xxxx其中?后面就是拿到的参数)的参数 // err_msg返回 空字符串表示鉴权成功 否则鉴权失败提示 //String param = ZLM_API.mk_media_info_get_params(url_info); ZLM_API.mk_auth_invoker_do(invoker, ""); }; //推流回调 可控制鉴权、录制、转协议控制等 mkEvents.on_mk_media_publish = (url_info, invoker, sender) -> { //这里拿到访问路径后(例如rtmp://xxxx/xxx/xxx?token=xxxx其中?后面就是拿到的参数)的参数 // err_msg返回 空字符串表示鉴权成功 否则鉴权失败提示 //String param = ZLM_API.mk_media_info_get_params(url_info); ZLM_API.mk_publish_auth_invoker_do(invoker, "", 0, 0); }; //添加全局回调 ZLM_API.mk_events_listen(mkEvents); //Pointer iniPointer = ZLM_API.mk_ini_dump_string(mkIni); //初始化zmk服务器 ZLM_API.mk_env_init1(1, 1, 1, null, 0, 0, null, 0, null, null); //创建http服务器 0:失败,非0:端口号 short http_server_port = ZLM_API.mk_http_server_start((short) 7788, 0); //创建rtsp服务器 0:失败,非0:端口号 short rtsp_server_port = ZLM_API.mk_rtsp_server_start((short) 554, 0); //创建rtmp服务器 0:失败,非0:端口号 short rtmp_server_port = ZLM_API.mk_rtmp_server_start((short) 1935, 0); /*****************************下面为推流及播放********************************/ // 推流:利用obs、ffmpeg 进行推流 RTMP推流:rtmp://127.0.0.1:rtmp_port/流APP/流名称 RTSP推流:rtsp://127.0.0.1:rtsp_port/流APP/流名称 // 下面是各协议拉流播放的访问格式 // FLV拉流:http://127.0.0.1:http_port/流APP/流名称.live.flv // WS-FLV拉流:ws://127.0.0.1:http_port/流APP/流名称.live.flv // HLS拉流:http://127.0.0.1:http_port/流APP/流名称/hls.m3u8 // RTMP拉流:rtmp://127.0.0.1:rtmp_port/流APP/流名称 // RTSP拉流:rtsp://127.0.0.1:rtsp_port/流APP/流名称 /*****************************下面为流代理演示********************************/ //创建拉流代理 MK_PROXY_PLAYER mk_proxy = ZLM_API.mk_proxy_player_create("__defaultVhost__", "live", "test", 0, 0); //回调关闭时间
package com.aizuda.test; /** * 测试程序 展示了服务器配置 系统配置 流媒体服务启动 回调监听 拉流代理 * * @author lidaofu * @since 2023/11/23 **/ public class Test { //动态链接库放在/resource/win32-x86-64&/resource/linux-x86-64下JNA会自动查找目录 //public static ZLMApi ZLM_API = Native.load("mk_api", ZLMApi.class); //Windows环境测试 public static ZLMApi ZLM_API = Native.load("D:\\ZLMediaKit\\source\\release\\windows\\Debug\\mk_api.dll", ZLMApi.class); //Linux环境测试 //public static ZLMApi ZLM_API = Native.load("/opt/media/libmk_api.so", ZLMApi.class); public static void main(String[] args) throws InterruptedException { //初始化环境配置 MK_INI mkIni = ZLM_API.mk_ini_default(); //配置参数 全部配置参数及说明见(resources/conf.ini) 打开自动关流 对应conf.ini中配置[protocol] auto_close ZLM_API.mk_ini_set_option_int(mkIni, "protocol.auto_close", 1); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_fmp4", 0); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_hls", 0); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_ts", 0); //全局回调 全部回调见MK_EVENTS内所有的回调属性,有些需要去实现,不然流无法播放或者无法推流 MK_EVENTS mkEvents = new MK_EVENTS(); //流状态改变回调 mkEvents.on_mk_media_changed = (regist, sender) -> { System.out.println("这里是流改变回调通知:" + regist); }; //无人观看回调 mkEvents.on_mk_media_no_reader = sender -> { System.out.println("这里是无人观看回调通知"); ZLM_API.mk_media_source_close(sender, 1); }; //播放回调可做播放鉴权 mkEvents.on_mk_media_play = (url_info, invoker, sender) -> { //这里拿到访问路径后(例如http://xxxx/xxx/xxx.live.flv?token=xxxx其中?后面就是拿到的参数)的参数 // err_msg返回 空字符串表示鉴权成功 否则鉴权失败提示 //String param = ZLM_API.mk_media_info_get_params(url_info); ZLM_API.mk_auth_invoker_do(invoker, ""); }; //推流回调 可控制鉴权、录制、转协议控制等 mkEvents.on_mk_media_publish = (url_info, invoker, sender) -> { //这里拿到访问路径后(例如rtmp://xxxx/xxx/xxx?token=xxxx其中?后面就是拿到的参数)的参数 // err_msg返回 空字符串表示鉴权成功 否则鉴权失败提示 //String param = ZLM_API.mk_media_info_get_params(url_info); ZLM_API.mk_publish_auth_invoker_do(invoker, "", 0, 0); }; //添加全局回调 ZLM_API.mk_events_listen(mkEvents); //Pointer iniPointer = ZLM_API.mk_ini_dump_string(mkIni); //初始化zmk服务器 ZLM_API.mk_env_init1(1, 1, 1, null, 0, 0, null, 0, null, null); //创建http服务器 0:失败,非0:端口号 short http_server_port = ZLM_API.mk_http_server_start((short) 7788, 0); //创建rtsp服务器 0:失败,非0:端口号 short rtsp_server_port = ZLM_API.mk_rtsp_server_start((short) 554, 0); //创建rtmp服务器 0:失败,非0:端口号 short rtmp_server_port = ZLM_API.mk_rtmp_server_start((short) 1935, 0); /*****************************下面为推流及播放********************************/ // 推流:利用obs、ffmpeg 进行推流 RTMP推流:rtmp://127.0.0.1:rtmp_port/流APP/流名称 RTSP推流:rtsp://127.0.0.1:rtsp_port/流APP/流名称 // 下面是各协议拉流播放的访问格式 // FLV拉流:http://127.0.0.1:http_port/流APP/流名称.live.flv // WS-FLV拉流:ws://127.0.0.1:http_port/流APP/流名称.live.flv // HLS拉流:http://127.0.0.1:http_port/流APP/流名称/hls.m3u8 // RTMP拉流:rtmp://127.0.0.1:rtmp_port/流APP/流名称 // RTSP拉流:rtsp://127.0.0.1:rtsp_port/流APP/流名称 /*****************************下面为流代理演示********************************/ //创建拉流代理 MK_PROXY_PLAYER mk_proxy = ZLM_API.mk_proxy_player_create("__defaultVhost__", "live", "test", 0, 0); //回调关闭时间
IMKProxyPlayCloseCallBack imkProxyPlayCloseCallBack = new IMKProxyPlayCloseCallBack() {
0
2023-11-23 11:05:10+00:00
24k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/gdxparticleeditor/Listeners.java
[ { "identifier": "UndoManager", "path": "core/src/main/java/com/ray3k/gdxparticleeditor/undo/UndoManager.java", "snippet": "public class UndoManager {\n public final static Array<Undoable> undoables = new Array<>();\n public static int undoIndex = -1;\n\n public static void add(Undoable undoable...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Buttons; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.backends.lwjgl3.Lwjgl3WindowAdapter; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Cursor.SystemCursor; import com.badlogic.gdx.scenes.scene2d.*; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.scenes.scene2d.utils.Disableable; import com.badlogic.gdx.scenes.scene2d.utils.FocusListener; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.ray3k.gdxparticleeditor.undo.UndoManager; import com.ray3k.gdxparticleeditor.undo.undoables.ImagesAddUndoable; import com.ray3k.gdxparticleeditor.widgets.InfSlider; import com.ray3k.gdxparticleeditor.widgets.NoCaptureKeyboardFocusListener; import com.ray3k.gdxparticleeditor.widgets.poptables.PopConfirmClose; import com.ray3k.stripe.PopTable; import com.ray3k.stripe.PopTable.PopTableStyle; import com.ray3k.stripe.PopTable.TableShowHideListener; import com.ray3k.stripe.ScrollFocusListener; import com.ray3k.stripe.Spinner; import java.util.Locale; import static com.ray3k.gdxparticleeditor.Core.*; import static com.ray3k.gdxparticleeditor.PreviewSettings.*; import static com.ray3k.gdxparticleeditor.Utils.showToast; import static com.ray3k.gdxparticleeditor.widgets.panels.EffectEmittersPanel.effectEmittersPanel; import static com.ray3k.gdxparticleeditor.widgets.panels.EmitterPropertiesPanel.emitterPropertiesPanel; import static com.ray3k.gdxparticleeditor.widgets.styles.Styles.infSliderStyle; import static com.ray3k.gdxparticleeditor.widgets.styles.Styles.tooltipBottomRightArrowStyle; import static com.ray3k.gdxparticleeditor.widgets.subpanels.ImagesSubPanel.imagesSubPanel;
20,763
} public static PopTable addTooltip(Actor actor, String text, int edge, int align, PopTableStyle popTableStyle, boolean foreground) { return addTooltip(actor, text, edge, align, 0, false, popTableStyle, foreground); } private static PopTable addTooltip(Actor actor, String text, int edge, int align, float width, boolean defineWidth, PopTableStyle popTableStyle) { return addTooltip(actor, text, edge, align, width, defineWidth, popTableStyle, true); } private static PopTable addTooltip(Actor actor, String text, int edge, int align, float width, boolean defineWidth, PopTableStyle popTableStyle, boolean foreground) { PopTable popTable = new PopTable(popTableStyle); var inputListener = new ClickListener() { boolean dismissed; Action showTableAction; { popTable.setModal(false); popTable.setTouchable(Touchable.disabled); var label = new Label(text, skin); if (defineWidth) { label.setWrap(true); popTable.add(label).width(width); } else { popTable.add(label); } } @Override public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) { if (!Utils.isWindowFocused()) return; if (Gdx.input.isButtonPressed(Buttons.LEFT) || Gdx.input.isButtonPressed(Buttons.RIGHT) || Gdx.input.isButtonPressed(Buttons.MIDDLE)) return; if (pointer == -1 && popTable.isHidden() && !dismissed) { if (fromActor == null || !event.getListenerActor().isAscendantOf(fromActor)) { if (showTableAction == null) { showTableAction = Actions.delay(.5f, Actions.run(() -> { showTable(actor); showTableAction = null; })); actor.addAction(showTableAction); } } } } private void showTable(Actor actor) { if (actor instanceof Disableable) { if (((Disableable) actor).isDisabled()) return; } var inputProcessor = Gdx.input.getInputProcessor(); if (inputProcessor != actor.getStage()) return; popTable.show(foreground ? foregroundStage : stage); popTable.attachToActor(actor, edge, align); if (popTableStyle == tooltipBottomRightArrowStyle) popTable.setAttachOffsetX(7); popTable.moveToInsideStage(); } @Override public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) { if (pointer == -1) { if (toActor == null || !toActor.isDescendantOf(event.getListenerActor())) { if (!popTable.isHidden()) popTable.hide(); dismissed = false; if (showTableAction != null) { actor.removeAction(showTableAction); showTableAction = null; } } } } @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { dismissed = true; popTable.hide(); if (showTableAction != null) { actor.removeAction(showTableAction); showTableAction = null; } return false; } @Override public void clicked(InputEvent event, float x, float y) { } }; popTable.addListener(new TableShowHideListener() { @Override public void tableShown(Event event) { tooltips.add(popTable); } @Override public void tableHidden(Event event) { tooltips.removeValue(popTable, true); } }); actor.addListener(inputListener); return popTable; } public static void hideAllTooltips() { for (var tooltip : tooltips) { tooltip.hide(); } } public static void addInfiniteSlider(Spinner valueSpinner, float increment, float range, boolean adjustByPPM, ChangeListener changeListener) { var sliderPop = new PopTable(); sliderPop.attachToActor(valueSpinner, Align.bottom, Align.bottom);
package com.ray3k.gdxparticleeditor; /** * A convenience class to organize and initialize the custom listeners for GDX Particle Editor. */ public class Listeners { public static SystemCursorListener handListener; public static SystemCursorListener handListenerIgnoreDisabled; public static SystemCursorListener ibeamListener; public static SystemCursorListener horizontalResizeListener; public static SystemCursorListener verticalResizeListener; public static SystemCursorListener neswResizeListener; public static SystemCursorListener nwseResizeListener; public static SystemCursorListener allResizeListener; public static SplitPaneSystemCursorListener splitPaneHorizontalSystemCursorListener; public static SplitPaneSystemCursorListener splitPaneVerticalSystemCursorListener; public static NoCaptureKeyboardFocusListener noCaptureKeyboardFocusListener; public static InputListener unfocusOnEnterKeyListener; static ScrollFocusListener scrollFocusListener; static ScrollFocusListener foregroundScrollFocusListener; public static void initializeListeners() { handListener = new SystemCursorListener(SystemCursor.Hand); handListenerIgnoreDisabled = new SystemCursorListener(SystemCursor.Hand); handListenerIgnoreDisabled.ignoreDisabled = true; ibeamListener = new SystemCursorListener(SystemCursor.Ibeam); neswResizeListener = new SystemCursorListener(SystemCursor.NESWResize); nwseResizeListener = new SystemCursorListener(SystemCursor.NWSEResize); horizontalResizeListener = new SystemCursorListener(SystemCursor.HorizontalResize); verticalResizeListener = new SystemCursorListener(SystemCursor.VerticalResize); allResizeListener = new SystemCursorListener(SystemCursor.AllResize); splitPaneHorizontalSystemCursorListener = new SplitPaneSystemCursorListener(SystemCursor.HorizontalResize); splitPaneVerticalSystemCursorListener = new SplitPaneSystemCursorListener(SystemCursor.VerticalResize); scrollFocusListener = new ScrollFocusListener(stage); foregroundScrollFocusListener = new ScrollFocusListener(foregroundStage); noCaptureKeyboardFocusListener = new NoCaptureKeyboardFocusListener(); unfocusOnEnterKeyListener = new InputListener() { @Override public boolean keyDown(InputEvent event, int keycode) { if (keycode == Keys.ENTER || keycode == Keys.NUMPAD_ENTER) event.getStage().setKeyboardFocus(null); return super.keyDown(event, keycode); } }; } public static ChangeListener onChange(Actor actor, Runnable runnable) { var changeListener = new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { runnable.run(); } }; actor.addListener(changeListener); return changeListener; } public static void onClick(Actor actor, Runnable runnable) { actor.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { runnable.run(); } }); } public static void onTouchDown(Actor actor, Runnable runnable) { actor.addListener(new InputListener() { @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { runnable.run(); return false; } }); } public static void onFocus(Actor actor, Runnable runnable) { actor.addListener(new FocusListener() { @Override public void keyboardFocusChanged(FocusEvent event, Actor actor, boolean focused) { if (event.isFocused()) runnable.run(); } }); } public static void addHandListener(Actor actor) { actor.addListener(handListener); } public static void addHandListenerIgnoreDisabled(Actor actor) { actor.addListener(handListenerIgnoreDisabled); } public static void addIbeamListener(Actor actor) { actor.addListener(ibeamListener); } public static void addScrollFocusListener(Actor actor) { actor.addListener(scrollFocusListener); } public static void addForegroundScrollFocusListener(Actor actor) { actor.addListener(foregroundScrollFocusListener); } public static void addHorizontalResizeListener(Actor actor) { actor.addListener(horizontalResizeListener); } public static void addVerticalResizeListener(Actor actor) { actor.addListener(verticalResizeListener); } public static void addNESWresizeListener(Actor actor) { actor.addListener(neswResizeListener); } public static void addNWSEresizeListener(Actor actor) { actor.addListener(nwseResizeListener); } public static void addAllResizeListener(Actor actor) { actor.addListener(allResizeListener); } public static void addSplitPaneHorizontalSystemCursorListener(Actor actor) { actor.addListener(splitPaneHorizontalSystemCursorListener); } public static void addSplitPaneVerticalSystemCursorListener(Actor actor) { actor.addListener(splitPaneVerticalSystemCursorListener); } public static void addUnfocusOnEnterKeyListener(Actor actor) { actor.addListener(unfocusOnEnterKeyListener); } public static PopTable addTooltip(Actor actor, String text, int edge, int align, float width, PopTableStyle popTableStyle) { return addTooltip(actor, text, edge, align, width, true, popTableStyle); } public static PopTable addTooltip(Actor actor, String text, int edge, int align, PopTableStyle popTableStyle) { return addTooltip(actor, text, edge, align, 0, false, popTableStyle); } public static PopTable addTooltip(Actor actor, String text, int edge, int align, PopTableStyle popTableStyle, boolean foreground) { return addTooltip(actor, text, edge, align, 0, false, popTableStyle, foreground); } private static PopTable addTooltip(Actor actor, String text, int edge, int align, float width, boolean defineWidth, PopTableStyle popTableStyle) { return addTooltip(actor, text, edge, align, width, defineWidth, popTableStyle, true); } private static PopTable addTooltip(Actor actor, String text, int edge, int align, float width, boolean defineWidth, PopTableStyle popTableStyle, boolean foreground) { PopTable popTable = new PopTable(popTableStyle); var inputListener = new ClickListener() { boolean dismissed; Action showTableAction; { popTable.setModal(false); popTable.setTouchable(Touchable.disabled); var label = new Label(text, skin); if (defineWidth) { label.setWrap(true); popTable.add(label).width(width); } else { popTable.add(label); } } @Override public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) { if (!Utils.isWindowFocused()) return; if (Gdx.input.isButtonPressed(Buttons.LEFT) || Gdx.input.isButtonPressed(Buttons.RIGHT) || Gdx.input.isButtonPressed(Buttons.MIDDLE)) return; if (pointer == -1 && popTable.isHidden() && !dismissed) { if (fromActor == null || !event.getListenerActor().isAscendantOf(fromActor)) { if (showTableAction == null) { showTableAction = Actions.delay(.5f, Actions.run(() -> { showTable(actor); showTableAction = null; })); actor.addAction(showTableAction); } } } } private void showTable(Actor actor) { if (actor instanceof Disableable) { if (((Disableable) actor).isDisabled()) return; } var inputProcessor = Gdx.input.getInputProcessor(); if (inputProcessor != actor.getStage()) return; popTable.show(foreground ? foregroundStage : stage); popTable.attachToActor(actor, edge, align); if (popTableStyle == tooltipBottomRightArrowStyle) popTable.setAttachOffsetX(7); popTable.moveToInsideStage(); } @Override public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) { if (pointer == -1) { if (toActor == null || !toActor.isDescendantOf(event.getListenerActor())) { if (!popTable.isHidden()) popTable.hide(); dismissed = false; if (showTableAction != null) { actor.removeAction(showTableAction); showTableAction = null; } } } } @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { dismissed = true; popTable.hide(); if (showTableAction != null) { actor.removeAction(showTableAction); showTableAction = null; } return false; } @Override public void clicked(InputEvent event, float x, float y) { } }; popTable.addListener(new TableShowHideListener() { @Override public void tableShown(Event event) { tooltips.add(popTable); } @Override public void tableHidden(Event event) { tooltips.removeValue(popTable, true); } }); actor.addListener(inputListener); return popTable; } public static void hideAllTooltips() { for (var tooltip : tooltips) { tooltip.hide(); } } public static void addInfiniteSlider(Spinner valueSpinner, float increment, float range, boolean adjustByPPM, ChangeListener changeListener) { var sliderPop = new PopTable(); sliderPop.attachToActor(valueSpinner, Align.bottom, Align.bottom);
var slider = new InfSlider(infSliderStyle);
15
2023-11-24 15:58:20+00:00
24k
siam1026/siam-server
siam-system/system-provider/src/main/java/com/siam/system/modular/package_user/service_impl/MemberBillingRecordServiceImpl.java
[ { "identifier": "StoneCustomerException", "path": "siam-common/src/main/java/com/siam/package_common/exception/StoneCustomerException.java", "snippet": "public class StoneCustomerException extends RuntimeException{\n // 结果码\n private Integer code = BasicResultCode.ERR;\n\n // 结果码描述\n private...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.exception.StoneCustomerException; import com.siam.system.modular.package_user.auth.cache.MemberSessionManager; import com.siam.system.modular.package_user.entity.Member; import com.siam.system.modular.package_user.entity.MemberBillingRecord; import com.siam.system.modular.package_user.mapper.MemberBillingRecordMapper; import com.siam.system.modular.package_user.model.dto.MemberBillingRecordDto; import com.siam.system.modular.package_user.model.example.MemberBillingRecordExample; import com.siam.system.modular.package_user.model.param.MemberBillingRecordParam; import com.siam.system.modular.package_user.service.MemberBillingRecordService; import com.siam.system.modular.package_user.service.MemberService; import com.siam.system.util.TokenUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Map;
14,489
package com.siam.system.modular.package_user.service_impl; @Service public class MemberBillingRecordServiceImpl implements MemberBillingRecordService { @Autowired private MemberBillingRecordMapper memberBillingRecordMapper; @Autowired private MemberService memberService; @Autowired private MemberSessionManager memberSessionManager; @Override public void deleteByPrimaryKey(Integer id) { memberBillingRecordMapper.deleteByPrimaryKey(id); } @Override public void insertSelective(MemberBillingRecord memberBillingRecord) { memberBillingRecordMapper.insertSelective(memberBillingRecord); } @Override public MemberBillingRecord selectByPrimaryKey(MemberBillingRecordParam param) { Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); MemberBillingRecord memberBillingRecord = memberBillingRecordMapper.selectByPrimaryKey(param.getId()); if(!memberBillingRecord.getMemberId().equals(loginMember.getId())){
package com.siam.system.modular.package_user.service_impl; @Service public class MemberBillingRecordServiceImpl implements MemberBillingRecordService { @Autowired private MemberBillingRecordMapper memberBillingRecordMapper; @Autowired private MemberService memberService; @Autowired private MemberSessionManager memberSessionManager; @Override public void deleteByPrimaryKey(Integer id) { memberBillingRecordMapper.deleteByPrimaryKey(id); } @Override public void insertSelective(MemberBillingRecord memberBillingRecord) { memberBillingRecordMapper.insertSelective(memberBillingRecord); } @Override public MemberBillingRecord selectByPrimaryKey(MemberBillingRecordParam param) { Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); MemberBillingRecord memberBillingRecord = memberBillingRecordMapper.selectByPrimaryKey(param.getId()); if(!memberBillingRecord.getMemberId().equals(loginMember.getId())){
throw new StoneCustomerException("500, 该账单不是你的,不允许查看");
0
2023-11-26 12:41:06+00:00
24k
3dcitydb/citydb-tool
citydb-io-citygml/src/main/java/org/citydb/io/citygml/adapter/generics/UriAttributeAdapter.java
[ { "identifier": "AbstractGenericAttributeAdapter", "path": "citydb-io-citygml/src/main/java/org/citydb/io/citygml/adapter/core/AbstractGenericAttributeAdapter.java", "snippet": "public abstract class AbstractGenericAttributeAdapter<T extends AbstractGenericAttribute<?>> implements ModelBuilder<T, Attrib...
import org.citygml4j.core.model.generics.UriAttribute; import org.citydb.io.citygml.adapter.core.AbstractGenericAttributeAdapter; import org.citydb.io.citygml.annotation.DatabaseType; import org.citydb.io.citygml.builder.ModelBuildException; import org.citydb.io.citygml.reader.ModelBuilderHelper; import org.citydb.io.citygml.serializer.ModelSerializeException; import org.citydb.io.citygml.writer.ModelSerializerHelper; import org.citydb.model.common.Namespaces; import org.citydb.model.property.Attribute; import org.citydb.model.property.DataType;
15,013
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * 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 org.citydb.io.citygml.adapter.generics; @DatabaseType(name = "UriAttribute", namespace = Namespaces.GENERICS) public class UriAttributeAdapter extends AbstractGenericAttributeAdapter<UriAttribute> { @Override
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * 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 org.citydb.io.citygml.adapter.generics; @DatabaseType(name = "UriAttribute", namespace = Namespaces.GENERICS) public class UriAttributeAdapter extends AbstractGenericAttributeAdapter<UriAttribute> { @Override
public void build(UriAttribute source, Attribute target, ModelBuilderHelper helper) throws ModelBuildException {
1
2023-11-19 12:29:54+00:00
24k
magmamaintained/Magma-1.12.2
src/main/java/org/bukkit/craftbukkit/v1_12_R1/inventory/InventoryWrapper.java
[ { "identifier": "Location", "path": "src/main/java/org/bukkit/Location.java", "snippet": "public class Location implements Cloneable, ConfigurationSerializable {\n private World world;\n private double x;\n private double y;\n private double z;\n private float pitch;\n private float ya...
import com.google.common.base.Predicates; import com.google.common.collect.Iterables; import java.util.ArrayList; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import org.bukkit.Location; import org.bukkit.craftbukkit.v1_12_R1.entity.CraftHumanEntity; import org.bukkit.craftbukkit.v1_12_R1.util.CraftChatMessage; import org.bukkit.entity.HumanEntity; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder;
17,856
} @Override public ItemStack removeStackFromSlot(int i) { // Copied from CraftItemStack ItemStack stack = getStackInSlot(i); ItemStack result; if (stack.isEmpty()) { return stack; } if (stack.getCount() <= 1) { this.setInventorySlotContents(i, ItemStack.EMPTY); result = stack; } else { result = CraftItemStack.copyNMSStack(stack, 1); stack.shrink(1); } return result; } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { inventory.setItem(i, CraftItemStack.asBukkitCopy(itemstack)); } @Override public int getInventoryStackLimit() { return inventory.getMaxStackSize(); } @Override public void markDirty() { } @Override public boolean isUsableByPlayer(EntityPlayer entityhuman) { return true; } @Override public void openInventory(EntityPlayer entityhuman) { } @Override public void closeInventory(EntityPlayer entityhuman) { } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { return true; } @Override public int getField(int i) { return 0; } @Override public void setField(int i, int j) { } @Override public int getFieldCount() { return 0; } @Override public void clear() { inventory.clear(); } @Override public List<ItemStack> getContents() { int size = getSizeInventory(); List<ItemStack> items = new ArrayList<ItemStack>(size); for (int i = 0; i < size; i++) { items.set(i, getStackInSlot(i)); } return items; } @Override public void onOpen(CraftHumanEntity who) { viewers.add(who); } @Override public void onClose(CraftHumanEntity who) { viewers.remove(who); } @Override public List<HumanEntity> getViewers() { return viewers; } @Override public InventoryHolder getOwner() { return inventory.getHolder(); } @Override public void setMaxStackSize(int size) { inventory.setMaxStackSize(size); } @Override public String getName() { return inventory.getName(); } @Override public boolean hasCustomName() { return getName() != null; } @Override public ITextComponent getDisplayName() {
package org.bukkit.craftbukkit.v1_12_R1.inventory; public class InventoryWrapper implements IInventory { private final Inventory inventory; private final List<HumanEntity> viewers = new ArrayList<HumanEntity>(); public InventoryWrapper(Inventory inventory) { this.inventory = inventory; } @Override public int getSizeInventory() { return inventory.getSize(); } @Override public ItemStack getStackInSlot(int i) { return CraftItemStack.asNMSCopy(inventory.getItem(i)); } @Override public ItemStack decrStackSize(int i, int j) { // Copied from CraftItemStack ItemStack stack = getStackInSlot(i); ItemStack result; if (stack.isEmpty()) { return stack; } if (stack.getCount() <= j) { this.setInventorySlotContents(i, ItemStack.EMPTY); result = stack; } else { result = CraftItemStack.copyNMSStack(stack, j); stack.shrink(j); } this.markDirty(); return result; } @Override public ItemStack removeStackFromSlot(int i) { // Copied from CraftItemStack ItemStack stack = getStackInSlot(i); ItemStack result; if (stack.isEmpty()) { return stack; } if (stack.getCount() <= 1) { this.setInventorySlotContents(i, ItemStack.EMPTY); result = stack; } else { result = CraftItemStack.copyNMSStack(stack, 1); stack.shrink(1); } return result; } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { inventory.setItem(i, CraftItemStack.asBukkitCopy(itemstack)); } @Override public int getInventoryStackLimit() { return inventory.getMaxStackSize(); } @Override public void markDirty() { } @Override public boolean isUsableByPlayer(EntityPlayer entityhuman) { return true; } @Override public void openInventory(EntityPlayer entityhuman) { } @Override public void closeInventory(EntityPlayer entityhuman) { } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { return true; } @Override public int getField(int i) { return 0; } @Override public void setField(int i, int j) { } @Override public int getFieldCount() { return 0; } @Override public void clear() { inventory.clear(); } @Override public List<ItemStack> getContents() { int size = getSizeInventory(); List<ItemStack> items = new ArrayList<ItemStack>(size); for (int i = 0; i < size; i++) { items.set(i, getStackInSlot(i)); } return items; } @Override public void onOpen(CraftHumanEntity who) { viewers.add(who); } @Override public void onClose(CraftHumanEntity who) { viewers.remove(who); } @Override public List<HumanEntity> getViewers() { return viewers; } @Override public InventoryHolder getOwner() { return inventory.getHolder(); } @Override public void setMaxStackSize(int size) { inventory.setMaxStackSize(size); } @Override public String getName() { return inventory.getName(); } @Override public boolean hasCustomName() { return getName() != null; } @Override public ITextComponent getDisplayName() {
return CraftChatMessage.fromString(getName())[0];
2
2023-11-22 11:25:51+00:00
24k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/common/metatileentities/multiblock/EPMetaTileEntityGeneralProcessingPlant.java
[ { "identifier": "EPMultiblockAbility", "path": "src/main/java/cn/gtcommunity/epimorphism/api/metatileentity/multiblock/EPMultiblockAbility.java", "snippet": "public class EPMultiblockAbility {\n\n public static final MultiblockAbility<IBuffer> BUFFER_MULTIBLOCK_ABILITY = new MultiblockAbility<>(\"buf...
import cn.gtcommunity.epimorphism.api.metatileentity.multiblock.EPMultiblockAbility; import cn.gtcommunity.epimorphism.api.capability.IIndustrialMaintenance; import cn.gtcommunity.epimorphism.api.recipe.EPRecipeMaps; import cn.gtcommunity.epimorphism.api.unification.EPMaterials; import cn.gtcommunity.epimorphism.client.renderer.texture.EPTextures; import cn.gtcommunity.epimorphism.common.blocks.EPBlockMultiblockCasing; import cn.gtcommunity.epimorphism.common.blocks.EPBlockMultiblockCasingB; import cn.gtcommunity.epimorphism.common.blocks.EPMetablocks; import gregtech.api.GTValues; import gregtech.api.capability.IMaintenanceHatch; import gregtech.api.capability.impl.MultiblockRecipeLogic; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockPart; import gregtech.api.metatileentity.multiblock.MultiMapMultiblockController; import gregtech.api.metatileentity.multiblock.MultiblockAbility; import gregtech.api.metatileentity.multiblock.RecipeMapMultiblockController; import gregtech.api.pattern.BlockPattern; import gregtech.api.pattern.FactoryBlockPattern; import gregtech.api.pattern.PatternMatchContext; import gregtech.api.recipes.RecipeMap; import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; import gregtech.api.util.GTUtility; import gregtech.client.renderer.ICubeRenderer; import gregtech.common.ConfigHolder; import gregtech.common.blocks.*; import net.minecraft.block.state.IBlockState; import net.minecraft.client.resources.I18n; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.util.Tuple; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Keyboard; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List;
21,590
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityGeneralProcessingPlant extends MultiMapMultiblockController { private int timeActive; private IMaintenanceHatch maintenanceHatch; // Used for tracking if this is the initial state of the machine, for maintenance hatches which automatically fix initial issues. private boolean initialMaintenanceDone; // Used for data preservation with Maintenance Hatch // private boolean storedTaped = false; public EPMetaTileEntityGeneralProcessingPlant(ResourceLocation metaTileEntityId) { super(metaTileEntityId, new RecipeMap[]{ EPRecipeMaps.GENERAL_RECIPES_A, EPRecipeMaps.GENERAL_RECIPES_B, EPRecipeMaps.GENERAL_RECIPES_C }); this.recipeMapWorkable = new GeneralRecipeLogic(this); this.maintenance_problems = 0b0000000; } @Override public MetaTileEntity createMetaTileEntity(IGregTechTileEntity iGregTechTileEntity) { return new EPMetaTileEntityGeneralProcessingPlant(metaTileEntityId); } @Override protected void formStructure(PatternMatchContext context) { super.formStructure(context); if (this.hasMaintenanceMechanics() && ConfigHolder.machines.enableMaintenance) { // nothing extra if no maintenance
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityGeneralProcessingPlant extends MultiMapMultiblockController { private int timeActive; private IMaintenanceHatch maintenanceHatch; // Used for tracking if this is the initial state of the machine, for maintenance hatches which automatically fix initial issues. private boolean initialMaintenanceDone; // Used for data preservation with Maintenance Hatch // private boolean storedTaped = false; public EPMetaTileEntityGeneralProcessingPlant(ResourceLocation metaTileEntityId) { super(metaTileEntityId, new RecipeMap[]{ EPRecipeMaps.GENERAL_RECIPES_A, EPRecipeMaps.GENERAL_RECIPES_B, EPRecipeMaps.GENERAL_RECIPES_C }); this.recipeMapWorkable = new GeneralRecipeLogic(this); this.maintenance_problems = 0b0000000; } @Override public MetaTileEntity createMetaTileEntity(IGregTechTileEntity iGregTechTileEntity) { return new EPMetaTileEntityGeneralProcessingPlant(metaTileEntityId); } @Override protected void formStructure(PatternMatchContext context) { super.formStructure(context); if (this.hasMaintenanceMechanics() && ConfigHolder.machines.enableMaintenance) { // nothing extra if no maintenance
if (getAbilities(EPMultiblockAbility.INDUSTRIAL_MAINTENANCE_MULTIBLOCK_ABILITY).isEmpty())
0
2023-11-26 01:56:35+00:00
24k
myzticbean/QSFindItemAddOn
src/main/java/io/myzticbean/finditemaddon/Handlers/GUIHandler/Menus/FoundShopsMenu.java
[ { "identifier": "ConfigProvider", "path": "src/main/java/io/myzticbean/finditemaddon/ConfigUtil/ConfigProvider.java", "snippet": "public class ConfigProvider {\n\n public final String PLUGIN_PREFIX = ColorTranslator.translateColorCodes(ConfigSetup.get().getString(\"plugin-prefix\"));\n public fina...
import io.myzticbean.finditemaddon.ConfigUtil.ConfigProvider; import io.myzticbean.finditemaddon.Dependencies.EssentialsXPlugin; import io.myzticbean.finditemaddon.Dependencies.PlayerWarpsPlugin; import io.myzticbean.finditemaddon.Dependencies.WGPlugin; import io.myzticbean.finditemaddon.FindItemAddOn; import io.myzticbean.finditemaddon.Handlers.GUIHandler.PaginatedMenu; import io.myzticbean.finditemaddon.Handlers.GUIHandler.PlayerMenuUtility; import io.myzticbean.finditemaddon.Models.FoundShopItemModel; import io.myzticbean.finditemaddon.Utils.Defaults.PlayerPerms; import io.myzticbean.finditemaddon.Utils.Defaults.ShopLorePlaceholders; import io.myzticbean.finditemaddon.Utils.JsonStorageUtils.ShopSearchActivityStorageUtil; import io.myzticbean.finditemaddon.Utils.LocationUtils; import io.myzticbean.finditemaddon.Utils.LoggerUtils; import io.myzticbean.finditemaddon.Utils.WarpUtils.EssentialWarpsUtil; import io.myzticbean.finditemaddon.Utils.WarpUtils.PlayerWarpsUtil; import io.myzticbean.finditemaddon.Utils.WarpUtils.WGRegionUtils; import io.papermc.lib.PaperLib; import me.kodysimpson.simpapi.colors.ColorTranslator; import org.apache.commons.lang3.StringUtils; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects;
17,355
} player.closeInventory(); } else if(FindItemAddOn.getConfigProvider().TP_PLAYER_TO_NEAREST_WARP) { // if list size = 1, it contains Warp name if(locDataList.size() == 1) { String warpName = locDataList.get(0); if(FindItemAddOn.getConfigProvider().NEAREST_WARP_MODE == 1) { Bukkit.dispatchCommand(player, "essentials:warp " + warpName); } else if(FindItemAddOn.getConfigProvider().NEAREST_WARP_MODE == 2) { PlayerWarpsPlugin.executeWarpPlayer(player, warpName); } } } } else { LoggerUtils.logError("PersistentDataContainer doesn't have the right kind of data!"); return; } } } private void handleMenuClickForNavToNextPage(InventoryClickEvent event) { if(!((index + 1) >= super.playerMenuUtility.getPlayerShopSearchResult().size())) { page = page + 1; super.open(super.playerMenuUtility.getPlayerShopSearchResult()); } else { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_NAV_LAST_PAGE_ALERT_MSG)) { event.getWhoClicked().sendMessage( ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().SHOP_NAV_LAST_PAGE_ALERT_MSG)); } } } private void handleMenuClickForNavToPrevPage(InventoryClickEvent event) { if(page == 0) { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_NAV_FIRST_PAGE_ALERT_MSG)) { event.getWhoClicked().sendMessage( ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().SHOP_NAV_FIRST_PAGE_ALERT_MSG)); } } else { page = page - 1; super.open(super.playerMenuUtility.getPlayerShopSearchResult()); } } /** * Empty method in case we need to handle static GUI icons in future */ @Override public void setMenuItems() {} /** * Sets the slots in the search result GUI * @param foundShops List of found shops */ @Override public void setMenuItems(List<FoundShopItemModel> foundShops) { addMenuBottomBar(); if(foundShops != null && !foundShops.isEmpty()) { int guiSlotCounter = 0; while(guiSlotCounter < super.maxItemsPerPage) { index = super.maxItemsPerPage * page + guiSlotCounter; if(index >= foundShops.size()) break; if(foundShops.get(index) != null) { // Place Search Results here FoundShopItemModel foundShop_i = foundShops.get(index); NamespacedKey key = new NamespacedKey(FindItemAddOn.getInstance(), "locationData"); ItemStack item = new ItemStack(foundShop_i.getItem().getType()); ItemMeta meta = item.getItemMeta(); List<String> lore; lore = new ArrayList<>(); com.olziedev.playerwarps.api.warp.Warp nearestPlayerWarp = null; String nearestEWarp = null; if(foundShop_i.getItem().hasItemMeta()) { meta = foundShop_i.getItem().getItemMeta(); if(foundShop_i.getItem().getItemMeta().hasLore()) { for(String s : foundShop_i.getItem().getItemMeta().getLore()) { lore.add(ColorTranslator.translateColorCodes(s)); } } } List<String> shopItemLore = FindItemAddOn.getConfigProvider().SHOP_GUI_ITEM_LORE; for(String shopItemLore_i : shopItemLore) { if(shopItemLore_i.contains(ShopLorePlaceholders.NEAREST_WARP.value())) { switch(FindItemAddOn.getConfigProvider().NEAREST_WARP_MODE) { case 1: // EssentialWarp: Check nearest warp if(EssentialsXPlugin.isEnabled()) { nearestEWarp = new EssentialWarpsUtil().findNearestWarp(foundShop_i.getShopLocation()); if(nearestEWarp != null && !StringUtils.isEmpty(nearestEWarp)) { lore.add(ColorTranslator.translateColorCodes(shopItemLore_i.replace(ShopLorePlaceholders.NEAREST_WARP.value(), nearestEWarp))); } else { lore.add(ColorTranslator.translateColorCodes(shopItemLore_i.replace(ShopLorePlaceholders.NEAREST_WARP.value(), NO_WARP_NEAR_SHOP_ERROR_MSG))); } } break; case 2: // PlayerWarp: Check nearest warp if(PlayerWarpsPlugin.getIsEnabled()) { nearestPlayerWarp = new PlayerWarpsUtil().findNearestWarp(foundShop_i.getShopLocation()); if(nearestPlayerWarp != null) { lore.add(ColorTranslator.translateColorCodes(shopItemLore_i.replace(ShopLorePlaceholders.NEAREST_WARP.value(), nearestPlayerWarp.getWarpName()))); } else { lore.add(ColorTranslator.translateColorCodes(shopItemLore_i.replace(ShopLorePlaceholders.NEAREST_WARP.value(), NO_WARP_NEAR_SHOP_ERROR_MSG))); } } break; case 3: // WG Region: Check nearest WG Region
package io.myzticbean.finditemaddon.Handlers.GUIHandler.Menus; /** * Handler class for FoundShops GUI * @author ronsane */ public class FoundShopsMenu extends PaginatedMenu { private final String NO_WARP_NEAR_SHOP_ERROR_MSG = "No Warp near this shop"; private final String NO_WG_REGION_NEAR_SHOP_ERROR_MSG = "No WG Region near this shop"; public FoundShopsMenu(PlayerMenuUtility playerMenuUtility, List<FoundShopItemModel> searchResult) { super(playerMenuUtility, searchResult); } @Override public String getMenuName() { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_GUI_TITLE)) { return ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().SHOP_SEARCH_GUI_TITLE); } else { return ColorTranslator.translateColorCodes("&l» &rShops"); } } @Override public int getSlots() { return 54; } @Override public void handleMenu(InventoryClickEvent event) { if(event.getSlot() == 45) { handleMenuClickForNavToPrevPage(event); } else if(event.getSlot() == 53) { handleMenuClickForNavToNextPage(event); } // Issue #31: Removing condition 'event.getCurrentItem().getType().equals(Material.BARRIER)' else if(event.getSlot() == 49) { event.getWhoClicked().closeInventory(); } else if(event.getCurrentItem().getType().equals(Material.AIR)) { // do nothing LoggerUtils.logDebugInfo(event.getWhoClicked().getName() + " just clicked on AIR!"); } else { Player player = (Player) event.getWhoClicked(); ItemStack item = event.getCurrentItem(); ItemMeta meta = item.getItemMeta(); NamespacedKey key = new NamespacedKey(FindItemAddOn.getInstance(), "locationData"); if(!meta.getPersistentDataContainer().isEmpty() && meta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { String locData = meta.getPersistentDataContainer().get(key, PersistentDataType.STRING); List<String> locDataList = Arrays.asList(locData.split("\\s*,\\s*")); if(FindItemAddOn.getConfigProvider().TP_PLAYER_DIRECTLY_TO_SHOP) { if(playerMenuUtility.getOwner().hasPermission(PlayerPerms.FINDITEM_SHOPTP.value())) { World world = Bukkit.getWorld(locDataList.get(0)); int locX = Integer.parseInt(locDataList.get(1)), locY = Integer.parseInt(locDataList.get(2)), locZ = Integer.parseInt(locDataList.get(3)); Location shopLocation = new Location(world, locX, locY, locZ); Location locToTeleport = LocationUtils.findSafeLocationAroundShop(shopLocation); if(locToTeleport != null) { // Add Player Visit Entry ShopSearchActivityStorageUtil.addPlayerVisitEntryAsync(shopLocation, player); // Add Short Blindness effect... maybe? /** * @// TODO: 16/06/22 Make this an option in config */ // player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 10, 0, false, false, false)); // Teleport // If EssentialsX is enabled, register last location before teleporting to make /back work if(EssentialsXPlugin.isEnabled()) { EssentialsXPlugin.getAPI().getUser(player).setLastLocation(); } // Check for TP delay if(StringUtils.isNumeric(FindItemAddOn.getConfigProvider().TP_DELAY_IN_SECONDS) && !"0".equals(FindItemAddOn.getConfigProvider().TP_DELAY_IN_SECONDS)) { long delay = Long.parseLong(FindItemAddOn.getConfigProvider().TP_DELAY_IN_SECONDS); LoggerUtils.logDebugInfo("Teleporting delay is set to: " + delay); String tpDelayMsg = FindItemAddOn.getConfigProvider().TP_DELAY_MESSAGE; if(!StringUtils.isEmpty(tpDelayMsg)) { player.sendMessage( ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + replaceDelayPlaceholder(tpDelayMsg,delay))); } Bukkit.getScheduler().scheduleSyncDelayedTask( FindItemAddOn.getInstance(), () -> PaperLib.teleportAsync(player, locToTeleport, PlayerTeleportEvent.TeleportCause.PLUGIN), delay*20); } else { PaperLib.teleportAsync(player, locToTeleport, PlayerTeleportEvent.TeleportCause.PLUGIN); } } else { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().UNSAFE_SHOP_AREA_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().UNSAFE_SHOP_AREA_MSG)); } } } else { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_TP_NO_PERMISSION_MSG)) { playerMenuUtility.getOwner() .sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().SHOP_TP_NO_PERMISSION_MSG)); event.getWhoClicked().closeInventory(); } } player.closeInventory(); } else if(FindItemAddOn.getConfigProvider().TP_PLAYER_TO_NEAREST_WARP) { // if list size = 1, it contains Warp name if(locDataList.size() == 1) { String warpName = locDataList.get(0); if(FindItemAddOn.getConfigProvider().NEAREST_WARP_MODE == 1) { Bukkit.dispatchCommand(player, "essentials:warp " + warpName); } else if(FindItemAddOn.getConfigProvider().NEAREST_WARP_MODE == 2) { PlayerWarpsPlugin.executeWarpPlayer(player, warpName); } } } } else { LoggerUtils.logError("PersistentDataContainer doesn't have the right kind of data!"); return; } } } private void handleMenuClickForNavToNextPage(InventoryClickEvent event) { if(!((index + 1) >= super.playerMenuUtility.getPlayerShopSearchResult().size())) { page = page + 1; super.open(super.playerMenuUtility.getPlayerShopSearchResult()); } else { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_NAV_LAST_PAGE_ALERT_MSG)) { event.getWhoClicked().sendMessage( ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().SHOP_NAV_LAST_PAGE_ALERT_MSG)); } } } private void handleMenuClickForNavToPrevPage(InventoryClickEvent event) { if(page == 0) { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_NAV_FIRST_PAGE_ALERT_MSG)) { event.getWhoClicked().sendMessage( ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().SHOP_NAV_FIRST_PAGE_ALERT_MSG)); } } else { page = page - 1; super.open(super.playerMenuUtility.getPlayerShopSearchResult()); } } /** * Empty method in case we need to handle static GUI icons in future */ @Override public void setMenuItems() {} /** * Sets the slots in the search result GUI * @param foundShops List of found shops */ @Override public void setMenuItems(List<FoundShopItemModel> foundShops) { addMenuBottomBar(); if(foundShops != null && !foundShops.isEmpty()) { int guiSlotCounter = 0; while(guiSlotCounter < super.maxItemsPerPage) { index = super.maxItemsPerPage * page + guiSlotCounter; if(index >= foundShops.size()) break; if(foundShops.get(index) != null) { // Place Search Results here FoundShopItemModel foundShop_i = foundShops.get(index); NamespacedKey key = new NamespacedKey(FindItemAddOn.getInstance(), "locationData"); ItemStack item = new ItemStack(foundShop_i.getItem().getType()); ItemMeta meta = item.getItemMeta(); List<String> lore; lore = new ArrayList<>(); com.olziedev.playerwarps.api.warp.Warp nearestPlayerWarp = null; String nearestEWarp = null; if(foundShop_i.getItem().hasItemMeta()) { meta = foundShop_i.getItem().getItemMeta(); if(foundShop_i.getItem().getItemMeta().hasLore()) { for(String s : foundShop_i.getItem().getItemMeta().getLore()) { lore.add(ColorTranslator.translateColorCodes(s)); } } } List<String> shopItemLore = FindItemAddOn.getConfigProvider().SHOP_GUI_ITEM_LORE; for(String shopItemLore_i : shopItemLore) { if(shopItemLore_i.contains(ShopLorePlaceholders.NEAREST_WARP.value())) { switch(FindItemAddOn.getConfigProvider().NEAREST_WARP_MODE) { case 1: // EssentialWarp: Check nearest warp if(EssentialsXPlugin.isEnabled()) { nearestEWarp = new EssentialWarpsUtil().findNearestWarp(foundShop_i.getShopLocation()); if(nearestEWarp != null && !StringUtils.isEmpty(nearestEWarp)) { lore.add(ColorTranslator.translateColorCodes(shopItemLore_i.replace(ShopLorePlaceholders.NEAREST_WARP.value(), nearestEWarp))); } else { lore.add(ColorTranslator.translateColorCodes(shopItemLore_i.replace(ShopLorePlaceholders.NEAREST_WARP.value(), NO_WARP_NEAR_SHOP_ERROR_MSG))); } } break; case 2: // PlayerWarp: Check nearest warp if(PlayerWarpsPlugin.getIsEnabled()) { nearestPlayerWarp = new PlayerWarpsUtil().findNearestWarp(foundShop_i.getShopLocation()); if(nearestPlayerWarp != null) { lore.add(ColorTranslator.translateColorCodes(shopItemLore_i.replace(ShopLorePlaceholders.NEAREST_WARP.value(), nearestPlayerWarp.getWarpName()))); } else { lore.add(ColorTranslator.translateColorCodes(shopItemLore_i.replace(ShopLorePlaceholders.NEAREST_WARP.value(), NO_WARP_NEAR_SHOP_ERROR_MSG))); } } break; case 3: // WG Region: Check nearest WG Region
if(WGPlugin.isEnabled()) {
3
2023-11-22 11:36:01+00:00
24k
DIDA-lJ/qiyao-12306
services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/service/impl/TicketServiceImpl.java
[ { "identifier": "RefundTypeEnum", "path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/common/enums/RefundTypeEnum.java", "snippet": "@Getter\n@RequiredArgsConstructor\npublic enum RefundTypeEnum {\n\n /**\n * 部分退款\n */\n PARTIAL_REFUND(11, 0, \"PARTIAL...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson2.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.google.common.collect.Lists; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.opengoofy.index12306.biz.ticketservice.common.enums.RefundTypeEnum; import org.opengoofy.index12306.biz.ticketservice.common.enums.SourceEnum; import org.opengoofy.index12306.biz.ticketservice.common.enums.TicketChainMarkEnum; import org.opengoofy.index12306.biz.ticketservice.common.enums.TicketStatusEnum; import org.opengoofy.index12306.biz.ticketservice.common.enums.VehicleTypeEnum; import org.opengoofy.index12306.biz.ticketservice.dao.entity.StationDO; import org.opengoofy.index12306.biz.ticketservice.dao.entity.TicketDO; import org.opengoofy.index12306.biz.ticketservice.dao.entity.TrainDO; import org.opengoofy.index12306.biz.ticketservice.dao.entity.TrainStationPriceDO; import org.opengoofy.index12306.biz.ticketservice.dao.entity.TrainStationRelationDO; import org.opengoofy.index12306.biz.ticketservice.dao.mapper.StationMapper; import org.opengoofy.index12306.biz.ticketservice.dao.mapper.TicketMapper; import org.opengoofy.index12306.biz.ticketservice.dao.mapper.TrainMapper; import org.opengoofy.index12306.biz.ticketservice.dao.mapper.TrainStationPriceMapper; import org.opengoofy.index12306.biz.ticketservice.dao.mapper.TrainStationRelationMapper; import org.opengoofy.index12306.biz.ticketservice.dto.domain.PurchaseTicketPassengerDetailDTO; import org.opengoofy.index12306.biz.ticketservice.dto.domain.RouteDTO; import org.opengoofy.index12306.biz.ticketservice.dto.domain.SeatClassDTO; import org.opengoofy.index12306.biz.ticketservice.dto.domain.TicketListDTO; import org.opengoofy.index12306.biz.ticketservice.dto.req.CancelTicketOrderReqDTO; import org.opengoofy.index12306.biz.ticketservice.dto.req.PurchaseTicketReqDTO; import org.opengoofy.index12306.biz.ticketservice.dto.req.RefundTicketReqDTO; import org.opengoofy.index12306.biz.ticketservice.dto.req.TicketOrderItemQueryReqDTO; import org.opengoofy.index12306.biz.ticketservice.dto.req.TicketPageQueryReqDTO; import org.opengoofy.index12306.biz.ticketservice.dto.resp.RefundTicketRespDTO; import org.opengoofy.index12306.biz.ticketservice.dto.resp.TicketOrderDetailRespDTO; import org.opengoofy.index12306.biz.ticketservice.dto.resp.TicketPageQueryRespDTO; import org.opengoofy.index12306.biz.ticketservice.dto.resp.TicketPurchaseRespDTO; import org.opengoofy.index12306.biz.ticketservice.remote.PayRemoteService; import org.opengoofy.index12306.biz.ticketservice.remote.TicketOrderRemoteService; import org.opengoofy.index12306.biz.ticketservice.remote.dto.PayInfoRespDTO; import org.opengoofy.index12306.biz.ticketservice.remote.dto.RefundReqDTO; import org.opengoofy.index12306.biz.ticketservice.remote.dto.RefundRespDTO; import org.opengoofy.index12306.biz.ticketservice.remote.dto.TicketOrderCreateRemoteReqDTO; import org.opengoofy.index12306.biz.ticketservice.remote.dto.TicketOrderItemCreateRemoteReqDTO; import org.opengoofy.index12306.biz.ticketservice.remote.dto.TicketOrderPassengerDetailRespDTO; import org.opengoofy.index12306.biz.ticketservice.service.SeatService; import org.opengoofy.index12306.biz.ticketservice.service.TicketService; import org.opengoofy.index12306.biz.ticketservice.service.TrainStationService; import org.opengoofy.index12306.biz.ticketservice.service.cache.SeatMarginCacheLoader; import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.dto.TrainPurchaseTicketRespDTO; import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.select.TrainSeatTypeSelector; import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.tokenbucket.TicketAvailabilityTokenBucket; import org.opengoofy.index12306.biz.ticketservice.toolkit.DateUtil; import org.opengoofy.index12306.biz.ticketservice.toolkit.TimeStringComparator; import org.opengoofy.index12306.framework.starter.bases.ApplicationContextHolder; import org.opengoofy.index12306.framework.starter.cache.DistributedCache; import org.opengoofy.index12306.framework.starter.cache.toolkit.CacheUtil; import org.opengoofy.index12306.framework.starter.common.toolkit.BeanUtil; import org.opengoofy.index12306.framework.starter.convention.exception.ServiceException; import org.opengoofy.index12306.framework.starter.convention.result.Result; import org.opengoofy.index12306.framework.starter.designpattern.chain.AbstractChainContext; import org.opengoofy.index12306.frameworks.starter.user.core.UserContext; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import static org.opengoofy.index12306.biz.ticketservice.common.constant.Index12306Constant.ADVANCE_TICKET_DAY; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.LOCK_PURCHASE_TICKETS; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.LOCK_PURCHASE_TICKETS_V2; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.LOCK_REGION_TRAIN_STATION; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.LOCK_REGION_TRAIN_STATION_MAPPING; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.REGION_TRAIN_STATION; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.REGION_TRAIN_STATION_MAPPING; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.TRAIN_INFO; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.TRAIN_STATION_PRICE; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.TRAIN_STATION_REMAINING_TICKET; import static org.opengoofy.index12306.biz.ticketservice.toolkit.DateUtil.convertDateToLocalTime;
21,479
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengoofy.index12306.biz.ticketservice.service.impl; /** * 车票接口实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class TicketServiceImpl extends ServiceImpl<TicketMapper, TicketDO> implements TicketService, CommandLineRunner {
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengoofy.index12306.biz.ticketservice.service.impl; /** * 车票接口实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class TicketServiceImpl extends ServiceImpl<TicketMapper, TicketDO> implements TicketService, CommandLineRunner {
private final TrainMapper trainMapper;
12
2023-11-23 07:59:11+00:00
24k
estkme-group/infineon-lpa-mirror
app/src/main/java/com/infineon/esim/lpa/lpa/LocalProfileAssistant.java
[ { "identifier": "LocalProfileAssistantCoreImpl", "path": "core/src/main/java/com/infineon/esim/lpa/core/LocalProfileAssistantCoreImpl.java", "snippet": "public class LocalProfileAssistantCoreImpl implements LocalProfileAssistantCore {\n private static final String TAG = LocalProfileAssistantCoreImpl....
import androidx.lifecycle.MutableLiveData; import com.infineon.esim.lpa.core.LocalProfileAssistantCoreImpl; import com.infineon.esim.lpa.core.dtos.ActivationCode; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.dtos.enums.ProfileActionType; import com.infineon.esim.lpa.core.dtos.profile.ProfileList; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult; import com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult; import com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult; import com.infineon.esim.lpa.data.StatusAndEventHandler; import com.infineon.esim.lpa.euicc.EuiccManager; import com.infineon.esim.lpa.euicc.base.EuiccConnection; import com.infineon.esim.lpa.euicc.base.EuiccConnectionConsumer; import com.infineon.esim.lpa.lpa.task.AuthenticateTask; import com.infineon.esim.lpa.lpa.task.CancelSessionTask; import com.infineon.esim.lpa.lpa.task.DownloadTask; import com.infineon.esim.lpa.lpa.task.GetEuiccInfoTask; import com.infineon.esim.lpa.lpa.task.GetProfileListTask; import com.infineon.esim.lpa.lpa.task.HandleAndClearAllNotificationsTask; import com.infineon.esim.lpa.lpa.task.ProfileActionTask; import com.infineon.esim.lpa.ui.generic.ActionStatus; import com.infineon.esim.lpa.ui.generic.Error; import com.infineon.esim.lpa.util.android.InternetConnectionConsumer; import com.infineon.esim.lpa.util.threading.TaskRunner; import com.infineon.esim.util.Log;
14,451
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.lpa; public final class LocalProfileAssistant extends LocalProfileAssistantCoreImpl implements EuiccConnectionConsumer, InternetConnectionConsumer { private static final String TAG = LocalProfileAssistant.class.getName(); private final StatusAndEventHandler statusAndEventHandler; private final MutableLiveData<ProfileList> profileList; private final NetworkStatusBroadcastReceiver networkStatusBroadcastReceiver; private EuiccConnection euiccConnection; private EuiccInfo euiccInfo; private AuthenticateResult authenticateResult; private DownloadResult downloadResult; private CancelSessionResult cancelSessionResult; public LocalProfileAssistant(EuiccManager euiccManager, StatusAndEventHandler statusAndEventHandler) { super(); Log.debug(TAG,"Creating LocalProfileAssistant..."); this.networkStatusBroadcastReceiver = new NetworkStatusBroadcastReceiver(this); this.statusAndEventHandler = statusAndEventHandler; this.profileList = new MutableLiveData<>(); networkStatusBroadcastReceiver.registerReceiver(); euiccManager.setEuiccConnectionConsumer(this); } public MutableLiveData<ProfileList> getProfileListLiveData() { return profileList; } public EuiccInfo getEuiccInfo() { return euiccInfo; } public AuthenticateResult getAuthenticateResult() { return authenticateResult; } public DownloadResult getDownloadResult() { return downloadResult; } public CancelSessionResult getCancelSessionResult() { return cancelSessionResult; } public Boolean resetEuicc() throws Exception { if(euiccConnection == null) { throw new Exception("Error: eUICC connection not available to LPA."); } else { return euiccConnection.resetEuicc(); } } public void refreshProfileList() { Log.debug(TAG,"Refreshing profile list."); statusAndEventHandler.onStatusChange(ActionStatus.GET_PROFILE_LIST_STARTED); new TaskRunner().executeAsync(new GetProfileListTask(this), result -> { statusAndEventHandler.onStatusChange(ActionStatus.GET_PROFILE_LIST_FINISHED); profileList.setValue(result); }, e -> statusAndEventHandler.onError(new Error("Exception during getting of profile list.", e.getMessage()))); } public void refreshEuiccInfo() { Log.debug(TAG, "Refreshing eUICC info."); statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_STARTED); new TaskRunner().executeAsync(new GetEuiccInfoTask(this), result -> { euiccInfo = result; statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_FINISHED); }, e -> statusAndEventHandler.onError(new Error("Exception during getting of eUICC info.", e.getMessage()))); } public void enableProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_STARTED); if(profile.isEnabled()) { Log.debug(TAG, "Profile already enabled!"); statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED); return; } new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_ENABLE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during enabling profile.", e.getMessage()))); } public void disableProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_STARTED); if(!profile.isEnabled()) { Log.debug(TAG, "Profile already disabled!"); statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED); return; } new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_DISABLE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during disabling of profile.", e.getMessage()))); } public void deleteProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_STARTED); new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_DELETE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during deleting of profile.", e.getMessage()))); } public void setNickname(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_STARTED); ProfileActionTask profileActionTask = new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_SET_NICKNAME, profile); new TaskRunner().executeAsync(profileActionTask, result -> statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during setting nickname of profile.", e.getMessage()))); } public void handleAndClearAllNotifications() { statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_STARTED); HandleAndClearAllNotificationsTask handleAndClearAllNotificationsTask = new HandleAndClearAllNotificationsTask(this); new TaskRunner().executeAsync(handleAndClearAllNotificationsTask, result -> statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during clearing of all eUICC notifications.", e.getMessage()))); } public void startAuthentication(ActivationCode activationCode) { authenticateResult = null; statusAndEventHandler.onStatusChange(ActionStatus.AUTHENTICATE_DOWNLOAD_STARTED);
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.lpa; public final class LocalProfileAssistant extends LocalProfileAssistantCoreImpl implements EuiccConnectionConsumer, InternetConnectionConsumer { private static final String TAG = LocalProfileAssistant.class.getName(); private final StatusAndEventHandler statusAndEventHandler; private final MutableLiveData<ProfileList> profileList; private final NetworkStatusBroadcastReceiver networkStatusBroadcastReceiver; private EuiccConnection euiccConnection; private EuiccInfo euiccInfo; private AuthenticateResult authenticateResult; private DownloadResult downloadResult; private CancelSessionResult cancelSessionResult; public LocalProfileAssistant(EuiccManager euiccManager, StatusAndEventHandler statusAndEventHandler) { super(); Log.debug(TAG,"Creating LocalProfileAssistant..."); this.networkStatusBroadcastReceiver = new NetworkStatusBroadcastReceiver(this); this.statusAndEventHandler = statusAndEventHandler; this.profileList = new MutableLiveData<>(); networkStatusBroadcastReceiver.registerReceiver(); euiccManager.setEuiccConnectionConsumer(this); } public MutableLiveData<ProfileList> getProfileListLiveData() { return profileList; } public EuiccInfo getEuiccInfo() { return euiccInfo; } public AuthenticateResult getAuthenticateResult() { return authenticateResult; } public DownloadResult getDownloadResult() { return downloadResult; } public CancelSessionResult getCancelSessionResult() { return cancelSessionResult; } public Boolean resetEuicc() throws Exception { if(euiccConnection == null) { throw new Exception("Error: eUICC connection not available to LPA."); } else { return euiccConnection.resetEuicc(); } } public void refreshProfileList() { Log.debug(TAG,"Refreshing profile list."); statusAndEventHandler.onStatusChange(ActionStatus.GET_PROFILE_LIST_STARTED); new TaskRunner().executeAsync(new GetProfileListTask(this), result -> { statusAndEventHandler.onStatusChange(ActionStatus.GET_PROFILE_LIST_FINISHED); profileList.setValue(result); }, e -> statusAndEventHandler.onError(new Error("Exception during getting of profile list.", e.getMessage()))); } public void refreshEuiccInfo() { Log.debug(TAG, "Refreshing eUICC info."); statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_STARTED); new TaskRunner().executeAsync(new GetEuiccInfoTask(this), result -> { euiccInfo = result; statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_FINISHED); }, e -> statusAndEventHandler.onError(new Error("Exception during getting of eUICC info.", e.getMessage()))); } public void enableProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_STARTED); if(profile.isEnabled()) { Log.debug(TAG, "Profile already enabled!"); statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED); return; } new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_ENABLE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during enabling profile.", e.getMessage()))); } public void disableProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_STARTED); if(!profile.isEnabled()) { Log.debug(TAG, "Profile already disabled!"); statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED); return; } new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_DISABLE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during disabling of profile.", e.getMessage()))); } public void deleteProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_STARTED); new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_DELETE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during deleting of profile.", e.getMessage()))); } public void setNickname(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_STARTED); ProfileActionTask profileActionTask = new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_SET_NICKNAME, profile); new TaskRunner().executeAsync(profileActionTask, result -> statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during setting nickname of profile.", e.getMessage()))); } public void handleAndClearAllNotifications() { statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_STARTED); HandleAndClearAllNotificationsTask handleAndClearAllNotificationsTask = new HandleAndClearAllNotificationsTask(this); new TaskRunner().executeAsync(handleAndClearAllNotificationsTask, result -> statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during clearing of all eUICC notifications.", e.getMessage()))); } public void startAuthentication(ActivationCode activationCode) { authenticateResult = null; statusAndEventHandler.onStatusChange(ActionStatus.AUTHENTICATE_DOWNLOAD_STARTED);
AuthenticateTask authenticateTask = new AuthenticateTask(
13
2023-11-22 07:46:30+00:00
24k
phamdung2209/FAP
src/main/java/com/Main.java
[ { "identifier": "BackToMain", "path": "src/main/java/com/func/BackToMain.java", "snippet": "public class BackToMain {\n public void backToMain() {\n System.out.println(\"Returning to main menu...\");\n System.out.println(\"--------MANAGE FAP SYSTEM--------\");\n System.out.printl...
import java.sql.Date; import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; import com.func.BackToMain; import com.func.ClassroomHandler.HandleClassroom; import com.func.CourseHandler.HandleCourse; import com.func.GradeHandler.HandleGrade; import com.func.LectureHandler.HandleLecture; import com.func.StudentHandler.HandleStudent; import com.persons.Administrator; import com.persons.User; import com.persons.personType.PersonType;
14,591
package com; public class Main { public static void main(String[] args) { // singleton pattern // Administrator admin = Administrator.getAdministrator(); // use factory method to create admin Administrator admin = (Administrator) User.getUser(PersonType.ADMINISTRATOR); Scanner scanner = new Scanner(System.in); BackToMain backToMain = new BackToMain(); backToMain.backToMain(); int option = -1; while (option != 0) { if (scanner.hasNextInt()) { option = scanner.nextInt(); switch (option) { case 1: System.out.println("------MANAGE STUDENT-----"); System.out.println("1. Add student"); System.out.println("2. Update student"); System.out.println("3. Delete student"); System.out.println("4. View student"); System.out.println("0. Back"); System.out.println("-------------------------"); System.out.print("Choose your option: "); int studentOption = -1; while (studentOption != 0) { if (scanner.hasNextInt()) { studentOption = scanner.nextInt(); HandleStudent handleStudent = new HandleStudent(); handleStudent.processStudent(studentOption, admin); } else { System.out.println("Invalid input. Please enter a number."); scanner.next(); } } break; case 2: System.out.println("------MANAGE LECTURE-----"); System.out.println("1. Add lecture"); System.out.println("2. Update lecture"); System.out.println("3. Delete lecture"); System.out.println("4. View lecture"); System.out.println("0. Back"); System.out.println("-------------------------"); System.out.print("Choose your option: "); int lectureOption = -1; while (lectureOption != 0) { if (scanner.hasNextInt()) { lectureOption = scanner.nextInt(); HandleLecture handleLecture = new HandleLecture(); handleLecture.processLecture(lectureOption, admin); } } break; case 3: System.out.println("------MANAGE COURSE-----"); System.out.println("1. Add course"); System.out.println("2. Update course"); System.out.println("3. Delete course"); System.out.println("4. View course"); System.out.println("0. Back"); System.out.println("-------------------------"); System.out.print("Choose your option: "); int courseOption = -1; while (courseOption != 0) { if (scanner.hasNextInt()) { courseOption = scanner.nextInt(); HandleCourse handleCourse = new HandleCourse(); handleCourse.processCourse(courseOption, admin); } } break; case 4: System.out.println("------MANAGE GRADE-----"); System.out.println("1. Add grade"); System.out.println("2. Update grade"); System.out.println("3. Delete grade"); System.out.println("4. View grade"); System.out.println("0. Back"); System.out.println("-------------------------"); System.out.print("Choose your option: "); int gradeOption = -1; while (gradeOption != 0) { if (scanner.hasNextInt()) { gradeOption = scanner.nextInt();
package com; public class Main { public static void main(String[] args) { // singleton pattern // Administrator admin = Administrator.getAdministrator(); // use factory method to create admin Administrator admin = (Administrator) User.getUser(PersonType.ADMINISTRATOR); Scanner scanner = new Scanner(System.in); BackToMain backToMain = new BackToMain(); backToMain.backToMain(); int option = -1; while (option != 0) { if (scanner.hasNextInt()) { option = scanner.nextInt(); switch (option) { case 1: System.out.println("------MANAGE STUDENT-----"); System.out.println("1. Add student"); System.out.println("2. Update student"); System.out.println("3. Delete student"); System.out.println("4. View student"); System.out.println("0. Back"); System.out.println("-------------------------"); System.out.print("Choose your option: "); int studentOption = -1; while (studentOption != 0) { if (scanner.hasNextInt()) { studentOption = scanner.nextInt(); HandleStudent handleStudent = new HandleStudent(); handleStudent.processStudent(studentOption, admin); } else { System.out.println("Invalid input. Please enter a number."); scanner.next(); } } break; case 2: System.out.println("------MANAGE LECTURE-----"); System.out.println("1. Add lecture"); System.out.println("2. Update lecture"); System.out.println("3. Delete lecture"); System.out.println("4. View lecture"); System.out.println("0. Back"); System.out.println("-------------------------"); System.out.print("Choose your option: "); int lectureOption = -1; while (lectureOption != 0) { if (scanner.hasNextInt()) { lectureOption = scanner.nextInt(); HandleLecture handleLecture = new HandleLecture(); handleLecture.processLecture(lectureOption, admin); } } break; case 3: System.out.println("------MANAGE COURSE-----"); System.out.println("1. Add course"); System.out.println("2. Update course"); System.out.println("3. Delete course"); System.out.println("4. View course"); System.out.println("0. Back"); System.out.println("-------------------------"); System.out.print("Choose your option: "); int courseOption = -1; while (courseOption != 0) { if (scanner.hasNextInt()) { courseOption = scanner.nextInt(); HandleCourse handleCourse = new HandleCourse(); handleCourse.processCourse(courseOption, admin); } } break; case 4: System.out.println("------MANAGE GRADE-----"); System.out.println("1. Add grade"); System.out.println("2. Update grade"); System.out.println("3. Delete grade"); System.out.println("4. View grade"); System.out.println("0. Back"); System.out.println("-------------------------"); System.out.print("Choose your option: "); int gradeOption = -1; while (gradeOption != 0) { if (scanner.hasNextInt()) { gradeOption = scanner.nextInt();
HandleGrade handleGrade = new HandleGrade();
3
2023-11-23 18:42:19+00:00
24k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/certificate/acme/api/endpoints/order/OrderInfoEndpoint.java
[ { "identifier": "Provisioner", "path": "src/main/java/de/morihofi/acmeserver/certificate/acme/api/Provisioner.java", "snippet": "public class Provisioner {\n\n\n /**\n * Get the ACME Server URL, reachable from other Hosts\n *\n * @return Full url (including HTTPS prefix) and port to this ...
import com.google.gson.Gson; import de.morihofi.acmeserver.certificate.acme.api.Provisioner; import de.morihofi.acmeserver.certificate.acme.api.abstractclass.AbstractAcmeEndpoint; import de.morihofi.acmeserver.certificate.acme.api.endpoints.objects.Identifier; import de.morihofi.acmeserver.certificate.acme.api.endpoints.order.objects.ACMEOrderResponse; import de.morihofi.acmeserver.certificate.acme.security.SignatureCheck; import de.morihofi.acmeserver.certificate.objects.ACMERequestBody; import de.morihofi.acmeserver.database.Database; import de.morihofi.acmeserver.certificate.acme.security.NonceManager; import de.morihofi.acmeserver.database.objects.ACMEIdentifier; import de.morihofi.acmeserver.tools.crypto.Crypto; import de.morihofi.acmeserver.tools.dateAndTime.DateTools; import io.javalin.http.Context; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.Date; import java.util.List;
15,344
package de.morihofi.acmeserver.certificate.acme.api.endpoints.order; public class OrderInfoEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass()); public OrderInfoEndpoint(Provisioner provisioner) { super(provisioner); } @Override public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception { String orderId = ctx.pathParam("orderId"); ctx.header("Content-Type", "application/json");
package de.morihofi.acmeserver.certificate.acme.api.endpoints.order; public class OrderInfoEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass()); public OrderInfoEndpoint(Provisioner provisioner) { super(provisioner); } @Override public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception { String orderId = ctx.pathParam("orderId"); ctx.header("Content-Type", "application/json");
ctx.header("Replay-Nonce", Crypto.createNonce());
9
2023-11-22 15:54:36+00:00
24k
clover/clover-tr34-host
src/test/java/com/clover/tr34/Tr34CloverTest.java
[ { "identifier": "CloverDevTr34KeyStoreData", "path": "src/main/java/com/clover/tr34/samples/CloverDevTr34KeyStoreData.java", "snippet": "public final class CloverDevTr34KeyStoreData extends Tr34KeyStoreData {\n\n // Generated via https://github.corp.clover.com/clover/go-pki-helpers/tree/tr34-test/TR3...
import com.clover.tr34.samples.CloverDevTr34KeyStoreData; import com.clover.tr34.samples.CloverSampleTr34Messages; import org.bouncycastle.cms.CMSSignedData; import org.junit.Test; import java.security.PrivateKey; import java.security.cert.X509Certificate; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals;
16,034
package com.clover.tr34; public class Tr34CloverTest { @Test public void cloverRandomTokenCreate() { byte[] rand = Tr34RandomToken.createNewRandom().getRandomNumber().getOctets(); assertEquals(16, rand.length); } @Test public void cloverRandomTokenCreateAndParse() { byte[] rand = Tr34RandomToken.create(Tr34RandomToken.createNewRandom().toASN1Primitive()) .getRandomNumber().getOctets(); assertEquals(16, rand.length); } @Test public void cloverGenerateKdhCredentialToken() throws Exception {
package com.clover.tr34; public class Tr34CloverTest { @Test public void cloverRandomTokenCreate() { byte[] rand = Tr34RandomToken.createNewRandom().getRandomNumber().getOctets(); assertEquals(16, rand.length); } @Test public void cloverRandomTokenCreateAndParse() { byte[] rand = Tr34RandomToken.create(Tr34RandomToken.createNewRandom().toASN1Primitive()) .getRandomNumber().getOctets(); assertEquals(16, rand.length); } @Test public void cloverGenerateKdhCredentialToken() throws Exception {
Tr34KeyStoreData keyStoreData = CloverDevTr34KeyStoreData.KDH_1;
0
2023-11-22 06:30:40+00:00
24k
NBHZW/hnustDatabaseCourseDesign
ruoyi-admin/src/main/java/com/ruoyi/web/controller/studentInformation/DepartmentController.java
[ { "identifier": "BaseController", "path": "ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java", "snippet": "public class BaseController\r\n{\r\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\r\n\r\n /**\r\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型...
import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.security.access.prepost.PreAuthorize; 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.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.studentInformation.domain.Department; import com.ruoyi.studentInformation.service.IDepartmentService; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.common.core.page.TableDataInfo;
16,948
package com.ruoyi.web.controller.studentInformation; /** * 院系信息Controller * * @author ruoyi * @date 2023-11-07 */ @RestController @RequestMapping("/system/department") public class DepartmentController extends BaseController { @Autowired private IDepartmentService departmentService; /** * 查询院系信息列表 */ @PreAuthorize("@ss.hasPermi('system:department:list')") @GetMapping("/list")
package com.ruoyi.web.controller.studentInformation; /** * 院系信息Controller * * @author ruoyi * @date 2023-11-07 */ @RestController @RequestMapping("/system/department") public class DepartmentController extends BaseController { @Autowired private IDepartmentService departmentService; /** * 查询院系信息列表 */ @PreAuthorize("@ss.hasPermi('system:department:list')") @GetMapping("/list")
public TableDataInfo list(Department department)
6
2023-11-25 02:50:45+00:00
24k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/mods/JERIceAndFire.java
[ { "identifier": "JERRenderHippocampus", "path": "src/main/java/com/invadermonky/justenoughmagiculture/client/model/entity/mods/iceandfire/JERRenderHippocampus.java", "snippet": "public class JERRenderHippocampus extends RenderHippocampus {\n public JERRenderHippocampus(RenderManager renderManager) {\...
import com.github.alexthe666.iceandfire.entity.*; import com.github.alexthe666.iceandfire.enums.EnumTroll; import com.github.alexthe666.iceandfire.item.IafItemRegistry; import com.github.alexthe666.iceandfire.world.gen.*; import com.github.alexthe666.rats.server.entity.EntityPirat; import com.github.alexthe666.rats.server.entity.EntityRat; import com.google.common.collect.Sets; import com.invadermonky.justenoughmagiculture.client.model.entity.mods.iceandfire.JERRenderHippocampus; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.rats.JERRenderPirat; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.rats.JERRenderRat; import com.invadermonky.justenoughmagiculture.configs.JEMConfig; import com.invadermonky.justenoughmagiculture.configs.mods.JEMConfigIceAndFire; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.jer.villager.CustomVanillaVillagerEntry; import com.invadermonky.justenoughmagiculture.integrations.jer.IJERIntegration; import com.invadermonky.justenoughmagiculture.integrations.jer.JERBase; import com.invadermonky.justenoughmagiculture.registry.CustomVillagerRegistry; import com.invadermonky.justenoughmagiculture.util.BiomeHelper; import com.invadermonky.justenoughmagiculture.util.LogHelper; import com.invadermonky.justenoughmagiculture.util.ReflectionHelper; import com.invadermonky.justenoughmagiculture.util.StringHelper; import com.invadermonky.justenoughmagiculture.util.modhelpers.IaFLootHelper; import gnu.trove.map.hash.THashMap; import gnu.trove.set.hash.THashSet; import jeresources.api.conditionals.LightLevel; import jeresources.api.drop.LootDrop; import jeresources.entry.MobEntry; import jeresources.registry.MobRegistry; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityWitherSkeleton; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.world.biome.Biome; import net.minecraftforge.common.BiomeDictionary; import net.minecraftforge.common.BiomeDictionary.Type; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerCareer; import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession; import org.apache.commons.lang3.reflect.FieldUtils; import javax.annotation.Nonnull; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; import java.util.Set;
14,935
})); } if(jerConfig.JER_MOBS.enableGorgon) { registerMob(new EntityGorgon(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.BEACH), EntityGorgon.LOOT); adjustHumanoidRenderHook(EntityGorgon.class); } if(jerConfig.JER_MOBS.enableHippocampus) { registerMob(new EntityHippocampus(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.OCEAN), EntityHippocampus.LOOT); } if(jerConfig.JER_MOBS.enableHippogryph) { registerMob(new EntityHippogryph(world), LightLevel.any, BiomeHelper.getTypeNamesForTypes(Type.HILLS), EntityHippogryph.LOOT); } if(jerConfig.JER_MOBS.enableHydra) { registerMob(new EntityHydra(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.SWAMP), EntityHydra.LOOT); registerRenderHook(EntityHydra.class, ((renderInfo, e) -> { GlStateManager.scale(1.75,1.75,1.75); GlStateManager.translate(-0.05,-0.4,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enablePixie) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.FOREST, Type.SPOOKY); validBiomes.addAll(BiomeDictionary.getBiomes(Type.MAGICAL)); registerMob(new EntityPixie(world), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityPixie.LOOT); } if(jerConfig.JER_MOBS.enableSiren) { THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.OCEAN)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.COLD)); registerMob(new EntitySiren(world), LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), EntitySiren.LOOT); } if(jerConfig.JER_MOBS.enableStymphalianBird) { registerMob(new EntityStymphalianBird(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.SWAMP), EntityStymphalianBird.LOOT); registerRenderHook(EntityStymphalianBird.class, ((renderInfo, e) -> { GlStateManager.scale(1.75,1.75,1.75); GlStateManager.translate(-0.05,-0.3,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableTrollForest) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.FOREST); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.FOREST_LOOT); } if(jerConfig.JER_MOBS.enableTrollFrost) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.FROST); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.FROST_LOOT); } if(jerConfig.JER_MOBS.enableTrollMountain) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.MOUNTAIN); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.MOUNTAIN_LOOT); } //Generic Render Hooks registerRenderHook(EntityTroll.class, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.8,0); return renderInfo; })); } public void registerRenderOverrides() { if(JEMConfig.ICE_AND_FIRE.enableRenderFixes) { //Ice and Fire uses the depreciated method to register entity renders. RenderingRegistry.registerEntityRenderingHandler(EntityHippocampus.class, new JERRenderHippocampus(Minecraft.getMinecraft().getRenderManager())); } } private THashSet<Biome> getIaFLinkedBiomes(Type... types) { THashSet<Biome> biomes = new THashSet<>(); for(Type type : types) { if(biomes.isEmpty()) { biomes.addAll(BiomeDictionary.getBiomes(type)); } else { biomes.removeIf(biome -> (!BiomeDictionary.getBiomes(type).contains(biome))); } } return biomes; } private String[] getIaFSpawnBiomesFromTypes(THashSet<Type> validTypes, THashSet<Type> invalidTypes) { THashSet<Biome> validBiomes = new THashSet<>(); for(Type validType : validTypes) { validBiomes.addAll(BiomeDictionary.getBiomes(validType)); } for(Type invalidType : invalidTypes) { validBiomes.removeAll(BiomeDictionary.getBiomes(invalidType)); } return validBiomes.isEmpty() ? new String[] {"jer.any"} : BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])); } private String[] getIaFSpawnBiomes(THashSet<Biome> biomes, THashSet<Type> invalidTypes) { for(Type type : invalidTypes) { biomes.removeAll(BiomeDictionary.getBiomes(type)); } return biomes.isEmpty() ? new String[] {"jer.any"} : BiomeHelper.getBiomeNamesForBiomes(biomes.toArray(new Biome[0])); } private void adjustHumanoidRenderHook(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.4,0); return renderInfo; })); } @Override public void registerModVillagers() {
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERIceAndFire extends JERBase implements IJERIntegration { private static JERIceAndFire instance; JEMConfigIceAndFire.JER jerConfig = JEMConfig.ICE_AND_FIRE.JUST_ENOUGH_RESOURCES; private JERIceAndFire() {} public JERIceAndFire(boolean enableJERDungeons, boolean enableJERMobs, boolean enableJERVillagers) { if(enableJERDungeons) registerModDungeons(); if(enableJERMobs) registerModEntities(); if(enableJERVillagers) registerModVillagers(); getInstance(); } public static JERIceAndFire getInstance() { return instance != null ? instance : (instance = new JERIceAndFire()); } /** * Ice and fire needs to register render overrides here because they don't work if registered normally. */ public void lateInit() { registerRenderOverrides(); injectLoot(); } @Override public void registerModDungeons() { registerIAFDungeon(WorldGenCyclopsCave.CYCLOPS_CHEST); registerIAFDungeon(WorldGenFireDragonCave.FIREDRAGON_CHEST); registerIAFDungeon(WorldGenFireDragonCave.FIREDRAGON_MALE_CHEST); registerIAFDungeon(WorldGenHydraCave.HYDRA_CHEST); registerIAFDungeon(WorldGenIceDragonCave.ICEDRAGON_CHEST); registerIAFDungeon(WorldGenIceDragonCave.ICEDRAGON_MALE_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.DESERT_MYRMEX_FOOD_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.JUNGLE_MYRMEX_FOOD_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.MYRMEX_GOLD_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.MYRMEX_TRASH_CHEST); } @Override public void registerModEntities() { registerDragons(); registerDeathworms(); registerDread(); registerMyrmex(); registerSeaSerpents(); registerMiscMobs(); } @Override @SuppressWarnings("unchecked") public void injectLoot() { if(JEMConfig.ICE_AND_FIRE.enableJERInjectedLoot) { for (MobEntry mobEntry : MobRegistry.getInstance().getMobs()) { if (mobEntry.getEntity() instanceof EntityWitherSkeleton) { try { Field entryField = MobRegistry.getInstance().getClass().getDeclaredField("registry"); entryField.setAccessible(true); Set<MobEntry> mobEntries = (Set<MobEntry>) entryField.get(MobRegistry.getInstance()); mobEntries.remove(mobEntry); Field dropsField = mobEntry.getClass().getDeclaredField("drops"); dropsField.setAccessible(true); mobEntry.addDrop(new LootDrop(IafItemRegistry.witherbone, 0, 1)); mobEntries.add(mobEntry); } catch(Exception ignored) {} } } } } private void registerDragons() { THashSet<Type> validFireTypes = new THashSet<>(Sets.newHashSet(Type.HILLS, Type.MOUNTAIN)); THashSet<Type> invalidForeTypes = new THashSet<>(Sets.newHashSet(Type.COLD, Type.SNOWY)); THashSet<Biome> validIceBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); THashSet<Type> invalidIceTypes = new THashSet<>(Sets.newHashSet(Type.BEACH)); if(jerConfig.JER_MOBS.enableFireDragonMale) { for (int i = 0; i < 3; i++) { EntityFireDragon fireDragon = new EntityFireDragon(world); fireDragon.setVariant(i); fireDragon.setCustomNameTag("entity.jem:iaf_fire_dragon_male.name"); List<LootDrop> drops = IaFLootHelper.toDrops(fireDragon, manager.getLootTableFromLocation(EntityFireDragon.MALE_LOOT)); if (jerConfig.JER_MOBS.enableFireDragonMale) { registerMob(fireDragon, LightLevel.any, getIaFSpawnBiomesFromTypes(validFireTypes, invalidForeTypes), drops); } } } if(jerConfig.JER_MOBS.enableIceDragonMale) { for (int i = 0; i < 3; i++) { EntityIceDragon iceDragon = new EntityIceDragon(world); iceDragon.setVariant(i); iceDragon.setCustomNameTag("entity.jem:iaf_ice_dragon_male.name"); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); List<LootDrop> drops = IaFLootHelper.toDrops(iceDragon, manager.getLootTableFromLocation(EntityIceDragon.MALE_LOOT)); if (jerConfig.JER_MOBS.enableFireDragonMale) { registerMob(iceDragon, LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), drops); } } } if(jerConfig.JER_MOBS.enableFireDragonFemale) { for (int i = 0; i < 3; i++) { EntityFireDragon fireDragon = new EntityFireDragon(world); fireDragon.setVariant(i); fireDragon.setCustomNameTag("entity.jem:iaf_fire_dragon_female.name"); List<LootDrop> femaleDrops = IaFLootHelper.toDrops(fireDragon, manager.getLootTableFromLocation(EntityFireDragon.FEMALE_LOOT)); registerMob(fireDragon, LightLevel.any, getIaFSpawnBiomesFromTypes(validFireTypes, invalidForeTypes), femaleDrops); } } if(jerConfig.JER_MOBS.enableIceDragonFemale) { for(int i = 0; i < 3; i++) { EntityIceDragon iceDragon = new EntityIceDragon(world); iceDragon.setVariant(i); iceDragon.setCustomNameTag("entity.jem:iaf_ice_dragon_female.name"); List<LootDrop> femaleDrops = IaFLootHelper.toDrops(iceDragon, manager.getLootTableFromLocation(EntityIceDragon.FEMALE_LOOT)); registerMob(iceDragon, LightLevel.any, getIaFSpawnBiomes(validIceBiomes, invalidIceTypes), femaleDrops); } } registerRenderHook(EntityDragonBase.class, ((renderInfo, e) -> { GlStateManager.scale(3.0,3.0,3.0); GlStateManager.translate(-0.005,-0.05,0); return renderInfo; })); } private void registerDeathworms() { if(jerConfig.JER_MOBS.enableDeathWormRed) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(2); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(5); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.RED_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormRedGiant) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(2); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(10); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.RED_GIANT_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormTan) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(0); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(5); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.TAN_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormTanGiant) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(0); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(10); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.TAN_GIANT_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormWhite) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(1); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(5); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.WHITE_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormWhiteGiant) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(1); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(10); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.WHITE_GIANT_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } } private void registerDread() { if(jerConfig.JER_MOBS.enableDreadBeast) { EntityDreadBeast dreadBeast = new EntityDreadBeast(world); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadBeast, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadBeast.LOOT); adjustHumanoidRenderHook(EntityDreadBeast.class); } if(jerConfig.JER_MOBS.enableDreadGhoul) { EntityDreadGhoul dreadGhoul = new EntityDreadGhoul(world); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadGhoul, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadGhoul.LOOT); adjustHumanoidRenderHook(EntityDreadGhoul.class); } if(jerConfig.JER_MOBS.enableDreadKnight) { EntityDreadKnight dreadKnight = new EntityDreadKnight(world); dreadKnight.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(IafItemRegistry.dread_knight_sword)); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadKnight, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadKnight.LOOT); registerRenderHook(EntityDreadKnight.class, ((renderInfo, e) -> { GlStateManager.translate(-0.05,0.2,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableDreadLich) { EntityDreadLich lich = new EntityDreadLich(world); lich.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(IafItemRegistry.lich_staff)); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(lich, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadLich.LOOT); adjustHumanoidRenderHook(EntityDreadLich.class); } if(jerConfig.JER_MOBS.enableDreadScuttler) { EntityDreadScuttler dreadScuttler = new EntityDreadScuttler(world); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadScuttler, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadScuttler.LOOT); registerRenderHook(EntityDreadScuttler.class, ((renderInfo, e) -> { GlStateManager.scale(0.9,0.9,0.9); GlStateManager.translate(0,-0.2,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableDreadThrall) { EntityDreadThrall dreadThrall = new EntityDreadThrall(world); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(IafItemRegistry.dread_sword)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.HEAD, new ItemStack(Items.CHAINMAIL_HELMET)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.CHEST, new ItemStack(Items.CHAINMAIL_CHESTPLATE)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.LEGS, new ItemStack(Items.CHAINMAIL_LEGGINGS)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.FEET, new ItemStack(Items.CHAINMAIL_BOOTS)); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadThrall, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadThrall.LOOT); adjustHumanoidRenderHook(dreadThrall.getClass()); } } private void registerMyrmex() { if(jerConfig.JER_MOBS.enableMyrmexDesertQueen) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexQueen(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexQueen.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertRoyal) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexRoyal(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexRoyal.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertSentinel) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexSentinel(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexSentinel.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertSoldier) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexSoldier(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexSoldier.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertWorker) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexWorker(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexWorker.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleQueen) { registerMob(setMyrmexTexture(new EntityMyrmexQueen(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexQueen.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleRoyal) { registerMob(setMyrmexTexture(new EntityMyrmexRoyal(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexRoyal.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleSentinel) { registerMob(setMyrmexTexture(new EntityMyrmexSentinel(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexSentinel.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleSoldier) { registerMob(setMyrmexTexture(new EntityMyrmexSoldier(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexSoldier.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleWorker) { registerMob(setMyrmexTexture(new EntityMyrmexWorker(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexWorker.JUNGLE_LOOT); } registerRenderHook(EntityMyrmexQueen.class, ((renderInfo, entityLivingBase) -> { GlStateManager.scale(1.7,1.7,1.7); return renderInfo; })); } private void registerSeaSerpents() { if(jerConfig.JER_MOBS.enableSeaSerpent) { for(int i = 0; i < 6; i++) { EntitySeaSerpent seaSerpent = new EntitySeaSerpent(world); NBTTagCompound tag = new NBTTagCompound(); tag.setFloat("Scale", 1f); seaSerpent.readEntityFromNBT(tag); seaSerpent.setVariant(i); List<LootDrop> drops = IaFLootHelper.toDrops(seaSerpent, manager.getLootTableFromLocation(EntitySeaSerpent.LOOT)); registerMob(seaSerpent, LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.OCEAN), drops); } } } private void registerMiscMobs() { if(jerConfig.JER_MOBS.enableAmphithere) { registerMob(new EntityAmphithere(world), LightLevel.any, BiomeHelper.getTypeNamesForTypes(Type.JUNGLE), EntityAmphithere.LOOT); registerRenderHook(EntityAmphithere.class, ((renderInfo, entityLivingBase) -> { GlStateManager.translate(-0.05,1.4,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableCockatrice) { registerMob(new EntityCockatrice(world), LightLevel.any, BiomeHelper.getTypeNamesForTypes(Type.SAVANNA, Type.SPARSE), EntityCockatrice.LOOT); } if(jerConfig.JER_MOBS.enableCyclops) { registerMob(new EntityCyclops(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.BEACH, Type.PLAINS), EntityCyclops.LOOT); registerRenderHook(EntityCyclops.class, ((renderInfo, entityLivingBase) -> { GlStateManager.scale(0.9,0.9,0.9); GlStateManager.translate(-0.05,-1.75,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableGorgon) { registerMob(new EntityGorgon(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.BEACH), EntityGorgon.LOOT); adjustHumanoidRenderHook(EntityGorgon.class); } if(jerConfig.JER_MOBS.enableHippocampus) { registerMob(new EntityHippocampus(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.OCEAN), EntityHippocampus.LOOT); } if(jerConfig.JER_MOBS.enableHippogryph) { registerMob(new EntityHippogryph(world), LightLevel.any, BiomeHelper.getTypeNamesForTypes(Type.HILLS), EntityHippogryph.LOOT); } if(jerConfig.JER_MOBS.enableHydra) { registerMob(new EntityHydra(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.SWAMP), EntityHydra.LOOT); registerRenderHook(EntityHydra.class, ((renderInfo, e) -> { GlStateManager.scale(1.75,1.75,1.75); GlStateManager.translate(-0.05,-0.4,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enablePixie) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.FOREST, Type.SPOOKY); validBiomes.addAll(BiomeDictionary.getBiomes(Type.MAGICAL)); registerMob(new EntityPixie(world), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityPixie.LOOT); } if(jerConfig.JER_MOBS.enableSiren) { THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.OCEAN)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.COLD)); registerMob(new EntitySiren(world), LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), EntitySiren.LOOT); } if(jerConfig.JER_MOBS.enableStymphalianBird) { registerMob(new EntityStymphalianBird(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.SWAMP), EntityStymphalianBird.LOOT); registerRenderHook(EntityStymphalianBird.class, ((renderInfo, e) -> { GlStateManager.scale(1.75,1.75,1.75); GlStateManager.translate(-0.05,-0.3,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableTrollForest) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.FOREST); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.FOREST_LOOT); } if(jerConfig.JER_MOBS.enableTrollFrost) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.FROST); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.FROST_LOOT); } if(jerConfig.JER_MOBS.enableTrollMountain) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.MOUNTAIN); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.MOUNTAIN_LOOT); } //Generic Render Hooks registerRenderHook(EntityTroll.class, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.8,0); return renderInfo; })); } public void registerRenderOverrides() { if(JEMConfig.ICE_AND_FIRE.enableRenderFixes) { //Ice and Fire uses the depreciated method to register entity renders. RenderingRegistry.registerEntityRenderingHandler(EntityHippocampus.class, new JERRenderHippocampus(Minecraft.getMinecraft().getRenderManager())); } } private THashSet<Biome> getIaFLinkedBiomes(Type... types) { THashSet<Biome> biomes = new THashSet<>(); for(Type type : types) { if(biomes.isEmpty()) { biomes.addAll(BiomeDictionary.getBiomes(type)); } else { biomes.removeIf(biome -> (!BiomeDictionary.getBiomes(type).contains(biome))); } } return biomes; } private String[] getIaFSpawnBiomesFromTypes(THashSet<Type> validTypes, THashSet<Type> invalidTypes) { THashSet<Biome> validBiomes = new THashSet<>(); for(Type validType : validTypes) { validBiomes.addAll(BiomeDictionary.getBiomes(validType)); } for(Type invalidType : invalidTypes) { validBiomes.removeAll(BiomeDictionary.getBiomes(invalidType)); } return validBiomes.isEmpty() ? new String[] {"jer.any"} : BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])); } private String[] getIaFSpawnBiomes(THashSet<Biome> biomes, THashSet<Type> invalidTypes) { for(Type type : invalidTypes) { biomes.removeAll(BiomeDictionary.getBiomes(type)); } return biomes.isEmpty() ? new String[] {"jer.any"} : BiomeHelper.getBiomeNamesForBiomes(biomes.toArray(new Biome[0])); } private void adjustHumanoidRenderHook(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.4,0); return renderInfo; })); } @Override public void registerModVillagers() {
CustomVillagerRegistry registry = CustomVillagerRegistry.getInstance();
8
2023-11-19 23:09:14+00:00
24k
codingmiao/hppt
ss/src/main/java/org/wowtools/hppt/ss/servlet/TalkServlet.java
[ { "identifier": "ProtoMessage", "path": "common/src/main/java/org/wowtools/hppt/common/protobuf/ProtoMessage.java", "snippet": "public final class ProtoMessage {\n private ProtoMessage() {}\n public static void registerAllExtensions(\n com.google.protobuf.ExtensionRegistryLite registry) {\n }\n\...
import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.wowtools.hppt.common.protobuf.ProtoMessage; import org.wowtools.hppt.common.util.BytesUtil; import org.wowtools.hppt.ss.StartSs; import org.wowtools.hppt.ss.service.ClientService; import org.wowtools.hppt.ss.service.ServerSessionService; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
17,220
package org.wowtools.hppt.ss.servlet; /** * @author liuyu * @date 2023/11/5 */ @Slf4j public class TalkServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String loginCode = req.getParameter("c"); loginCode = loginCode.replace(" ", "+"); ClientService.Client client = ClientService.getClient(loginCode); if (null == client) { throw new RuntimeException("not login: " + loginCode); } String clientId = client.clientId; //读请求体里带过来的bytes byte[] bytes; try (InputStream inputStream = req.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); } bytes = byteArrayOutputStream.toByteArray(); } //解密、解压
package org.wowtools.hppt.ss.servlet; /** * @author liuyu * @date 2023/11/5 */ @Slf4j public class TalkServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String loginCode = req.getParameter("c"); loginCode = loginCode.replace(" ", "+"); ClientService.Client client = ClientService.getClient(loginCode); if (null == client) { throw new RuntimeException("not login: " + loginCode); } String clientId = client.clientId; //读请求体里带过来的bytes byte[] bytes; try (InputStream inputStream = req.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); } bytes = byteArrayOutputStream.toByteArray(); } //解密、解压
if (StartSs.config.enableEncrypt) {
2
2023-12-22 14:14:27+00:00
24k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/modules/combat/Bomber.java
[ { "identifier": "Phobot", "path": "src/main/java/me/earth/phobot/Phobot.java", "snippet": "@Getter\n@RequiredArgsConstructor\n@SuppressWarnings(\"ClassCanBeRecord\")\npublic class Phobot {\n public static final String NAME = \"Phobot\";\n\n private final PingBypass pingBypass;\n private final E...
import lombok.Getter; import lombok.extern.slf4j.Slf4j; import me.earth.phobot.Phobot; import me.earth.phobot.damagecalc.CrystalPosition; import me.earth.phobot.ducks.IEntity; import me.earth.phobot.modules.BlockPlacingModule; import me.earth.phobot.modules.combat.autocrystal.AutoCrystal; import me.earth.phobot.modules.combat.autocrystal.CrystalPlacingModule; import me.earth.phobot.modules.misc.Speedmine; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.util.ResetUtil; import me.earth.phobot.util.entity.EntityUtil; import me.earth.phobot.util.math.PositionUtil; import me.earth.phobot.util.mutables.MutPos; import me.earth.phobot.util.time.TimeUtil; import me.earth.phobot.util.world.BlockStateLevel; import me.earth.pingbypass.api.event.listeners.generic.Listener; import me.earth.pingbypass.api.module.impl.Categories; import me.earth.pingbypass.commons.event.SafeListener; import me.earth.pingbypass.commons.event.network.PacketEvent; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.boss.enderdragon.EndCrystal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.phys.AABB; import org.apache.commons.lang3.mutable.MutableObject; import org.jetbrains.annotations.Nullable; import java.util.Objects; import java.util.function.Consumer;
16,794
package me.earth.phobot.modules.combat; // TODO: stop bombing ourselves! // TODO: Anvil Bomber // TODO: distance to target player!!! // TODO: Spam crystals against surround without AutoCrystal calculation @Slf4j public class Bomber extends BlockPlacingModule { private final PositionsThatBlowUpDrops positions = new PositionsThatBlowUpDrops(); @Getter private final AutoCrystal autoCrystal;
package me.earth.phobot.modules.combat; // TODO: stop bombing ourselves! // TODO: Anvil Bomber // TODO: distance to target player!!! // TODO: Spam crystals against surround without AutoCrystal calculation @Slf4j public class Bomber extends BlockPlacingModule { private final PositionsThatBlowUpDrops positions = new PositionsThatBlowUpDrops(); @Getter private final AutoCrystal autoCrystal;
private final Speedmine speedmine;
6
2023-12-22 14:32:16+00:00
24k
ArmanKhanDev/FakepixelDungeonHelper
build/sources/main/java/io/github/quantizr/gui/WaypointsGUI.java
[ { "identifier": "AutoRoom", "path": "build/sources/main/java/io/github/quantizr/core/AutoRoom.java", "snippet": "public class AutoRoom {\n Minecraft mc = Minecraft.getMinecraft();\n\n static int tickAmount = 1;\n public static List<String> autoTextOutput = null;\n public static boolean chatT...
import io.github.quantizr.core.AutoRoom; import io.github.quantizr.core.Waypoints; import io.github.quantizr.handlers.ConfigHandler; import io.github.quantizr.handlers.TextRenderer; import io.github.quantizr.utils.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumChatFormatting; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
15,742
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM 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. DRM 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 DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class WaypointsGUI extends GuiScreen { private GuiButton waypointsEnabled; private GuiButton showEntrance; private GuiButton showSuperboom; private GuiButton showSecrets; private GuiButton showFairySouls; private GuiButton disableWhenAllFound; private GuiButton sneakToDisable; private GuiButton close; public static List<GuiButton> secretButtonList = new ArrayList<>(Arrays.asList(new GuiButton[9])); private static boolean waypointGuiOpened = false; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); waypointGuiOpened = true; ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); waypointsEnabled = new GuiButton(0, width / 2 - 100, height / 6, 200, 20, waypointBtnText()); showEntrance = new GuiButton(1, (width / 2 - 100) - 110, height / 6 + 30, 200, 20, "Show Entrance Waypoints: " + getOnOff(Waypoints.showEntrance)); showSuperboom = new GuiButton(2, (width / 2 - 100) + 110, height / 6 + 30, 200, 20, "Show Superboom Waypoints: " + getOnOff(Waypoints.showSuperboom)); showSecrets = new GuiButton(3, (width / 2 - 100) - 110, height / 6 + 60, 200, 20, "Show Secret Waypoints: " + getOnOff(Waypoints.showSecrets)); showFairySouls = new GuiButton(4, (width / 2 - 100) + 110, height / 6 + 60, 200, 20, "Show Fairy Soul Waypoints: " + getOnOff(Waypoints.showFairySouls)); sneakToDisable = new GuiButton(5, (width / 2 - 100) - 110, height / 6 + 90, 200, 20, "Double-Tap Sneak to Hide Nearby: " + getOnOff(Waypoints.sneakToDisable)); disableWhenAllFound = new GuiButton(6, (width / 2 - 100) + 110, height / 6 + 90, 200, 20, "Disable when all secrets found: " + getOnOff(Waypoints.disableWhenAllFound)); close = new GuiButton(7, width / 2 - 100, (height / 6) * 5, 200, 20, "Close"); this.buttonList.add(waypointsEnabled); this.buttonList.add(showEntrance); this.buttonList.add(showSuperboom); this.buttonList.add(showSecrets); this.buttonList.add(showFairySouls); this.buttonList.add(sneakToDisable); this.buttonList.add(disableWhenAllFound); this.buttonList.add(close); if (Utils.inDungeons) { if (Waypoints.secretNum > 0) { if (Waypoints.secretNum <= 5) { for (int i = 1; i <= Waypoints.secretNum; i++) { int adjustPos = (-40 * (Waypoints.secretNum)) - 70 + (80 * i); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 170, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } } else { for (int i = 1; i <= (int) Math.ceil((double) Waypoints.secretNum / 2); i++) { int adjustPos = (-40 * ((int) Math.ceil((double) Waypoints.secretNum / 2))) - 70 + (80 * i); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 170, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } for (int i = (int) Math.ceil((double) Waypoints.secretNum / 2) + 1; i <= Waypoints.secretNum; i++) { int adjustPos = (-40 * (Waypoints.secretNum - (int) Math.ceil((double) Waypoints.secretNum / 2))) - 70 + (80 * (i-(int) Math.ceil((double) Waypoints.secretNum / 2))); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 200, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } } } } } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); Minecraft mc = Minecraft.getMinecraft(); String displayText = "FakepixelDungeonHelper Waypoints:"; int displayWidth = mc.fontRendererObj.getStringWidth(displayText); TextRenderer.drawText(mc, displayText, width / 2 - displayWidth / 2, height / 6 - 20, 1D, false); String subtext1 = "Toggle Room Specific Waypoints:"; int subtext1Width = mc.fontRendererObj.getStringWidth(subtext1); TextRenderer.drawText(mc, subtext1, width / 2 - subtext1Width / 2, height / 6 + 140, 1D, false); String subtext2 = "(You can also press the # key matching the secret instead)"; int subtext2Width = mc.fontRendererObj.getStringWidth(subtext2); TextRenderer.drawText(mc, EnumChatFormatting.GRAY + subtext2, width / 2 - subtext2Width / 2, height / 6 + 150, 1D, false); if (!Utils.inDungeons) { String subtext3 = "Not in dungeons"; int subtext3Width = mc.fontRendererObj.getStringWidth(subtext3); TextRenderer.drawText(mc, EnumChatFormatting.RED + subtext3, width / 2 - subtext3Width / 2, height / 6 + 170, 1D, false); } else if (Waypoints.secretNum == 0) { String subtext3 = "No secrets in this room"; int subtext3Width = mc.fontRendererObj.getStringWidth(subtext3); TextRenderer.drawText(mc, EnumChatFormatting.RED + subtext3, width / 2 - subtext3Width / 2, height / 6 + 170, 1D, false); } super.drawScreen(mouseX, mouseY, partialTicks); } @Override public void actionPerformed(GuiButton button) { EntityPlayer player = Minecraft.getMinecraft().thePlayer; if (button == waypointsEnabled) { Waypoints.enabled = !Waypoints.enabled;
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM 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. DRM 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 DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class WaypointsGUI extends GuiScreen { private GuiButton waypointsEnabled; private GuiButton showEntrance; private GuiButton showSuperboom; private GuiButton showSecrets; private GuiButton showFairySouls; private GuiButton disableWhenAllFound; private GuiButton sneakToDisable; private GuiButton close; public static List<GuiButton> secretButtonList = new ArrayList<>(Arrays.asList(new GuiButton[9])); private static boolean waypointGuiOpened = false; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); waypointGuiOpened = true; ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); waypointsEnabled = new GuiButton(0, width / 2 - 100, height / 6, 200, 20, waypointBtnText()); showEntrance = new GuiButton(1, (width / 2 - 100) - 110, height / 6 + 30, 200, 20, "Show Entrance Waypoints: " + getOnOff(Waypoints.showEntrance)); showSuperboom = new GuiButton(2, (width / 2 - 100) + 110, height / 6 + 30, 200, 20, "Show Superboom Waypoints: " + getOnOff(Waypoints.showSuperboom)); showSecrets = new GuiButton(3, (width / 2 - 100) - 110, height / 6 + 60, 200, 20, "Show Secret Waypoints: " + getOnOff(Waypoints.showSecrets)); showFairySouls = new GuiButton(4, (width / 2 - 100) + 110, height / 6 + 60, 200, 20, "Show Fairy Soul Waypoints: " + getOnOff(Waypoints.showFairySouls)); sneakToDisable = new GuiButton(5, (width / 2 - 100) - 110, height / 6 + 90, 200, 20, "Double-Tap Sneak to Hide Nearby: " + getOnOff(Waypoints.sneakToDisable)); disableWhenAllFound = new GuiButton(6, (width / 2 - 100) + 110, height / 6 + 90, 200, 20, "Disable when all secrets found: " + getOnOff(Waypoints.disableWhenAllFound)); close = new GuiButton(7, width / 2 - 100, (height / 6) * 5, 200, 20, "Close"); this.buttonList.add(waypointsEnabled); this.buttonList.add(showEntrance); this.buttonList.add(showSuperboom); this.buttonList.add(showSecrets); this.buttonList.add(showFairySouls); this.buttonList.add(sneakToDisable); this.buttonList.add(disableWhenAllFound); this.buttonList.add(close); if (Utils.inDungeons) { if (Waypoints.secretNum > 0) { if (Waypoints.secretNum <= 5) { for (int i = 1; i <= Waypoints.secretNum; i++) { int adjustPos = (-40 * (Waypoints.secretNum)) - 70 + (80 * i); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 170, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } } else { for (int i = 1; i <= (int) Math.ceil((double) Waypoints.secretNum / 2); i++) { int adjustPos = (-40 * ((int) Math.ceil((double) Waypoints.secretNum / 2))) - 70 + (80 * i); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 170, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } for (int i = (int) Math.ceil((double) Waypoints.secretNum / 2) + 1; i <= Waypoints.secretNum; i++) { int adjustPos = (-40 * (Waypoints.secretNum - (int) Math.ceil((double) Waypoints.secretNum / 2))) - 70 + (80 * (i-(int) Math.ceil((double) Waypoints.secretNum / 2))); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 200, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } } } } } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); Minecraft mc = Minecraft.getMinecraft(); String displayText = "FakepixelDungeonHelper Waypoints:"; int displayWidth = mc.fontRendererObj.getStringWidth(displayText); TextRenderer.drawText(mc, displayText, width / 2 - displayWidth / 2, height / 6 - 20, 1D, false); String subtext1 = "Toggle Room Specific Waypoints:"; int subtext1Width = mc.fontRendererObj.getStringWidth(subtext1); TextRenderer.drawText(mc, subtext1, width / 2 - subtext1Width / 2, height / 6 + 140, 1D, false); String subtext2 = "(You can also press the # key matching the secret instead)"; int subtext2Width = mc.fontRendererObj.getStringWidth(subtext2); TextRenderer.drawText(mc, EnumChatFormatting.GRAY + subtext2, width / 2 - subtext2Width / 2, height / 6 + 150, 1D, false); if (!Utils.inDungeons) { String subtext3 = "Not in dungeons"; int subtext3Width = mc.fontRendererObj.getStringWidth(subtext3); TextRenderer.drawText(mc, EnumChatFormatting.RED + subtext3, width / 2 - subtext3Width / 2, height / 6 + 170, 1D, false); } else if (Waypoints.secretNum == 0) { String subtext3 = "No secrets in this room"; int subtext3Width = mc.fontRendererObj.getStringWidth(subtext3); TextRenderer.drawText(mc, EnumChatFormatting.RED + subtext3, width / 2 - subtext3Width / 2, height / 6 + 170, 1D, false); } super.drawScreen(mouseX, mouseY, partialTicks); } @Override public void actionPerformed(GuiButton button) { EntityPlayer player = Minecraft.getMinecraft().thePlayer; if (button == waypointsEnabled) { Waypoints.enabled = !Waypoints.enabled;
ConfigHandler.writeBooleanConfig("toggles", "waypointsToggled", Waypoints.enabled);
2
2023-12-22 04:44:39+00:00
24k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/LauncherWindow.java
[ { "identifier": "GenericWindow", "path": "app/src/main/java/net/lonelytransistor/launcher/generics/GenericWindow.java", "snippet": "public class GenericWindow {\n private static final String TAG = \"GenericWindow\";\n\n private static final int FADE_DURATION = 500;\n\n private static WindowMana...
import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.media.tv.TvContract; import android.media.tv.TvInputInfo; import android.media.tv.TvInputManager; import android.media.tv.TvView; import android.provider.Settings; import android.view.KeyEvent; import android.view.View; import net.lonelytransistor.launcher.generics.GenericWindow; import net.lonelytransistor.launcher.repos.ApkRepo; import net.lonelytransistor.launcher.repos.JustWatch; import net.lonelytransistor.launcher.repos.MovieRepo; import net.lonelytransistor.launcher.repos.MovieTitle; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor;
16,883
String id = inputInfo.getId(); int state = inputManager.getInputState(id); Drawable img = inputInfo.loadIcon(ctx); if (state != TvInputManager.INPUT_STATE_DISCONNECTED && ApkRepo.isSystemApp(inputInfo.getServiceInfo().packageName) && img != null) { BadgeCard card = new BadgeCard(String.valueOf(inputInfo.loadLabel(ctx)), img, (state == TvInputManager.INPUT_STATE_CONNECTED_STANDBY) ? R.drawable.power_off : (state == TvInputManager.INPUT_STATE_CONNECTED ? R.drawable.running : null), new Card.Callback() { @Override public boolean onClicked(Card card) { tvView.tune(inputInfo.getId(), TvContract.buildChannelUriForPassthroughInput(inputInfo.getId())); hide(); return false; } @Override public void onHovered(Card card, boolean hovered) {} }); launcherBar.addItem(row, card); } } } row = launcherBar.addRow(new BadgeCard("", "Resume\nPlayback", R.drawable.icon_play_rounded, 0xFFFFFFFF,0xFFBF8C00,null)); rows.put(RESUME_ROW, row); timestamps.put(RESUME_ROW, 0L); row = launcherBar.addRow(new BadgeCard("", "Popular\nMovies", R.drawable.icon_recommend, 0xFFFFFFFF,0xFFC01F1F,null)); rows.put(POPULAR_MOVIES_ROW, row); timestamps.put(POPULAR_MOVIES_ROW, 0L); row = launcherBar.addRow(new BadgeCard("", "Popular\nSeries", R.drawable.icon_recommend, 0xFFFFFFFF,0xFF4F4FB0,null)); rows.put(POPULAR_SERIES_ROW, row); timestamps.put(POPULAR_SERIES_ROW, 0L); for (ApkRepo.App app : ApkRepo.getPlatformApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, 0L); } for (ApkRepo.App app : ApkRepo.getNonPlatformVideoApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, 0L); } for (ApkRepo.App app : ApkRepo.getAudioApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, System.currentTimeMillis()); } for (ApkRepo.App app : ApkRepo.getGamingApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, System.currentTimeMillis()); } row = launcherBar.addRow(new BadgeCard("", "Other\nApps", R.drawable.icon_apps, 0xFFFFFFFF,0xFF2CAAEE,null)); rows.put(OTHER_APPS_ROW, row); timestamps.put(OTHER_APPS_ROW, System.currentTimeMillis()); { List<ApkRepo.App> apps = new ArrayList<>(ApkRepo.getPlatformApps()); apps.addAll(ApkRepo.getNonPlatformVideoApps()); apps.addAll(ApkRepo.getAudioApps()); apps.addAll(ApkRepo.getGamingApps()); for (ApkRepo.App app : ApkRepo.getApps(null, apps)) { launcherBar.addItem(row, new BadgeCard(app.name, app.badge != null ? app.badge : app.icon, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); } } row = launcherBar.addRow( new BadgeCard("Settings", ApkRepo.getActionBadge(Settings.ACTION_SETTINGS), new Card.Callback() { @Override public boolean onClicked(Card card) { startActivity(new Intent(Settings.ACTION_SETTINGS)); return false; } @Override public void onHovered(Card card, boolean hovered) {} }) ); rows.put(SETTINGS_ROW, row); launcherBar.addItems(row, widgetBar.getAllWidgetCards()); timestamps.put(SETTINGS_ROW, System.currentTimeMillis()); //clockInterval = new Utils.Interval(() -> launcherBar.post(() -> updateClock()), 1000); } private void updateRows() { long timeNow = System.currentTimeMillis(); int row; if (MovieRepo.getWatchNextTimestamp() > timestamps.get(RESUME_ROW)) { row = rows.get(RESUME_ROW); timestamps.put(RESUME_ROW, timeNow); launcherBar.clearRow(row); long dayNow = timeNow/1000/3600/24; for (MovieTitle movie : MovieRepo.getWatchNext()) { if ((dayNow - movie.system.lastWatched/1000/3600/24) < 30 && movie.system.state != MovieTitle.System.State.WATCHED) { launcherBar.addItem(row, new MovieCard(movie)); } } } if (MovieRepo.getRecommendedTimestamp() > timestamps.get(POPULAR_MOVIES_ROW)) { row = rows.get(POPULAR_MOVIES_ROW); timestamps.put(POPULAR_MOVIES_ROW, timeNow); launcherBar.clearRow(row);
package net.lonelytransistor.launcher; @SuppressLint("RestrictedApi") public class LauncherWindow extends GenericWindow { private static final String TAG = "LauncherWindow"; private final Executor executor; private final View.OnKeyListener mKeyListener = (v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ESCAPE: hide(); return true; } } return false; }; private static final String INPUTS_ROW = "INPUTS_ROW"; private static final String RESUME_ROW = "RESUME_ROW"; private static final String POPULAR_MOVIES_ROW = "POPULAR_MOVIES_ROW"; private static final String POPULAR_SERIES_ROW = "POPULAR_SERIES_ROW"; private static final String OTHER_APPS_ROW = "OTHER_APPS_ROW"; private static final String SETTINGS_ROW = "SETTINGS_ROW"; private final Map<String, Integer> rows = new HashMap<>(); private final Map<String, Long> timestamps = new HashMap<>(); private final LauncherBar launcherBar; private final WidgetBar widgetBar; public LauncherWindow(Context ctx) { super(ctx, R.layout.activity_launcher_new); widgetBar = (WidgetBar) findViewById(R.id.widget_bar); launcherBar = (LauncherBar) findViewById(R.id.launcher_bar); getView().setOnKeyListener(mKeyListener); launcherBar.setOnKeyListener(mKeyListener); launcherBar.setOnClickListener(v -> hide()); executor = ctx.getMainExecutor(); int row; row = launcherBar.addRow(new BadgeCard("", "Select\nInput", R.drawable.icon_input, 0xFFFFFFFF,0xFF229C8F,null)); rows.put(INPUTS_ROW, row); timestamps.put(INPUTS_ROW, System.currentTimeMillis()); { TvInputManager inputManager = (TvInputManager) ctx.getSystemService(Context.TV_INPUT_SERVICE); TvView tvView = new TvView(ctx); for (TvInputInfo inputInfo : inputManager.getTvInputList()) { String id = inputInfo.getId(); int state = inputManager.getInputState(id); Drawable img = inputInfo.loadIcon(ctx); if (state != TvInputManager.INPUT_STATE_DISCONNECTED && ApkRepo.isSystemApp(inputInfo.getServiceInfo().packageName) && img != null) { BadgeCard card = new BadgeCard(String.valueOf(inputInfo.loadLabel(ctx)), img, (state == TvInputManager.INPUT_STATE_CONNECTED_STANDBY) ? R.drawable.power_off : (state == TvInputManager.INPUT_STATE_CONNECTED ? R.drawable.running : null), new Card.Callback() { @Override public boolean onClicked(Card card) { tvView.tune(inputInfo.getId(), TvContract.buildChannelUriForPassthroughInput(inputInfo.getId())); hide(); return false; } @Override public void onHovered(Card card, boolean hovered) {} }); launcherBar.addItem(row, card); } } } row = launcherBar.addRow(new BadgeCard("", "Resume\nPlayback", R.drawable.icon_play_rounded, 0xFFFFFFFF,0xFFBF8C00,null)); rows.put(RESUME_ROW, row); timestamps.put(RESUME_ROW, 0L); row = launcherBar.addRow(new BadgeCard("", "Popular\nMovies", R.drawable.icon_recommend, 0xFFFFFFFF,0xFFC01F1F,null)); rows.put(POPULAR_MOVIES_ROW, row); timestamps.put(POPULAR_MOVIES_ROW, 0L); row = launcherBar.addRow(new BadgeCard("", "Popular\nSeries", R.drawable.icon_recommend, 0xFFFFFFFF,0xFF4F4FB0,null)); rows.put(POPULAR_SERIES_ROW, row); timestamps.put(POPULAR_SERIES_ROW, 0L); for (ApkRepo.App app : ApkRepo.getPlatformApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, 0L); } for (ApkRepo.App app : ApkRepo.getNonPlatformVideoApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, 0L); } for (ApkRepo.App app : ApkRepo.getAudioApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, System.currentTimeMillis()); } for (ApkRepo.App app : ApkRepo.getGamingApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, System.currentTimeMillis()); } row = launcherBar.addRow(new BadgeCard("", "Other\nApps", R.drawable.icon_apps, 0xFFFFFFFF,0xFF2CAAEE,null)); rows.put(OTHER_APPS_ROW, row); timestamps.put(OTHER_APPS_ROW, System.currentTimeMillis()); { List<ApkRepo.App> apps = new ArrayList<>(ApkRepo.getPlatformApps()); apps.addAll(ApkRepo.getNonPlatformVideoApps()); apps.addAll(ApkRepo.getAudioApps()); apps.addAll(ApkRepo.getGamingApps()); for (ApkRepo.App app : ApkRepo.getApps(null, apps)) { launcherBar.addItem(row, new BadgeCard(app.name, app.badge != null ? app.badge : app.icon, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); } } row = launcherBar.addRow( new BadgeCard("Settings", ApkRepo.getActionBadge(Settings.ACTION_SETTINGS), new Card.Callback() { @Override public boolean onClicked(Card card) { startActivity(new Intent(Settings.ACTION_SETTINGS)); return false; } @Override public void onHovered(Card card, boolean hovered) {} }) ); rows.put(SETTINGS_ROW, row); launcherBar.addItems(row, widgetBar.getAllWidgetCards()); timestamps.put(SETTINGS_ROW, System.currentTimeMillis()); //clockInterval = new Utils.Interval(() -> launcherBar.post(() -> updateClock()), 1000); } private void updateRows() { long timeNow = System.currentTimeMillis(); int row; if (MovieRepo.getWatchNextTimestamp() > timestamps.get(RESUME_ROW)) { row = rows.get(RESUME_ROW); timestamps.put(RESUME_ROW, timeNow); launcherBar.clearRow(row); long dayNow = timeNow/1000/3600/24; for (MovieTitle movie : MovieRepo.getWatchNext()) { if ((dayNow - movie.system.lastWatched/1000/3600/24) < 30 && movie.system.state != MovieTitle.System.State.WATCHED) { launcherBar.addItem(row, new MovieCard(movie)); } } } if (MovieRepo.getRecommendedTimestamp() > timestamps.get(POPULAR_MOVIES_ROW)) { row = rows.get(POPULAR_MOVIES_ROW); timestamps.put(POPULAR_MOVIES_ROW, timeNow); launcherBar.clearRow(row);
for (MovieTitle movie : MovieRepo.getRecommended(JustWatch.Type.MOVIE)) {
2
2023-12-28 18:24:12+00:00
24k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/controller/ClickController.java
[ { "identifier": "Main", "path": "CS109_2022_Fall/Chess/Main.java", "snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素...
import Chess.Main; import Chess.chessComponent.SquareComponent; import Chess.model.ChessColor; import Chess.view.ChessGameFrame; import Chess.view.Chessboard; import javax.swing.*;
17,607
package Chess.controller; public class ClickController { private final Chessboard chessboard; private SquareComponent first; public ClickController(Chessboard chessboard) { this.chessboard = chessboard; } private int count = 0; public void onClick(SquareComponent squareComponent) { Main.playNotifyMusic("click"); //判断第一次点击 if (first == null) { if (handleFirst(squareComponent)) { squareComponent.setSelected(true); first = squareComponent; first.repaint();//还没有实现显示可以当前棋子可以移动的坐标 } } else { if (first == squareComponent) { // 再次点击取消选取 squareComponent.setSelected(false); SquareComponent recordFirst = first; first = null; recordFirst.repaint(); } else if (handleSecond(squareComponent)) { //repaint in swap chess method. chessboard.swapChessComponents(first, squareComponent); chessboard.clickController.swapPlayer(); first.setSelected(false); first = null; } } } /** * @param squareComponent 目标选取的棋子 * @return 目标选取的棋子是否与棋盘记录的当前行棋方颜色相同 */ private boolean handleFirst(SquareComponent squareComponent) { if (!squareComponent.isReversal()) { squareComponent.setReversal(true); squareComponent.setCheating(false); System.out.printf("onClick to reverse a chess [%d,%d]\n", squareComponent.getChessboardPoint().getX(), squareComponent.getChessboardPoint().getY()); chessboard.isPlayerDo = true; Chessboard.isComReverse = true; Chessboard.Now.push(squareComponent); squareComponent.repaint(); if (count == 0) { count++; chessboard.setCurrentColor(squareComponent.getChessColor()); chessboard.setPlayerColor(squareComponent.getChessColor());
package Chess.controller; public class ClickController { private final Chessboard chessboard; private SquareComponent first; public ClickController(Chessboard chessboard) { this.chessboard = chessboard; } private int count = 0; public void onClick(SquareComponent squareComponent) { Main.playNotifyMusic("click"); //判断第一次点击 if (first == null) { if (handleFirst(squareComponent)) { squareComponent.setSelected(true); first = squareComponent; first.repaint();//还没有实现显示可以当前棋子可以移动的坐标 } } else { if (first == squareComponent) { // 再次点击取消选取 squareComponent.setSelected(false); SquareComponent recordFirst = first; first = null; recordFirst.repaint(); } else if (handleSecond(squareComponent)) { //repaint in swap chess method. chessboard.swapChessComponents(first, squareComponent); chessboard.clickController.swapPlayer(); first.setSelected(false); first = null; } } } /** * @param squareComponent 目标选取的棋子 * @return 目标选取的棋子是否与棋盘记录的当前行棋方颜色相同 */ private boolean handleFirst(SquareComponent squareComponent) { if (!squareComponent.isReversal()) { squareComponent.setReversal(true); squareComponent.setCheating(false); System.out.printf("onClick to reverse a chess [%d,%d]\n", squareComponent.getChessboardPoint().getX(), squareComponent.getChessboardPoint().getY()); chessboard.isPlayerDo = true; Chessboard.isComReverse = true; Chessboard.Now.push(squareComponent); squareComponent.repaint(); if (count == 0) { count++; chessboard.setCurrentColor(squareComponent.getChessColor()); chessboard.setPlayerColor(squareComponent.getChessColor());
if (squareComponent.getChessColor() == ChessColor.BLACK) {
2
2023-12-31 05:50:13+00:00
24k
psobiech/opengr8on
lib/src/main/java/pl/psobiech/opengr8on/client/CLUClient.java
[ { "identifier": "LuaScriptCommand", "path": "lib/src/main/java/pl/psobiech/opengr8on/client/commands/LuaScriptCommand.java", "snippet": "public class LuaScriptCommand {\n public static final String CHECK_ALIVE = \"checkAlive()\";\n\n private static final int IP_ADDRESS_PART = 1;\n\n private sta...
import java.io.Closeable; import java.io.IOException; import java.net.Inet4Address; import java.nio.file.Path; import java.time.Duration; import java.util.Objects; import java.util.Optional; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.psobiech.opengr8on.client.commands.LuaScriptCommand; import pl.psobiech.opengr8on.client.commands.ResetCommand; import pl.psobiech.opengr8on.client.commands.ResetCommand.Response; import pl.psobiech.opengr8on.client.commands.SetIpCommand; import pl.psobiech.opengr8on.client.commands.SetKeyCommand; import pl.psobiech.opengr8on.client.commands.StartTFTPdCommand; import pl.psobiech.opengr8on.client.device.CLUDevice; import pl.psobiech.opengr8on.client.device.CipherTypeEnum; import pl.psobiech.opengr8on.exceptions.UnexpectedException; import pl.psobiech.opengr8on.tftp.TFTPClient; import pl.psobiech.opengr8on.tftp.TFTPTransferMode; import pl.psobiech.opengr8on.tftp.exceptions.TFTPPacketException; import pl.psobiech.opengr8on.tftp.packets.TFTPErrorType; import pl.psobiech.opengr8on.util.FileUtil; import pl.psobiech.opengr8on.util.HexUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.RandomUtil; import pl.psobiech.opengr8on.util.SocketUtil; import pl.psobiech.opengr8on.util.SocketUtil.Payload; import pl.psobiech.opengr8on.util.Util;
17,479
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class CLUClient extends Client implements Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(CLUClient.class); private static final Duration DEFAULT_TIMEOUT_DURATION = Duration.ofMillis(SocketUtil.DEFAULT_TIMEOUT); private final CLUDevice cluDevice; private final TFTPClient tftpClient; private CipherKey cipherKey; public CLUClient(Inet4Address localAddress, CLUDevice cluDevice) { this(localAddress, cluDevice, cluDevice.getCipherKey()); } public CLUClient(Inet4Address localAddress, Inet4Address ipAddress, CipherKey cipherKey) { this(localAddress, ipAddress, cipherKey, COMMAND_PORT); } public CLUClient(Inet4Address localAddress, Inet4Address ipAddress, CipherKey cipherKey, int port) { this( localAddress, new CLUDevice(ipAddress, CipherTypeEnum.PROJECT), cipherKey, IPv4AddressUtil.BROADCAST_ADDRESS, port ); } public CLUClient(Inet4Address localAddress, CLUDevice cluDevice, CipherKey cipherKey) { this(localAddress, cluDevice, cipherKey, IPv4AddressUtil.BROADCAST_ADDRESS, COMMAND_PORT); } public CLUClient(Inet4Address localAddress, CLUDevice cluDevice, CipherKey cipherKey, Inet4Address broadcastAddress, int port) { super(localAddress, broadcastAddress, port); this.cluDevice = cluDevice; this.cipherKey = cipherKey; this.tftpClient = new TFTPClient(SocketUtil.udpRandomPort(localAddress)); tftpClient.open(); } public Inet4Address getAddress() { return getCluDevice().getAddress(); } public Optional<Inet4Address> setAddress(Inet4Address newAddress, Inet4Address gatewayAddress) { final SetIpCommand.Request command = SetIpCommand.request(cluDevice.getSerialNumber(), newAddress, gatewayAddress); return request(command, DEFAULT_TIMEOUT_DURATION) .flatMap(payload -> { final Optional<SetIpCommand.Response> responseOptional = SetIpCommand.responseFromByteArray(payload.buffer()); if (responseOptional.isEmpty()) { return Optional.empty(); } final SetIpCommand.Response response = responseOptional.get(); final Inet4Address ipAddress = response.getIpAddress(); cluDevice.setAddress(ipAddress); return Optional.of(ipAddress); }); } public CipherKey getCipherKey() { return cipherKey; } public Optional<Boolean> updateCipherKey(CipherKey newCipherKey) { final byte[] randomBytes = RandomUtil.bytes(Command.RANDOM_SIZE); return request( newCipherKey,
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class CLUClient extends Client implements Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(CLUClient.class); private static final Duration DEFAULT_TIMEOUT_DURATION = Duration.ofMillis(SocketUtil.DEFAULT_TIMEOUT); private final CLUDevice cluDevice; private final TFTPClient tftpClient; private CipherKey cipherKey; public CLUClient(Inet4Address localAddress, CLUDevice cluDevice) { this(localAddress, cluDevice, cluDevice.getCipherKey()); } public CLUClient(Inet4Address localAddress, Inet4Address ipAddress, CipherKey cipherKey) { this(localAddress, ipAddress, cipherKey, COMMAND_PORT); } public CLUClient(Inet4Address localAddress, Inet4Address ipAddress, CipherKey cipherKey, int port) { this( localAddress, new CLUDevice(ipAddress, CipherTypeEnum.PROJECT), cipherKey, IPv4AddressUtil.BROADCAST_ADDRESS, port ); } public CLUClient(Inet4Address localAddress, CLUDevice cluDevice, CipherKey cipherKey) { this(localAddress, cluDevice, cipherKey, IPv4AddressUtil.BROADCAST_ADDRESS, COMMAND_PORT); } public CLUClient(Inet4Address localAddress, CLUDevice cluDevice, CipherKey cipherKey, Inet4Address broadcastAddress, int port) { super(localAddress, broadcastAddress, port); this.cluDevice = cluDevice; this.cipherKey = cipherKey; this.tftpClient = new TFTPClient(SocketUtil.udpRandomPort(localAddress)); tftpClient.open(); } public Inet4Address getAddress() { return getCluDevice().getAddress(); } public Optional<Inet4Address> setAddress(Inet4Address newAddress, Inet4Address gatewayAddress) { final SetIpCommand.Request command = SetIpCommand.request(cluDevice.getSerialNumber(), newAddress, gatewayAddress); return request(command, DEFAULT_TIMEOUT_DURATION) .flatMap(payload -> { final Optional<SetIpCommand.Response> responseOptional = SetIpCommand.responseFromByteArray(payload.buffer()); if (responseOptional.isEmpty()) { return Optional.empty(); } final SetIpCommand.Response response = responseOptional.get(); final Inet4Address ipAddress = response.getIpAddress(); cluDevice.setAddress(ipAddress); return Optional.of(ipAddress); }); } public CipherKey getCipherKey() { return cipherKey; } public Optional<Boolean> updateCipherKey(CipherKey newCipherKey) { final byte[] randomBytes = RandomUtil.bytes(Command.RANDOM_SIZE); return request( newCipherKey,
SetKeyCommand.request(
4
2023-12-23 09:56:14+00:00
24k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/source/org/jfree/chart/title/TextTitle.java
[ { "identifier": "BlockResult", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/block/BlockResult.java", "snippet": "public class BlockResult implements EntityBlockResult {\r\n\r\n /** The entities from the block. */\r\n private EntityCollection entities;\r\n\r\n /**\r\n * Creates a ne...
import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.block.BlockResult; import org.jfree.chart.block.EntityBlockParams; import org.jfree.chart.block.LengthConstraintType; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.entity.ChartEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.StandardEntityCollection; import org.jfree.chart.entity.TitleEntity; import org.jfree.chart.event.TitleChangeEvent; import org.jfree.chart.util.ParamChecks; import org.jfree.data.Range; import org.jfree.io.SerialUtilities; import org.jfree.text.G2TextMeasurer; import org.jfree.text.TextBlock; import org.jfree.text.TextBlockAnchor; import org.jfree.text.TextUtilities; import org.jfree.ui.HorizontalAlignment; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RectangleInsets; import org.jfree.ui.Size2D; import org.jfree.ui.VerticalAlignment; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable;
15,065
if (this.expandToFitSpace) { return new Size2D(contentSize.getHeight(), maxWidth); } else { return new Size2D(contentSize.height, contentSize.width); } } else { throw new RuntimeException("Unrecognised exception."); } } /** * Arranges the content for this title assuming a range constraint for the * width and no bounds on the height, and returns the required size. This * will reflect the fact that a text title positioned on the left or right * of a chart will be rotated by 90 degrees. * * @param g2 the graphics target. * @param widthRange the range for the width. * * @return The content size. * * @since 1.0.9 */ protected Size2D arrangeRN(Graphics2D g2, Range widthRange) { Size2D s = arrangeNN(g2); if (widthRange.contains(s.getWidth())) { return s; } double ww = widthRange.constrain(s.getWidth()); return arrangeFN(g2, ww); } /** * Returns the content size for the title. This will reflect the fact that * a text title positioned on the left or right of a chart will be rotated * 90 degrees. * * @param g2 the graphics device. * @param widthRange the width range. * @param heightRange the height range. * * @return The content size. */ protected Size2D arrangeRR(Graphics2D g2, Range widthRange, Range heightRange) { RectangleEdge position = getPosition(); if (position == RectangleEdge.TOP || position == RectangleEdge.BOTTOM) { float maxWidth = (float) widthRange.getUpperBound(); g2.setFont(this.font); this.content = TextUtilities.createTextBlock(this.text, this.font, this.paint, maxWidth, this.maximumLinesToDisplay, new G2TextMeasurer(g2)); this.content.setLineAlignment(this.textAlignment); Size2D contentSize = this.content.calculateDimensions(g2); if (this.expandToFitSpace) { return new Size2D(maxWidth, contentSize.getHeight()); } else { return contentSize; } } else if (position == RectangleEdge.LEFT || position == RectangleEdge.RIGHT) { float maxWidth = (float) heightRange.getUpperBound(); g2.setFont(this.font); this.content = TextUtilities.createTextBlock(this.text, this.font, this.paint, maxWidth, this.maximumLinesToDisplay, new G2TextMeasurer(g2)); this.content.setLineAlignment(this.textAlignment); Size2D contentSize = this.content.calculateDimensions(g2); // transpose the dimensions, because the title is rotated if (this.expandToFitSpace) { return new Size2D(contentSize.getHeight(), maxWidth); } else { return new Size2D(contentSize.height, contentSize.width); } } else { throw new RuntimeException("Unrecognised exception."); } } /** * Draws the title on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param area the area allocated for the title. */ @Override public void draw(Graphics2D g2, Rectangle2D area) { draw(g2, area, null); } /** * Draws the block within the specified area. * * @param g2 the graphics device. * @param area the area. * @param params if this is an instance of {@link EntityBlockParams} it * is used to determine whether or not an * {@link EntityCollection} is returned by this method. * * @return An {@link EntityCollection} containing a chart entity for the * title, or <code>null</code>. */ @Override public Object draw(Graphics2D g2, Rectangle2D area, Object params) { if (this.content == null) { return null; } area = trimMargin(area); drawBorder(g2, area); if (this.text.equals("")) { return null; }
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------- * TextTitle.java * -------------- * (C) Copyright 2000-2013, by David Berry and Contributors. * * Original Author: David Berry; * Contributor(s): David Gilbert (for Object Refinery Limited); * Nicolas Brodu; * Peter Kolb - patch 2603321; * * Changes (from 18-Sep-2001) * -------------------------- * 18-Sep-2001 : Added standard header (DG); * 07-Nov-2001 : Separated the JCommon Class Library classes, JFreeChart now * requires jcommon.jar (DG); * 09-Jan-2002 : Updated Javadoc comments (DG); * 07-Feb-2002 : Changed Insets --> Spacer in AbstractTitle.java (DG); * 06-Mar-2002 : Updated import statements (DG); * 25-Jun-2002 : Removed redundant imports (DG); * 18-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 28-Oct-2002 : Small modifications while changing JFreeChart class (DG); * 13-Mar-2003 : Changed width used for relative spacing to fix bug 703050 (DG); * 26-Mar-2003 : Implemented Serializable (DG); * 15-Jul-2003 : Fixed null pointer exception (DG); * 11-Sep-2003 : Implemented Cloneable (NB) * 22-Sep-2003 : Added checks for null values and throw nullpointer * exceptions (TM); * Background paint was not serialized. * 07-Oct-2003 : Added fix for exception caused by empty string in title (DG); * 29-Oct-2003 : Added workaround for text alignment in PDF output (DG); * 03-Feb-2004 : Fixed bug in getPreferredWidth() method (DG); * 17-Feb-2004 : Added clone() method and fixed bug in equals() method (DG); * 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D * because of JDK bug 4976448 which persists on JDK 1.3.1. Also * fixed bug in getPreferredHeight() method (DG); * 29-Apr-2004 : Fixed bug in getPreferredWidth() method - see bug id * 944173 (DG); * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 * release (DG); * 08-Feb-2005 : Updated for changes in RectangleConstraint class (DG); * 11-Feb-2005 : Implemented PublicCloneable (DG); * 20-Apr-2005 : Added support for tooltips (DG); * 26-Apr-2005 : Removed LOGGER (DG); * 06-Jun-2005 : Modified equals() to handle GradientPaint (DG); * 06-Jul-2005 : Added flag to control whether or not the title expands to * fit the available space (DG); * 07-Oct-2005 : Added textAlignment attribute (DG); * ------------- JFREECHART 1.0.x RELEASED ------------------------------------ * 13-Dec-2005 : Fixed bug 1379331 - incorrect drawing with LEFT or RIGHT * title placement (DG); * 19-Dec-2007 : Implemented some of the missing arrangement options (DG); * 28-Apr-2008 : Added option for maximum lines, and fixed minor bugs in * equals() method (DG); * 19-Mar-2009 : Changed ChartEntity to TitleEntity - see patch 2603321 by * Peter Kolb (DG); * 03-Jul-2013 : Use ParamChecks (DG); * */ package org.jfree.chart.title; /** * A chart title that displays a text string with automatic wrapping as * required. */ public class TextTitle extends Title implements Serializable, Cloneable, PublicCloneable { /** For serialization. */ private static final long serialVersionUID = 8372008692127477443L; /** The default font. */ public static final Font DEFAULT_FONT = new Font("SansSerif", Font.BOLD, 12); /** The default text color. */ public static final Paint DEFAULT_TEXT_PAINT = Color.black; /** The title text. */ private String text; /** The font used to display the title. */ private Font font; /** The text alignment. */ private HorizontalAlignment textAlignment; /** The paint used to display the title text. */ private transient Paint paint; /** The background paint. */ private transient Paint backgroundPaint; /** The tool tip text (can be <code>null</code>). */ private String toolTipText; /** The URL text (can be <code>null</code>). */ private String urlText; /** The content. */ private TextBlock content; /** * A flag that controls whether the title expands to fit the available * space.. */ private boolean expandToFitSpace = false; /** * The maximum number of lines to display. * * @since 1.0.10 */ private int maximumLinesToDisplay = Integer.MAX_VALUE; /** * Creates a new title, using default attributes where necessary. */ public TextTitle() { this(""); } /** * Creates a new title, using default attributes where necessary. * * @param text the title text (<code>null</code> not permitted). */ public TextTitle(String text) { this(text, TextTitle.DEFAULT_FONT, TextTitle.DEFAULT_TEXT_PAINT, Title.DEFAULT_POSITION, Title.DEFAULT_HORIZONTAL_ALIGNMENT, Title.DEFAULT_VERTICAL_ALIGNMENT, Title.DEFAULT_PADDING); } /** * Creates a new title, using default attributes where necessary. * * @param text the title text (<code>null</code> not permitted). * @param font the title font (<code>null</code> not permitted). */ public TextTitle(String text, Font font) { this(text, font, TextTitle.DEFAULT_TEXT_PAINT, Title.DEFAULT_POSITION, Title.DEFAULT_HORIZONTAL_ALIGNMENT, Title.DEFAULT_VERTICAL_ALIGNMENT, Title.DEFAULT_PADDING); } /** * Creates a new title. * * @param text the text for the title (<code>null</code> not permitted). * @param font the title font (<code>null</code> not permitted). * @param paint the title paint (<code>null</code> not permitted). * @param position the title position (<code>null</code> not permitted). * @param horizontalAlignment the horizontal alignment (<code>null</code> * not permitted). * @param verticalAlignment the vertical alignment (<code>null</code> not * permitted). * @param padding the space to leave around the outside of the title. */ public TextTitle(String text, Font font, Paint paint, RectangleEdge position, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, RectangleInsets padding) { super(position, horizontalAlignment, verticalAlignment, padding); if (text == null) { throw new NullPointerException("Null 'text' argument."); } if (font == null) { throw new NullPointerException("Null 'font' argument."); } if (paint == null) { throw new NullPointerException("Null 'paint' argument."); } this.text = text; this.font = font; this.paint = paint; // the textAlignment and the horizontalAlignment are separate things, // but it makes sense for the default textAlignment to match the // title's horizontal alignment... this.textAlignment = horizontalAlignment; this.backgroundPaint = null; this.content = null; this.toolTipText = null; this.urlText = null; } /** * Returns the title text. * * @return The text (never <code>null</code>). * * @see #setText(String) */ public String getText() { return this.text; } /** * Sets the title to the specified text and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param text the text (<code>null</code> not permitted). */ public void setText(String text) { ParamChecks.nullNotPermitted(text, "text"); if (!this.text.equals(text)) { this.text = text; notifyListeners(new TitleChangeEvent(this)); } } /** * Returns the text alignment. This controls how the text is aligned * within the title's bounds, whereas the title's horizontal alignment * controls how the title's bounding rectangle is aligned within the * drawing space. * * @return The text alignment. */ public HorizontalAlignment getTextAlignment() { return this.textAlignment; } /** * Sets the text alignment and sends a {@link TitleChangeEvent} to * all registered listeners. * * @param alignment the alignment (<code>null</code> not permitted). */ public void setTextAlignment(HorizontalAlignment alignment) { ParamChecks.nullNotPermitted(alignment, "alignment"); this.textAlignment = alignment; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the font used to display the title string. * * @return The font (never <code>null</code>). * * @see #setFont(Font) */ public Font getFont() { return this.font; } /** * Sets the font used to display the title string. Registered listeners * are notified that the title has been modified. * * @param font the new font (<code>null</code> not permitted). * * @see #getFont() */ public void setFont(Font font) { ParamChecks.nullNotPermitted(font, "font"); if (!this.font.equals(font)) { this.font = font; notifyListeners(new TitleChangeEvent(this)); } } /** * Returns the paint used to display the title string. * * @return The paint (never <code>null</code>). * * @see #setPaint(Paint) */ public Paint getPaint() { return this.paint; } /** * Sets the paint used to display the title string. Registered listeners * are notified that the title has been modified. * * @param paint the new paint (<code>null</code> not permitted). * * @see #getPaint() */ public void setPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); if (!this.paint.equals(paint)) { this.paint = paint; notifyListeners(new TitleChangeEvent(this)); } } /** * Returns the background paint. * * @return The paint (possibly <code>null</code>). */ public Paint getBackgroundPaint() { return this.backgroundPaint; } /** * Sets the background paint and sends a {@link TitleChangeEvent} to all * registered listeners. If you set this attribute to <code>null</code>, * no background is painted (which makes the title background transparent). * * @param paint the background paint (<code>null</code> permitted). */ public void setBackgroundPaint(Paint paint) { this.backgroundPaint = paint; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the tool tip text. * * @return The tool tip text (possibly <code>null</code>). */ public String getToolTipText() { return this.toolTipText; } /** * Sets the tool tip text to the specified text and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param text the text (<code>null</code> permitted). */ public void setToolTipText(String text) { this.toolTipText = text; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the URL text. * * @return The URL text (possibly <code>null</code>). */ public String getURLText() { return this.urlText; } /** * Sets the URL text to the specified text and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param text the text (<code>null</code> permitted). */ public void setURLText(String text) { this.urlText = text; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the flag that controls whether or not the title expands to fit * the available space. * * @return The flag. */ public boolean getExpandToFitSpace() { return this.expandToFitSpace; } /** * Sets the flag that controls whether the title expands to fit the * available space, and sends a {@link TitleChangeEvent} to all registered * listeners. * * @param expand the flag. */ public void setExpandToFitSpace(boolean expand) { this.expandToFitSpace = expand; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the maximum number of lines to display. * * @return The maximum. * * @since 1.0.10 * * @see #setMaximumLinesToDisplay(int) */ public int getMaximumLinesToDisplay() { return this.maximumLinesToDisplay; } /** * Sets the maximum number of lines to display and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param max the maximum. * * @since 1.0.10. * * @see #getMaximumLinesToDisplay() */ public void setMaximumLinesToDisplay(int max) { this.maximumLinesToDisplay = max; notifyListeners(new TitleChangeEvent(this)); } /** * Arranges the contents of the block, within the given constraints, and * returns the block size. * * @param g2 the graphics device. * @param constraint the constraint (<code>null</code> not permitted). * * @return The block size (in Java2D units, never <code>null</code>). */ @Override public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) { RectangleConstraint cc = toContentConstraint(constraint); LengthConstraintType w = cc.getWidthConstraintType(); LengthConstraintType h = cc.getHeightConstraintType(); Size2D contentSize = null; if (w == LengthConstraintType.NONE) { if (h == LengthConstraintType.NONE) { contentSize = arrangeNN(g2); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } else if (w == LengthConstraintType.RANGE) { if (h == LengthConstraintType.NONE) { contentSize = arrangeRN(g2, cc.getWidthRange()); } else if (h == LengthConstraintType.RANGE) { contentSize = arrangeRR(g2, cc.getWidthRange(), cc.getHeightRange()); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } else if (w == LengthConstraintType.FIXED) { if (h == LengthConstraintType.NONE) { contentSize = arrangeFN(g2, cc.getWidth()); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } assert contentSize != null; // suppress compiler warning return new Size2D(calculateTotalWidth(contentSize.getWidth()), calculateTotalHeight(contentSize.getHeight())); } /** * Arranges the content for this title assuming no bounds on the width * or the height, and returns the required size. This will reflect the * fact that a text title positioned on the left or right of a chart will * be rotated by 90 degrees. * * @param g2 the graphics target. * * @return The content size. * * @since 1.0.9 */ protected Size2D arrangeNN(Graphics2D g2) { Range max = new Range(0.0, Float.MAX_VALUE); return arrangeRR(g2, max, max); } /** * Arranges the content for this title assuming a fixed width and no bounds * on the height, and returns the required size. This will reflect the * fact that a text title positioned on the left or right of a chart will * be rotated by 90 degrees. * * @param g2 the graphics target. * @param w the width. * * @return The content size. * * @since 1.0.9 */ protected Size2D arrangeFN(Graphics2D g2, double w) { RectangleEdge position = getPosition(); if (position == RectangleEdge.TOP || position == RectangleEdge.BOTTOM) { float maxWidth = (float) w; g2.setFont(this.font); this.content = TextUtilities.createTextBlock(this.text, this.font, this.paint, maxWidth, this.maximumLinesToDisplay, new G2TextMeasurer(g2)); this.content.setLineAlignment(this.textAlignment); Size2D contentSize = this.content.calculateDimensions(g2); if (this.expandToFitSpace) { return new Size2D(maxWidth, contentSize.getHeight()); } else { return contentSize; } } else if (position == RectangleEdge.LEFT || position == RectangleEdge.RIGHT) { float maxWidth = Float.MAX_VALUE; g2.setFont(this.font); this.content = TextUtilities.createTextBlock(this.text, this.font, this.paint, maxWidth, this.maximumLinesToDisplay, new G2TextMeasurer(g2)); this.content.setLineAlignment(this.textAlignment); Size2D contentSize = this.content.calculateDimensions(g2); // transpose the dimensions, because the title is rotated if (this.expandToFitSpace) { return new Size2D(contentSize.getHeight(), maxWidth); } else { return new Size2D(contentSize.height, contentSize.width); } } else { throw new RuntimeException("Unrecognised exception."); } } /** * Arranges the content for this title assuming a range constraint for the * width and no bounds on the height, and returns the required size. This * will reflect the fact that a text title positioned on the left or right * of a chart will be rotated by 90 degrees. * * @param g2 the graphics target. * @param widthRange the range for the width. * * @return The content size. * * @since 1.0.9 */ protected Size2D arrangeRN(Graphics2D g2, Range widthRange) { Size2D s = arrangeNN(g2); if (widthRange.contains(s.getWidth())) { return s; } double ww = widthRange.constrain(s.getWidth()); return arrangeFN(g2, ww); } /** * Returns the content size for the title. This will reflect the fact that * a text title positioned on the left or right of a chart will be rotated * 90 degrees. * * @param g2 the graphics device. * @param widthRange the width range. * @param heightRange the height range. * * @return The content size. */ protected Size2D arrangeRR(Graphics2D g2, Range widthRange, Range heightRange) { RectangleEdge position = getPosition(); if (position == RectangleEdge.TOP || position == RectangleEdge.BOTTOM) { float maxWidth = (float) widthRange.getUpperBound(); g2.setFont(this.font); this.content = TextUtilities.createTextBlock(this.text, this.font, this.paint, maxWidth, this.maximumLinesToDisplay, new G2TextMeasurer(g2)); this.content.setLineAlignment(this.textAlignment); Size2D contentSize = this.content.calculateDimensions(g2); if (this.expandToFitSpace) { return new Size2D(maxWidth, contentSize.getHeight()); } else { return contentSize; } } else if (position == RectangleEdge.LEFT || position == RectangleEdge.RIGHT) { float maxWidth = (float) heightRange.getUpperBound(); g2.setFont(this.font); this.content = TextUtilities.createTextBlock(this.text, this.font, this.paint, maxWidth, this.maximumLinesToDisplay, new G2TextMeasurer(g2)); this.content.setLineAlignment(this.textAlignment); Size2D contentSize = this.content.calculateDimensions(g2); // transpose the dimensions, because the title is rotated if (this.expandToFitSpace) { return new Size2D(contentSize.getHeight(), maxWidth); } else { return new Size2D(contentSize.height, contentSize.width); } } else { throw new RuntimeException("Unrecognised exception."); } } /** * Draws the title on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param area the area allocated for the title. */ @Override public void draw(Graphics2D g2, Rectangle2D area) { draw(g2, area, null); } /** * Draws the block within the specified area. * * @param g2 the graphics device. * @param area the area. * @param params if this is an instance of {@link EntityBlockParams} it * is used to determine whether or not an * {@link EntityCollection} is returned by this method. * * @return An {@link EntityCollection} containing a chart entity for the * title, or <code>null</code>. */ @Override public Object draw(Graphics2D g2, Rectangle2D area, Object params) { if (this.content == null) { return null; } area = trimMargin(area); drawBorder(g2, area); if (this.text.equals("")) { return null; }
ChartEntity entity = null;
4
2023-12-24 12:36:47+00:00
24k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/module/impl/skills/Fishing.java
[ { "identifier": "MayOBeesConfig", "path": "src/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java", "snippet": "public class MayOBeesConfig extends Config {\n\n //<editor-fold desc=\"COMBAT\">\n @KeyBind(\n name = \"Shortbow Aura\",\n description = \"Automatica...
import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.event.SpawnParticleEvent; import com.github.may2beez.mayobees.handler.RotationHandler; import com.github.may2beez.mayobees.module.IModule; import com.github.may2beez.mayobees.module.IModuleActive; import com.github.may2beez.mayobees.module.impl.combat.MobKiller; import com.github.may2beez.mayobees.util.*; import com.github.may2beez.mayobees.util.helper.Clock; import com.github.may2beez.mayobees.util.helper.Rotation; import com.github.may2beez.mayobees.util.helper.RotationConfiguration; import com.github.may2beez.mayobees.util.helper.Timer; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.projectile.EntityFishHook; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.util.List; import java.util.Random; import java.util.concurrent.CopyOnWriteArrayList;
14,916
package com.github.may2beez.mayobees.module.impl.skills; public class Fishing implements IModuleActive { private static Fishing instance; public static Fishing getInstance() { if (instance == null) { instance = new Fishing(); } return instance; } @Override public String getName() { return "Fishing"; } private final Minecraft mc = Minecraft.getMinecraft(); private static final List<String> fishingMobs = JsonUtils.getListFromUrl("https://raw.githubusercontent.com/May2Beez/May2BeezQoL/master/sea_creatures_list.json", "mobs"); private final Timer throwTimer = new Timer(); private final Timer inWaterTimer = new Timer(); private final Clock attackDelay = new Clock(); private final Timer antiAfkTimer = new Timer(); private double oldBobberPosY = 0.0D; private Rotation startRotation = null; private static final CopyOnWriteArrayList<ParticleEntry> particles = new CopyOnWriteArrayList<>(); private int rodSlot = 0; @Override public boolean isRunning() { return MayOBeesConfig.fishing; } private enum AutoFishState { THROWING, IN_WATER, FISH_BITE } private enum AntiAfkState { AWAY, BACK } private AntiAfkState antiAfkState = AntiAfkState.AWAY; private AutoFishState currentState = AutoFishState.THROWING; @Override public void onEnable() { currentState = AutoFishState.THROWING; throwTimer.schedule(); inWaterTimer.schedule(); attackDelay.reset(); antiAfkTimer.schedule(); if (MayOBeesConfig.mouseUngrab) UngrabUtils.ungrabMouse(); oldBobberPosY = 0.0D; particles.clear(); rodSlot = InventoryUtils.getSlotIdOfItemInHotbar("Rod"); if (rodSlot == -1) { LogUtils.error("No rod found in hotbar!"); onDisable(); return; } startRotation = new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch); KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), MayOBeesConfig.sneakWhileFishing);
package com.github.may2beez.mayobees.module.impl.skills; public class Fishing implements IModuleActive { private static Fishing instance; public static Fishing getInstance() { if (instance == null) { instance = new Fishing(); } return instance; } @Override public String getName() { return "Fishing"; } private final Minecraft mc = Minecraft.getMinecraft(); private static final List<String> fishingMobs = JsonUtils.getListFromUrl("https://raw.githubusercontent.com/May2Beez/May2BeezQoL/master/sea_creatures_list.json", "mobs"); private final Timer throwTimer = new Timer(); private final Timer inWaterTimer = new Timer(); private final Clock attackDelay = new Clock(); private final Timer antiAfkTimer = new Timer(); private double oldBobberPosY = 0.0D; private Rotation startRotation = null; private static final CopyOnWriteArrayList<ParticleEntry> particles = new CopyOnWriteArrayList<>(); private int rodSlot = 0; @Override public boolean isRunning() { return MayOBeesConfig.fishing; } private enum AutoFishState { THROWING, IN_WATER, FISH_BITE } private enum AntiAfkState { AWAY, BACK } private AntiAfkState antiAfkState = AntiAfkState.AWAY; private AutoFishState currentState = AutoFishState.THROWING; @Override public void onEnable() { currentState = AutoFishState.THROWING; throwTimer.schedule(); inWaterTimer.schedule(); attackDelay.reset(); antiAfkTimer.schedule(); if (MayOBeesConfig.mouseUngrab) UngrabUtils.ungrabMouse(); oldBobberPosY = 0.0D; particles.clear(); rodSlot = InventoryUtils.getSlotIdOfItemInHotbar("Rod"); if (rodSlot == -1) { LogUtils.error("No rod found in hotbar!"); onDisable(); return; } startRotation = new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch); KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), MayOBeesConfig.sneakWhileFishing);
MobKiller.getInstance().start();
5
2023-12-24 15:39:11+00:00
24k
viceice/verbrauchsapp
app/src/main/java/de/anipe/verbrauchsapp/fragments/CarContentFragment.java
[ { "identifier": "CarInputActivity", "path": "app/src/main/java/de/anipe/verbrauchsapp/CarInputActivity.java", "snippet": "public class CarInputActivity extends AppCompatActivity {\n\n private ConsumptionDataSource dataSource;\n private FileSystemAccessor accessor;\n private long carId;\n pri...
import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.fragment.app.Fragment; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.text.DecimalFormat; import de.anipe.verbrauchsapp.CarInputActivity; import de.anipe.verbrauchsapp.ConsumptionInputActivity; import de.anipe.verbrauchsapp.ConsumptionListActivity; import de.anipe.verbrauchsapp.GDriveStoreActivity; import de.anipe.verbrauchsapp.GraphViewPlot; import de.anipe.verbrauchsapp.ImportActivity; import de.anipe.verbrauchsapp.MainActivity; import de.anipe.verbrauchsapp.PictureImportActivity; import de.anipe.verbrauchsapp.R; import de.anipe.verbrauchsapp.db.ConsumptionDataSource; import de.anipe.verbrauchsapp.io.FileSystemAccessor; import de.anipe.verbrauchsapp.io.XMLHandler; import de.anipe.verbrauchsapp.objects.Car;
17,966
package de.anipe.verbrauchsapp.fragments; /** * */ public class CarContentFragment extends Fragment { private FileSystemAccessor accessor; private ConsumptionDataSource dataSource; private long carId; private View rootView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accessor = FileSystemAccessor.getInstance(); dataSource = ConsumptionDataSource.getInstance(getActivity()); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { carId = getArguments().getLong("carid"); // The last two arguments ensure LayoutParams are inflated properly. rootView = inflater.inflate(R.layout.activity_car_content, container, false); FloatingActionButton btn = rootView.findViewById(R.id.float_add); btn.setOnClickListener(clickListener); return rootView; } @Override public void onResume() { updateView(); super.onResume(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.car_menubar, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_edit_entry: createCarEditActivity(); return true; case R.id.action_add_picture: createAddPictureActivity(); return true; case R.id.action_view_consumptions: createViewConsumptionsActivity(); return true; case R.id.action_view_chart: createConsumptionPlotActivity(); return true; case R.id.action_remove_entry: removeEntry(); return true; case R.id.action_import_data: createImportDataActivity(); return true; case R.id.action_export_data: // exportData(); storeDriveData(); return true; default: return super.onOptionsItemSelected(item); } } // Create an anonymous implementation of OnClickListener private OnClickListener clickListener = v -> { switch (v.getId()) { case R.id.float_add: createAddConsumptionActivity(); break; } }; private void createCarEditActivity() { Intent intent = new Intent(getActivity(), CarInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("update", true); getActivity().startActivity(intent); } private void createAddConsumptionActivity() { Intent intent = new Intent(getActivity(), ConsumptionInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("kmstate", dataSource.getMileageForCar(carId)); getActivity().startActivity(intent); } private void createAddPictureActivity() { Intent intent = new Intent(getActivity(),
package de.anipe.verbrauchsapp.fragments; /** * */ public class CarContentFragment extends Fragment { private FileSystemAccessor accessor; private ConsumptionDataSource dataSource; private long carId; private View rootView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accessor = FileSystemAccessor.getInstance(); dataSource = ConsumptionDataSource.getInstance(getActivity()); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { carId = getArguments().getLong("carid"); // The last two arguments ensure LayoutParams are inflated properly. rootView = inflater.inflate(R.layout.activity_car_content, container, false); FloatingActionButton btn = rootView.findViewById(R.id.float_add); btn.setOnClickListener(clickListener); return rootView; } @Override public void onResume() { updateView(); super.onResume(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.car_menubar, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_edit_entry: createCarEditActivity(); return true; case R.id.action_add_picture: createAddPictureActivity(); return true; case R.id.action_view_consumptions: createViewConsumptionsActivity(); return true; case R.id.action_view_chart: createConsumptionPlotActivity(); return true; case R.id.action_remove_entry: removeEntry(); return true; case R.id.action_import_data: createImportDataActivity(); return true; case R.id.action_export_data: // exportData(); storeDriveData(); return true; default: return super.onOptionsItemSelected(item); } } // Create an anonymous implementation of OnClickListener private OnClickListener clickListener = v -> { switch (v.getId()) { case R.id.float_add: createAddConsumptionActivity(); break; } }; private void createCarEditActivity() { Intent intent = new Intent(getActivity(), CarInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("update", true); getActivity().startActivity(intent); } private void createAddConsumptionActivity() { Intent intent = new Intent(getActivity(), ConsumptionInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("kmstate", dataSource.getMileageForCar(carId)); getActivity().startActivity(intent); } private void createAddPictureActivity() { Intent intent = new Intent(getActivity(),
PictureImportActivity.class);
7
2023-12-28 12:33:52+00:00
24k
strokegmd/StrokeClient
stroke/client/modules/ModuleManager.java
[ { "identifier": "AntiKnockback", "path": "stroke/client/modules/combat/AntiKnockback.java", "snippet": "public class AntiKnockback extends BaseModule {\r\n\tpublic static AntiKnockback instance;\r\n\t\r\n\tpublic AntiKnockback() {\r\n\t\tsuper(\"AntiKnockBack\", \"Disables knockback\", 0x00, ModuleCateg...
import java.util.ArrayList; import java.util.Comparator; import net.minecraft.client.Minecraft; import net.stroke.client.modules.combat.AntiKnockback; import net.stroke.client.modules.combat.AutoArmor; import net.stroke.client.modules.combat.AutoGApple; import net.stroke.client.modules.combat.AutoTotem; import net.stroke.client.modules.combat.Criticals; import net.stroke.client.modules.combat.CrystalAura; import net.stroke.client.modules.combat.KillAura; import net.stroke.client.modules.fun.HalalMode; import net.stroke.client.modules.misc.DiscordRPCModule; import net.stroke.client.modules.misc.MCF; import net.stroke.client.modules.misc.MigrationCape; import net.stroke.client.modules.misc.SelfDestruct; import net.stroke.client.modules.misc.Spammer; import net.stroke.client.modules.misc.StashLogger; import net.stroke.client.modules.movement.AirJump; import net.stroke.client.modules.movement.AutoJump; import net.stroke.client.modules.movement.EntitySpeed; import net.stroke.client.modules.movement.Flight; import net.stroke.client.modules.movement.InventoryMove; import net.stroke.client.modules.movement.NoSlowDown; import net.stroke.client.modules.movement.SafeWalk; import net.stroke.client.modules.movement.Sprint; import net.stroke.client.modules.movement.Step; import net.stroke.client.modules.player.Blink; import net.stroke.client.modules.player.ChestStealer; import net.stroke.client.modules.player.FastPlace; import net.stroke.client.modules.player.Freecam; import net.stroke.client.modules.player.NoFall; import net.stroke.client.modules.player.Portals; import net.stroke.client.modules.player.Timer; import net.stroke.client.modules.render.AntiOverlay; import net.stroke.client.modules.render.BlockHitAnim; import net.stroke.client.modules.render.ClickGui; import net.stroke.client.modules.render.FullBright; import net.stroke.client.modules.render.Hud; import net.stroke.client.modules.render.NameTags; import net.stroke.client.modules.render.NoScoreBoard; import net.stroke.client.modules.render.NoWeather; import net.stroke.client.modules.render.PlayerESP; import net.stroke.client.modules.render.StorageESP; import net.stroke.client.modules.render.TargetHUD; import net.stroke.client.modules.render.Tracers; import net.stroke.client.modules.render.ViewModel; import net.stroke.client.modules.render.Wallhack; import net.stroke.client.modules.render.XRay;
16,494
package net.stroke.client.modules; public class ModuleManager { public static Minecraft mc = Minecraft.getMinecraft(); public static ArrayList<BaseModule> modules = new ArrayList<BaseModule>(); public static void addModule(BaseModule module) { modules.add(module); } public static void sortModules() { modules.sort(Comparator.comparingInt(module -> mc.fontRendererObj.getStringWidth(((BaseModule)module).name)).reversed()); } public static void loadModules() { ModuleManager.addModule(new AntiKnockback()); ModuleManager.addModule(new AutoArmor()); ModuleManager.addModule(new AutoGApple()); ModuleManager.addModule(new AutoTotem()); ModuleManager.addModule(new Criticals()); ModuleManager.addModule(new CrystalAura()); ModuleManager.addModule(new KillAura()); ModuleManager.addModule(new AirJump()); ModuleManager.addModule(new AutoJump()); ModuleManager.addModule(new EntitySpeed()); ModuleManager.addModule(new Flight()); ModuleManager.addModule(new InventoryMove()); ModuleManager.addModule(new NoSlowDown()); ModuleManager.addModule(new SafeWalk()); ModuleManager.addModule(new Sprint()); ModuleManager.addModule(new Step()); ModuleManager.addModule(new Blink()); ModuleManager.addModule(new ChestStealer()); ModuleManager.addModule(new FastPlace()); ModuleManager.addModule(new Freecam()); ModuleManager.addModule(new NoFall()); ModuleManager.addModule(new Portals()); ModuleManager.addModule(new Timer()); ModuleManager.addModule(new AntiOverlay()); ModuleManager.addModule(new BlockHitAnim()); ModuleManager.addModule(new ClickGui()); ModuleManager.addModule(new FullBright()); ModuleManager.addModule(new Hud()); ModuleManager.addModule(new NameTags()); ModuleManager.addModule(new NoScoreBoard()); ModuleManager.addModule(new NoWeather());
package net.stroke.client.modules; public class ModuleManager { public static Minecraft mc = Minecraft.getMinecraft(); public static ArrayList<BaseModule> modules = new ArrayList<BaseModule>(); public static void addModule(BaseModule module) { modules.add(module); } public static void sortModules() { modules.sort(Comparator.comparingInt(module -> mc.fontRendererObj.getStringWidth(((BaseModule)module).name)).reversed()); } public static void loadModules() { ModuleManager.addModule(new AntiKnockback()); ModuleManager.addModule(new AutoArmor()); ModuleManager.addModule(new AutoGApple()); ModuleManager.addModule(new AutoTotem()); ModuleManager.addModule(new Criticals()); ModuleManager.addModule(new CrystalAura()); ModuleManager.addModule(new KillAura()); ModuleManager.addModule(new AirJump()); ModuleManager.addModule(new AutoJump()); ModuleManager.addModule(new EntitySpeed()); ModuleManager.addModule(new Flight()); ModuleManager.addModule(new InventoryMove()); ModuleManager.addModule(new NoSlowDown()); ModuleManager.addModule(new SafeWalk()); ModuleManager.addModule(new Sprint()); ModuleManager.addModule(new Step()); ModuleManager.addModule(new Blink()); ModuleManager.addModule(new ChestStealer()); ModuleManager.addModule(new FastPlace()); ModuleManager.addModule(new Freecam()); ModuleManager.addModule(new NoFall()); ModuleManager.addModule(new Portals()); ModuleManager.addModule(new Timer()); ModuleManager.addModule(new AntiOverlay()); ModuleManager.addModule(new BlockHitAnim()); ModuleManager.addModule(new ClickGui()); ModuleManager.addModule(new FullBright()); ModuleManager.addModule(new Hud()); ModuleManager.addModule(new NameTags()); ModuleManager.addModule(new NoScoreBoard()); ModuleManager.addModule(new NoWeather());
ModuleManager.addModule(new PlayerESP());
38
2023-12-31 10:56:59+00:00
24k
HuXin0817/shop_api
framework/src/main/java/cn/lili/modules/payment/kit/plugin/alipay/AliPayPlugin.java
[ { "identifier": "ThreadContextHolder", "path": "framework/src/main/java/cn/lili/common/context/ThreadContextHolder.java", "snippet": "public class ThreadContextHolder {\n\n public static HttpServletResponse getHttpResponse() {\n ServletRequestAttributes servletRequestAttributes = (ServletReque...
import cn.hutool.core.net.URLDecoder; import cn.hutool.core.net.URLEncoder; import cn.hutool.json.JSONUtil; import cn.lili.common.context.ThreadContextHolder; import cn.lili.common.enums.ResultCode; import cn.lili.common.enums.ResultUtil; import cn.lili.common.exception.ServiceException; import cn.lili.common.properties.ApiProperties; import cn.lili.common.properties.DomainProperties; import cn.lili.common.utils.BeanUtil; import cn.lili.common.utils.SnowFlake; import cn.lili.common.utils.StringUtils; import cn.lili.common.vo.ResultMessage; import cn.lili.modules.payment.entity.RefundLog; import cn.lili.modules.payment.entity.enums.PaymentMethodEnum; import cn.lili.modules.payment.kit.CashierSupport; import cn.lili.modules.payment.kit.Payment; import cn.lili.modules.payment.kit.dto.PayParam; import cn.lili.modules.payment.kit.dto.PaymentSuccessParams; import cn.lili.modules.payment.kit.params.dto.CashierParam; import cn.lili.modules.payment.service.PaymentService; import cn.lili.modules.payment.service.RefundLogService; import cn.lili.modules.system.entity.dos.Setting; import cn.lili.modules.system.entity.dto.payment.AlipayPaymentSetting; import cn.lili.modules.system.entity.enums.SettingEnum; import cn.lili.modules.system.service.SettingService; import cn.lili.modules.wallet.entity.dos.MemberWithdrawApply; import cn.lili.modules.wallet.entity.dto.TransferResultDTO; import com.alibaba.fastjson.JSONObject; import com.alipay.api.AlipayApiException; import com.alipay.api.domain.*; import com.alipay.api.internal.util.AlipaySignature; import com.alipay.api.response.AlipayFundTransUniTransferResponse; import com.alipay.api.response.AlipayTradeRefundResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.nio.charset.StandardCharsets; import java.util.Map;
19,206
package cn.lili.modules.payment.kit.plugin.alipay; /** * 支付宝支付 * * @author Chopper * @since 2020/12/17 09:55 */ @Slf4j @Component public class AliPayPlugin implements Payment { /** * 支付日志 */ @Autowired private PaymentService paymentService; /** * 退款日志 */ @Autowired private RefundLogService refundLogService; /** * 收银台 */ @Autowired private CashierSupport cashierSupport; /** * 设置 */ @Autowired private SettingService settingService; /** * API域名 */ @Autowired private ApiProperties apiProperties; /** * 域名配置 */ @Autowired private DomainProperties domainProperties; @Override public ResultMessage<Object> h5pay(HttpServletRequest request, HttpServletResponse response, PayParam payParam) { CashierParam cashierParam = cashierSupport.cashierParam(payParam); //请求订单编号 String outTradeNo = SnowFlake.getIdStr(); //准备支付参数 AlipayTradeWapPayModel payModel = new AlipayTradeWapPayModel(); payModel.setBody(cashierParam.getTitle()); payModel.setSubject(cashierParam.getDetail()); payModel.setTotalAmount(cashierParam.getPrice() + ""); //回传数据 payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8)); //3分钟超时 payModel.setTimeoutExpress("3m"); payModel.setOutTradeNo(outTradeNo); payModel.setProductCode("QUICK_WAP_PAY"); try { log.info("支付宝H5支付:{}", JSONUtil.toJsonStr(payModel)); AliPayRequest.wapPay(response, payModel, callbackUrl(apiProperties.getBuyer(), PaymentMethodEnum.ALIPAY), notifyUrl(apiProperties.getBuyer(), PaymentMethodEnum.ALIPAY)); } catch (Exception e) { log.error("H5支付异常", e); throw new ServiceException(ResultCode.ALIPAY_EXCEPTION); } return null; } @Override public ResultMessage<Object> jsApiPay(HttpServletRequest request, PayParam payParam) { throw new ServiceException(ResultCode.PAY_NOT_SUPPORT); } @Override public ResultMessage<Object> appPay(HttpServletRequest request, PayParam payParam) { try { CashierParam cashierParam = cashierSupport.cashierParam(payParam); //请求订单编号 String outTradeNo = SnowFlake.getIdStr(); AlipayTradeAppPayModel payModel = new AlipayTradeAppPayModel(); payModel.setBody(cashierParam.getTitle()); payModel.setSubject(cashierParam.getDetail()); payModel.setTotalAmount(cashierParam.getPrice() + ""); //3分钟超时 payModel.setTimeoutExpress("3m"); //回传数据 payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8)); payModel.setOutTradeNo(outTradeNo); payModel.setProductCode("QUICK_MSECURITY_PAY"); log.info("支付宝APP支付:{}", payModel); String orderInfo = AliPayRequest.appPayToResponse(payModel, notifyUrl(apiProperties.getBuyer(), PaymentMethodEnum.ALIPAY)).getBody(); log.info("支付宝APP支付返回内容:{}", orderInfo);
package cn.lili.modules.payment.kit.plugin.alipay; /** * 支付宝支付 * * @author Chopper * @since 2020/12/17 09:55 */ @Slf4j @Component public class AliPayPlugin implements Payment { /** * 支付日志 */ @Autowired private PaymentService paymentService; /** * 退款日志 */ @Autowired private RefundLogService refundLogService; /** * 收银台 */ @Autowired private CashierSupport cashierSupport; /** * 设置 */ @Autowired private SettingService settingService; /** * API域名 */ @Autowired private ApiProperties apiProperties; /** * 域名配置 */ @Autowired private DomainProperties domainProperties; @Override public ResultMessage<Object> h5pay(HttpServletRequest request, HttpServletResponse response, PayParam payParam) { CashierParam cashierParam = cashierSupport.cashierParam(payParam); //请求订单编号 String outTradeNo = SnowFlake.getIdStr(); //准备支付参数 AlipayTradeWapPayModel payModel = new AlipayTradeWapPayModel(); payModel.setBody(cashierParam.getTitle()); payModel.setSubject(cashierParam.getDetail()); payModel.setTotalAmount(cashierParam.getPrice() + ""); //回传数据 payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8)); //3分钟超时 payModel.setTimeoutExpress("3m"); payModel.setOutTradeNo(outTradeNo); payModel.setProductCode("QUICK_WAP_PAY"); try { log.info("支付宝H5支付:{}", JSONUtil.toJsonStr(payModel)); AliPayRequest.wapPay(response, payModel, callbackUrl(apiProperties.getBuyer(), PaymentMethodEnum.ALIPAY), notifyUrl(apiProperties.getBuyer(), PaymentMethodEnum.ALIPAY)); } catch (Exception e) { log.error("H5支付异常", e); throw new ServiceException(ResultCode.ALIPAY_EXCEPTION); } return null; } @Override public ResultMessage<Object> jsApiPay(HttpServletRequest request, PayParam payParam) { throw new ServiceException(ResultCode.PAY_NOT_SUPPORT); } @Override public ResultMessage<Object> appPay(HttpServletRequest request, PayParam payParam) { try { CashierParam cashierParam = cashierSupport.cashierParam(payParam); //请求订单编号 String outTradeNo = SnowFlake.getIdStr(); AlipayTradeAppPayModel payModel = new AlipayTradeAppPayModel(); payModel.setBody(cashierParam.getTitle()); payModel.setSubject(cashierParam.getDetail()); payModel.setTotalAmount(cashierParam.getPrice() + ""); //3分钟超时 payModel.setTimeoutExpress("3m"); //回传数据 payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8)); payModel.setOutTradeNo(outTradeNo); payModel.setProductCode("QUICK_MSECURITY_PAY"); log.info("支付宝APP支付:{}", payModel); String orderInfo = AliPayRequest.appPayToResponse(payModel, notifyUrl(apiProperties.getBuyer(), PaymentMethodEnum.ALIPAY)).getBody(); log.info("支付宝APP支付返回内容:{}", orderInfo);
return ResultUtil.data(orderInfo);
2
2023-12-24 19:45:18+00:00
24k
huidongyin/kafka-2.7.2
clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java
[ { "identifier": "ApiVersions", "path": "clients/src/main/java/org/apache/kafka/clients/ApiVersions.java", "snippet": "public class ApiVersions {\n\n private final Map<String, NodeApiVersions> nodeApiVersions = new HashMap<>();\n private byte maxUsableProduceMagic = RecordBatch.CURRENT_MAGIC_VALUE;...
import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.kafka.clients.ApiVersions; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.common.*; import org.apache.kafka.common.errors.UnsupportedVersionException; import org.apache.kafka.common.header.Header; import org.apache.kafka.common.metrics.Measurable; import org.apache.kafka.common.metrics.MetricConfig; import org.apache.kafka.common.metrics.Metrics; import org.apache.kafka.common.record.*; import org.apache.kafka.common.utils.CopyOnWriteMap; import org.apache.kafka.common.utils.LogContext; import org.apache.kafka.common.utils.ProducerIdAndEpoch; import org.apache.kafka.common.utils.Time; import org.slf4j.Logger;
16,845
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients.producer.internals; /** * This class acts as a queue that accumulates records into {@link MemoryRecords} * instances to be sent to the server. * <p> * The accumulator uses a bounded amount of memory and append calls will block when that memory is exhausted, unless * this behavior is explicitly disabled. */ public final class RecordAccumulator { private final Logger log; //标志位,表示累加器是否已经关闭 private volatile boolean closed; //计数器,用于跟踪正在进行的刷新操作的数量。 private final AtomicInteger flushesInProgress; //计数器,用于跟踪正在进行的追加操作的数量。 private final AtomicInteger appendsInProgress; //记录批次的大小,即每个批次中消息的数量限制。 private final int batchSize; //消息的压缩方式。 private final CompressionType compression; //消息在从消息缓冲区发送出去之前要等待的时间。 private final int lingerMs; //发生重试时的等待时间。 private final long retryBackoffMs; //消息投递的超时时间。 private final int deliveryTimeoutMs; //缓冲池,用于管理可用于内存分配的内存缓冲区。 private final BufferPool free; //用于管理和获取时间戳。 private final Time time; //Kafka支持的API版本 private final ApiVersions apiVersions; //保存生产者批次的映射,按照主题和分区进行存储。 private final ConcurrentMap<TopicPartition, Deque<ProducerBatch>> batches; //未完成批次的处理器。 private final IncompleteBatches incomplete; // The following variables are only accessed by the sender thread, so we don't need to protect them. //存储被暂停的分区集合。 private final Set<TopicPartition> muted; //消息发送者线程的专用索引,用于控制消息的发送。 private int drainIndex; //事务管理器,处理生产者端的事务性操作。 private final TransactionManager transactionManager; //下一个批次过期时间的绝对时间戳,标志着一个批次消息的最早过期时间。 private long nextBatchExpiryTimeMs = Long.MAX_VALUE; // the earliest time (absolute) a batch will expire. /** * Create a new record accumulator * * @param logContext The log context used for logging * @param batchSize The size to use when allocating {@link MemoryRecords} instances * @param compression The compression codec for the records * @param lingerMs An artificial delay time to add before declaring a records instance that isn't full ready for * sending. This allows time for more records to arrive. Setting a non-zero lingerMs will trade off some * latency for potentially better throughput due to more batching (and hence fewer, larger requests). * @param retryBackoffMs An artificial delay time to retry the produce request upon receiving an error. This avoids * exhausting all retries in a short period of time. * @param metrics The metrics * @param time The time instance to use * @param apiVersions Request API versions for current connected brokers * @param transactionManager The shared transaction state object which tracks producer IDs, epochs, and sequence * numbers per partition. */ public RecordAccumulator(LogContext logContext, int batchSize, CompressionType compression, int lingerMs, long retryBackoffMs, int deliveryTimeoutMs, Metrics metrics, String metricGrpName, Time time, ApiVersions apiVersions, TransactionManager transactionManager, BufferPool bufferPool) { this.log = logContext.logger(RecordAccumulator.class); this.drainIndex = 0; this.closed = false; this.flushesInProgress = new AtomicInteger(0); this.appendsInProgress = new AtomicInteger(0); this.batchSize = batchSize; this.compression = compression; this.lingerMs = lingerMs; this.retryBackoffMs = retryBackoffMs; this.deliveryTimeoutMs = deliveryTimeoutMs; this.batches = new CopyOnWriteMap<>(); this.free = bufferPool; this.incomplete = new IncompleteBatches(); this.muted = new HashSet<>(); this.time = time; this.apiVersions = apiVersions; this.transactionManager = transactionManager; registerMetrics(metrics, metricGrpName); } private void registerMetrics(Metrics metrics, String metricGrpName) { MetricName metricName = metrics.metricName("waiting-threads", metricGrpName, "The number of user threads blocked waiting for buffer memory to enqueue their records"); Measurable waitingThreads = new Measurable() { @Override public double measure(MetricConfig config, long now) { return free.queued(); } }; metrics.addMetric(metricName, waitingThreads); metricName = metrics.metricName("buffer-total-bytes", metricGrpName, "The maximum amount of buffer memory the client can use (whether or not it is currently used)."); Measurable totalBytes = new Measurable() { @Override public double measure(MetricConfig config, long now) { return free.totalMemory(); } }; metrics.addMetric(metricName, totalBytes); metricName = metrics.metricName("buffer-available-bytes", metricGrpName, "The total amount of buffer memory that is not being used (either unallocated or in the free list)."); Measurable availableBytes = new Measurable() { @Override public double measure(MetricConfig config, long now) { return free.availableMemory(); } }; metrics.addMetric(metricName, availableBytes); } /** * Add a record to the accumulator, return the append result * <p> * The append result will contain the future metadata, and flag for whether the appended batch is full or a new batch is created * <p> * * @param tp The topic/partition to which this record is being sent * @param timestamp The timestamp of the record * @param key The key for the record * @param value The value for the record * @param headers the Headers for the record * @param callback The user-supplied callback to execute when the request is complete * @param maxTimeToBlock The maximum time in milliseconds to block for buffer memory to be available * @param abortOnNewBatch A boolean that indicates returning before a new batch is created and * running the partitioner's onNewBatch method before trying to append again * @param nowMs The current time, in milliseconds */ public RecordAppendResult append(TopicPartition tp, long timestamp, byte[] key, byte[] value, Header[] headers,
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients.producer.internals; /** * This class acts as a queue that accumulates records into {@link MemoryRecords} * instances to be sent to the server. * <p> * The accumulator uses a bounded amount of memory and append calls will block when that memory is exhausted, unless * this behavior is explicitly disabled. */ public final class RecordAccumulator { private final Logger log; //标志位,表示累加器是否已经关闭 private volatile boolean closed; //计数器,用于跟踪正在进行的刷新操作的数量。 private final AtomicInteger flushesInProgress; //计数器,用于跟踪正在进行的追加操作的数量。 private final AtomicInteger appendsInProgress; //记录批次的大小,即每个批次中消息的数量限制。 private final int batchSize; //消息的压缩方式。 private final CompressionType compression; //消息在从消息缓冲区发送出去之前要等待的时间。 private final int lingerMs; //发生重试时的等待时间。 private final long retryBackoffMs; //消息投递的超时时间。 private final int deliveryTimeoutMs; //缓冲池,用于管理可用于内存分配的内存缓冲区。 private final BufferPool free; //用于管理和获取时间戳。 private final Time time; //Kafka支持的API版本 private final ApiVersions apiVersions; //保存生产者批次的映射,按照主题和分区进行存储。 private final ConcurrentMap<TopicPartition, Deque<ProducerBatch>> batches; //未完成批次的处理器。 private final IncompleteBatches incomplete; // The following variables are only accessed by the sender thread, so we don't need to protect them. //存储被暂停的分区集合。 private final Set<TopicPartition> muted; //消息发送者线程的专用索引,用于控制消息的发送。 private int drainIndex; //事务管理器,处理生产者端的事务性操作。 private final TransactionManager transactionManager; //下一个批次过期时间的绝对时间戳,标志着一个批次消息的最早过期时间。 private long nextBatchExpiryTimeMs = Long.MAX_VALUE; // the earliest time (absolute) a batch will expire. /** * Create a new record accumulator * * @param logContext The log context used for logging * @param batchSize The size to use when allocating {@link MemoryRecords} instances * @param compression The compression codec for the records * @param lingerMs An artificial delay time to add before declaring a records instance that isn't full ready for * sending. This allows time for more records to arrive. Setting a non-zero lingerMs will trade off some * latency for potentially better throughput due to more batching (and hence fewer, larger requests). * @param retryBackoffMs An artificial delay time to retry the produce request upon receiving an error. This avoids * exhausting all retries in a short period of time. * @param metrics The metrics * @param time The time instance to use * @param apiVersions Request API versions for current connected brokers * @param transactionManager The shared transaction state object which tracks producer IDs, epochs, and sequence * numbers per partition. */ public RecordAccumulator(LogContext logContext, int batchSize, CompressionType compression, int lingerMs, long retryBackoffMs, int deliveryTimeoutMs, Metrics metrics, String metricGrpName, Time time, ApiVersions apiVersions, TransactionManager transactionManager, BufferPool bufferPool) { this.log = logContext.logger(RecordAccumulator.class); this.drainIndex = 0; this.closed = false; this.flushesInProgress = new AtomicInteger(0); this.appendsInProgress = new AtomicInteger(0); this.batchSize = batchSize; this.compression = compression; this.lingerMs = lingerMs; this.retryBackoffMs = retryBackoffMs; this.deliveryTimeoutMs = deliveryTimeoutMs; this.batches = new CopyOnWriteMap<>(); this.free = bufferPool; this.incomplete = new IncompleteBatches(); this.muted = new HashSet<>(); this.time = time; this.apiVersions = apiVersions; this.transactionManager = transactionManager; registerMetrics(metrics, metricGrpName); } private void registerMetrics(Metrics metrics, String metricGrpName) { MetricName metricName = metrics.metricName("waiting-threads", metricGrpName, "The number of user threads blocked waiting for buffer memory to enqueue their records"); Measurable waitingThreads = new Measurable() { @Override public double measure(MetricConfig config, long now) { return free.queued(); } }; metrics.addMetric(metricName, waitingThreads); metricName = metrics.metricName("buffer-total-bytes", metricGrpName, "The maximum amount of buffer memory the client can use (whether or not it is currently used)."); Measurable totalBytes = new Measurable() { @Override public double measure(MetricConfig config, long now) { return free.totalMemory(); } }; metrics.addMetric(metricName, totalBytes); metricName = metrics.metricName("buffer-available-bytes", metricGrpName, "The total amount of buffer memory that is not being used (either unallocated or in the free list)."); Measurable availableBytes = new Measurable() { @Override public double measure(MetricConfig config, long now) { return free.availableMemory(); } }; metrics.addMetric(metricName, availableBytes); } /** * Add a record to the accumulator, return the append result * <p> * The append result will contain the future metadata, and flag for whether the appended batch is full or a new batch is created * <p> * * @param tp The topic/partition to which this record is being sent * @param timestamp The timestamp of the record * @param key The key for the record * @param value The value for the record * @param headers the Headers for the record * @param callback The user-supplied callback to execute when the request is complete * @param maxTimeToBlock The maximum time in milliseconds to block for buffer memory to be available * @param abortOnNewBatch A boolean that indicates returning before a new batch is created and * running the partitioner's onNewBatch method before trying to append again * @param nowMs The current time, in milliseconds */ public RecordAppendResult append(TopicPartition tp, long timestamp, byte[] key, byte[] value, Header[] headers,
Callback callback,
1
2023-12-23 07:12:18+00:00
24k
qiusunshine/xiu
app/src/main/java/org/mozilla/xiu/browser/dlan/MediaPlayActivity.java
[ { "identifier": "Intents", "path": "clinglibrary/src/main/java/com/qingfeng/clinglibrary/Intents.java", "snippet": "public class Intents {\n /**\n * Prefix for all intents created\n */\n public static final String INTENT_PREFIX = \"com.zane.androidupnpdemo.\";\n\n /**\n * Prefix for...
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatSeekBar; import com.alibaba.fastjson.JSON; import com.qingfeng.clinglibrary.Intents; import com.qingfeng.clinglibrary.control.ClingPlayControl; import com.qingfeng.clinglibrary.control.callback.ControlCallback; import com.qingfeng.clinglibrary.control.callback.ControlReceiveCallback; import com.qingfeng.clinglibrary.entity.ClingVolumeResponse; import com.qingfeng.clinglibrary.entity.DLANPlayState; import com.qingfeng.clinglibrary.entity.IResponse; import com.qingfeng.clinglibrary.service.manager.ClingManager; import org.fourthline.cling.model.ModelUtil; import org.fourthline.cling.support.model.PositionInfo; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.mozilla.xiu.browser.R; import org.mozilla.xiu.browser.base.BaseActivity; import org.mozilla.xiu.browser.utils.StringUtil; import org.mozilla.xiu.browser.utils.ToastMgr; import java.util.Timer; import java.util.TimerTask;
21,209
} }); } /** * 停止 */ private void stop() { mClingPlayControl.stop(new ControlCallback() { @Override public void success(IResponse response) { } @Override public void fail(IResponse response) { } }); } /** * 暂停 */ private void pause() { mClingPlayControl.pause(new ControlCallback() { @Override public void success(IResponse response) { isPlaying = false; // tvVideoStatus.setText("暂停投屏中"); } @Override public void fail(IResponse response) { Log.e(TAG, "pause fail"); } }); } @Override protected void onDestroy() { super.onDestroy(); // stop(); // mPlayer.release(); if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); } mHandler.removeCallbacksAndMessages(null); endGetProgress(); unregisterReceiver(TransportStateBroadcastReceiver); } private void registerReceivers() { //Register play status broadcast IntentFilter filter = new IntentFilter(); filter.addAction(Intents.ACTION_PLAYING); filter.addAction(Intents.ACTION_PAUSED_PLAYBACK); filter.addAction(Intents.ACTION_STOPPED); filter.addAction(Intents.ACTION_TRANSITIONING); filter.addAction(Intents.ACTION_POSITION_CALLBACK); filter.addAction(Intents.ACTION_PLAY_COMPLETE); registerReceiver(TransportStateBroadcastReceiver, filter); } private final class InnerHandler extends Handler { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case PLAY_ACTION: Log.i(TAG, "Execute PLAY_ACTION"); // Toast.makeText(mContext, "正在投放", Toast.LENGTH_SHORT).show(); startGetProgress(); mClingPlayControl.setCurrentState(DLANPlayState.PLAY); break; case PAUSE_ACTION: Log.i(TAG, "Execute PAUSE_ACTION"); mClingPlayControl.setCurrentState(DLANPlayState.PAUSE); break; case STOP_ACTION: Log.i(TAG, "Execute STOP_ACTION"); mClingPlayControl.setCurrentState(DLANPlayState.STOP); // foot.ivPlay.setImageResource(R.drawable.icon_video_pause); break; case TRANSITIONING_ACTION: Log.i(TAG, "Execute TRANSITIONING_ACTION"); Toast.makeText(mContext, "正在连接", Toast.LENGTH_SHORT).show(); break; case ACTION_POSITION_CALLBACK: // foot.setCurProgress(msg.arg1); break; case ACTION_PLAY_COMPLETE: Log.i(TAG, "Execute GET_POSITION_INFO_ACTION"); // ToastUtils.showLong("播放完成"); break; case ERROR_ACTION: Log.e(TAG, "Execute ERROR_ACTION"); Toast.makeText(mContext, "投放失败", Toast.LENGTH_SHORT).show(); if (DlanListPopUtil.instance().getUsedDevice() != null) { DlanListPopUtil.instance().reInit(); } break; } } } private void startGetProgress() { TimerTask timerTask = new TimerTask() { @Override public void run() { if (mClingPlayControl != null) mClingPlayControl.getPositionInfo(new ControlReceiveCallback() { @Override public void receive(IResponse response) { Log.d(TAG, "receive: " + JSON.toJSONString(response)); Object responseResponse = response.getResponse();
package org.mozilla.xiu.browser.dlan; public class MediaPlayActivity extends AppCompatActivity { private static final String TAG = "MediaPlayActivity"; /** * 连接设备状态: 播放状态 */ public static final int PLAY_ACTION = 0xa1; /** * 连接设备状态: 暂停状态 */ public static final int PAUSE_ACTION = 0xa2; /** * 连接设备状态: 停止状态 */ public static final int STOP_ACTION = 0xa3; /** * 连接设备状态: 转菊花状态 */ public static final int TRANSITIONING_ACTION = 0xa4; /** * 获取进度 */ public static final int EXTRA_POSITION = 0xa5; /** * 投放失败 */ public static final int ERROR_ACTION = 0xa6; /** * tv端播放完成 */ public static final int ACTION_PLAY_COMPLETE = 0xa7; public static final int ACTION_POSITION_CALLBACK = 0xa8; private TextView tvVideoName; private Context mContext; private Handler mHandler = new InnerHandler(); private Timer timer = null; private boolean isPlaying = false; private ClingPlayControl mClingPlayControl = new ClingPlayControl();//投屏控制器 private AppCompatSeekBar seekBar; private ImageView playBt; private TextView currTime; private TextView countTime; private long hostLength; private ImageView plusVolume; private ImageView reduceVolume; private int currentVolume; private TextView playStatus; private boolean isSeeking = false; private int pos = -1; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { BaseActivity.checkForceDarkMode(this); super.onCreate(savedInstanceState); mContext = this; initStatusBar(); setContentView(R.layout.activity_dlan_play_layout); initView(); initListener(); registerReceivers(); String playUrl = getIntent().getStringExtra(DLandataInter.Key.PLAYURL); String playTitle = getIntent().getStringExtra(DLandataInter.Key.PLAY_TITLE); String headers = getIntent().getStringExtra(DLandataInter.Key.HEADER); pos = getIntent().getIntExtra(DLandataInter.Key.PLAY_POS, -1); initData(playUrl, playTitle, headers); if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } } private void initStatusBar() { requestWindowFeature(Window.FEATURE_NO_TITLE); //去除状态栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } private void initView() { tvVideoName = findViewById(R.id.text_content_title); playBt = findViewById(R.id.img_play); findViewById(R.id.backup).setOnClickListener(v -> finish()); seekBar = findViewById(R.id.seek_bar_progress); currTime = findViewById(R.id.text_play_time); countTime = findViewById(R.id.text_play_max_time); playStatus = findViewById(R.id.play_status); plusVolume = findViewById(R.id.plus_volume); reduceVolume = findViewById(R.id.reduce_volume); getVolume(); plusVolume.setOnClickListener(v -> { if (currentVolume >= 96) { return; } currentVolume += 4; mClingPlayControl.setVolume(currentVolume, new ControlCallback() { @Override public void success(IResponse response) { getVolume(); } @Override public void fail(IResponse response) { getVolume(); } }); }); reduceVolume.setOnClickListener(v -> { if (currentVolume <= 4) { return; } currentVolume -= 4; mClingPlayControl.setVolume(currentVolume, new ControlCallback() { @Override public void success(IResponse response) { getVolume(); } @Override public void fail(IResponse response) { } }); }); findViewById(R.id.img_next).setOnClickListener(v -> { ToastMgr.shortCenter(getContext(), "暂不支持此功能"); }); findViewById(R.id.img_previous).setOnClickListener(v -> { ToastMgr.shortCenter(getContext(), "嘿嘿,我是个假按钮~"); }); } private void next() { } @Subscribe(threadMode = ThreadMode.MAIN) public void onDlan(DlanPlayEvent event) { initData(event.getUrl(), event.getTitle(), event.getHeaders()); } private Context getContext() { return this; } private void getVolume() { mClingPlayControl.getVolume(new ControlReceiveCallback() { @Override public void receive(IResponse response) { Object responseResponse = response.getResponse(); if (responseResponse instanceof ClingVolumeResponse) { ClingVolumeResponse resp = (ClingVolumeResponse) response; currentVolume = resp.getResponse(); } } @Override public void success(IResponse response) { } @Override public void fail(IResponse response) { } }); } private void initData(String playUrl, String playTitle, String headers) { tvVideoName.setText(playTitle); playStatus.setText("正在缓冲..."); playNew(playUrl, playTitle, headers); Log.d(TAG, "initData: playUrl==>" + playUrl + ", playTitle==>" + playTitle + ", headers==>" + headers); } private void initListener() { playBt.setOnClickListener(v -> { if (isPlaying) { pause(); playBt.setSelected(false); playStatus.setText("暂停播放..."); } else { continuePlay(); playBt.setSelected(true); playStatus.setText("正在播放"); } }); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int newProgress = (int) (hostLength * (progress * 0.01f)); String time = ModelUtil.toTimeString(newProgress); currTime.setText(time); } @Override public void onStartTrackingTouch(SeekBar seekBar) { isSeeking = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { int currentProgress = seekBar.getProgress(); // 转为毫秒 isSeeking = false; int progress = (int) (hostLength * 1000 * (currentProgress * 0.01f)); mClingPlayControl.seek(progress, new ControlCallback() { @Override public void success(IResponse response) { Log.e(TAG, "seek success"); } @Override public void fail(IResponse response) { Log.e(TAG, "seek fail"); } }); } }); // } private String getPlayUrl(String url, String headers) { if (StringUtil.isEmpty(headers)) { return url; } String device = DlanListPopUtil.instance().getUsedDeviceName(); if (StringUtil.isNotEmpty(device) && (device.contains("波澜投屏2") || device.contains("Macast"))) { //拼接header return url + "##|" + headers; } return url; } private void playNew(String url, String playTitle, String headers) { url = getPlayUrl(url, headers); Log.d(TAG, "playNew start: " + url); mClingPlayControl.playNew(url, playTitle, new ControlCallback() { @Override public void success(IResponse response) { Log.d(TAG, "playNew success: "); isPlaying = true; playBt.setSelected(true); ClingManager.getInstance().registerAVTransport(mContext); ClingManager.getInstance().registerRenderingControl(mContext); endGetProgress(); startGetProgress(); playStatus.setText("正在播放"); } @Override public void fail(IResponse response) { mHandler.sendEmptyMessage(ERROR_ACTION); Log.d(TAG, "playNew fail: "); } }); } private void continuePlay() { mClingPlayControl.play(new ControlCallback() { @Override public void success(IResponse response) { isPlaying = true; // tvVideoStatus.setText("正在投屏中"); Log.e(TAG, "play success"); } @Override public void fail(IResponse response) { Log.e(TAG, "play fail"); } }); } /** * 停止 */ private void stop() { mClingPlayControl.stop(new ControlCallback() { @Override public void success(IResponse response) { } @Override public void fail(IResponse response) { } }); } /** * 暂停 */ private void pause() { mClingPlayControl.pause(new ControlCallback() { @Override public void success(IResponse response) { isPlaying = false; // tvVideoStatus.setText("暂停投屏中"); } @Override public void fail(IResponse response) { Log.e(TAG, "pause fail"); } }); } @Override protected void onDestroy() { super.onDestroy(); // stop(); // mPlayer.release(); if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); } mHandler.removeCallbacksAndMessages(null); endGetProgress(); unregisterReceiver(TransportStateBroadcastReceiver); } private void registerReceivers() { //Register play status broadcast IntentFilter filter = new IntentFilter(); filter.addAction(Intents.ACTION_PLAYING); filter.addAction(Intents.ACTION_PAUSED_PLAYBACK); filter.addAction(Intents.ACTION_STOPPED); filter.addAction(Intents.ACTION_TRANSITIONING); filter.addAction(Intents.ACTION_POSITION_CALLBACK); filter.addAction(Intents.ACTION_PLAY_COMPLETE); registerReceiver(TransportStateBroadcastReceiver, filter); } private final class InnerHandler extends Handler { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case PLAY_ACTION: Log.i(TAG, "Execute PLAY_ACTION"); // Toast.makeText(mContext, "正在投放", Toast.LENGTH_SHORT).show(); startGetProgress(); mClingPlayControl.setCurrentState(DLANPlayState.PLAY); break; case PAUSE_ACTION: Log.i(TAG, "Execute PAUSE_ACTION"); mClingPlayControl.setCurrentState(DLANPlayState.PAUSE); break; case STOP_ACTION: Log.i(TAG, "Execute STOP_ACTION"); mClingPlayControl.setCurrentState(DLANPlayState.STOP); // foot.ivPlay.setImageResource(R.drawable.icon_video_pause); break; case TRANSITIONING_ACTION: Log.i(TAG, "Execute TRANSITIONING_ACTION"); Toast.makeText(mContext, "正在连接", Toast.LENGTH_SHORT).show(); break; case ACTION_POSITION_CALLBACK: // foot.setCurProgress(msg.arg1); break; case ACTION_PLAY_COMPLETE: Log.i(TAG, "Execute GET_POSITION_INFO_ACTION"); // ToastUtils.showLong("播放完成"); break; case ERROR_ACTION: Log.e(TAG, "Execute ERROR_ACTION"); Toast.makeText(mContext, "投放失败", Toast.LENGTH_SHORT).show(); if (DlanListPopUtil.instance().getUsedDevice() != null) { DlanListPopUtil.instance().reInit(); } break; } } } private void startGetProgress() { TimerTask timerTask = new TimerTask() { @Override public void run() { if (mClingPlayControl != null) mClingPlayControl.getPositionInfo(new ControlReceiveCallback() { @Override public void receive(IResponse response) { Log.d(TAG, "receive: " + JSON.toJSONString(response)); Object responseResponse = response.getResponse();
if (responseResponse instanceof PositionInfo) {
9
2023-11-10 14:28:40+00:00
24k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/commandexecutors/ShrineCommandExecutor.java
[ { "identifier": "Deity", "path": "src/main/java/me/xidentified/devotions/Deity.java", "snippet": "public class Deity {\n private final Devotions plugin;\n // Getter methods below\n @Getter public final String name;\n @Getter private final String lore;\n @Getter private final String alignm...
import de.cubbossa.tinytranslations.GlobalMessages; import me.xidentified.devotions.Deity; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.Shrine; import me.xidentified.devotions.managers.DevotionManager; import me.xidentified.devotions.managers.FavorManager; import me.xidentified.devotions.managers.ShrineManager; import me.xidentified.devotions.util.Messages; import net.kyori.adventure.text.minimessage.tag.resolver.Formatter; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; import org.jetbrains.annotations.NotNull; import java.util.*;
15,599
package me.xidentified.devotions.commandexecutors; public class ShrineCommandExecutor implements CommandExecutor, Listener, TabCompleter { private final Map<Player, Deity> pendingShrineDesignations = new HashMap<>(); private final Map<UUID, Boolean> pendingShrineRemovals = new HashMap<>(); private final DevotionManager devotionManager; private final ShrineManager shrineManager; public ShrineCommandExecutor(DevotionManager devotionManager, ShrineManager shrineManager) { this.devotionManager = devotionManager; this.shrineManager = shrineManager; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length > 0) { if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("devotions.shrine.list")) { displayShrineList(player); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_LIST); } return true; } else if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("devotions.shrine.remove")) { pendingShrineRemovals.put(player.getUniqueId(), true); Devotions.getInstance().sendMessage(player, Messages.SHRINE_RC_TO_REMOVE); //Bukkit.getLogger().log(Level.WARNING, "Current pendingShrineRemovals map: " + pendingShrineRemovals); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_REMOVE); } return true; } } else if (player.hasPermission("devotions.shrine.set")) { int currentShrineCount = shrineManager.getShrineCount(player); int shrineLimit = shrineManager.getPlugin().getShrineLimit(); if (currentShrineCount >= shrineLimit) { Devotions.getInstance().sendMessage(player, Messages.SHRINE_LIMIT_REACHED.formatted( Formatter.number("limit", shrineLimit) )); return true; } // If the player doesn't follow a deity, don't let them make a shrine FavorManager favorManager = devotionManager.getPlayerDevotion(player.getUniqueId()); if (favorManager == null || favorManager.getDeity() == null) { Devotions.getInstance().sendMessage(player, Messages.SHRINE_FOLLOW_DEITY_TO_DESIGNATE); return true; } // Fetch the deity directly from the player's FavorManager Deity deity = favorManager.getDeity(); pendingShrineDesignations.put(player, deity); Devotions.getInstance().sendMessage(player, Messages.SHRINE_CLICK_BLOCK_TO_DESIGNATE.formatted( Placeholder.unparsed("deity", deity.getName()) )); return true; } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_SET); return false; } return false; } @EventHandler public void onShrineDesignation(PlayerInteractEvent event) { Player player = event.getPlayer(); if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getHand() != EquipmentSlot.HAND) return; if (pendingShrineDesignations.containsKey(player)) { Block clickedBlock = event.getClickedBlock(); if (clickedBlock != null) {
package me.xidentified.devotions.commandexecutors; public class ShrineCommandExecutor implements CommandExecutor, Listener, TabCompleter { private final Map<Player, Deity> pendingShrineDesignations = new HashMap<>(); private final Map<UUID, Boolean> pendingShrineRemovals = new HashMap<>(); private final DevotionManager devotionManager; private final ShrineManager shrineManager; public ShrineCommandExecutor(DevotionManager devotionManager, ShrineManager shrineManager) { this.devotionManager = devotionManager; this.shrineManager = shrineManager; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length > 0) { if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("devotions.shrine.list")) { displayShrineList(player); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_LIST); } return true; } else if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("devotions.shrine.remove")) { pendingShrineRemovals.put(player.getUniqueId(), true); Devotions.getInstance().sendMessage(player, Messages.SHRINE_RC_TO_REMOVE); //Bukkit.getLogger().log(Level.WARNING, "Current pendingShrineRemovals map: " + pendingShrineRemovals); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_REMOVE); } return true; } } else if (player.hasPermission("devotions.shrine.set")) { int currentShrineCount = shrineManager.getShrineCount(player); int shrineLimit = shrineManager.getPlugin().getShrineLimit(); if (currentShrineCount >= shrineLimit) { Devotions.getInstance().sendMessage(player, Messages.SHRINE_LIMIT_REACHED.formatted( Formatter.number("limit", shrineLimit) )); return true; } // If the player doesn't follow a deity, don't let them make a shrine FavorManager favorManager = devotionManager.getPlayerDevotion(player.getUniqueId()); if (favorManager == null || favorManager.getDeity() == null) { Devotions.getInstance().sendMessage(player, Messages.SHRINE_FOLLOW_DEITY_TO_DESIGNATE); return true; } // Fetch the deity directly from the player's FavorManager Deity deity = favorManager.getDeity(); pendingShrineDesignations.put(player, deity); Devotions.getInstance().sendMessage(player, Messages.SHRINE_CLICK_BLOCK_TO_DESIGNATE.formatted( Placeholder.unparsed("deity", deity.getName()) )); return true; } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_SET); return false; } return false; } @EventHandler public void onShrineDesignation(PlayerInteractEvent event) { Player player = event.getPlayer(); if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getHand() != EquipmentSlot.HAND) return; if (pendingShrineDesignations.containsKey(player)) { Block clickedBlock = event.getClickedBlock(); if (clickedBlock != null) {
Shrine existingShrine = shrineManager.getShrineAtLocation(clickedBlock.getLocation());
2
2023-11-10 07:03:24+00:00
24k
SplitfireUptown/datalinkx
flinkx/flinkx-hive/flinkx-hive-writer/src/main/java/com/dtstack/flinkx/hive/writer/HiveOutputFormat.java
[ { "identifier": "WriteRecordException", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/exception/WriteRecordException.java", "snippet": "public class WriteRecordException extends Exception {\n\n private int colIndex = -1;\n private Row row;\n\n public int getColIndex() {\n ...
import com.dtstack.flinkx.exception.WriteRecordException; import com.dtstack.flinkx.hdfs.writer.BaseHdfsOutputFormat; import com.dtstack.flinkx.hdfs.writer.HdfsOutputFormatBuilder; import com.dtstack.flinkx.hive.TableInfo; import com.dtstack.flinkx.hive.TimePartitionFormat; import com.dtstack.flinkx.hive.util.HiveDbUtil; import com.dtstack.flinkx.hive.util.HiveUtil; import com.dtstack.flinkx.hive.util.PathConverterUtil; import com.dtstack.flinkx.outputformat.BaseRichOutputFormat; import com.dtstack.flinkx.restore.FormatState; import com.dtstack.flinkx.util.ExceptionUtil; import com.dtstack.flinkx.util.GsonUtil; import com.google.gson.JsonSyntaxException; import org.apache.commons.collections.MapUtils; import org.apache.commons.math3.util.Pair; import org.apache.flink.types.Row; import org.apache.hadoop.conf.Configuration; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import static com.dtstack.flinkx.hive.HiveConfigKeys.KEY_SCHEMA; import static com.dtstack.flinkx.hive.HiveConfigKeys.KEY_TABLE;
18,274
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.dtstack.flinkx.hive.writer; /** * @author toutian */ public class HiveOutputFormat extends BaseRichOutputFormat { private static final String SP = "/"; /** * hdfs高可用配置 */ protected Map<String, Object> hadoopConfig; protected String fileType; /** * 写入模式 */ protected String writeMode; /** * 压缩方式 */ protected String compress; protected String defaultFs; protected String delimiter; protected String charsetName = "UTF-8"; protected Configuration conf; protected int rowGroupSize; protected long maxFileSize; /* ----------以上hdfs插件参数----------- */ protected Map<String, TableInfo> tableInfos; protected Map<String, String> distributeTableMapping; protected String partition; protected String partitionType; protected String partitionPath; protected String tbPath; protected long bufferSize; protected String jdbcUrl; protected String username; protected String password; protected String tableBasePath; protected boolean autoCreateTable; protected String schema; private transient HiveUtil hiveUtil; private transient TimePartitionFormat partitionFormat; private org.apache.flink.configuration.Configuration parameters; private int taskNumber; private int numTasks; private Map<String, TableInfo> tableCache; private Map<String, BaseHdfsOutputFormat> outputFormats;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.dtstack.flinkx.hive.writer; /** * @author toutian */ public class HiveOutputFormat extends BaseRichOutputFormat { private static final String SP = "/"; /** * hdfs高可用配置 */ protected Map<String, Object> hadoopConfig; protected String fileType; /** * 写入模式 */ protected String writeMode; /** * 压缩方式 */ protected String compress; protected String defaultFs; protected String delimiter; protected String charsetName = "UTF-8"; protected Configuration conf; protected int rowGroupSize; protected long maxFileSize; /* ----------以上hdfs插件参数----------- */ protected Map<String, TableInfo> tableInfos; protected Map<String, String> distributeTableMapping; protected String partition; protected String partitionType; protected String partitionPath; protected String tbPath; protected long bufferSize; protected String jdbcUrl; protected String username; protected String password; protected String tableBasePath; protected boolean autoCreateTable; protected String schema; private transient HiveUtil hiveUtil; private transient TimePartitionFormat partitionFormat; private org.apache.flink.configuration.Configuration parameters; private int taskNumber; private int numTasks; private Map<String, TableInfo> tableCache; private Map<String, BaseHdfsOutputFormat> outputFormats;
private Map<String, FormatState> formatStateMap = new HashMap<>();
9
2023-11-16 02:22:52+00:00
24k
bdmarius/jndarray-toolbox
src/main/java/internals/TensorDot.java
[ { "identifier": "JNumDataType", "path": "src/main/java/utils/JNumDataType.java", "snippet": "public enum JNumDataType {\n BYTE,\n SHORT,\n INT,\n LONG,\n FLOAT,\n DOUBLE\n}" }, { "identifier": "NumberUtils", "path": "src/main/java/utils/NumberUtils.java", "snippet": "pu...
import utils.JNumDataType; import utils.NumberUtils; import utils.TypeUtils; import java.util.Arrays;
20,130
package internals; public class TensorDot { /** * If either one of the tensors is a scalar (shape length is 0), then TensorArithmetic.multiply is returned. * If both tensors are 1-D, inner product is returned * If both tensors are 2-D, matrix multiplication is returned * If first tensor is N-D and the second tensor is 1-D, then: * - a (N-1)-D tensor is returned * - The difference between the first tensor shape and the result shape is that the N-th element from the first * tensor shape is dropped. Rest of elements remain the same * - the result tensor is the sum product over the last axis of the first tensor and the second tensor * If first tensor is N-D and the second tensor is M-D (M >= 2), then: * - a (M+N-2)-D tensor is returned * - The new tensor looks like this: we copy the first N-1 elements from the first tensor shape, * then we continue with the elements from the second tensor shape, except for the second-to-last one * - the result tensor is the sum product over the last axis of the first tensor and the second-to-last * dimension of the first tensor */ static Tensor dot(Tensor firstTensor, Tensor secondTensor) { int[] firstTensorShape = firstTensor.getShape(); int[] secondTensorShape = secondTensor.getShape(); if (firstTensorShape.length == 0 || secondTensorShape.length == 0) { return TensorArithmetic.multiply(firstTensor, secondTensor); } if (firstTensorShape.length == 1 && secondTensorShape.length == 1) { return doInnerProduct(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } if (firstTensorShape.length == 2 && secondTensorShape.length == 2) { return doMatrixMultiplication(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } if (firstTensorShape.length >= 2 && secondTensorShape.length == 1) { return doSumProductWith1D(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } return doSumProduct(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } private static Tensor doInnerProduct(Tensor firstTensor, int[] firstTensorShape, Tensor secondTensor, int[] secondTensorShape) { if (firstTensorShape[0] != secondTensorShape[0]) { throw new IllegalArgumentException( String.format("Shapes %s and %s do not match for dot operation because " + "%s (dim 0) != %s (dim 0)", Arrays.toString(firstTensorShape), Arrays.toString(secondTensorShape), firstTensorShape[0], secondTensorShape[0])); }
package internals; public class TensorDot { /** * If either one of the tensors is a scalar (shape length is 0), then TensorArithmetic.multiply is returned. * If both tensors are 1-D, inner product is returned * If both tensors are 2-D, matrix multiplication is returned * If first tensor is N-D and the second tensor is 1-D, then: * - a (N-1)-D tensor is returned * - The difference between the first tensor shape and the result shape is that the N-th element from the first * tensor shape is dropped. Rest of elements remain the same * - the result tensor is the sum product over the last axis of the first tensor and the second tensor * If first tensor is N-D and the second tensor is M-D (M >= 2), then: * - a (M+N-2)-D tensor is returned * - The new tensor looks like this: we copy the first N-1 elements from the first tensor shape, * then we continue with the elements from the second tensor shape, except for the second-to-last one * - the result tensor is the sum product over the last axis of the first tensor and the second-to-last * dimension of the first tensor */ static Tensor dot(Tensor firstTensor, Tensor secondTensor) { int[] firstTensorShape = firstTensor.getShape(); int[] secondTensorShape = secondTensor.getShape(); if (firstTensorShape.length == 0 || secondTensorShape.length == 0) { return TensorArithmetic.multiply(firstTensor, secondTensor); } if (firstTensorShape.length == 1 && secondTensorShape.length == 1) { return doInnerProduct(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } if (firstTensorShape.length == 2 && secondTensorShape.length == 2) { return doMatrixMultiplication(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } if (firstTensorShape.length >= 2 && secondTensorShape.length == 1) { return doSumProductWith1D(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } return doSumProduct(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } private static Tensor doInnerProduct(Tensor firstTensor, int[] firstTensorShape, Tensor secondTensor, int[] secondTensorShape) { if (firstTensorShape[0] != secondTensorShape[0]) { throw new IllegalArgumentException( String.format("Shapes %s and %s do not match for dot operation because " + "%s (dim 0) != %s (dim 0)", Arrays.toString(firstTensorShape), Arrays.toString(secondTensorShape), firstTensorShape[0], secondTensorShape[0])); }
JNumDataType resultDataType = TypeUtils.getHighestDataType(firstTensor.getDataType(), secondTensor.getDataType());
0
2023-11-13 19:53:02+00:00
24k
raphael-goetz/betterflowers
src/main/java/com/uroria/betterflowers/menus/FlowerCreationMenu.java
[ { "identifier": "BetterFlowers", "path": "src/main/java/com/uroria/betterflowers/BetterFlowers.java", "snippet": "@Getter\npublic final class BetterFlowers extends JavaPlugin {\n\n private final FlowerManager flowerManager;\n private final LanguageManager languageManager;\n\n public BetterFlowe...
import com.uroria.betterflowers.BetterFlowers; import com.uroria.betterflowers.data.FlowerGroupData; import com.uroria.betterflowers.flowers.SingleFlower; import com.uroria.betterflowers.flowers.placable.FlowerGroup; import com.uroria.betterflowers.managers.LanguageManager; import com.uroria.betterflowers.utils.BukkitPlayerInventory; import com.uroria.betterflowers.utils.CandleCollection; import com.uroria.betterflowers.utils.FlowerCollection; import com.uroria.betterflowers.data.FlowerData; import com.uroria.betterflowers.utils.ItemBuilder; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
21,080
package com.uroria.betterflowers.menus; public final class FlowerCreationMenu extends BukkitPlayerInventory { private final LanguageManager languageManager; private final List<FlowerData> personalFlower; private final List<Boolean> isGroup; private final List<Boolean> randomizer; private final Player player; private final ItemStack active; private final ItemStack notActive; private final ItemStack wholeCategoryRan; private final ItemStack wholeCategory; private final BetterFlowers betterFlowers; public FlowerCreationMenu(Player player, BetterFlowers betterFlowers) { super(betterFlowers.getLanguageManager().getComponent("gui.flower.title"), 6); this.player = player; this.betterFlowers = betterFlowers; this.languageManager = betterFlowers.getLanguageManager(); this.personalFlower = new ArrayList<>(); this.randomizer = new ArrayList<>(); this.isGroup = new ArrayList<>(); this.active = new ItemBuilder(Material.LIME_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.no")) .build(); this.notActive = new ItemBuilder(Material.RED_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.group.no.no")) .build(); this.wholeCategoryRan = new ItemBuilder(Material.BLUE_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.yes")) .build(); this.wholeCategory = new ItemBuilder(Material.MAGENTA_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.no.yes")) .build(); } public void open() { this.closeActions.add(() -> { personalFlower.clear(); randomizer.clear(); isGroup.clear(); }); generateCategories(); openInventory(player); } private void generateFlowerOverlay() { //generates placeholder for (var index = 27; index < 54; index++) { if (index >= 36 && index <= 44) continue; this.setSlot(index, new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.placeholder")) .build(), this::cancelClick); } //generates the display for the randomizer for (var index = 0; index < 9; index++) { if (index >= randomizer.size() || index >= isGroup.size()) break; if (isGroup.get(index) && randomizer.get(index)) setSlot(45 + index, wholeCategoryRan, this::cancelClick); if (isGroup.get(index) && !randomizer.get(index)) setSlot(45 + index, wholeCategory, this::cancelClick); if (!isGroup.get(index) && randomizer.get(index)) setSlot((45 + index), active, this::cancelClick); if (!isGroup.get(index) && !randomizer.get(index)) setSlot((45 + index), notActive, this::cancelClick); } //generates the chosen list of flowers to display the current flower list for (var index = 0; index < personalFlower.size(); index++) { final var singleFlower = personalFlower.get(index); setSlot((36 + index), new ItemBuilder(singleFlower.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%",singleFlower.getName() + " ID " + index)) .build(), this::cancelClick); } setSlot(29, new ItemBuilder(Material.ECHO_SHARD) .setName(languageManager.getComponent("gui.flower.item.display.create")) .build(), this::onCreateClick); setSlot(30, new ItemBuilder(Material.STRUCTURE_VOID) .setName(languageManager.getComponent("gui.flower.item.display.back")) .build(), this::onBackClick); setSlot(32, new ItemBuilder(Material.BARRIER) .setName(languageManager.getComponent("gui.flower.item.display.delete")) .build(), this::onDeleteClick); setSlot(33, new ItemBuilder(Material.REDSTONE) .setName(languageManager.getComponent("gui.flower.item.display.remove")) .build(), this::onRemoveClick); } private void generateCategories() { clearSlots(); generateFlowerOverlay(); final var flowers = List.copyOf(Arrays.stream(FlowerCollection.values()).toList()); for (int index = 0; index < 28; index++) { if (index > flowers.size()) break; if (index == flowers.size()) { this.setSlot(index, new ItemBuilder(Material.CANDLE) .setName(languageManager.getComponent("gui.flower.item.display.candle")).build(), this::createCandleCategories); break; } final var currentFlowers = flowers.get(index).getFlowerGroup(); setSlot(index, new ItemBuilder(currentFlowers.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%", currentFlowers.getDisplayName())) .setLore(languageManager.getComponents("gui.flower.item.lore.flowers")).build(), inventoryClickEvent -> onCategoryClick(inventoryClickEvent, currentFlowers) ); } } private void createCandleCategories(InventoryClickEvent inventoryClickEvent) { inventoryClickEvent.setCancelled(true); clearSlots(); generateFlowerOverlay(); final var candles = List.copyOf(Arrays.stream(CandleCollection.values()).toList()); for (int index = 0; index < 28; index++) { if (index >= candles.size()) break; final var currentCandle = candles.get(index).getFlowerGroup(); setSlot(index, new ItemBuilder(currentCandle.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%", currentCandle.getDisplayName())) .setLore(languageManager.getComponents("gui.flower.item.lore.flowers")).build(), clickEvent -> onCategoryClick(clickEvent, currentCandle) ); } }
package com.uroria.betterflowers.menus; public final class FlowerCreationMenu extends BukkitPlayerInventory { private final LanguageManager languageManager; private final List<FlowerData> personalFlower; private final List<Boolean> isGroup; private final List<Boolean> randomizer; private final Player player; private final ItemStack active; private final ItemStack notActive; private final ItemStack wholeCategoryRan; private final ItemStack wholeCategory; private final BetterFlowers betterFlowers; public FlowerCreationMenu(Player player, BetterFlowers betterFlowers) { super(betterFlowers.getLanguageManager().getComponent("gui.flower.title"), 6); this.player = player; this.betterFlowers = betterFlowers; this.languageManager = betterFlowers.getLanguageManager(); this.personalFlower = new ArrayList<>(); this.randomizer = new ArrayList<>(); this.isGroup = new ArrayList<>(); this.active = new ItemBuilder(Material.LIME_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.no")) .build(); this.notActive = new ItemBuilder(Material.RED_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.group.no.no")) .build(); this.wholeCategoryRan = new ItemBuilder(Material.BLUE_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.yes")) .build(); this.wholeCategory = new ItemBuilder(Material.MAGENTA_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.no.yes")) .build(); } public void open() { this.closeActions.add(() -> { personalFlower.clear(); randomizer.clear(); isGroup.clear(); }); generateCategories(); openInventory(player); } private void generateFlowerOverlay() { //generates placeholder for (var index = 27; index < 54; index++) { if (index >= 36 && index <= 44) continue; this.setSlot(index, new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.placeholder")) .build(), this::cancelClick); } //generates the display for the randomizer for (var index = 0; index < 9; index++) { if (index >= randomizer.size() || index >= isGroup.size()) break; if (isGroup.get(index) && randomizer.get(index)) setSlot(45 + index, wholeCategoryRan, this::cancelClick); if (isGroup.get(index) && !randomizer.get(index)) setSlot(45 + index, wholeCategory, this::cancelClick); if (!isGroup.get(index) && randomizer.get(index)) setSlot((45 + index), active, this::cancelClick); if (!isGroup.get(index) && !randomizer.get(index)) setSlot((45 + index), notActive, this::cancelClick); } //generates the chosen list of flowers to display the current flower list for (var index = 0; index < personalFlower.size(); index++) { final var singleFlower = personalFlower.get(index); setSlot((36 + index), new ItemBuilder(singleFlower.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%",singleFlower.getName() + " ID " + index)) .build(), this::cancelClick); } setSlot(29, new ItemBuilder(Material.ECHO_SHARD) .setName(languageManager.getComponent("gui.flower.item.display.create")) .build(), this::onCreateClick); setSlot(30, new ItemBuilder(Material.STRUCTURE_VOID) .setName(languageManager.getComponent("gui.flower.item.display.back")) .build(), this::onBackClick); setSlot(32, new ItemBuilder(Material.BARRIER) .setName(languageManager.getComponent("gui.flower.item.display.delete")) .build(), this::onDeleteClick); setSlot(33, new ItemBuilder(Material.REDSTONE) .setName(languageManager.getComponent("gui.flower.item.display.remove")) .build(), this::onRemoveClick); } private void generateCategories() { clearSlots(); generateFlowerOverlay(); final var flowers = List.copyOf(Arrays.stream(FlowerCollection.values()).toList()); for (int index = 0; index < 28; index++) { if (index > flowers.size()) break; if (index == flowers.size()) { this.setSlot(index, new ItemBuilder(Material.CANDLE) .setName(languageManager.getComponent("gui.flower.item.display.candle")).build(), this::createCandleCategories); break; } final var currentFlowers = flowers.get(index).getFlowerGroup(); setSlot(index, new ItemBuilder(currentFlowers.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%", currentFlowers.getDisplayName())) .setLore(languageManager.getComponents("gui.flower.item.lore.flowers")).build(), inventoryClickEvent -> onCategoryClick(inventoryClickEvent, currentFlowers) ); } } private void createCandleCategories(InventoryClickEvent inventoryClickEvent) { inventoryClickEvent.setCancelled(true); clearSlots(); generateFlowerOverlay(); final var candles = List.copyOf(Arrays.stream(CandleCollection.values()).toList()); for (int index = 0; index < 28; index++) { if (index >= candles.size()) break; final var currentCandle = candles.get(index).getFlowerGroup(); setSlot(index, new ItemBuilder(currentCandle.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%", currentCandle.getDisplayName())) .setLore(languageManager.getComponents("gui.flower.item.lore.flowers")).build(), clickEvent -> onCategoryClick(clickEvent, currentCandle) ); } }
private void generateSubCategories(FlowerGroup flowerGroup) {
2
2023-11-18 16:13:59+00:00
24k
jpdev01/asaasSdk
src/main/java/io/github/jpdev/asaassdk/doc/Examples.java
[ { "identifier": "Asaas", "path": "src/main/java/io/github/jpdev/asaassdk/http/Asaas.java", "snippet": "public class Asaas {\n\n private static final String ENDPOINT_PRODUCTION = \"https://www.asaas.com/api/v3\";\n private static final String ENDPOINT_SANDBOX = \"https://sandbox.asaas.com/api/v3\";...
import io.github.jpdev.asaassdk.http.Asaas; import io.github.jpdev.asaassdk.rest.accounts.Account; import io.github.jpdev.asaassdk.rest.accounts.AccountCreator; import io.github.jpdev.asaassdk.rest.action.ResourceSet; import io.github.jpdev.asaassdk.rest.bill.Bill; import io.github.jpdev.asaassdk.rest.commons.DeletedResource; import io.github.jpdev.asaassdk.rest.customeraccount.CustomerAccount; import io.github.jpdev.asaassdk.rest.finance.FinanceBalance; import io.github.jpdev.asaassdk.rest.financialtransaction.FinancialTransaction; import io.github.jpdev.asaassdk.rest.installment.Installment; import io.github.jpdev.asaassdk.rest.invoice.Invoice; import io.github.jpdev.asaassdk.rest.invoice.Taxes; import io.github.jpdev.asaassdk.rest.myaccount.accountnumber.AccountNumber; import io.github.jpdev.asaassdk.rest.myaccount.commercialinfo.CommercialInfo; import io.github.jpdev.asaassdk.rest.myaccount.fee.AccountFee; import io.github.jpdev.asaassdk.rest.myaccount.status.MyAccountStatus; import io.github.jpdev.asaassdk.rest.notification.NotificationConfig; import io.github.jpdev.asaassdk.rest.payment.Payment; import io.github.jpdev.asaassdk.rest.payment.enums.PaymentLinkChargeType; import io.github.jpdev.asaassdk.rest.payment.enums.PaymentStatus; import io.github.jpdev.asaassdk.rest.payment.identificationfield.PaymentIdentificationField; import io.github.jpdev.asaassdk.rest.payment.status.PaymentStatusData; import io.github.jpdev.asaassdk.rest.paymentlink.PaymentLink; import io.github.jpdev.asaassdk.rest.pix.addresskey.PixAddressKey; import io.github.jpdev.asaassdk.rest.pix.enums.PixAddressKeyStatus; import io.github.jpdev.asaassdk.rest.pix.enums.PixAddressKeyType; import io.github.jpdev.asaassdk.rest.pix.enums.PixTransactionType; import io.github.jpdev.asaassdk.rest.pix.qrcode.PixQrCode; import io.github.jpdev.asaassdk.rest.pix.qrcode.decode.PixDecodedQrCode; import io.github.jpdev.asaassdk.rest.pix.transaction.PixTransaction; import io.github.jpdev.asaassdk.rest.transfer.Transfer; import io.github.jpdev.asaassdk.rest.transfer.children.BankAccountSetting; import io.github.jpdev.asaassdk.rest.transfer.children.BankAccountType; import io.github.jpdev.asaassdk.rest.transfer.children.BankSetting; import io.github.jpdev.asaassdk.utils.BillingType; import io.github.jpdev.asaassdk.utils.Money; import java.math.BigDecimal; import java.util.Date;
20,327
package io.github.jpdev.asaassdk.doc; public class Examples { public static void main(String[] args) { Asaas.init(Secret.getAccessToken()); myStatus(); subAccount(); } private void pixTransaction() { ResourceSet<PixTransaction> pixTransactionResourceSet = PixTransaction.reader().read(); PixTransaction pixTransaction = PixTransaction.fetcher("bc515f74-d5c7-4bc2-93e5-3bafc0a9b15d").fetch(); PixTransaction cancelledPixTransaction = PixTransaction.canceller("35363f6e-93e2-11ec-b9d9-96f4053b1bd4").create(); ResourceSet<PixTransaction> pixTransactionDebitResourceSet = PixTransaction.reader() .setType(PixTransactionType.DEBIT) .read(); } private void pixAddressKey() { ResourceSet<PixAddressKey> pixAddressKeyResourceSet = PixAddressKey.reader() .setStatus(PixAddressKeyStatus.ACTIVE) .setLimit(1) .read(); PixAddressKey.creator().setType(PixAddressKeyType.EVP).create(); PixAddressKey.reader().read(); } private void decodePixQrCode() { PixDecodedQrCode decodedQrCode = PixDecodedQrCode.decoder() .setPayload("payload") .create(); } private void transfer() { ResourceSet<Transfer> transferList = Transfer.reader().read(); Transfer transfer = Transfer.pixAddressKeyCreator() .setPixAddressKey("09414368965") .setValue(Money.create(0.01)) .setDescription("teste") .setPixAddressKeyType(PixAddressKeyType.CPF) .create(); System.out.println(transfer.getValue().toString()); Date birthDate = new Date(); BankAccountSetting bankAccountSetting = new BankAccountSetting() .setBank(
package io.github.jpdev.asaassdk.doc; public class Examples { public static void main(String[] args) { Asaas.init(Secret.getAccessToken()); myStatus(); subAccount(); } private void pixTransaction() { ResourceSet<PixTransaction> pixTransactionResourceSet = PixTransaction.reader().read(); PixTransaction pixTransaction = PixTransaction.fetcher("bc515f74-d5c7-4bc2-93e5-3bafc0a9b15d").fetch(); PixTransaction cancelledPixTransaction = PixTransaction.canceller("35363f6e-93e2-11ec-b9d9-96f4053b1bd4").create(); ResourceSet<PixTransaction> pixTransactionDebitResourceSet = PixTransaction.reader() .setType(PixTransactionType.DEBIT) .read(); } private void pixAddressKey() { ResourceSet<PixAddressKey> pixAddressKeyResourceSet = PixAddressKey.reader() .setStatus(PixAddressKeyStatus.ACTIVE) .setLimit(1) .read(); PixAddressKey.creator().setType(PixAddressKeyType.EVP).create(); PixAddressKey.reader().read(); } private void decodePixQrCode() { PixDecodedQrCode decodedQrCode = PixDecodedQrCode.decoder() .setPayload("payload") .create(); } private void transfer() { ResourceSet<Transfer> transferList = Transfer.reader().read(); Transfer transfer = Transfer.pixAddressKeyCreator() .setPixAddressKey("09414368965") .setValue(Money.create(0.01)) .setDescription("teste") .setPixAddressKeyType(PixAddressKeyType.CPF) .create(); System.out.println(transfer.getValue().toString()); Date birthDate = new Date(); BankAccountSetting bankAccountSetting = new BankAccountSetting() .setBank(
new BankSetting().setCode("085")
33
2023-11-12 01:19:17+00:00
24k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/client/gui/hud/items/HudItemAirQuality.java
[ { "identifier": "Gui_EventManager", "path": "src/main/java/enviromine/client/gui/Gui_EventManager.java", "snippet": "@SideOnly(Side.CLIENT)\npublic class Gui_EventManager\n{\n\n\tint width, height;\n\n\t//Render HUD\n\t//Render Player\n\n\t// Button Functions\n\tGuiButton enviromine;\n\n\t// Captures th...
import org.lwjgl.opengl.GL11; import enviromine.client.gui.Gui_EventManager; import enviromine.client.gui.UI_Settings; import enviromine.client.gui.hud.HUDRegistry; import enviromine.client.gui.hud.HudItem; import enviromine.core.EM_Settings; import enviromine.utils.Alignment; import enviromine.utils.EnviroUtils; import enviromine.utils.RenderAssist; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector;
18,925
package enviromine.client.gui.hud.items; public class HudItemAirQuality extends HudItem { @Override public String getName() { return "Air Quality"; } public String getNameLoc() { return StatCollector.translateToLocal("options.enviromine.hud.air"); } @Override public String getButtonLabel() { return getNameLoc() + " Bar"; } @Override public Alignment getDefaultAlignment() { return Alignment.BOTTOMRIGHT; } @Override public int getDefaultPosX() { return(((HUDRegistry.screenWidth - 4) - getWidth())); } @Override public int getDefaultPosY() { return(HUDRegistry.screenHeight - 15); } @Override public int getWidth() { return UI_Settings.minimalHud && !rotated ? 0 : 64; } @Override public int getHeight() { return 8; } @Override public boolean isEnabledByDefault() {
package enviromine.client.gui.hud.items; public class HudItemAirQuality extends HudItem { @Override public String getName() { return "Air Quality"; } public String getNameLoc() { return StatCollector.translateToLocal("options.enviromine.hud.air"); } @Override public String getButtonLabel() { return getNameLoc() + " Bar"; } @Override public Alignment getDefaultAlignment() { return Alignment.BOTTOMRIGHT; } @Override public int getDefaultPosX() { return(((HUDRegistry.screenWidth - 4) - getWidth())); } @Override public int getDefaultPosY() { return(HUDRegistry.screenHeight - 15); } @Override public int getWidth() { return UI_Settings.minimalHud && !rotated ? 0 : 64; } @Override public int getHeight() { return 8; } @Override public boolean isEnabledByDefault() {
return EM_Settings.enableAirQ;
4
2023-11-16 18:15:29+00:00
24k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/render/GenericGunRenderer.java
[ { "identifier": "ClientProxy", "path": "src/main/java/sheridan/gunscraft/ClientProxy.java", "snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa...
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.AbstractClientPlayerEntity; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.PlayerRenderer; import net.minecraft.client.renderer.model.ItemCameraTransforms; import net.minecraft.client.renderer.model.ModelRenderer; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.vector.Matrix4f; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.lwjgl.opengl.GL11; import sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationData; import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationHandler; import sheridan.gunscraft.capability.CapabilityHandler; import sheridan.gunscraft.events.PlayerEvents; import sheridan.gunscraft.events.RenderEvents; import sheridan.gunscraft.items.attachments.util.GunAttachmentSlot; import sheridan.gunscraft.items.attachments.util.GunRenderContext; import sheridan.gunscraft.items.attachments.util.NBTAttachmentsMap; import sheridan.gunscraft.items.guns.IGenericGun; import sheridan.gunscraft.model.IGunModel; import sheridan.gunscraft.render.bulletShell.BulletShellRenderer; import sheridan.gunscraft.render.fx.muzzleFlash.CommonMuzzleFlash; import sheridan.gunscraft.render.fx.muzzleFlash.MuzzleFlash; import sheridan.gunscraft.render.fx.muzzleFlash.MuzzleFlashTrans; import static sheridan.gunscraft.ClientProxy.TICK_LEN; import static sheridan.gunscraft.ClientProxy.bulletSpread;
19,956
package sheridan.gunscraft.render; @OnlyIn(Dist.CLIENT) public class GenericGunRenderer implements IGunRender{ private static final Matrix4f DEFAULT_FIRST_PERSON_FOV_MATRIX; public static final float DEFAULT_FIRST_PERSON_FOV = 56.75f; public PlayerEntity player; static { DEFAULT_FIRST_PERSON_FOV_MATRIX = new Matrix4f(); DEFAULT_FIRST_PERSON_FOV_MATRIX.setIdentity(); Minecraft minecraft = Minecraft.getInstance(); DEFAULT_FIRST_PERSON_FOV_MATRIX.mul(Matrix4f.perspective(DEFAULT_FIRST_PERSON_FOV, (float) minecraft.getMainWindow().getFramebufferWidth() / (float) minecraft.getMainWindow().getFramebufferHeight(), 0.05F, (float) minecraft.gameSettings.renderDistanceChunks * 64F)); } public void justRenderModel(ItemStack itemStackIn, ItemCameraTransforms.TransformType transformTypeIn, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int combinedLightIn, int combinedOverlayIn, IGenericGun gun, IGunModel model, TransformData transformData) { if (model != null) { if (transformData != null) { matrixStackIn.push(); transformData.applyTransform(transformTypeIn, matrixStackIn, false, 0); int fireMode = gun.getFireMode(itemStackIn); int ammoLeft = gun.getAmmoLeft(itemStackIn);
package sheridan.gunscraft.render; @OnlyIn(Dist.CLIENT) public class GenericGunRenderer implements IGunRender{ private static final Matrix4f DEFAULT_FIRST_PERSON_FOV_MATRIX; public static final float DEFAULT_FIRST_PERSON_FOV = 56.75f; public PlayerEntity player; static { DEFAULT_FIRST_PERSON_FOV_MATRIX = new Matrix4f(); DEFAULT_FIRST_PERSON_FOV_MATRIX.setIdentity(); Minecraft minecraft = Minecraft.getInstance(); DEFAULT_FIRST_PERSON_FOV_MATRIX.mul(Matrix4f.perspective(DEFAULT_FIRST_PERSON_FOV, (float) minecraft.getMainWindow().getFramebufferWidth() / (float) minecraft.getMainWindow().getFramebufferHeight(), 0.05F, (float) minecraft.gameSettings.renderDistanceChunks * 64F)); } public void justRenderModel(ItemStack itemStackIn, ItemCameraTransforms.TransformType transformTypeIn, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int combinedLightIn, int combinedOverlayIn, IGenericGun gun, IGunModel model, TransformData transformData) { if (model != null) { if (transformData != null) { matrixStackIn.push(); transformData.applyTransform(transformTypeIn, matrixStackIn, false, 0); int fireMode = gun.getFireMode(itemStackIn); int ammoLeft = gun.getAmmoLeft(itemStackIn);
long fireDis = (gun.getShootDelay() - 1) * TICK_LEN;
16
2023-11-14 14:00:55+00:00
24k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/service/impl/MenuServiceImpl.java
[ { "identifier": "BadRequestException", "path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java", "snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) ...
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.dimple.exception.BadRequestException; import com.dimple.exception.EntityExistException; import com.dimple.modules.system.domain.Menu; import com.dimple.modules.system.domain.Role; import com.dimple.modules.system.domain.User; import com.dimple.modules.system.domain.vo.MenuMetaVO; import com.dimple.modules.system.domain.vo.MenuVO; import com.dimple.modules.system.repository.MenuRepository; import com.dimple.modules.system.repository.UserRepository; import com.dimple.modules.system.service.MenuService; import com.dimple.modules.system.service.RoleService; import com.dimple.modules.system.service.dto.MenuDTO; import com.dimple.modules.system.service.dto.MenuQueryCriteria; import com.dimple.modules.system.service.dto.RoleSmallDTO; import com.dimple.modules.system.service.mapstruct.MenuMapper; import com.dimple.utils.FileUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.RedisUtils; import com.dimple.utils.StringUtils; import com.dimple.utils.ValidationUtil; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors;
16,997
ValidationUtil.isNull(menu.getId(), "Permission", "id", resources.getId()); if (resources.getIFrame()) { String http = "http://", https = "https://"; if (!(resources.getPath().toLowerCase().startsWith(http) || resources.getPath().toLowerCase().startsWith(https))) { throw new BadRequestException("外链必须以http://或者https://开头"); } } Menu menu1 = menuRepository.findByTitle(resources.getTitle()); if (menu1 != null && !menu1.getId().equals(menu.getId())) { throw new EntityExistException(Menu.class, "title", resources.getTitle()); } if (resources.getPid().equals(0L)) { resources.setPid(null); } // 记录的父节点ID Long oldPid = menu.getPid(); Long newPid = resources.getPid(); if (StringUtils.isNotBlank(resources.getComponentName())) { menu1 = menuRepository.findByComponentName(resources.getComponentName()); if (menu1 != null && !menu1.getId().equals(menu.getId())) { throw new EntityExistException(Menu.class, "componentName", resources.getComponentName()); } } menu.setTitle(resources.getTitle()); menu.setComponent(resources.getComponent()); menu.setPath(resources.getPath()); menu.setIcon(resources.getIcon()); menu.setIFrame(resources.getIFrame()); menu.setPid(resources.getPid()); menu.setMenuSort(resources.getMenuSort()); menu.setCache(resources.getCache()); menu.setHidden(resources.getHidden()); menu.setComponentName(resources.getComponentName()); menu.setPermission(resources.getPermission()); menu.setType(resources.getType()); menuRepository.save(menu); // 计算父级菜单节点数目 updateSubCnt(oldPid); updateSubCnt(newPid); // 清理缓存 delCaches(resources.getId(), oldPid, newPid); } @Override public Set<Menu> getDeleteMenus(List<Menu> menuList, Set<Menu> menuSet) { // 递归找出待删除的菜单 for (Menu menu1 : menuList) { menuSet.add(menu1); List<Menu> menus = menuRepository.findByPid(menu1.getId()); if (menus != null && menus.size() != 0) { getDeleteMenus(menus, menuSet); } } return menuSet; } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Menu> menuSet) { for (Menu menu : menuSet) { // 清理缓存 delCaches(menu.getId(), menu.getPid(), null); roleService.untiedMenu(menu.getId()); menuRepository.deleteById(menu.getId()); updateSubCnt(menu.getPid()); } } @Override @Cacheable(key = "'pid:' + #p0") public List<MenuDTO> getMenus(Long pid) { List<Menu> menus; if (pid != null && !pid.equals(0L)) { menus = menuRepository.findByPid(pid); } else { menus = menuRepository.findByPidIsNull(); } return menuMapper.toDto(menus); } @Override public List<MenuDTO> getSuperior(MenuDTO menuDto, List<Menu> menus) { if (menuDto.getPid() == null) { menus.addAll(menuRepository.findByPidIsNull()); return menuMapper.toDto(menus); } menus.addAll(menuRepository.findByPid(menuDto.getPid())); return getSuperior(findById(menuDto.getPid()), menus); } @Override public List<MenuDTO> buildTree(List<MenuDTO> menuDTOS) { List<MenuDTO> trees = new ArrayList<>(); Set<Long> ids = new HashSet<>(); for (MenuDTO menuDTO : menuDTOS) { if (menuDTO.getPid() == null) { trees.add(menuDTO); } for (MenuDTO it : menuDTOS) { if (menuDTO.getId().equals(it.getPid())) { if (menuDTO.getChildren() == null) { menuDTO.setChildren(new ArrayList<>()); } menuDTO.getChildren().add(it); ids.add(it.getId()); } } } if (trees.size() == 0) { trees = menuDTOS.stream().filter(s -> !ids.contains(s.getId())).collect(Collectors.toList()); } return trees; } @Override
package com.dimple.modules.system.service.impl; /** * @className: MenuServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "menu") public class MenuServiceImpl implements MenuService { private final MenuRepository menuRepository; private final UserRepository userRepository; private final MenuMapper menuMapper; private final RoleService roleService; private final RedisUtils redisUtils; @Override public List<MenuDTO> queryAll(MenuQueryCriteria criteria, Boolean isQuery) throws Exception { Sort sort = new Sort(Sort.Direction.ASC, "menuSort"); if (isQuery) { criteria.setPidIsNull(true); List<Field> fields = QueryHelp.getAllFields(criteria.getClass(), new ArrayList<>()); for (Field field : fields) { //设置对象的访问权限,保证对private的属性的访问 field.setAccessible(true); Object val = field.get(criteria); if ("pidIsNull".equals(field.getName())) { continue; } if (ObjectUtil.isNotNull(val)) { criteria.setPidIsNull(null); break; } } } return menuMapper.toDto(menuRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), sort)); } @Override // @Cacheable(key = "'id:' + #p0") public MenuDTO findById(long id) { Menu menu = menuRepository.findById(id).orElseGet(Menu::new); ValidationUtil.isNull(menu.getId(), "Menu", "id", id); return menuMapper.toDto(menu); } /** * 用户角色改变时需清理缓存 * * @param currentUserId / * @return / */ @Override // @Cacheable(key = "'user:' + #p0") public List<MenuDTO> findByUser(Long currentUserId) { LinkedHashSet<Menu> menus; if (Objects.equals(currentUserId, 1L)) { //todo if current user id admin,get all permission for it. menus = menuRepository.findByTypeNot(2); } else { List<RoleSmallDTO> roles = roleService.findByUsersId(currentUserId); Set<Long> roleIds = roles.stream().map(RoleSmallDTO::getId).collect(Collectors.toSet()); menus= menuRepository.findByRoleIdsAndTypeNot(roleIds, 2); } return menus.stream().map(menuMapper::toDto).collect(Collectors.toList()); } @Override @Transactional(rollbackFor = Exception.class) public void create(Menu resources) { if (menuRepository.findByTitle(resources.getTitle()) != null) { throw new EntityExistException(Menu.class, "title", resources.getTitle()); } if (StringUtils.isNotBlank(resources.getComponentName())) { if (menuRepository.findByComponentName(resources.getComponentName()) != null) { throw new EntityExistException(Menu.class, "componentName", resources.getComponentName()); } } if (resources.getPid().equals(0L)) { resources.setPid(null); } if (resources.getIFrame()) { String http = "http://", https = "https://"; if (!(resources.getPath().toLowerCase().startsWith(http) || resources.getPath().toLowerCase().startsWith(https))) { throw new BadRequestException("外链必须以http://或者https://开头"); } } menuRepository.save(resources); // 计算子节点数目 resources.setSubCount(0); // 更新父节点菜单数目 updateSubCnt(resources.getPid()); redisUtils.del("menu::pid:" + (resources.getPid() == null ? 0 : resources.getPid())); } @Override @Transactional(rollbackFor = Exception.class) public void update(Menu resources) { if (resources.getId().equals(resources.getPid())) { throw new BadRequestException("上级不能为自己"); } Menu menu = menuRepository.findById(resources.getId()).orElseGet(Menu::new); ValidationUtil.isNull(menu.getId(), "Permission", "id", resources.getId()); if (resources.getIFrame()) { String http = "http://", https = "https://"; if (!(resources.getPath().toLowerCase().startsWith(http) || resources.getPath().toLowerCase().startsWith(https))) { throw new BadRequestException("外链必须以http://或者https://开头"); } } Menu menu1 = menuRepository.findByTitle(resources.getTitle()); if (menu1 != null && !menu1.getId().equals(menu.getId())) { throw new EntityExistException(Menu.class, "title", resources.getTitle()); } if (resources.getPid().equals(0L)) { resources.setPid(null); } // 记录的父节点ID Long oldPid = menu.getPid(); Long newPid = resources.getPid(); if (StringUtils.isNotBlank(resources.getComponentName())) { menu1 = menuRepository.findByComponentName(resources.getComponentName()); if (menu1 != null && !menu1.getId().equals(menu.getId())) { throw new EntityExistException(Menu.class, "componentName", resources.getComponentName()); } } menu.setTitle(resources.getTitle()); menu.setComponent(resources.getComponent()); menu.setPath(resources.getPath()); menu.setIcon(resources.getIcon()); menu.setIFrame(resources.getIFrame()); menu.setPid(resources.getPid()); menu.setMenuSort(resources.getMenuSort()); menu.setCache(resources.getCache()); menu.setHidden(resources.getHidden()); menu.setComponentName(resources.getComponentName()); menu.setPermission(resources.getPermission()); menu.setType(resources.getType()); menuRepository.save(menu); // 计算父级菜单节点数目 updateSubCnt(oldPid); updateSubCnt(newPid); // 清理缓存 delCaches(resources.getId(), oldPid, newPid); } @Override public Set<Menu> getDeleteMenus(List<Menu> menuList, Set<Menu> menuSet) { // 递归找出待删除的菜单 for (Menu menu1 : menuList) { menuSet.add(menu1); List<Menu> menus = menuRepository.findByPid(menu1.getId()); if (menus != null && menus.size() != 0) { getDeleteMenus(menus, menuSet); } } return menuSet; } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Menu> menuSet) { for (Menu menu : menuSet) { // 清理缓存 delCaches(menu.getId(), menu.getPid(), null); roleService.untiedMenu(menu.getId()); menuRepository.deleteById(menu.getId()); updateSubCnt(menu.getPid()); } } @Override @Cacheable(key = "'pid:' + #p0") public List<MenuDTO> getMenus(Long pid) { List<Menu> menus; if (pid != null && !pid.equals(0L)) { menus = menuRepository.findByPid(pid); } else { menus = menuRepository.findByPidIsNull(); } return menuMapper.toDto(menus); } @Override public List<MenuDTO> getSuperior(MenuDTO menuDto, List<Menu> menus) { if (menuDto.getPid() == null) { menus.addAll(menuRepository.findByPidIsNull()); return menuMapper.toDto(menus); } menus.addAll(menuRepository.findByPid(menuDto.getPid())); return getSuperior(findById(menuDto.getPid()), menus); } @Override public List<MenuDTO> buildTree(List<MenuDTO> menuDTOS) { List<MenuDTO> trees = new ArrayList<>(); Set<Long> ids = new HashSet<>(); for (MenuDTO menuDTO : menuDTOS) { if (menuDTO.getPid() == null) { trees.add(menuDTO); } for (MenuDTO it : menuDTOS) { if (menuDTO.getId().equals(it.getPid())) { if (menuDTO.getChildren() == null) { menuDTO.setChildren(new ArrayList<>()); } menuDTO.getChildren().add(it); ids.add(it.getId()); } } } if (trees.size() == 0) { trees = menuDTOS.stream().filter(s -> !ids.contains(s.getId())).collect(Collectors.toList()); } return trees; } @Override
public List<MenuVO> buildMenus(List<MenuDTO> menuDTOS) {
6
2023-11-10 03:30:36+00:00
24k
LazyCoder0101/LazyCoder
ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/component/operation/container/MainFormatContainer.java
[ { "identifier": "CodeFormatFlagParam", "path": "database/src/main/java/com/lazycoder/database/CodeFormatFlagParam.java", "snippet": "@NoArgsConstructor\n@Data\npublic class CodeFormatFlagParam implements BaseModel, DataFormatType {\n\n /**\n * 代码文件类型\n */\n private int formatType = MAIN_TY...
import com.lazycoder.database.CodeFormatFlagParam; import com.lazycoder.database.common.MarkElementName; import com.lazycoder.database.common.NotNamed; import com.lazycoder.database.model.MainInfo; import com.lazycoder.service.fileStructure.SourceGenerateFileStructure; import com.lazycoder.uicodegeneration.component.CodeGenerationFrameHolder; import com.lazycoder.uicodegeneration.component.operation.component.typeset.format.main.MainSetTypeFolder; import com.lazycoder.uicodegeneration.component.operation.container.component.FormatTypePane; import com.lazycoder.uicodegeneration.component.operation.container.sendparam.FormatOpratingContainerParam; import com.lazycoder.uicodegeneration.component.operation.container.sendparam.MainSetTypeOperatingContainerParam; import com.lazycoder.uicodegeneration.generalframe.codeshown.CodeShowPane; import com.lazycoder.uicodegeneration.proj.stostr.operation.base.AbstractOperatingContainerModel; import com.lazycoder.uicodegeneration.proj.stostr.operation.container.MainFormatContainerModel; import java.io.File; import java.util.ArrayList;
18,757
package com.lazycoder.uicodegeneration.component.operation.container; public class MainFormatContainer extends AbstractFormatContainer { /** * 宽度比例 */ protected static final double PROPOTION = 0.29; /** * */ private static final long serialVersionUID = -8299364698878473271L; private MainSetTypeFolder mainSetTypeFolder; private MainInfo mainInfo; /** * 新建 * * @param formatOpratingContainerParam * @param fileName * @param mainInfo */ public MainFormatContainer(FormatOpratingContainerParam formatOpratingContainerParam, String fileName, MainInfo mainInfo) { // TODO Auto-generated constructor stub super(); this.mainInfo = mainInfo; if (mainInfo.getFormatState() == MainInfo.TRUE_) { init(true, true, "格式", AbstractCommandOpratingContainer.PROPOTION); } else { init(false, true, "格式", AbstractCommandOpratingContainer.PROPOTION); } currentCodeFileName = fileName; this.formatOpratingContainerParam = formatOpratingContainerParam; generateOperationalContent(formatOpratingContainerParam); if (formatState == true) { MainSetTypeOperatingContainerParam mainSetTypeOperatingContainerParam = new MainSetTypeOperatingContainerParam(); mainSetTypeOperatingContainerParam.setFormatContainer(MainFormatContainer.this); mainSetTypeOperatingContainerParam .setFormatControlPane(formatOpratingContainerParam.getFormatControlPane()); mainSetTypeOperatingContainerParam.setMainInfo(mainInfo); mainSetTypeFolder = new MainSetTypeFolder(mainSetTypeOperatingContainerParam); formatTypePane.setInternalComponent(mainSetTypeFolder.getParentScrollPane()); } setAppropriateSize(); } /** * 还原 * * @param formatOpratingContainerParam * @param model */ public MainFormatContainer(FormatOpratingContainerParam formatOpratingContainerParam, MainFormatContainerModel model) { super(); this.formatOpratingContainerParam = formatOpratingContainerParam; this.mainInfo = model.getMainInfo(); if (model.isFormatState() == true) { init(true, true, "格式", AbstractCommandOpratingContainer.PROPOTION); } else if (model.isFormatState() == false) { init(false, true, "格式", AbstractCommandOpratingContainer.PROPOTION); } restoreContent(model, formatOpratingContainerParam); if (formatState == true) { MainSetTypeOperatingContainerParam mainSetTypeOperatingContainerParam = new MainSetTypeOperatingContainerParam(); mainSetTypeOperatingContainerParam.setFormatContainer(MainFormatContainer.this); mainSetTypeOperatingContainerParam .setFormatControlPane(formatOpratingContainerParam.getFormatControlPane()); mainSetTypeOperatingContainerParam.setMainInfo(this.mainInfo); mainSetTypeFolder = new MainSetTypeFolder(mainSetTypeOperatingContainerParam, model.getMainSetTypeFolderModel()); formatTypePane.setInternalComponent(mainSetTypeFolder.getParentScrollPane()); } setAppropriateSize(); } @Override public void delThis() { super.delThis(); if (formatState == true) { if (mainSetTypeFolder != null) { mainSetTypeFolder.delThis(); } } } @Override public ArrayList<CodeShowPane> getCodePaneList() { // TODO Auto-generated method stub ArrayList<CodeShowPane> list = new ArrayList<>();
package com.lazycoder.uicodegeneration.component.operation.container; public class MainFormatContainer extends AbstractFormatContainer { /** * 宽度比例 */ protected static final double PROPOTION = 0.29; /** * */ private static final long serialVersionUID = -8299364698878473271L; private MainSetTypeFolder mainSetTypeFolder; private MainInfo mainInfo; /** * 新建 * * @param formatOpratingContainerParam * @param fileName * @param mainInfo */ public MainFormatContainer(FormatOpratingContainerParam formatOpratingContainerParam, String fileName, MainInfo mainInfo) { // TODO Auto-generated constructor stub super(); this.mainInfo = mainInfo; if (mainInfo.getFormatState() == MainInfo.TRUE_) { init(true, true, "格式", AbstractCommandOpratingContainer.PROPOTION); } else { init(false, true, "格式", AbstractCommandOpratingContainer.PROPOTION); } currentCodeFileName = fileName; this.formatOpratingContainerParam = formatOpratingContainerParam; generateOperationalContent(formatOpratingContainerParam); if (formatState == true) { MainSetTypeOperatingContainerParam mainSetTypeOperatingContainerParam = new MainSetTypeOperatingContainerParam(); mainSetTypeOperatingContainerParam.setFormatContainer(MainFormatContainer.this); mainSetTypeOperatingContainerParam .setFormatControlPane(formatOpratingContainerParam.getFormatControlPane()); mainSetTypeOperatingContainerParam.setMainInfo(mainInfo); mainSetTypeFolder = new MainSetTypeFolder(mainSetTypeOperatingContainerParam); formatTypePane.setInternalComponent(mainSetTypeFolder.getParentScrollPane()); } setAppropriateSize(); } /** * 还原 * * @param formatOpratingContainerParam * @param model */ public MainFormatContainer(FormatOpratingContainerParam formatOpratingContainerParam, MainFormatContainerModel model) { super(); this.formatOpratingContainerParam = formatOpratingContainerParam; this.mainInfo = model.getMainInfo(); if (model.isFormatState() == true) { init(true, true, "格式", AbstractCommandOpratingContainer.PROPOTION); } else if (model.isFormatState() == false) { init(false, true, "格式", AbstractCommandOpratingContainer.PROPOTION); } restoreContent(model, formatOpratingContainerParam); if (formatState == true) { MainSetTypeOperatingContainerParam mainSetTypeOperatingContainerParam = new MainSetTypeOperatingContainerParam(); mainSetTypeOperatingContainerParam.setFormatContainer(MainFormatContainer.this); mainSetTypeOperatingContainerParam .setFormatControlPane(formatOpratingContainerParam.getFormatControlPane()); mainSetTypeOperatingContainerParam.setMainInfo(this.mainInfo); mainSetTypeFolder = new MainSetTypeFolder(mainSetTypeOperatingContainerParam, model.getMainSetTypeFolderModel()); formatTypePane.setInternalComponent(mainSetTypeFolder.getParentScrollPane()); } setAppropriateSize(); } @Override public void delThis() { super.delThis(); if (formatState == true) { if (mainSetTypeFolder != null) { mainSetTypeFolder.delThis(); } } } @Override public ArrayList<CodeShowPane> getCodePaneList() { // TODO Auto-generated method stub ArrayList<CodeShowPane> list = new ArrayList<>();
CodeShowPane deafaultPane = CodeGenerationFrameHolder.codeShowPanel.getMainDefaultCodeShowPane();
5
2023-11-16 11:55:06+00:00
24k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506/KSVentilation.java
[ { "identifier": "ByteArrayBuffer", "path": "app/src/main/java/kr/or/kashi/hde/base/ByteArrayBuffer.java", "snippet": "public final class ByteArrayBuffer {\n private static final int INITIAL_CAPACITY = 16;\n private static final int CAPACITY_INCREMENT = 8;\n\n private byte[] mBuffer;\n privat...
import android.util.Log; import kr.or.kashi.hde.base.ByteArrayBuffer; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.HomePacket; import kr.or.kashi.hde.MainContext; import kr.or.kashi.hde.HomeDevice; import kr.or.kashi.hde.device.Thermostat; import kr.or.kashi.hde.device.Ventilation; import kr.or.kashi.hde.ksx4506.KSDeviceContextBase; import kr.or.kashi.hde.ksx4506.KSPacket; import java.util.Map;
15,678
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /** * [KS X 4506] The ventilation implementation for Ventilation */ public class KSVentilation extends KSDeviceContextBase { private static final String TAG = "KSVentilation"; private static final boolean DBG = true; public static final int CMD_POWER_CONTROL_REQ = CMD_SINGLE_CONTROL_REQ; public static final int CMD_POWER_CONTROL_RSP = CMD_SINGLE_CONTROL_RSP; public static final int CMD_FAN_SPEED_CONTROL_REQ = 0x42; public static final int CMD_FAN_SPEED_CONTROL_RSP = 0xC2; public static final int CMD_MODE_CONTROL_REQ = 0x43; public static final int CMD_MODE_CONTROL_RSP = 0xC3; private int mMinFanSpeedLevel = 0; private int mMaxFanSpeedLevel = 5; public KSVentilation(MainContext mainContext, Map defaultProps) { super(mainContext, defaultProps, Ventilation.class); if (isMaster()) { // Register the tasks to be performed when specific property changes. setPropertyTask(HomeDevice.PROP_ONOFF, this::onPowerControlTask); setPropertyTask(Ventilation.PROP_CUR_FAN_SPEED, this::onFanSpeedControlTask); setPropertyTask(Ventilation.PROP_OPERATION_MODE, this::onModeControlTask); setPropertyTask(Ventilation.PROP_OPERATION_ALARM, this::onAlarmControlTask); } else { // TEMP: Initialize some properties as specific values in slave mode. long supportedModes = 0; supportedModes |= Ventilation.Mode.NORMAL; supportedModes |= Ventilation.Mode.SLEEP; supportedModes |= Ventilation.Mode.RECYCLE; supportedModes |= Ventilation.Mode.AUTO; supportedModes |= Ventilation.Mode.SAVING; supportedModes |= Ventilation.Mode.CLEANAIR; supportedModes |= Ventilation.Mode.INTERNAL; mRxPropertyMap.put(Ventilation.PROP_SUPPORTED_MODES, supportedModes); long supportedSensors = 0; supportedSensors |= Ventilation.Sensor.CO2; mRxPropertyMap.put(Ventilation.PROP_SUPPORTED_SENSORS, supportedSensors); mRxPropertyMap.put(Ventilation.PROP_OPERATION_MODE, Ventilation.Mode.NORMAL); mRxPropertyMap.put(Ventilation.PROP_OPERATION_ALARM, 0); mRxPropertyMap.put(Ventilation.PROP_CUR_FAN_SPEED, mMinFanSpeedLevel); mRxPropertyMap.put(Ventilation.PROP_MIN_FAN_SPEED, mMinFanSpeedLevel); mRxPropertyMap.put(Ventilation.PROP_MAX_FAN_SPEED, mMaxFanSpeedLevel); mRxPropertyMap.commit(); } } @Override protected int getCapabilities() { return CAP_STATUS_SINGLE | CAP_CHARAC_SINGLE; } @Override public @ParseResult int parsePayload(KSPacket packet, PropertyMap outProps) { // TODO: Use some new interface of parsing action. switch (packet.commandType) { case CMD_POWER_CONTROL_REQ: return parsePowerControlReq(packet, outProps); case CMD_FAN_SPEED_CONTROL_REQ: return parseFanSpeedControlReq(packet, outProps); case CMD_MODE_CONTROL_REQ: return parseModeControlReq(packet, outProps); case CMD_POWER_CONTROL_RSP: case CMD_FAN_SPEED_CONTROL_RSP: case CMD_MODE_CONTROL_RSP: { return parseSingleControlRsp(packet, outProps); } } return super.parsePayload(packet, outProps); } @Override protected @ParseResult int parseStatusReq(KSPacket packet, PropertyMap outProps) { // No data to parse from request packet. final PropertyMap props = getReadPropertyMap();
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /** * [KS X 4506] The ventilation implementation for Ventilation */ public class KSVentilation extends KSDeviceContextBase { private static final String TAG = "KSVentilation"; private static final boolean DBG = true; public static final int CMD_POWER_CONTROL_REQ = CMD_SINGLE_CONTROL_REQ; public static final int CMD_POWER_CONTROL_RSP = CMD_SINGLE_CONTROL_RSP; public static final int CMD_FAN_SPEED_CONTROL_REQ = 0x42; public static final int CMD_FAN_SPEED_CONTROL_RSP = 0xC2; public static final int CMD_MODE_CONTROL_REQ = 0x43; public static final int CMD_MODE_CONTROL_RSP = 0xC3; private int mMinFanSpeedLevel = 0; private int mMaxFanSpeedLevel = 5; public KSVentilation(MainContext mainContext, Map defaultProps) { super(mainContext, defaultProps, Ventilation.class); if (isMaster()) { // Register the tasks to be performed when specific property changes. setPropertyTask(HomeDevice.PROP_ONOFF, this::onPowerControlTask); setPropertyTask(Ventilation.PROP_CUR_FAN_SPEED, this::onFanSpeedControlTask); setPropertyTask(Ventilation.PROP_OPERATION_MODE, this::onModeControlTask); setPropertyTask(Ventilation.PROP_OPERATION_ALARM, this::onAlarmControlTask); } else { // TEMP: Initialize some properties as specific values in slave mode. long supportedModes = 0; supportedModes |= Ventilation.Mode.NORMAL; supportedModes |= Ventilation.Mode.SLEEP; supportedModes |= Ventilation.Mode.RECYCLE; supportedModes |= Ventilation.Mode.AUTO; supportedModes |= Ventilation.Mode.SAVING; supportedModes |= Ventilation.Mode.CLEANAIR; supportedModes |= Ventilation.Mode.INTERNAL; mRxPropertyMap.put(Ventilation.PROP_SUPPORTED_MODES, supportedModes); long supportedSensors = 0; supportedSensors |= Ventilation.Sensor.CO2; mRxPropertyMap.put(Ventilation.PROP_SUPPORTED_SENSORS, supportedSensors); mRxPropertyMap.put(Ventilation.PROP_OPERATION_MODE, Ventilation.Mode.NORMAL); mRxPropertyMap.put(Ventilation.PROP_OPERATION_ALARM, 0); mRxPropertyMap.put(Ventilation.PROP_CUR_FAN_SPEED, mMinFanSpeedLevel); mRxPropertyMap.put(Ventilation.PROP_MIN_FAN_SPEED, mMinFanSpeedLevel); mRxPropertyMap.put(Ventilation.PROP_MAX_FAN_SPEED, mMaxFanSpeedLevel); mRxPropertyMap.commit(); } } @Override protected int getCapabilities() { return CAP_STATUS_SINGLE | CAP_CHARAC_SINGLE; } @Override public @ParseResult int parsePayload(KSPacket packet, PropertyMap outProps) { // TODO: Use some new interface of parsing action. switch (packet.commandType) { case CMD_POWER_CONTROL_REQ: return parsePowerControlReq(packet, outProps); case CMD_FAN_SPEED_CONTROL_REQ: return parseFanSpeedControlReq(packet, outProps); case CMD_MODE_CONTROL_REQ: return parseModeControlReq(packet, outProps); case CMD_POWER_CONTROL_RSP: case CMD_FAN_SPEED_CONTROL_RSP: case CMD_MODE_CONTROL_RSP: { return parseSingleControlRsp(packet, outProps); } } return super.parsePayload(packet, outProps); } @Override protected @ParseResult int parseStatusReq(KSPacket packet, PropertyMap outProps) { // No data to parse from request packet. final PropertyMap props = getReadPropertyMap();
final ByteArrayBuffer data = new ByteArrayBuffer();
0
2023-11-10 01:19:44+00:00
24k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/ui/pluginMenu/PluginMenu.java
[ { "identifier": "ScreenWidget", "path": "src/main/java/io/xlorey/FluxLoader/client/ui/ScreenWidget.java", "snippet": "public class ScreenWidget implements IWidget {\n /**\n * Flag indicating whether the mouse cursor is inside the widget\n */\n private boolean isWidgetHovered = false;\n\n ...
import imgui.ImGui; import imgui.flag.ImGuiCol; import imgui.flag.ImGuiStyleVar; import imgui.flag.ImGuiWindowFlags; import imgui.type.ImBoolean; import io.xlorey.FluxLoader.client.ui.ScreenWidget; import io.xlorey.FluxLoader.interfaces.IControlsWidget; import io.xlorey.FluxLoader.plugin.Metadata; import io.xlorey.FluxLoader.plugin.Plugin; import io.xlorey.FluxLoader.shared.PluginManager; import io.xlorey.FluxLoader.utils.Constants; import zombie.GameWindow; import zombie.core.textures.Texture; import zombie.gameStates.MainScreenState; import java.util.HashSet; import java.util.List; import java.util.Map;
18,698
package io.xlorey.FluxLoader.client.ui.pluginMenu; /** * Plugin management menu */ public class PluginMenu extends ScreenWidget { /** * Flag indicating whether the window is open */ private static final ImBoolean isOpened = new ImBoolean(false); /** * ID of the selected plugin in the menu */ private String selectedPluginId; /** * Loaded client plugins */
package io.xlorey.FluxLoader.client.ui.pluginMenu; /** * Plugin management menu */ public class PluginMenu extends ScreenWidget { /** * Flag indicating whether the window is open */ private static final ImBoolean isOpened = new ImBoolean(false); /** * ID of the selected plugin in the menu */ private String selectedPluginId; /** * Loaded client plugins */
private final Map<String, Plugin> loadedPlugins = PluginManager.getLoadedClientPlugins();
4
2023-11-16 09:05:44+00:00
24k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/events/listeners/SkyblockDamageListener.java
[ { "identifier": "SkyBlock", "path": "src/main/java/com/sweattypalms/skyblock/SkyBlock.java", "snippet": "public final class SkyBlock extends JavaPlugin {\n\n private static SkyBlock instance;\n\n public static SkyBlock getInstance() {\n return instance;\n }\n\n public boolean debug = ...
import com.sweattypalms.skyblock.SkyBlock; import com.sweattypalms.skyblock.core.enchants.EnchantManager; import com.sweattypalms.skyblock.core.events.def.SkyblockMobDamagePlayerEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockPlayerDamageEntityEvent; import com.sweattypalms.skyblock.core.helpers.DamageCalculator; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.abilities.IHasAbility; import com.sweattypalms.skyblock.core.items.builder.abilities.types.DamageAbility; import com.sweattypalms.skyblock.core.items.builder.abilities.types.FullSetBonus; import com.sweattypalms.skyblock.core.items.builder.abilities.types.ITriggerableAbility; import com.sweattypalms.skyblock.core.mobs.builder.MobAttributes; import com.sweattypalms.skyblock.core.mobs.builder.SkyblockMob; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.scheduler.BukkitRunnable;
14,583
package com.sweattypalms.skyblock.core.events.listeners; public class SkyblockDamageListener implements Listener { /** * This event should only be used for damage calculation. * CALLED FASTEST * * @param event SkyblockPlayerDamageEntityEvent */ @EventHandler(priority = EventPriority.LOWEST) public void onSkyblockPlayerDamageEntityDamageCalculation(SkyblockPlayerDamageEntityEvent event) { if (event.isCancelled()) return; if (event.getSkyblockMob() == null) return; EnchantManager.run(event.getPlayer(), event); // Item Abilities (Item in hand) SkyblockItem item = event.getSkyblockPlayer().getInventoryManager().getSkyblockItemInHand(); if (item instanceof IHasAbility iHasAbility) { iHasAbility.getAbilities().forEach(ability -> { if (!(ability instanceof ITriggerableAbility triggerable)) return; boolean isDamageAbility = ability instanceof DamageAbility; isDamageAbility = isDamageAbility && ((DamageAbility) ability).preCalc(); boolean shouldTrigger = triggerable.trigger(event) && isDamageAbility; if (shouldTrigger) { ability.apply(event); } }); } // Full Set Bonus FullSetBonus fullSetBonus = event.getSkyblockPlayer().getInventoryManager().getEquippedFullSetBonus(); if (fullSetBonus != null) { // Not checking for trigger because it is already checked in getEquippedFullSetBonus() through isFullSetEquipped() fullSetBonus.apply(event); } double damage; if (event.getDamageType() == SkyblockPlayerDamageEntityEvent.DamageType.ABILITY) { damage = DamageCalculator.calculateAbilityDamage(event); } else { damage = DamageCalculator.calculateNormalDamage(event); } event.setDamage(damage); // System.out.printf( // "Player %s damaged %s for %s damage%n", // event.getPlayer().getName(), // event.getEntity().getType(), // event.getDamage() // ); } @EventHandler public void onSkyblockPlayerDamageEntity(SkyblockPlayerDamageEntityEvent event) { if (event.isCancelled()) return; if (event.getSkyblockMob() == null) return; SkyblockMob skyblockMob = event.getSkyblockMob(); double damage = event.getDamage(); // System.out.printf( // "Player %s damaged %s for %s damage%n", // event.getPlayer().getName(), // event.getEntity().getType(), // event.getDamage() // ); event.setPreCalc(false); EnchantManager.run(event.getPlayer(), event); // Item Abilities SkyblockItem item = event.getSkyblockPlayer().getInventoryManager().getSkyblockItemInHand(); if (item instanceof IHasAbility iHasAbility) { iHasAbility.getAbilities().forEach(ability -> { if (!(ability instanceof ITriggerableAbility triggerable)) return; boolean isDamageAbility = ability instanceof DamageAbility; isDamageAbility = isDamageAbility && !((DamageAbility) ability).preCalc(); boolean shouldTrigger = triggerable.trigger(event) && isDamageAbility; if (shouldTrigger) { ability.apply(event); } }); } skyblockMob.damageEntityWithCause(event); if(event.getDamageType() == SkyblockPlayerDamageEntityEvent.DamageType.ABILITY && !event.isApplyFerocityOnAbility()) return; /* ------- FEROCITY ------- */
package com.sweattypalms.skyblock.core.events.listeners; public class SkyblockDamageListener implements Listener { /** * This event should only be used for damage calculation. * CALLED FASTEST * * @param event SkyblockPlayerDamageEntityEvent */ @EventHandler(priority = EventPriority.LOWEST) public void onSkyblockPlayerDamageEntityDamageCalculation(SkyblockPlayerDamageEntityEvent event) { if (event.isCancelled()) return; if (event.getSkyblockMob() == null) return; EnchantManager.run(event.getPlayer(), event); // Item Abilities (Item in hand) SkyblockItem item = event.getSkyblockPlayer().getInventoryManager().getSkyblockItemInHand(); if (item instanceof IHasAbility iHasAbility) { iHasAbility.getAbilities().forEach(ability -> { if (!(ability instanceof ITriggerableAbility triggerable)) return; boolean isDamageAbility = ability instanceof DamageAbility; isDamageAbility = isDamageAbility && ((DamageAbility) ability).preCalc(); boolean shouldTrigger = triggerable.trigger(event) && isDamageAbility; if (shouldTrigger) { ability.apply(event); } }); } // Full Set Bonus FullSetBonus fullSetBonus = event.getSkyblockPlayer().getInventoryManager().getEquippedFullSetBonus(); if (fullSetBonus != null) { // Not checking for trigger because it is already checked in getEquippedFullSetBonus() through isFullSetEquipped() fullSetBonus.apply(event); } double damage; if (event.getDamageType() == SkyblockPlayerDamageEntityEvent.DamageType.ABILITY) { damage = DamageCalculator.calculateAbilityDamage(event); } else { damage = DamageCalculator.calculateNormalDamage(event); } event.setDamage(damage); // System.out.printf( // "Player %s damaged %s for %s damage%n", // event.getPlayer().getName(), // event.getEntity().getType(), // event.getDamage() // ); } @EventHandler public void onSkyblockPlayerDamageEntity(SkyblockPlayerDamageEntityEvent event) { if (event.isCancelled()) return; if (event.getSkyblockMob() == null) return; SkyblockMob skyblockMob = event.getSkyblockMob(); double damage = event.getDamage(); // System.out.printf( // "Player %s damaged %s for %s damage%n", // event.getPlayer().getName(), // event.getEntity().getType(), // event.getDamage() // ); event.setPreCalc(false); EnchantManager.run(event.getPlayer(), event); // Item Abilities SkyblockItem item = event.getSkyblockPlayer().getInventoryManager().getSkyblockItemInHand(); if (item instanceof IHasAbility iHasAbility) { iHasAbility.getAbilities().forEach(ability -> { if (!(ability instanceof ITriggerableAbility triggerable)) return; boolean isDamageAbility = ability instanceof DamageAbility; isDamageAbility = isDamageAbility && !((DamageAbility) ability).preCalc(); boolean shouldTrigger = triggerable.trigger(event) && isDamageAbility; if (shouldTrigger) { ability.apply(event); } }); } skyblockMob.damageEntityWithCause(event); if(event.getDamageType() == SkyblockPlayerDamageEntityEvent.DamageType.ABILITY && !event.isApplyFerocityOnAbility()) return; /* ------- FEROCITY ------- */
int ferocity = event.getSkyblockPlayer().getStatsManager().getMaxStats().get(Stats.FEROCITY).intValue();
12
2023-11-15 15:05:58+00:00
24k
Hikaito/Fox-Engine
src/system/gui/editorPane/GuiFieldControls.java
[ { "identifier": "Program", "path": "src/system/Program.java", "snippet": "public class Program {\n\n //region initialization------------------------------------------\n\n // \"global\" variables\n private static UserSetting userSetting;\n private static MainWindow window;\n private static...
import system.Program; import system.gui.GuiOperations; import system.layerTree.data.LayerManager; import system.layerTree.data.SelectionManager; import system.layerTree.data.Folder; import system.layerTree.data.Layer; import system.layerTree.data.LayerCore; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
14,434
} catch(Exception ee){ alphaInput.setValue(layer.getAlpha()); } // Program.redrawAllRegions(); } }); alphaInput.setColumns(3); return alphaPanel; } //endregion //endregion //region layer only manipulation ======================================== //region color ------------------------------ //generate color toggle for layer public static JCheckBox makeColorToggle(Layer layer){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("use color", layer.getUseColor()); //on selection, toggle using original color clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setUseColor()); layer.setUseColor(); //Program.redrawAllRegions(); //redraw editor and canvas } }); return clipBox; } //add color chooser to field (and helper) public static void addColorChooser(JPanel innerField, Layer layer){addColorChooser(innerField, 1, Color.BLACK, layer);} //text positions: 0 = none, 1 = left, 2 = right public static void addColorChooser(JPanel innerField, int textPosition, Color textColor, Layer layer){ //create button with image color JButton colorButton = new JButton(" "); colorButton.setBackground(layer.getColor()); //set color //make label for color text NOTE: text field is selectable JTextField colorLabel = new JTextField(GuiOperations.formatColor(layer.getColor())); //get color label from unit color colorLabel.setEditable(false); colorLabel.setForeground(textColor); //set text color to make it visible on darker bg //positioning of text switch(textPosition){ //no text case 0: innerField.add(colorButton); break; //text to left case 1: innerField.add(colorButton); innerField.add(colorLabel); break; //text to right case 2: innerField.add(colorLabel); innerField.add(colorButton); break; } //on button click, change color colorButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ //FIXME the show dialogue creates a new window, but it disregards any custom works. To do: rework so only HSV pane //FIXME generates an error now when exiting from the color selector without making a selection //Collect color from color selection dialogue; resets layer color Color selection = JColorChooser.showDialog(null,"Select a color", layer.getColor()); //System.out.println(selection); //if color was a color, alter color choices if(selection == null) return; //Program.addUndo(layer.setColor(selection)); layer.setColor(selection); //process color change in GUI colorButton.setBackground(layer.getColor()); //reset color for button colorLabel.setText(GuiOperations.formatColor(layer.getColor())); //reset color label innerField.revalidate(); //repaint Program.redrawAllRegions(); //redraw canvas } }); } //endregion //region file loading------------------------ // load file as layer: open file selection dialogue public static JButton loadFileAsLayerButton(Layer layer){ // pick text String text = "Pick File"; //button JButton buttonOut = new JButton(text); //generate button buttonOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //open editor Program.selectFileFromProject(layer); } }); return buttonOut; } //endregion //endregion //region folder only manipulation ======================================== //region children expansion ------------------------------ //generate button to toggle expansion of children layer visibility [folder]
package system.gui.editorPane; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== // field controls for Layer objects public class GuiFieldControls { //region core unit manipulation ======================================== //region clone and delete-------------------------------------- //add delete button: adds deletion button to field public static JButton makeDelete(LayerCore layer){ //add button JButton button = new JButton("delete"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.deleteTreeUnit(layer, false); } }); return button; } //add delete all button: adds deletion of children button to field public static JButton makeDeleteAll(LayerCore layer){ //add button JButton button = new JButton("delete (deep)"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.deleteTreeUnit(layer, true); } }); return button; } //add duplicate button public static JButton makeDuplicate(LayerCore layer){ //add button JButton button = new JButton("clone"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.duplicateTreeUnit(layer); } }); return button; } //endregion //region movement control --------------------------- //function for adding location controls to panel [adds buttons to field] public static void addLocationControls(JPanel innerField, LayerCore layer){ //generate panel for holding buttons JPanel buttonBox = new JPanel(); innerField.add(buttonBox); //add buttons for location movement----------- buttonBox.add(makeButtonOut(layer)); //register button buttonBox.add(makeButtonUp(layer)); //label for level //JLabel levelLabel = new JLabel("level " + 0); //fixme 0 was level //buttonBox.add(levelLabel); buttonBox.add(makeButtonDown(layer)); buttonBox.add(makeButtonIn(layer)); } //get button for in public static JButton makeButtonIn(LayerCore layer){ //in: button to signal moving deeper in hierarchy JButton buttonIn = new JButton("->"); buttonIn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.IN); } }); return buttonIn; } //get button for down public static JButton makeButtonDown(LayerCore layer){ //down: button to signal moving down in hierarchy JButton buttonDown = new JButton("v"); buttonDown.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.DOWN); } }); return buttonDown; } //get button for up public static JButton makeButtonUp(LayerCore layer){ //up: button to signal moving up in hierarchy JButton buttonUp = new JButton("^"); buttonUp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.UP); } }); return buttonUp; } ///get button for out public static JButton makeButtonOut(LayerCore layer){ //out: button to signal moving out of the hierarchy JButton buttonOut = new JButton("<-"); //generate button buttonOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.OUT); } }); return buttonOut; } //endregion //region selection --------------------------- // function for selection public static JButton makeSelectionButton(LayerCore layer){ // pick text String text = "Deselect"; // test for selection: selection type is select if not selected if (Program.checkSelection(layer) == SelectionManager.selectionPriority.NONE) text = "Select"; //out: button to signal moving out of the hierarchy JButton buttonOut = new JButton(text); //generate button buttonOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //check selection value // select if unselected if (Program.checkSelection(layer) == SelectionManager.selectionPriority.NONE) Program.addSelection(layer); //otherwise unselect if selected else Program.removeSelection(layer); //on click, move out in hierarchy Program.redrawLayerEditor(); //redraw layer map //Program.redrawLayerEditor(); //layer.signalRedraw(); //redraw canvas //fixme idk about this } }); return buttonOut; } //endregion //endregion //region common element manipulation ======================================== //region title------------------------ //generate title label public static JLabel makeTitle(LayerCore layer){ return new JLabel(layer.getTitle()); } // generate title text field public static JTextField makeTitleField(LayerCore layer){ JTextField title = new JTextField(10); //generate text field with preferred size title.setText(layer.getTitle()); // action title.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setTitle(title.getText())); layer.setTitle(title.getText()); Program.redrawLayerEditor(); } }); return title; } //endregion- //region clipping------------------------------- //add clipping toggle to field public static JCheckBox makeClippingToggle(LayerCore layer){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("clip", layer.getClipToParent()); //on selection, toggle clipping in layer clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setClipToParent()); layer.setClipToParent(); // Program.redrawAllRegions(); } }); return clipBox; } //generate clipping label public static JLabel makeClippingLabel(LayerCore layer){ if (layer.getClipToParent()) return new JLabel("clipped"); else return null; } //endregion //region visibility ---------------------- //make toggle to visibility public static JCheckBox makeVisibleToggle(LayerCore layer){ //create toggle; set value to existing values JCheckBox clipBox = new JCheckBox("Visible", layer.getVisible()); //on selection, toggle visibility clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setViewAlpha()); layer.setVisible(); //Program.redrawAllRegions(); //layer.signalRedraw(); //redraw canvas } }); return clipBox; } //endregion //region visibilty toggle button------------------------- //add duplicate button public static JButton makeVisibilityToggleButton(LayerCore layer){ // text String text; if (layer.getVisible() == false) text = "-"; else text = "\uD83D\uDC41"; //👁 //add button JButton button = new JButton(text); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ layer.setVisible(); //Program.redrawAllRegions(); } }); return button; } //endregion //region alpha ------------------------- //add alpha edit box public static JPanel makeAlpha(LayerCore layer){ //add alpha box JPanel alphaPanel = new JPanel(); //create field for alpha text entering with a label JFormattedTextField alphaInput = new JFormattedTextField(layer.getAlpha()); //creates field with default alpha JLabel alphaLabel = new JLabel("alpha"); //creates label alphaPanel.add(alphaLabel); alphaPanel.add(alphaInput); //when change is detected, adjust alpha alphaInput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //if input is valid, set input to alpha. Otherwise, set alpha to input. try{ //parse double; if a valid number, establish range Double input = Double.parseDouble(alphaInput.getText()); layer.setAlpha(input); //setAlpha performs validity checking //layer.signalRedraw(); //redraw canvas } catch(Exception ee){ alphaInput.setValue(layer.getAlpha()); } // Program.redrawAllRegions(); } }); alphaInput.setColumns(3); return alphaPanel; } //endregion //endregion //region layer only manipulation ======================================== //region color ------------------------------ //generate color toggle for layer public static JCheckBox makeColorToggle(Layer layer){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("use color", layer.getUseColor()); //on selection, toggle using original color clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setUseColor()); layer.setUseColor(); //Program.redrawAllRegions(); //redraw editor and canvas } }); return clipBox; } //add color chooser to field (and helper) public static void addColorChooser(JPanel innerField, Layer layer){addColorChooser(innerField, 1, Color.BLACK, layer);} //text positions: 0 = none, 1 = left, 2 = right public static void addColorChooser(JPanel innerField, int textPosition, Color textColor, Layer layer){ //create button with image color JButton colorButton = new JButton(" "); colorButton.setBackground(layer.getColor()); //set color //make label for color text NOTE: text field is selectable JTextField colorLabel = new JTextField(GuiOperations.formatColor(layer.getColor())); //get color label from unit color colorLabel.setEditable(false); colorLabel.setForeground(textColor); //set text color to make it visible on darker bg //positioning of text switch(textPosition){ //no text case 0: innerField.add(colorButton); break; //text to left case 1: innerField.add(colorButton); innerField.add(colorLabel); break; //text to right case 2: innerField.add(colorLabel); innerField.add(colorButton); break; } //on button click, change color colorButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ //FIXME the show dialogue creates a new window, but it disregards any custom works. To do: rework so only HSV pane //FIXME generates an error now when exiting from the color selector without making a selection //Collect color from color selection dialogue; resets layer color Color selection = JColorChooser.showDialog(null,"Select a color", layer.getColor()); //System.out.println(selection); //if color was a color, alter color choices if(selection == null) return; //Program.addUndo(layer.setColor(selection)); layer.setColor(selection); //process color change in GUI colorButton.setBackground(layer.getColor()); //reset color for button colorLabel.setText(GuiOperations.formatColor(layer.getColor())); //reset color label innerField.revalidate(); //repaint Program.redrawAllRegions(); //redraw canvas } }); } //endregion //region file loading------------------------ // load file as layer: open file selection dialogue public static JButton loadFileAsLayerButton(Layer layer){ // pick text String text = "Pick File"; //button JButton buttonOut = new JButton(text); //generate button buttonOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //open editor Program.selectFileFromProject(layer); } }); return buttonOut; } //endregion //endregion //region folder only manipulation ======================================== //region children expansion ------------------------------ //generate button to toggle expansion of children layer visibility [folder]
public static JCheckBox makeChildrenExpand(Folder layer){
4
2023-11-12 21:12:21+00:00
24k
ryosoraa/E-Rapor
src/main/java/com/erapor/erapor/service/UserServices.java
[ { "identifier": "ApiException", "path": "src/main/java/com/erapor/erapor/exception/ApiException.java", "snippet": "public class ApiException extends RuntimeException{\n public ApiException(String message) {\n super(message);\n }\n}" }, { "identifier": "AccountsDAO", "path": "src...
import com.erapor.erapor.exception.ApiException; import com.erapor.erapor.model.DAO.AccountsDAO; import com.erapor.erapor.model.DTO.RegisterDTO; import com.erapor.erapor.repository.AccountsRepository; import com.erapor.erapor.security.BCrypt; import jakarta.validation.ConstraintViolation; import jakarta.validation.ConstraintViolationException; import jakarta.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Set;
16,579
package com.erapor.erapor.service; @Service public class UserServices { @Autowired AccountsRepository accountsRepository; @Autowired Validator validator; @Transactional public void register(RegisterDTO registerDTO){ Set<ConstraintViolation<RegisterDTO>> constraintViolation = validator.validate(registerDTO); if(constraintViolation.isEmpty()){ throw new ConstraintViolationException(constraintViolation); } if(accountsRepository.findByEmail(registerDTO.getEmail())){ throw new ApiException("email already exist!"); }
package com.erapor.erapor.service; @Service public class UserServices { @Autowired AccountsRepository accountsRepository; @Autowired Validator validator; @Transactional public void register(RegisterDTO registerDTO){ Set<ConstraintViolation<RegisterDTO>> constraintViolation = validator.validate(registerDTO); if(constraintViolation.isEmpty()){ throw new ConstraintViolationException(constraintViolation); } if(accountsRepository.findByEmail(registerDTO.getEmail())){ throw new ApiException("email already exist!"); }
AccountsDAO accountsDAO = new AccountsDAO();
1
2023-11-11 19:40:43+00:00
24k
shizotoaster/thaumon
forge/src/main/java/jdlenl/thaumon/forge/datagen/ThaumonBlockLootTables.java
[ { "identifier": "ThaumonBlocks", "path": "common/src/main/java/jdlenl/thaumon/block/ThaumonBlocks.java", "snippet": "public class ThaumonBlocks {\n public static Supplier<Block> AMBER;\n public static Supplier<Block> AMBER_STAIRS;\n public static Supplier<Block> AMBER_SLAB;\n public static S...
import jdlenl.thaumon.block.ThaumonBlocks; import jdlenl.thaumon.block.forge.ThaumonBlocksImpl; import net.minecraft.block.Block; import net.minecraft.data.server.loottable.BlockLootTableGenerator; import net.minecraft.item.Item; import net.minecraft.resource.featuretoggle.FeatureFlags; import net.minecraft.resource.featuretoggle.FeatureSet; import net.minecraftforge.registries.RegistryObject; import java.util.Set;
14,589
package jdlenl.thaumon.forge.datagen; public class ThaumonBlockLootTables extends BlockLootTableGenerator { protected ThaumonBlockLootTables() { super(Set.of(), FeatureFlags.FEATURE_MANAGER.getFeatureSet()); } @Override protected void generate() {
package jdlenl.thaumon.forge.datagen; public class ThaumonBlockLootTables extends BlockLootTableGenerator { protected ThaumonBlockLootTables() { super(Set.of(), FeatureFlags.FEATURE_MANAGER.getFeatureSet()); } @Override protected void generate() {
this.addDrop(ThaumonBlocks.AMBER.get());
0
2023-11-16 06:03:29+00:00
24k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/predictionengine/movementtick/MovementTickerHorse.java
[ { "identifier": "GrimPlayer", "path": "src/main/java/ac/grim/grimac/player/GrimPlayer.java", "snippet": "public class GrimPlayer {\n public final UUID playerUUID;\n public final int entityID;\n public final Player bukkitPlayer;\n // Determining player ping\n // The difference between keep...
import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.utils.data.packetentity.PacketEntityHorse; import ac.grim.grimac.utils.nmsutil.Collisions; import ac.grim.grimac.utils.nmsutil.JumpPower; import io.github.retrooper.packetevents.utils.player.ClientVersion; import org.bukkit.util.Vector;
14,779
package ac.grim.grimac.predictionengine.movementtick; public class MovementTickerHorse extends MovementTickerLivingVehicle { public MovementTickerHorse(GrimPlayer player) { super(player);
package ac.grim.grimac.predictionengine.movementtick; public class MovementTickerHorse extends MovementTickerLivingVehicle { public MovementTickerHorse(GrimPlayer player) { super(player);
PacketEntityHorse horsePacket = (PacketEntityHorse) player.playerVehicle;
1
2023-11-11 05:14:12+00:00
24k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/fragment/HomeFragment.java
[ { "identifier": "DataBaseHelper", "path": "app/src/main/java/com/buaa/food/DataBaseHelper.java", "snippet": "public class DataBaseHelper extends SQLiteOpenHelper {\n private static final String DB_NAME = \"BuaaFood.db\";\n private Context context;\n\n private ByteArrayOutputStream byteArrayOutp...
import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import androidx.appcompat.widget.AppCompatImageView; import androidx.appcompat.widget.AppCompatTextView; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import com.buaa.food.DataBaseHelper; import com.buaa.food.DishPreview; import com.buaa.food.http.glide.GlideApp; import com.buaa.food.ui.activity.DishDetailActivity; import com.bumptech.glide.load.MultiTransformation; import com.bumptech.glide.load.resource.bitmap.CenterCrop; import com.bumptech.glide.load.resource.bitmap.CenterInside; import com.gyf.immersionbar.ImmersionBar; import com.hjq.base.FragmentPagerAdapter; import com.buaa.food.R; import com.buaa.food.app.AppFragment; import com.buaa.food.app.TitleBarFragment; import com.buaa.food.ui.activity.HomeActivity; import com.buaa.food.ui.adapter.TabAdapter; import com.buaa.food.widget.XCollapsingToolbarLayout; import com.umeng.commonsdk.debug.D; import java.util.ArrayList; import java.util.List; import java.util.Random; import timber.log.Timber;
21,115
package com.buaa.food.ui.fragment; public final class HomeFragment extends TitleBarFragment<HomeActivity> implements TabAdapter.OnTabListener, ViewPager.OnPageChangeListener, XCollapsingToolbarLayout.OnScrimsListener { private XCollapsingToolbarLayout mCollapsingToolbarLayout; private Toolbar mToolbar; private TextView mHintView; private RecyclerView mTabView; private ViewPager mViewPager; private TabAdapter mTabAdapter; private FragmentPagerAdapter<AppFragment<?>> mPagerAdapter;
package com.buaa.food.ui.fragment; public final class HomeFragment extends TitleBarFragment<HomeActivity> implements TabAdapter.OnTabListener, ViewPager.OnPageChangeListener, XCollapsingToolbarLayout.OnScrimsListener { private XCollapsingToolbarLayout mCollapsingToolbarLayout; private Toolbar mToolbar; private TextView mHintView; private RecyclerView mTabView; private ViewPager mViewPager; private TabAdapter mTabAdapter; private FragmentPagerAdapter<AppFragment<?>> mPagerAdapter;
private DataBaseHelper dataBaseHelper;
0
2023-11-14 10:04:26+00:00
24k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/block/processed/BlockModel.java
[ { "identifier": "ModelHelper", "path": "src/main/java/useless/dragonfly/helper/ModelHelper.java", "snippet": "public class ModelHelper {\n\tpublic static final Map<NamespaceId, ModelData> modelDataFiles = new HashMap<>();\n\tpublic static final Map<NamespaceId, BlockModel> registeredModels = new HashMap...
import useless.dragonfly.helper.ModelHelper; import useless.dragonfly.model.block.data.ModelData; import useless.dragonfly.model.block.data.PositionData; import useless.dragonfly.registries.TextureRegistry; import useless.dragonfly.utilities.NamespaceId; import javax.annotation.Nonnull; import java.util.HashMap;
16,148
package useless.dragonfly.model.block.processed; public class BlockModel { private static final HashMap<String, PositionData> defaultDisplays = new HashMap<>(); static { PositionData gui = new PositionData(); gui.rotation = new double[]{30, 225, 0}; gui.translation = new double[] {0, 0, 0}; gui.scale = new double[]{0.625, 0.625, 0.625}; PositionData ground = new PositionData(); ground.rotation = new double[]{0, 0, 0}; ground.translation = new double[] {0, 3, 0}; ground.scale = new double[]{0.25, 0.25, 0.25}; PositionData right_3rd = new PositionData(); right_3rd.rotation = new double[]{75, 45, 0}; right_3rd.translation = new double[] {0, 2.5, 0}; right_3rd.scale = new double[]{0.375, 0.375, 0.375}; PositionData right_first = new PositionData(); right_first.rotation = new double[]{0, 45, 0}; right_first.translation = new double[] {0, 0, 0}; right_first.scale = new double[]{0.4, 0.4, 0.4}; defaultDisplays.put("gui", gui); defaultDisplays.put("ground", ground); defaultDisplays.put("thirdperson_righthand", right_3rd); defaultDisplays.put("firstperson_righthand", right_first); } public BlockCube[] blockCubes = new BlockCube[0]; protected ModelData modelData; protected BlockModel parentModel; public HashMap<String, String> textureMap; public HashMap<String, PositionData> display;
package useless.dragonfly.model.block.processed; public class BlockModel { private static final HashMap<String, PositionData> defaultDisplays = new HashMap<>(); static { PositionData gui = new PositionData(); gui.rotation = new double[]{30, 225, 0}; gui.translation = new double[] {0, 0, 0}; gui.scale = new double[]{0.625, 0.625, 0.625}; PositionData ground = new PositionData(); ground.rotation = new double[]{0, 0, 0}; ground.translation = new double[] {0, 3, 0}; ground.scale = new double[]{0.25, 0.25, 0.25}; PositionData right_3rd = new PositionData(); right_3rd.rotation = new double[]{75, 45, 0}; right_3rd.translation = new double[] {0, 2.5, 0}; right_3rd.scale = new double[]{0.375, 0.375, 0.375}; PositionData right_first = new PositionData(); right_first.rotation = new double[]{0, 45, 0}; right_first.translation = new double[] {0, 0, 0}; right_first.scale = new double[]{0.4, 0.4, 0.4}; defaultDisplays.put("gui", gui); defaultDisplays.put("ground", ground); defaultDisplays.put("thirdperson_righthand", right_3rd); defaultDisplays.put("firstperson_righthand", right_first); } public BlockCube[] blockCubes = new BlockCube[0]; protected ModelData modelData; protected BlockModel parentModel; public HashMap<String, String> textureMap; public HashMap<String, PositionData> display;
public final NamespaceId namespaceId;
4
2023-11-16 01:10:52+00:00
24k
Shushandr/offroad
src/net/sourceforge/offroad/actions/RemovePolylineAction.java
[ { "identifier": "Polyline", "path": "src/net/osmand/plus/views/DrawPolylineLayer.java", "snippet": "@XmlRootElement\npublic static class Polyline {\n\tprivate Vector<LatLon> mCoordinates = new Vector<>();\n\tpublic LatLon set(int pIndex, LatLon pElement) {\n\t\treturn mCoordinates.set(pIndex, pElement);...
import net.sourceforge.offroad.OsmWindow; import java.awt.event.ActionEvent; import net.osmand.plus.views.DrawPolylineLayer.Polyline;
19,087
/** OffRoad Copyright (C) 2017 Christian Foltin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.sourceforge.offroad.actions; /** * @author foltin * @date 19.05.2017 */ public class RemovePolylineAction extends OffRoadAction { private Polyline mPolyline;
/** OffRoad Copyright (C) 2017 Christian Foltin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.sourceforge.offroad.actions; /** * @author foltin * @date 19.05.2017 */ public class RemovePolylineAction extends OffRoadAction { private Polyline mPolyline;
public RemovePolylineAction(OsmWindow pContext, Polyline pPolyline) {
1
2023-11-15 05:04:55+00:00
24k
WuKongOpenSource/Wukong_HRM
common/common-field/src/main/java/com/kakarote/common/field/utils/EsUtil.java
[ { "identifier": "EsFieldTypeEnum", "path": "common/common-field/src/main/java/com/kakarote/common/field/constant/EsFieldTypeEnum.java", "snippet": "@Getter\npublic enum EsFieldTypeEnum {\n /**\n * 普通单行文本\n */\n KEYWORD(1),\n /**\n * 日期\n */\n DATE(2),\n /**\n * 数字\n ...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.ObjectUtil; import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch._types.*; import co.elastic.clients.elasticsearch._types.analysis.Normalizer; import co.elastic.clients.elasticsearch._types.mapping.*; import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery; import co.elastic.clients.elasticsearch._types.query_dsl.ChildScoreMode; import co.elastic.clients.elasticsearch._types.query_dsl.Query; import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders; import co.elastic.clients.elasticsearch.core.*; import co.elastic.clients.elasticsearch.core.bulk.BulkOperation; import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem; import co.elastic.clients.elasticsearch.indices.*; import co.elastic.clients.json.JsonData; import co.elastic.clients.transport.endpoints.BooleanResponse; import co.elastic.clients.util.ObjectBuilder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.util.TypeUtils; import com.kakarote.common.field.constant.EsFieldTypeEnum; import com.kakarote.common.field.constant.RangeTypeEnum; import com.kakarote.common.field.entity.FieldLabel; import com.kakarote.common.field.entity.RangeEntity; import com.kakarote.common.field.entity.SearchEntity; import com.kakarote.core.common.enums.FieldEnum; import com.kakarote.core.common.enums.FieldSearchEnum; import com.kakarote.core.common.enums.SystemCodeEnum; import com.kakarote.core.entity.ModuleSimpleFieldBO; import com.kakarote.core.entity.Search; import com.kakarote.core.exception.CrmException; import com.kakarote.core.feign.crm.entity.BiParams; import com.kakarote.core.servlet.ApplicationContextHolder; import com.kakarote.core.utils.BiTimeUtil; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors;
18,107
/** * 创建es排序 * * @param order 排序方式 * @param fields 排序字段 * @return */ public static SortOptions sort(SortOrder order, String... fields) { return SortOptionsBuilders.field(b -> { b.order(order); for (String field : fields) { b.field(field); } return b; }); } /** * QueryBuilders.nestedQuery */ public static Query nestedQuery(String path, Query query, ChildScoreMode scoreMode) { return QueryBuilders.nested(b -> { b.path(path); b.query(query); b.scoreMode(scoreMode); return b; }); } public static Query rangeQuery(String fieldName, List<RangeEntity> data) { return QueryBuilders.range(b -> { b.queryName(String.format("%sSize", fieldName)); for (RangeEntity rangeEntity : data) { switch (rangeEntity.getType()) { case GT: b.gt(JsonData.of(rangeEntity.getValue())); break; case GTE: b.gte(JsonData.of(rangeEntity.getValue())); break; case LT: b.lt(JsonData.of(rangeEntity.getValue())); break; case LTE: b.lte(JsonData.of(rangeEntity.getValue())); break; } } return b; }); } /** * QueryBuilders.rangeQuery */ public static Query rangeQuery(String fieldName, Object value, RangeTypeEnum rangeTypeEnum) { return QueryBuilders.range(b -> { b.queryName(String.format("%sSize", fieldName)); switch (rangeTypeEnum) { case GT: b.gt(JsonData.of(value)); break; case GTE: b.gte(JsonData.of(value)); break; case LT: b.lt(JsonData.of(value)); break; case LTE: b.lte(JsonData.of(value)); break; } return b; }); } /** * QueryBuilders.matchQuery */ public static Query matchQuery(String field, Object value) { return QueryBuilders.match(b -> { b.field(field); b.query(parseFieldValue(value)); return b; }); } /** * QueryBuilders.idsQuery */ public static Query idsQuery(List<?> value) { return QueryBuilders.ids(b -> { List<String> ids = value.stream().map(TypeUtils::castToString).collect(Collectors.toList()); b.values(ids); return b; }); } /** * QueryBuilders.idsQuery */ public static Query idsQuery(Object... value) { return QueryBuilders.ids(b -> { List<String> list = Arrays.stream(value).map(TypeUtils::castToString).collect(Collectors.toList()); b.values(list); return b; }); } /** * 追加搜索条件 * * @param search 搜索条件 * @param boolQuery boolQuery */
package com.kakarote.common.field.utils; /** * @author elasticSearch的一些通用操作 */ @Slf4j public class EsUtil { private static ElasticsearchClient client; /** * 获取ElasticsearchRestTemplate对象 * * @return ElasticsearchRestTemplate */ public static ElasticsearchClient getClient() { if (client == null) { synchronized (EsUtil.class) { client = ApplicationContextHolder.getBean(ElasticsearchClient.class); } } return client; } /** * 批量提交es数据 */ public static void bulk(List<Function<BulkOperation.Builder, ObjectBuilder<BulkOperation>>> operationList) { bulk(operationList, operationList.size()); } /** * 批量提交es数据 * * @param num 分批次提交,每次提交多少条 */ public static void bulk(List<Function<BulkOperation.Builder, ObjectBuilder<BulkOperation>>> operationList, int num) { if (operationList.isEmpty()) { return; } BulkRequest.Builder bulkRequest = new BulkRequest.Builder(); boolean submitted = false; int size = 0; for (Function<BulkOperation.Builder, ObjectBuilder<BulkOperation>> fn : operationList) { bulkRequest.operations(fn); size++; if (size % num == 0) { bulk(bulkRequest.build()); if (operationList.size() != size) { bulkRequest = new BulkRequest.Builder(); } else { submitted = true; break; } } } if (!submitted) { bulk(bulkRequest.build()); } } /** * 批量提交es数据 * * @param bulkRequest request */ public static void bulk(BulkRequest bulkRequest) { bulk(bulkRequest, 3); } /** * @param bulkRequest request * @param retryNum 重试次数 */ private static void bulk(BulkRequest bulkRequest, int retryNum) { if (bulkRequest == null || bulkRequest.operations().isEmpty()) { return; } try { BulkResponse responses = getClient().bulk(bulkRequest); if (responses.errors()) { Set<String> ids = new HashSet<>(); for (BulkResponseItem item : responses.items()) { //修改文档忽略404异常 if (Objects.equals(SystemCodeEnum.SYSTEM_NO_FOUND.getCode(), item.status())) { continue; } if (item.status() != 200 && item.error() != null) { ids.add(item.id()); if (retryNum == 0) { log.warn("bulk item error:{}", item.error()); } } } if (retryNum > 0) { BulkRequest.Builder builder = new BulkRequest.Builder(); boolean hasOperation = false; for (BulkOperation operation : bulkRequest.operations()) { String operationId = ""; if (operation.isCreate()) { operationId = operation.create().id(); } else if (operation.isIndex()) { operationId = operation.index().id(); } else if (operation.isUpdate()) { operationId = operation.update().id(); } else if (operation.isDelete()) { operationId = operation.delete().id(); } if (ids.contains(operationId)) { builder.operations(operation); hasOperation = true; } } if (hasOperation) { log.warn("批量提交es数据重试:{}", retryNum); bulk(builder.build(), --retryNum); } } } } catch (IOException e) { log.error("bulk异常", e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 获取BulkUpdateOperation */ public static Function<BulkOperation.Builder, ObjectBuilder<BulkOperation>> updateOperations(Object id, String index, Map<String, Object> map) { return updateOperations(id, index, map, false); } /** * 获取BulkUpdateOperation */ public static Function<BulkOperation.Builder, ObjectBuilder<BulkOperation>> updateOperations(Object id, String index, Map<String, Object> map, boolean docAsUpsert) { return setting -> { setting.update(i -> { i.id(id.toString()); i.index(index); i.action(acc -> { acc.doc(map); acc.docAsUpsert(docAsUpsert); return acc; }); return i; }); return setting; }; } /** * 获取BulkIndexOperation */ public static Function<BulkOperation.Builder, ObjectBuilder<BulkOperation>> indexOperations(Object id, String index, Object document) { return setting -> { setting.index(i -> { i.id(id.toString()); i.index(index); i.document(document); return i; }); return setting; }; } /** * 索引增加字段 * * @param fieldName 字段名 * @param property es字段类型 * @param fieldLabel 索引参数 */ public static void addField(String fieldName, Property property, FieldLabel fieldLabel) { try { Map<String, Property> object = Collections.singletonMap(fieldName, property); PutMappingRequest request = PutMappingRequest.of(setting -> { setting.index(fieldLabel.getIndex()); setting.properties(object); return setting; }); getClient().indices().putMapping(request); } catch (IOException e) { log.error("新增字段错误", e); throw new CrmException(SystemCodeEnum.SYSTEM_ERROR); } } /** * 项目默认的分词器 * * @return IndexSettingsAnalysis */ public static IndexSettingsAnalysis defaultAnalysis() { return IndexSettingsAnalysis.of(builder -> { builder.normalizer("lowercase_normalizer", new Normalizer.Builder().custom(normal -> { normal.charFilter(new ArrayList<>()); normal.filter("lowercase"); return normal; }).build()); return builder; }); } /** * 创建索引 * * @param mappingMap 字段参数 * @param fieldLabel 索引参数 */ public static void createIndex(Map<String, Property> mappingMap, IndexSettingsAnalysis settingsAnalysis, FieldLabel fieldLabel) { try { CreateIndexResponse createIndexResponse = getClient().indices().create(CreateIndexRequest.of(setting -> { setting.index(fieldLabel.getIndex()); setting.settings(settings -> { settings.numberOfShards("5"); settings.numberOfReplicas("0"); if (settingsAnalysis != null) { settings.analysis(settingsAnalysis); } return settings; }); if (fieldLabel.getAlias() != null) { setting.aliases(fieldLabel.getAlias(), Alias.of(alias -> alias)); } setting.mappings(mapping -> { mapping.properties(mappingMap); mapping.enabled(true); return mapping; }); return setting; })); if (createIndexResponse.acknowledged()) { log.info("创建索引成功,{}", fieldLabel.getIndex()); } else { log.error("创建索引失败,{},{}", fieldLabel.getIndex(), createIndexResponse); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } catch (IOException e) { log.error("创建索引失败,{}", fieldLabel.getIndex(), e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 索引是否存在 * * @param fieldLabel 索引名称 * @return true代表索引存在 */ public static boolean indexExist(FieldLabel fieldLabel) { try { BooleanResponse booleanResponse = getClient().indices().exists(i -> i.index(fieldLabel.getIndex())); return booleanResponse.value(); } catch (IOException e) { log.error("查询索引是否存在错误", e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 设置mapping */ public static void putMapping(Map<String, Property> mappingMap, FieldLabel fieldLabel) { try { getClient().indices().putMapping(p -> { p.index(fieldLabel.getIndex()); p.properties(mappingMap); return p; }); } catch (IOException e) { log.error("设置mapping错误", e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 获取mapping */ public static Map<String, Property> getMapping(FieldLabel fieldLabel) { try { GetMappingResponse mapping = getClient().indices().getMapping(p -> { p.index(fieldLabel.getIndex()); return p; }); return mapping.result().get(fieldLabel.getIndex()).mappings().properties(); } catch (IOException e) { log.error("获取mapping错误", e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 刷新索引 * * @param fieldLabel 索引名称 */ public static void refresh(FieldLabel fieldLabel) { try { getClient().indices().refresh(RefreshRequest.of(setting -> { setting.index(fieldLabel.getIndex()); return setting; })); } catch (IOException e) { log.error("刷新索引错误", e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 格式化字段类型 * * @param fieldTypeEnum 字段类型 * @return es字段类型 */ public static Property parseEsType(EsFieldTypeEnum fieldTypeEnum) { switch (fieldTypeEnum) { case DATETIME: case DATE: return DateProperty.of(setting -> { setting.format("yyyy-MM-dd || yyyy-MM-dd HH:mm:ss || yyyy-MM"); return setting; })._toProperty(); case NUMBER: return ScaledFloatNumberProperty.of(setting -> { setting.scalingFactor(100D); return setting; })._toProperty(); case NESTED: return NestedProperty.of(setting -> { setting.dynamic(DynamicMapping.True); setting.enabled(true); return setting; })._toProperty(); case TEXT: return TextProperty.of(setting -> { setting.analyzer("standard"); return setting; })._toProperty(); default: return KeywordProperty.of(setting -> { setting.ignoreAbove(200); setting.normalizer("lowercase_normalizer"); setting.fields("sort", s -> { s._custom("sort", new JSONObject().fluentPut("type", "icu_collation_keyword").fluentPut("language", "zh").fluentPut("country", "CN")); return s; }); return setting; })._toProperty(); } } /** * 字段类型转换ES字段类型 * * @param type 字段类型 * @return es字段类型 */ public static EsFieldTypeEnum fieldType2EsType(Integer type) { FieldEnum fieldEnum = FieldEnum.parse(type); return fieldEnum2EsType(fieldEnum); } /** * 字段类型转换ES字段类型 * * @param fieldEnum 字段类型 * @return es字段类型 */ public static EsFieldTypeEnum fieldEnum2EsType(FieldEnum fieldEnum) { switch (fieldEnum) { case TEXTAREA: case RTF: return EsFieldTypeEnum.TEXT; case DATE: return EsFieldTypeEnum.DATE; case DATETIME: return EsFieldTypeEnum.DATETIME; case NUMBER: case FLOATNUMBER: case BOOLEAN_VALUE: case PERCENT: case ATTENTION: return EsFieldTypeEnum.NUMBER; case SELECT: case CHECKBOX: case AREA_POSITION: case DATE_INTERVAL: case TAG: case DETAIL_TABLE: return EsFieldTypeEnum.NESTED; default: return EsFieldTypeEnum.KEYWORD; } } public static Property field2EsType(FieldEnum fieldEnum) { switch (fieldEnum) { case TEXTAREA: case PIC: return TextProperty.of(setting -> { setting.analyzer("standard"); return setting; })._toProperty(); case DATETIME: case DATE: return DateProperty.of(setting -> { setting.format("yyyy-MM-dd || yyyy-MM-dd HH:mm:ss || yyyy-MM"); return setting; })._toProperty(); case NUMBER: return ScaledFloatNumberProperty.of(setting -> { setting.scalingFactor(1D); return setting; })._toProperty(); case FLOATNUMBER: return ScaledFloatNumberProperty.of(setting -> { setting.scalingFactor(100D); return setting; })._toProperty(); case INTENTIONAL_BUSINESS: case SUPERIOR_CUSTOMER: case CUSTOMER_RELATIONS: return NestedProperty.of(setting -> { setting.dynamic(DynamicMapping.True); setting.enabled(true); return setting; })._toProperty(); default: return KeywordProperty.of(setting -> { setting.ignoreAbove(200); setting.normalizer("lowercase_normalizer"); setting.fields("sort", s -> { s._custom("sort", new JSONObject().fluentPut("type", "icu_collation_keyword").fluentPut("language", "zh").fluentPut("country", "CN")); return s; }); return setting; })._toProperty(); } } /** * 修改多条数据中多个字段的值 * * @param dataMap 数据map * @param ids ids * @param fieldLabel 索引名称 */ public static void updateField(Map<String, Object> dataMap, List<?> ids, FieldLabel fieldLabel) { updateField(dataMap, ids, fieldLabel, false); } /** * 修改多条数据中多个字段的值 * * @param dataMap 数据map * @param ids ids * @param fieldLabel 索引名称 */ public static void updateField(Map<String, Object> dataMap, List<?> ids, FieldLabel fieldLabel, boolean docAsUpsert) { if (ids.isEmpty()) { return; } BulkRequest.Builder builder = new BulkRequest.Builder(); if (fieldLabel.isRefreshIndex()) { builder.refresh(Refresh.WaitFor); } for (Object id : ids) { builder.operations(setting -> { setting.update(i -> { i.id(id.toString()); i.index(fieldLabel.getIndex()); i.action(acc -> { acc.doc(dataMap); acc.docAsUpsert(docAsUpsert); return acc; }); return i; }); return setting; }); } bulk(builder.build()); } /** * 修改一条数据中多个字段的值 * * @param dataMap 数据map * @param id id * @param fieldLabel 索引名称 */ public static void updateField(Map<String, Object> dataMap, Object id, FieldLabel fieldLabel) { updateField(dataMap, id, fieldLabel, false); } /** * 修改一条数据中多个字段的值 * * @param dataMap 数据map * @param id id * @param fieldLabel 索引名称 * @param docAsUpsert 索引不存在是否新增 */ public static void updateField(Map<String, Object> dataMap, Object id, FieldLabel fieldLabel, boolean docAsUpsert) { updateField(dataMap, id, fieldLabel, docAsUpsert, fieldLabel.isRefreshIndex()); } /** * 修改一条数据中多个字段的值 * * @param dataMap 数据map * @param id id * @param fieldLabel 索引名称 * @param isRefreshIndex 是否刷新索引 */ public static void updateField(Map<String, Object> dataMap, Object id, FieldLabel fieldLabel, boolean docAsUpsert, boolean isRefreshIndex) { try { getClient().update(UpdateRequest.of(setting -> { setting.id(id.toString()); setting.index(fieldLabel.getIndex()); setting.doc(dataMap); setting.docAsUpsert(docAsUpsert); if (isRefreshIndex) { setting.refresh(Refresh.WaitFor); } return setting; }), JSONObject.class); } catch (IOException e) { log.error("修改字段错误", e); } } /** * 保存单条数据 * * @param objectMap 数据对象 * @param fieldLabel 索引信息 */ public static void saveData(Map<String, Object> objectMap, FieldLabel fieldLabel) { try { getClient().index(IndexRequest.of(data -> { Object key = objectMap.get(fieldLabel.getPrimaryKey()); if (key != null) { data.id(key.toString()); } data.index(fieldLabel.getIndex()); data.document(objectMap); if (fieldLabel.isRefreshIndex()) { data.refresh(Refresh.WaitFor); } return data; })); } catch (IOException e) { log.error("保存数据错误", e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 保存数据集,此操作不会刷新索引 * * @param valueList 数据集 * @param fieldLabel 索引名称 * @param isAdd 是否是新增 */ public static void saveData(List<Map<String, Object>> valueList, FieldLabel fieldLabel, boolean isAdd) { if (valueList == null || valueList.isEmpty()) { return; } if (valueList.size() == 1) { saveData(valueList.get(0), fieldLabel); } else { BulkRequest.Builder builder = new BulkRequest.Builder(); if (fieldLabel.isRefreshIndex()) { builder.refresh(Refresh.WaitFor); } builder.index(fieldLabel.getIndex()); for (Map<String, Object> value : valueList) { builder.operations(setting -> { Object key = value.get(fieldLabel.getPrimaryKey()); if (isAdd) { setting.create(i -> { if (key != null) { i.id(key.toString()); } i.index(fieldLabel.getIndex()); i.document(value); return i; }); } else { setting.update(i -> { if (key != null) { i.id(key.toString()); } i.index(fieldLabel.getIndex()); i.action(acc -> { acc.doc(value); acc.docAsUpsert(false); return acc; }); return i; }); } return setting; }); } bulk(builder.build()); } } /** * 删除数据 * * @param ids id集合 * @param fieldLabel 索引信息 */ public static void deleteData(List<?> ids, FieldLabel fieldLabel) { if (ids == null || ids.isEmpty()) { return; } if (ids.size() == 1) { try { getClient().delete(DeleteRequest.of(setting -> { setting.id(ids.get(0).toString()); setting.index(fieldLabel.getIndex()); if (fieldLabel.isRefreshIndex()) { setting.refresh(Refresh.WaitFor); } return setting; })); } catch (IOException e) { log.error("删除数据错误", e); } return; } BulkRequest.Builder builder = new BulkRequest.Builder(); if (fieldLabel.isRefreshIndex()) { builder.refresh(Refresh.WaitFor); } for (Object id : ids) { builder.operations(setting -> { setting.delete(i -> { i.id(id.toString()); i.index(fieldLabel.getIndex()); return i; }); return setting; }); } bulk(builder.build()); } /** * 根据条件删除 */ public static void deleteByQuery(DeleteByQueryRequest deleteByQueryRequest) { try { getClient().deleteByQuery(deleteByQueryRequest); } catch (IOException e) { log.error("根据条件删除错误", e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 根据id查询接口 * * @param id ID * @param index 索引 * @return 查询结果 */ public static GetResponse<JSONObject> getById(Object id, String index) { try { return getClient().get(GetRequest.of(b -> { b.id(id.toString()); b.index(index); return b; }), JSONObject.class); } catch (IOException e) { log.error("查询错误", e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 查询接口 * * @param request 查询参数 * @return 查询结果 */ public static SearchResponse<JSONObject> search(SearchRequest request) { try { return getClient().search(request, JSONObject.class); } catch (IOException e) { log.error("查询错误", e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 根据查询条件查询数量接口 * * @param query 查询条件 * @param fieldLabel 索引名称 * @return 查询结果 */ public static long count(Query query, FieldLabel fieldLabel) { try { return getClient().count(CountRequest.of(request -> { request.query(query); request.index(fieldLabel.getIndex()); return request; })).count(); } catch (IOException e) { log.error("查询错误", e); throw new CrmException(SystemCodeEnum.SYSTEM_SERVER_ERROR); } } /** * 解析字段值 * * @param value 值 */ public static FieldValue parseFieldValue(Object value) { FieldValue fieldValue = null; if (value instanceof String) { fieldValue = FieldValue.of((String) value); } else if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) { fieldValue = FieldValue.of(((Number) value).longValue()); } else if (value instanceof Boolean) { fieldValue = FieldValue.of((boolean) value); } else if (value instanceof Double || value instanceof Float) { fieldValue = FieldValue.of(((Number) value).doubleValue()); } return fieldValue; } /** * QueryBuilders.termQuery */ public static Query termQuery(String field, Object value) { return QueryBuilders.term(b -> { b.field(field); b.value(parseFieldValue(value)); return b; }); } /** * QueryBuilders.termsQuery */ public static Query termsQuery(String field, Collection<?> values) { List<FieldValue> fieldValueList = new ArrayList<>(); for (Object value : values) { fieldValueList.add(parseFieldValue(value)); } return QueryBuilders.terms(b -> { b.field(field); b.terms(t -> t.value(fieldValueList)); return b; }); } /** * QueryBuilders.existsQuery */ public static Query existsQuery(String field) { return QueryBuilders.exists(b -> { b.field(field); return b; }); } /** * QueryBuilders.prefixQuery */ public static Query prefixQuery(String field, String value) { return QueryBuilders.prefix(b -> { b.field(field); b.value(value); return b; }); } /** * QueryBuilders.wildcardQuery */ public static Query wildcardQuery(String field, String value) { return QueryBuilders.wildcard(b -> { b.field(field); b.value(value); return b; }); } /** * QueryBuilders.scriptQuery */ public static Query scriptQuery(String source, Map<String, Object> map) { Script script = new Script.Builder().inline(b -> { b.lang("painless"); for (String key : map.keySet()) { Object value = map.get(key); b.params(key, JsonData.of(value)); } b.source(source); return b; }).build(); return QueryBuilders.script(b -> { b.script(script); return b; }); } /** * QueryBuilders.nestedQuery */ public static Query nestedQuery(String path, Query query) { return nestedQuery(path, query, ChildScoreMode.None); } /** * 创建es排序 * * @param order 排序方式 * @param fields 排序字段 * @return */ public static SortOptions sort(SortOrder order, String... fields) { return SortOptionsBuilders.field(b -> { b.order(order); for (String field : fields) { b.field(field); } return b; }); } /** * QueryBuilders.nestedQuery */ public static Query nestedQuery(String path, Query query, ChildScoreMode scoreMode) { return QueryBuilders.nested(b -> { b.path(path); b.query(query); b.scoreMode(scoreMode); return b; }); } public static Query rangeQuery(String fieldName, List<RangeEntity> data) { return QueryBuilders.range(b -> { b.queryName(String.format("%sSize", fieldName)); for (RangeEntity rangeEntity : data) { switch (rangeEntity.getType()) { case GT: b.gt(JsonData.of(rangeEntity.getValue())); break; case GTE: b.gte(JsonData.of(rangeEntity.getValue())); break; case LT: b.lt(JsonData.of(rangeEntity.getValue())); break; case LTE: b.lte(JsonData.of(rangeEntity.getValue())); break; } } return b; }); } /** * QueryBuilders.rangeQuery */ public static Query rangeQuery(String fieldName, Object value, RangeTypeEnum rangeTypeEnum) { return QueryBuilders.range(b -> { b.queryName(String.format("%sSize", fieldName)); switch (rangeTypeEnum) { case GT: b.gt(JsonData.of(value)); break; case GTE: b.gte(JsonData.of(value)); break; case LT: b.lt(JsonData.of(value)); break; case LTE: b.lte(JsonData.of(value)); break; } return b; }); } /** * QueryBuilders.matchQuery */ public static Query matchQuery(String field, Object value) { return QueryBuilders.match(b -> { b.field(field); b.query(parseFieldValue(value)); return b; }); } /** * QueryBuilders.idsQuery */ public static Query idsQuery(List<?> value) { return QueryBuilders.ids(b -> { List<String> ids = value.stream().map(TypeUtils::castToString).collect(Collectors.toList()); b.values(ids); return b; }); } /** * QueryBuilders.idsQuery */ public static Query idsQuery(Object... value) { return QueryBuilders.ids(b -> { List<String> list = Arrays.stream(value).map(TypeUtils::castToString).collect(Collectors.toList()); b.values(list); return b; }); } /** * 追加搜索条件 * * @param search 搜索条件 * @param boolQuery boolQuery */
public static void appendSearchCondition(SearchEntity search, BoolQuery.Builder boolQuery) {
4
2023-10-17 05:49:52+00:00
24k
ballerina-platform/module-ballerinax-copybook
commons/src/main/java/io/ballerina/lib/copybook/commons/schema/SchemaBuilder.java
[ { "identifier": "CopybookVisitor", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/generated/CopybookVisitor.java", "snippet": "public interface CopybookVisitor<T> extends ParseTreeVisitor<T> {\n\t/**\n\t * Visit a parse tree produced by {@link CopybookParser#startRule}.\n\t * @param ct...
import io.ballerina.lib.copybook.commons.generated.CopybookVisitor; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.RuleNode; import org.antlr.v4.runtime.tree.TerminalNode; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.BooleanLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CicsDfhRespLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CicsDfhValueLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CobolWordContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.ConditionNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataBlankWhenZeroClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryClausesContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat1Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat2Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat3Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataExternalClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataGlobalClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataJustifiedClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursSortContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursToContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataPictureClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataRedefinesClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataRenamesClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataSignClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataSynchronizedClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataUsageClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalFromContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalToContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.FigurativeConstantContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IdentifierContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IndexNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IntegerLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.LiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.NumericLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureCardinalityContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureCharsContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureStringContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.QualifiedDataNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.StartRuleContext;
19,872
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.copybook.commons.schema; class SchemaBuilder implements CopybookVisitor<CopybookNode> { private final Schema schema = new Schema(); private GroupItem possibleParent; private final Set<String> redefinedItemNames = new HashSet<>(); private final List<String> errors = new ArrayList<>(); Schema getSchema() { return this.schema; } @Override public CopybookNode visitStartRule(StartRuleContext ctx) { this.possibleParent = null; visitDataDescription(ctx.dataDescription()); for (CopybookNode typedef : this.schema.getTypeDefinitions()) { addRedefinedItems(typedef); } this.schema.addErrors(this.errors); return null; } private void addRedefinedItems(CopybookNode item) { if (this.redefinedItemNames.contains(item.getName())) { this.schema.addRedefinedItem(item); return; } if (item instanceof GroupItem groupItem) { groupItem.getChildren().forEach(this::addRedefinedItems); } } @Override public CopybookNode visitDataDescription(DataDescriptionContext ctx) { for (int i = 0; i < ctx.getChildCount(); i++) { CopybookNode copybookNode = visitDataDescriptionEntry(ctx.dataDescriptionEntry(i)); if (copybookNode instanceof GroupItem groupItem) { this.possibleParent = groupItem; } if (isRootLevelNode(copybookNode)) { this.schema.addTypeDefinition(copybookNode); } } return null; } private boolean isRootLevelNode(CopybookNode copybookNode) { return copybookNode != null && copybookNode.getLevel() == 1; } @Override public CopybookNode visitDataDescriptionEntry(DataDescriptionEntryContext ctx) { if (ctx.dataDescriptionEntryFormat1() != null) { return visitDataDescriptionEntryFormat1(ctx.dataDescriptionEntryFormat1()); } // skipping level 66 and 88 return null; } @Override public CopybookNode visitDataDescriptionEntryFormat1(DataDescriptionEntryFormat1Context ctx) { if (ctx.LEVEL_NUMBER_77() != null) { // skipping level 77 return null; } boolean redefines = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0) != null; String redefinedItemName = null; if (redefines) { redefinedItemName = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0).dataName().getText(); this.redefinedItemNames.add(redefinedItemName); } int level = Integer.parseInt(ctx.INTEGERLITERAL().getText()); String name = ctx.dataName() != null ? ctx.dataName().getText() : ctx.FILLER().getText(); DataPictureClauseContext pictureClause = ctx.dataDescriptionEntryClauses().dataPictureClause(0); DataOccursClauseContext occursClause = ctx.dataDescriptionEntryClauses().dataOccursClause(0); int occurs = Utils.getOccurringCount(occursClause); if (pictureClause == null || pictureClause.pictureString() == null) { return new GroupItem(level, name, occurs, redefinedItemName, getParent(level)); } PictureStringContext pictureType = pictureClause.pictureString(); validatePicture(pictureType); return new DataItem(level, name, Utils.getPictureString(pictureType), Utils.isNumeric(pictureType), Utils.getReadLength(pictureType), occurs, Utils.getFloatingPointLength(pictureType), redefinedItemName, getParent(level)); } private void validatePicture(PictureStringContext pictureType) { String pictureString = Utils.getPictureString(pictureType); if (PictureStringValidator.isSupportedPictureString(pictureString)) { return; } String errorMsg = "Unsupported picture string '" + pictureString + "' found in copybook schema"; this.addError(pictureType.start.getLine(), pictureType.start.getCharPositionInLine(), errorMsg); } private void addError(int line, int charPositionInLine, String msg) { this.errors.add("Error at line " + line + ", column " + charPositionInLine + ": " + msg); } @Override public CopybookNode visitDataDescriptionEntryClauses(DataDescriptionEntryClausesContext ctx) { return null; } private GroupItem getParent(int currentLevel) { GroupItem parent = this.possibleParent; while (parent != null && parent.getLevel() >= currentLevel) { parent = parent.getParent(); } return parent; } @Override public CopybookNode visitDataDescriptionEntryFormat2(DataDescriptionEntryFormat2Context ctx) { return null; } @Override public CopybookNode visitDataDescriptionEntryFormat3(DataDescriptionEntryFormat3Context ctx) { return null; } @Override public CopybookNode visitDataBlankWhenZeroClause(DataBlankWhenZeroClauseContext ctx) { return null; } @Override public CopybookNode visitDataExternalClause(DataExternalClauseContext ctx) { return null; } @Override
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.copybook.commons.schema; class SchemaBuilder implements CopybookVisitor<CopybookNode> { private final Schema schema = new Schema(); private GroupItem possibleParent; private final Set<String> redefinedItemNames = new HashSet<>(); private final List<String> errors = new ArrayList<>(); Schema getSchema() { return this.schema; } @Override public CopybookNode visitStartRule(StartRuleContext ctx) { this.possibleParent = null; visitDataDescription(ctx.dataDescription()); for (CopybookNode typedef : this.schema.getTypeDefinitions()) { addRedefinedItems(typedef); } this.schema.addErrors(this.errors); return null; } private void addRedefinedItems(CopybookNode item) { if (this.redefinedItemNames.contains(item.getName())) { this.schema.addRedefinedItem(item); return; } if (item instanceof GroupItem groupItem) { groupItem.getChildren().forEach(this::addRedefinedItems); } } @Override public CopybookNode visitDataDescription(DataDescriptionContext ctx) { for (int i = 0; i < ctx.getChildCount(); i++) { CopybookNode copybookNode = visitDataDescriptionEntry(ctx.dataDescriptionEntry(i)); if (copybookNode instanceof GroupItem groupItem) { this.possibleParent = groupItem; } if (isRootLevelNode(copybookNode)) { this.schema.addTypeDefinition(copybookNode); } } return null; } private boolean isRootLevelNode(CopybookNode copybookNode) { return copybookNode != null && copybookNode.getLevel() == 1; } @Override public CopybookNode visitDataDescriptionEntry(DataDescriptionEntryContext ctx) { if (ctx.dataDescriptionEntryFormat1() != null) { return visitDataDescriptionEntryFormat1(ctx.dataDescriptionEntryFormat1()); } // skipping level 66 and 88 return null; } @Override public CopybookNode visitDataDescriptionEntryFormat1(DataDescriptionEntryFormat1Context ctx) { if (ctx.LEVEL_NUMBER_77() != null) { // skipping level 77 return null; } boolean redefines = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0) != null; String redefinedItemName = null; if (redefines) { redefinedItemName = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0).dataName().getText(); this.redefinedItemNames.add(redefinedItemName); } int level = Integer.parseInt(ctx.INTEGERLITERAL().getText()); String name = ctx.dataName() != null ? ctx.dataName().getText() : ctx.FILLER().getText(); DataPictureClauseContext pictureClause = ctx.dataDescriptionEntryClauses().dataPictureClause(0); DataOccursClauseContext occursClause = ctx.dataDescriptionEntryClauses().dataOccursClause(0); int occurs = Utils.getOccurringCount(occursClause); if (pictureClause == null || pictureClause.pictureString() == null) { return new GroupItem(level, name, occurs, redefinedItemName, getParent(level)); } PictureStringContext pictureType = pictureClause.pictureString(); validatePicture(pictureType); return new DataItem(level, name, Utils.getPictureString(pictureType), Utils.isNumeric(pictureType), Utils.getReadLength(pictureType), occurs, Utils.getFloatingPointLength(pictureType), redefinedItemName, getParent(level)); } private void validatePicture(PictureStringContext pictureType) { String pictureString = Utils.getPictureString(pictureType); if (PictureStringValidator.isSupportedPictureString(pictureString)) { return; } String errorMsg = "Unsupported picture string '" + pictureString + "' found in copybook schema"; this.addError(pictureType.start.getLine(), pictureType.start.getCharPositionInLine(), errorMsg); } private void addError(int line, int charPositionInLine, String msg) { this.errors.add("Error at line " + line + ", column " + charPositionInLine + ": " + msg); } @Override public CopybookNode visitDataDescriptionEntryClauses(DataDescriptionEntryClausesContext ctx) { return null; } private GroupItem getParent(int currentLevel) { GroupItem parent = this.possibleParent; while (parent != null && parent.getLevel() >= currentLevel) { parent = parent.getParent(); } return parent; } @Override public CopybookNode visitDataDescriptionEntryFormat2(DataDescriptionEntryFormat2Context ctx) { return null; } @Override public CopybookNode visitDataDescriptionEntryFormat3(DataDescriptionEntryFormat3Context ctx) { return null; } @Override public CopybookNode visitDataBlankWhenZeroClause(DataBlankWhenZeroClauseContext ctx) { return null; } @Override public CopybookNode visitDataExternalClause(DataExternalClauseContext ctx) { return null; } @Override
public CopybookNode visitDataGlobalClause(DataGlobalClauseContext ctx) {
14
2023-10-24 04:51:53+00:00
24k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BlockRegister.java
[ { "identifier": "BasicBlocks", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BasicBlocks.java", "snippet": "public class BasicBlocks {\n\n public static final Block MetaBlock01 = new BlockBase01(\"MetaBlock01\", \"MetaBlock01\");\n public static final Block PhotonControllerUpgr...
import static com.Nxer.TwistSpaceTechnology.common.block.BasicBlocks.*; import static com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.BlockNuclearReactor.NuclearReactorBlockMeta; import com.Nxer.TwistSpaceTechnology.common.GTCMItemList; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockStar; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.BlockNuclearReactor; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.PhotonControllerUpgradeCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.PhotonControllerUpgradeCasingItemBlock; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationAntiGravityCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationAntiGravityCasingItemBlock; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationStructureCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationStructureCasingItemBlock; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.ItemBlockBase01; import com.Nxer.TwistSpaceTechnology.common.tile.TileStar; import com.Nxer.TwistSpaceTechnology.config.Config; import cpw.mods.fml.common.registry.GameRegistry;
18,758
package com.Nxer.TwistSpaceTechnology.common.block; public class BlockRegister { public static void registryBlocks() { GameRegistry.registerBlock(MetaBlock01, ItemBlockBase01.class, MetaBlock01.getUnlocalizedName()); GameRegistry.registerBlock( PhotonControllerUpgrade,
package com.Nxer.TwistSpaceTechnology.common.block; public class BlockRegister { public static void registryBlocks() { GameRegistry.registerBlock(MetaBlock01, ItemBlockBase01.class, MetaBlock01.getUnlocalizedName()); GameRegistry.registerBlock( PhotonControllerUpgrade,
PhotonControllerUpgradeCasingItemBlock.class,
6
2023-10-16 09:57:15+00:00
24k