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
Traben-0/resource_explorer
common/src/main/java/traben/resource_explorer/explorer/REResourceFile.java
[ { "identifier": "SpriteAtlasTextureAccessor", "path": "common/src/main/java/traben/resource_explorer/mixin/SpriteAtlasTextureAccessor.java", "snippet": "@Mixin(SpriteAtlasTexture.class)\npublic interface SpriteAtlasTextureAccessor {\n @Accessor\n int getWidth();\n\n @Accessor\n int getHeight();\n}" }, { "identifier": "outputResourceToPackInternal", "path": "common/src/main/java/traben/resource_explorer/explorer/REExplorer.java", "snippet": "@SuppressWarnings(\"ResultOfMethodCallIgnored\")\nstatic boolean outputResourceToPackInternal(REResourceFile reResourceFile) {\n //only save existing file resources\n if (reResourceFile.resource == null)\n return false;\n\n Path resourcePackFolder = MinecraftClient.getInstance().getResourcePackDir();\n File thisPackFolder = new File(resourcePackFolder.toFile(), \"resource_explorer/\");\n\n if (validateOutputResourcePack(thisPackFolder)) {\n if (thisPackFolder.exists()) {\n File assets = new File(thisPackFolder, \"assets\");\n if (!assets.exists()) {\n assets.mkdir();\n }\n File namespace = new File(assets, reResourceFile.identifier.getNamespace());\n if (!namespace.exists()) {\n namespace.mkdir();\n }\n String[] pathList = reResourceFile.identifier.getPath().split(\"/\");\n String file = pathList[pathList.length - 1];\n String directories = reResourceFile.identifier.getPath().replace(file, \"\");\n File directoryFolder = new File(namespace, directories);\n if (!directoryFolder.exists()) {\n directoryFolder.mkdirs();\n }\n if (directoryFolder.exists()) {\n\n File outputFile = new File(directoryFolder, file);\n try {\n byte[] buffer = reResourceFile.resource.getInputStream().readAllBytes();\n OutputStream outStream = new FileOutputStream(outputFile);\n outStream.write(buffer);\n IOUtils.closeQuietly(outStream);\n return true;\n } catch (IOException e) {\n e.printStackTrace();\n ResourceExplorerClient.log(\" Exporting resource file failed for: \" + reResourceFile.identifier);\n }\n }\n }\n }\n return false;\n}" } ]
import net.minecraft.client.MinecraftClient; import net.minecraft.client.font.MultilineText; import net.minecraft.client.texture.AbstractTexture; import net.minecraft.client.texture.NativeImage; import net.minecraft.client.texture.NativeImageBackedTexture; import net.minecraft.client.texture.SpriteAtlasTexture; import net.minecraft.resource.Resource; import net.minecraft.resource.metadata.ResourceMetadata; import net.minecraft.text.OrderedText; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import org.jetbrains.annotations.Nullable; import traben.resource_explorer.mixin.SpriteAtlasTextureAccessor; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Objects; import static traben.resource_explorer.explorer.REExplorer.outputResourceToPackInternal;
917
package traben.resource_explorer.explorer; public class REResourceFile extends REResourceEntry { public static final REResourceFile FAILED_FILE = new REResourceFile(); public final Identifier identifier; @Nullable public final Resource resource; public final FileType fileType; public final LinkedList<String> folderStructureList; final AbstractTexture abstractTexture; private final String displayName; private final OrderedText displayText; public MultilineText readTextByLineBreaks = null; public int height = 1; public int width = 1; boolean imageDone = false; Boolean hasMetaData = null; private REResourceFile() { //failed file this.identifier = new Identifier("search_failed:fail"); this.resource = null; this.abstractTexture = null; this.fileType = FileType.OTHER; displayName = "search_failed"; folderStructureList = new LinkedList<>(); this.displayText = Text.of("search_failed").asOrderedText(); } public REResourceFile(Identifier identifier, AbstractTexture texture) { this.identifier = identifier; this.resource = null; this.abstractTexture = texture; //try to capture some sizes if (abstractTexture instanceof SpriteAtlasTexture atlasTexture) {
package traben.resource_explorer.explorer; public class REResourceFile extends REResourceEntry { public static final REResourceFile FAILED_FILE = new REResourceFile(); public final Identifier identifier; @Nullable public final Resource resource; public final FileType fileType; public final LinkedList<String> folderStructureList; final AbstractTexture abstractTexture; private final String displayName; private final OrderedText displayText; public MultilineText readTextByLineBreaks = null; public int height = 1; public int width = 1; boolean imageDone = false; Boolean hasMetaData = null; private REResourceFile() { //failed file this.identifier = new Identifier("search_failed:fail"); this.resource = null; this.abstractTexture = null; this.fileType = FileType.OTHER; displayName = "search_failed"; folderStructureList = new LinkedList<>(); this.displayText = Text.of("search_failed").asOrderedText(); } public REResourceFile(Identifier identifier, AbstractTexture texture) { this.identifier = identifier; this.resource = null; this.abstractTexture = texture; //try to capture some sizes if (abstractTexture instanceof SpriteAtlasTexture atlasTexture) {
width = ((SpriteAtlasTextureAccessor) atlasTexture).getWidth();
0
2023-11-05 17:35:39+00:00
2k
cypcodestudio/rbacspring
rbacspring/src/main/java/com/cypcode/rbacspring/security/SecurityPrincipal.java
[ { "identifier": "User", "path": "rbacspring/src/main/java/com/cypcode/rbacspring/entity/User.java", "snippet": "@Entity\n@Table(name = \"WUser\")\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class User implements Serializable, UserDetails{\n\n\tprivate static final long serialVersionUID = 5926468583005150707L;\n\t\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id;\n\n\t@Column(name = \"username\", unique = true)\n\tprivate String username;\n\n\t@Column(name = \"password\")\n\tprivate String password;\n\n\t@Column(name = \"entity_no\", unique = true)\n\tprivate String entityNo;\n\n\t/**\n\t * @return the id\n\t */\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id the id to set\n\t */\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the username\n\t */\n\t@Override\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t/**\n\t * @param username the username to set\n\t */\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\t/**\n\t * @return the password\n\t */\n\t@Override\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\t/**\n\t * @param password the password to set\n\t */\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\t/**\n\t * @return the entityNo\n\t */\n\tpublic String getEntityNo() {\n\t\treturn entityNo;\n\t}\n\n\t/**\n\t * @param entityNo the entityNo to set\n\t */\n\tpublic void setEntityNo(String entityNo) {\n\t\tthis.entityNo = entityNo;\n\t}\n\n\t@Override\n\tpublic Collection<? extends GrantedAuthority> getAuthorities() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean isAccountNonExpired() {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isAccountNonLocked() {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isCredentialsNonExpired() {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isEnabled() {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\t\n\t\n\n}" }, { "identifier": "WUserService", "path": "rbacspring/src/main/java/com/cypcode/rbacspring/service/WUserService.java", "snippet": "@Service\n@Transactional\npublic class WUserService implements UserDetailsService {\n\tprivate static final Logger LOG = LoggerFactory.getLogger(WUserService.class);\n\n\t@Autowired\n\tprivate IUserRepository userRepository;\n\n\t@Autowired\n\tprivate IUserRoleRepository userRoleRepository;\n\n\t@Autowired\n\tWRoleService roleService;\n\n\t@Override\n\tpublic UserDetails loadUserByUsername(String username) {\n\t\tUser user = userRepository.findByUsername(username);\n\t\tif (user != null) {\n\t\t\tList<UserRole> userRoles = userRoleRepository.findAllByUserId(user.getId());\n\n\t\t\tCollection<SimpleGrantedAuthority> authorities = new ArrayList<>();\n\n\t\t\tuserRoles.forEach(userRole -> {\n\t\t\t\tauthorities.add(new SimpleGrantedAuthority(userRole.getRole().getName()));\n\t\t\t});\n\n\t\t\tUserDetails principal = new org.springframework.security.core.userdetails.User(user.getUsername(),\n\t\t\t\t\tuser.getPassword(), authorities);\n\n\t\t\treturn principal;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic User findByUsername(String username) {\n\t\treturn userRepository.findByUsername(username);\n\t}\n\n\tpublic String createUser(UserRegisterRequestDTO request) {\n\t\ttry {\n\t\t\tUser user = (User) dtoMapperRequestDtoToUser(request);\n\n\t\t\tuser = userRepository.save(user);\n\t\t\tif (!request.getRoleList().isEmpty()) {\n\t\t\t\tfor (String role : request.getRoleList()) {\n\t\t\t\t\tRole existingRole = roleService.findRoleByName(\"ROLE_\" + role.toUpperCase());\n\t\t\t\t\tif(existingRole != null) {\n\t\t\t\t\t\taddUserRole(user, existingRole);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\taddUserRole(user, null);\n\t\t\t}\n\n\t\t\treturn \"User successfully created.\";\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn e.getCause().getMessage();\n\t\t}\n\n\t}\n\n\tpublic List<User> retrieveAllUserList() {\n\t\treturn userRepository.findAll();\n\t}\n\n\tpublic User updateUser(UserRegisterRequestDTO userRequestDTO) {\n\n\t\tUser user = (User) dtoMapperRequestDtoToUser(userRequestDTO);\n\n\t\tuser = userRepository.save(user);\n\t\taddUserRole(user, null);\n\n\t\treturn user;\n\t}\n\n\tpublic User findCurrentUser() {\n\t\treturn userRepository.findById(SecurityPrincipal.getInstance().getLoggedInPrincipal().getId()).get();\n\n\t}\n\n\tpublic List<UserRole> findAllCurrentUserRole() {\n\t\treturn userRoleRepository.findAllByUserId(SecurityPrincipal.getInstance().getLoggedInPrincipal().getId());\n\n\t}\n\n\tpublic Optional<User> findUserById(long id) {\n\t\treturn userRepository.findById(id);\n\t}\n\n\tpublic void addUserRole(User user, Role role) {\n\n\t\tUserRole userRole = new UserRole();\n\t\tuserRole.setUser(user);\n\n\t\tif (role == null) {\n\t\t\trole = roleService.findDefaultRole();\n\t\t}\n\t\t\n\t\tuserRole.setRole(role);\n\t\tuserRoleRepository.save(userRole);\n\t}\n\n\tprivate Object dtoMapperRequestDtoToUser(UserRegisterRequestDTO source) {\n\t\tUser target = new User();\n\t\ttarget.setEntityNo(source.getEntityNo());\n\t\ttarget.setUsername(source.getUsername());\n\t\ttarget.setPassword(source.getPassword());\n\n\t\treturn target;\n\t}\n\n}" } ]
import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; import com.cypcode.rbacspring.entity.User; import com.cypcode.rbacspring.service.WUserService;
1,570
/** * */ package com.cypcode.rbacspring.security; @Service public class SecurityPrincipal { private static SecurityPrincipal securityPrincipal = null; private Authentication principal = SecurityContextHolder.getContext().getAuthentication();
/** * */ package com.cypcode.rbacspring.security; @Service public class SecurityPrincipal { private static SecurityPrincipal securityPrincipal = null; private Authentication principal = SecurityContextHolder.getContext().getAuthentication();
private static WUserService userService;
1
2023-11-05 05:38:31+00:00
2k
txline0420/nacos-dm
plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/dm/TenantInfoMapperByDm.java
[ { "identifier": "DataSourceConstant", "path": "plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/constants/DataSourceConstant.java", "snippet": "public class DataSourceConstant {\n public static final String MYSQL = \"mysql\";\n public static final String DM = \"dm\";\n public static final String DERBY = \"derby\";\n}" }, { "identifier": "AbstractMapper", "path": "plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/AbstractMapper.java", "snippet": "public abstract class AbstractMapper implements Mapper {\n \n @Override\n public String select(List<String> columns, List<String> where) {\n StringBuilder sql = new StringBuilder();\n String method = \"SELECT \";\n sql.append(method);\n for (int i = 0; i < columns.size(); i++) {\n sql.append(columns.get(i));\n if (i == columns.size() - 1) {\n sql.append(\" \");\n } else {\n sql.append(\",\");\n }\n }\n sql.append(\"FROM \");\n sql.append(getTableName());\n sql.append(\" \");\n \n if (where.size() == 0) {\n return sql.toString();\n }\n \n sql.append(\"WHERE \");\n for (int i = 0; i < where.size(); i++) {\n sql.append(where.get(i)).append(\" = \").append(\"?\");\n if (i != where.size() - 1) {\n sql.append(\" AND \");\n }\n }\n return sql.toString();\n }\n \n @Override\n public String insert(List<String> columns) {\n StringBuilder sql = new StringBuilder();\n String method = \"INSERT INTO \";\n sql.append(method);\n sql.append(getTableName());\n \n int size = columns.size();\n sql.append(\"(\");\n for (int i = 0; i < size; i++) {\n sql.append(columns.get(i));\n if (i != columns.size() - 1) {\n sql.append(\", \");\n }\n }\n sql.append(\") \");\n \n sql.append(\"VALUES\");\n sql.append(\"(\");\n for (int i = 0; i < size; i++) {\n sql.append(\"?\");\n if (i != columns.size() - 1) {\n sql.append(\",\");\n }\n }\n sql.append(\")\");\n return sql.toString();\n }\n \n @Override\n public String update(List<String> columns, List<String> where) {\n StringBuilder sql = new StringBuilder();\n String method = \"UPDATE \";\n sql.append(method);\n sql.append(getTableName()).append(\" \").append(\"SET \");\n \n for (int i = 0; i < columns.size(); i++) {\n sql.append(columns.get(i)).append(\" = \").append(\"?\");\n if (i != columns.size() - 1) {\n sql.append(\",\");\n }\n }\n \n if (where.size() == 0) {\n return sql.toString();\n }\n \n sql.append(\" WHERE \");\n \n for (int i = 0; i < where.size(); i++) {\n sql.append(where.get(i)).append(\" = \").append(\"?\");\n if (i != where.size() - 1) {\n sql.append(\" AND \");\n }\n }\n return sql.toString();\n }\n \n @Override\n public String delete(List<String> params) {\n StringBuilder sql = new StringBuilder();\n String method = \"DELETE \";\n sql.append(method).append(\"FROM \").append(getTableName()).append(\" \").append(\"WHERE \");\n for (int i = 0; i < params.size(); i++) {\n sql.append(params.get(i)).append(\" \").append(\"=\").append(\" ? \");\n if (i != params.size() - 1) {\n sql.append(\"AND \");\n }\n }\n \n return sql.toString();\n }\n \n @Override\n public String count(List<String> where) {\n StringBuilder sql = new StringBuilder();\n String method = \"SELECT \";\n sql.append(method);\n sql.append(\"COUNT(*) FROM \");\n sql.append(getTableName());\n sql.append(\" \");\n \n if (null == where || where.size() == 0) {\n return sql.toString();\n }\n \n sql.append(\"WHERE \");\n for (int i = 0; i < where.size(); i++) {\n sql.append(where.get(i)).append(\" = \").append(\"?\");\n if (i != where.size() - 1) {\n sql.append(\" AND \");\n }\n }\n return sql.toString();\n }\n \n @Override\n public String[] getPrimaryKeyGeneratedKeys() {\n return new String[]{\"id\"};\n }\n}" }, { "identifier": "TenantInfoMapper", "path": "plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/TenantInfoMapper.java", "snippet": "public interface TenantInfoMapper extends Mapper {\n \n /**\n * 获取返回表名.\n *\n * @return 表名\n */\n default String getTableName() {\n return TableConstant.TENANT_INFO;\n }\n\n}" } ]
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.TenantInfoMapper;
1,426
/* * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.plugin.datasource.impl.dm; /** * The DM implementation of TenantInfoMapper. * * @author TXLINE **/ public class TenantInfoMapperByDm extends AbstractMapper implements TenantInfoMapper { @Override public String getDataSource() {
/* * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.plugin.datasource.impl.dm; /** * The DM implementation of TenantInfoMapper. * * @author TXLINE **/ public class TenantInfoMapperByDm extends AbstractMapper implements TenantInfoMapper { @Override public String getDataSource() {
return DataSourceConstant.DM;
0
2023-11-02 01:34:09+00:00
2k
Kinyarasam/RideShareX
RideShareX/src/main/java/com/ridesharex/controller/UserController.java
[ { "identifier": "User", "path": "RideShareX/src/main/java/com/ridesharex/model/User.java", "snippet": "@Entity\n@Table(name = \"users\")\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"username\", unique = true)\n private String username;\n\n @Column(name = \"password\")\n private String password;\n\n @Column(name = \"email\")\n private String email;\n\n @CreationTimestamp\n private LocalDateTime createdAt;\n\n @UpdateTimestamp\n private LocalDateTime updatedAt;\n\n // Constructors\n\n // Getters\n public Long getId() {\n return id;\n }\n\n public String getUsername() {\n return username;\n }\n\n // private String getPassword() {\n // return password;\n // }\n\n public String getEmail() {\n return email;\n }\n\n // Setters\n public void setUsername(String username) {\n this.username = username;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n}" }, { "identifier": "UserService", "path": "RideShareX/src/main/java/com/ridesharex/service/UserService.java", "snippet": "@Service\npublic class UserService {\n private final UserRepository userRepository;\n\n @Autowired\n public UserService(UserRepository userRepository) {\n this.userRepository = userRepository;\n }\n\n public List<User> getAllUsers() {\n return userRepository.findAll();\n }\n\n // Create a new user\n public User createUser(User user) {\n return userRepository.save(user);\n }\n\n // Retrieve a user ID\n public User getUserById(Long userId) {\n return userRepository.findById(userId).orElse(null);\n }\n\n // Update user information\n public User updateUser(Long userId, User updatedUser) {\n User existingUser = userRepository.findById(userId).orElse(null);\n if (existingUser != null) {\n existingUser.setUsername(updatedUser.getUsername());\n existingUser.setEmail(updatedUser.getEmail());\n\n return userRepository.save(existingUser);\n }\n return null;\n }\n\n // Delete a user by ID\n public void deleteUser(Long userId) {\n userRepository.deleteById(userId);\n }\n\n public List<RideRequest> getUserRideRequests(Long userId) {\n return null;\n }\n}" } ]
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; 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.ridesharex.model.User; import com.ridesharex.service.UserService;
759
package com.ridesharex.controller; @RestController @RequestMapping("/users") public class UserController { private final UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } @GetMapping
package com.ridesharex.controller; @RestController @RequestMapping("/users") public class UserController { private final UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } @GetMapping
public List<User> getAllUsers() {
0
2023-11-07 06:52:56+00:00
2k
MCMDEV/chatchannels
src/main/java/dev/gamemode/chatchannels/config/ConfigReader.java
[ { "identifier": "Channel", "path": "src/main/java/dev/gamemode/chatchannels/model/channel/Channel.java", "snippet": "public interface Channel {\n\n boolean canSee(Audience audience);\n\n String getName();\n\n Component getDisplayName();\n\n Collection<Audience> getViewers();\n\n ChannelRenderer getRenderer();\n\n}" }, { "identifier": "SetCollectionChannel", "path": "src/main/java/dev/gamemode/chatchannels/model/channel/SetCollectionChannel.java", "snippet": "@RequiredArgsConstructor\npublic class SetCollectionChannel implements MembershipChannel {\n\n private final String name;\n private final Component displayName;\n private final Set<Player> viewers;\n private final ChannelRenderer channelRenderer;\n\n @Override\n public boolean shouldAutojoin(Player player) {\n return player.hasPermission(\"chatchannels.autojoin.\" + name);\n }\n\n @Override\n public boolean canSee(Audience audience) {\n if (audience instanceof Player player) {\n return canJoin(player);\n }\n return true;\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public Component getDisplayName() {\n return displayName;\n }\n\n @Override\n public Collection<Audience> getViewers() {\n return viewers.stream()\n .map(player -> (Audience) player)\n .collect(Collectors.toSet());\n }\n\n @Override\n public ChannelRenderer getRenderer() {\n return channelRenderer;\n }\n\n @Override\n public boolean canJoin(Player player) {\n return player.hasPermission(\"chatchannels.join.\" + name);\n }\n\n @Override\n public void join(Player player) {\n viewers.add(player);\n }\n\n @Override\n public boolean isMember(Player player) {\n return viewers.contains(player);\n }\n\n @Override\n public void leave(Player player) {\n viewers.remove(player);\n }\n}" }, { "identifier": "ChannelProvider", "path": "src/main/java/dev/gamemode/chatchannels/model/provider/ChannelProvider.java", "snippet": "public interface ChannelProvider {\n\n Optional<Channel> getChannel(String name);\n\n Collection<Channel> getChannels();\n}" }, { "identifier": "MapChannelProvider", "path": "src/main/java/dev/gamemode/chatchannels/model/provider/MapChannelProvider.java", "snippet": "@RequiredArgsConstructor\npublic class MapChannelProvider implements ChannelProvider {\n\n private final Map<String, Channel> channels;\n\n @Override\n public Optional<Channel> getChannel(String name) {\n return Optional.ofNullable(channels.get(name));\n }\n\n @Override\n public Collection<Channel> getChannels() {\n return channels.values();\n }\n}" }, { "identifier": "ChannelRenderer", "path": "src/main/java/dev/gamemode/chatchannels/renderer/ChannelRenderer.java", "snippet": "public interface ChannelRenderer {\n\n Component render(Component channelName, Component sourceDisplayName, Component message);\n\n}" }, { "identifier": "ConfiguredRenderer", "path": "src/main/java/dev/gamemode/chatchannels/renderer/ConfiguredRenderer.java", "snippet": "@RequiredArgsConstructor\npublic class ConfiguredRenderer implements ChannelRenderer {\n\n private final String input;\n\n /*\n This is okay according to the Paper team.\n https://discord.com/channels/289587909051416579/555462289851940864/1171503384700919830\n */\n @Override\n public Component render(Component channelName, Component sourceDisplayName, Component message) {\n return MiniMessage.miniMessage()\n .deserialize(input,\n TagResolver.resolver(\"source_display_name\",\n Tag.selfClosingInserting(sourceDisplayName)),\n TagResolver.resolver(\"message\", Tag.selfClosingInserting(message)),\n TagResolver.resolver(\"channel_name\", Tag.selfClosingInserting(channelName))\n );\n }\n}" } ]
import com.electronwill.nightconfig.core.Config; import com.electronwill.nightconfig.core.file.FileConfig; import com.electronwill.nightconfig.core.file.FileNotFoundAction; import dev.gamemode.chatchannels.model.channel.Channel; import dev.gamemode.chatchannels.model.channel.SetCollectionChannel; import dev.gamemode.chatchannels.model.provider.ChannelProvider; import dev.gamemode.chatchannels.model.provider.MapChannelProvider; import dev.gamemode.chatchannels.renderer.ChannelRenderer; import dev.gamemode.chatchannels.renderer.ConfiguredRenderer; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.stream.Collectors; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.MiniMessage;
1,161
package dev.gamemode.chatchannels.config; public class ConfigReader { private FileConfig fileConfig; public void load(File dataFolder) { if (!dataFolder.exists()) { dataFolder.mkdirs(); } File filePath = new File(dataFolder, "config.yml"); this.fileConfig = FileConfig.builder(filePath) .onFileNotFound( FileNotFoundAction.copyData(ConfigReader.class.getResourceAsStream("/config.yml"))) .charset(StandardCharsets.UTF_8) .build(); this.fileConfig.load(); }
package dev.gamemode.chatchannels.config; public class ConfigReader { private FileConfig fileConfig; public void load(File dataFolder) { if (!dataFolder.exists()) { dataFolder.mkdirs(); } File filePath = new File(dataFolder, "config.yml"); this.fileConfig = FileConfig.builder(filePath) .onFileNotFound( FileNotFoundAction.copyData(ConfigReader.class.getResourceAsStream("/config.yml"))) .charset(StandardCharsets.UTF_8) .build(); this.fileConfig.load(); }
public ChannelProvider configureProvider() {
2
2023-11-07 20:33:27+00:00
2k
data-harness-cloud/data_harness-be
common/common-quartz/src/main/java/supie/common/quartz/utils/QuaryzUtil.java
[ { "identifier": "JobFieldType", "path": "common/common-quartz/src/main/java/supie/common/quartz/object/JobFieldType.java", "snippet": "public enum JobFieldType {\n\n JOB_NAME(\"任务名称\"),\n JOB_GROUP(\"任务分组\"),\n DESCRIPTION(\"任务描述\"),\n JOB_CLASS_NAME(\"作业执行类\"),\n CRON_EXPRESSION(\"Cron表达式\"),\n START_TIME(\"起始时间\"),\n END_TIME(\"结束时间\"),\n JOB_DATA_MAP(\"Job的参数数据\"),\n STATE(\"状态\");\n\n /**\n * 枚举常量描述\n */\n private String enumerateConstantDescriptions;\n\n JobFieldType(String enumerateConstantDescriptions) {\n this.enumerateConstantDescriptions = enumerateConstantDescriptions;\n }\n\n public String getFieldDescription() {\n return enumerateConstantDescriptions;\n }\n}" }, { "identifier": "QuartzJobData", "path": "common/common-quartz/src/main/java/supie/common/quartz/object/QuartzJobData.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class QuartzJobData extends QuartzJobParam {\n\n /**\n * trigger 名称。\n */\n private String triggerName;\n /**\n * trigger 分组。\n */\n private String triggerGroup;\n /**\n * trigger 状态。\n */\n private String state;\n}" }, { "identifier": "QuartzJobParam", "path": "common/common-quartz/src/main/java/supie/common/quartz/object/QuartzJobParam.java", "snippet": "@Data\npublic class QuartzJobParam {\n\n /**\n * job 名称。\n */\n private String jobName;\n /**\n * 任务分组。\n */\n private String jobGroup;\n /**\n * 任务描述。\n */\n private String description;\n /**\n * 作业执行类。\n */\n private String jobClassName;\n /**\n * cron表达式。\n */\n private String cronExpression;\n /**\n * 开始时间\n */\n private Date startTime;\n /**\n * 结束时间\n */\n private Date endTime;\n /**\n * job的参数数据。\n */\n private Map<String, Object> jobDataMap;\n}" } ]
import cn.hutool.core.util.ReflectUtil; import cn.hutool.json.JSONUtil; import supie.common.quartz.object.JobField; import supie.common.quartz.object.JobFieldType; import supie.common.quartz.object.QuartzJobData; import supie.common.quartz.object.QuartzJobParam; import java.lang.reflect.Field; import java.util.Date; import java.util.Map;
782
package supie.common.quartz.utils; /** * 描述: * * @author 王立宏 * @date 2023/10/24 10:53 * @path SDT-supie.common.quartz.utils-QuaryzUtil */ public class QuaryzUtil { public static <MDto> QuartzJobParam modelDtoToJobParam(MDto model) { QuartzJobParam quartzJobParam = new QuartzJobParam(); Class<?> modelClass = model.getClass(); Field[] fields = ReflectUtil.getFields(modelClass); for (Field field : fields) { Object fieldValue = ReflectUtil.getFieldValue(model, field); if (fieldValue == null) continue; if (field.isAnnotationPresent(JobField.class)) { JobField jobField = field.getAnnotation(JobField.class);
package supie.common.quartz.utils; /** * 描述: * * @author 王立宏 * @date 2023/10/24 10:53 * @path SDT-supie.common.quartz.utils-QuaryzUtil */ public class QuaryzUtil { public static <MDto> QuartzJobParam modelDtoToJobParam(MDto model) { QuartzJobParam quartzJobParam = new QuartzJobParam(); Class<?> modelClass = model.getClass(); Field[] fields = ReflectUtil.getFields(modelClass); for (Field field : fields) { Object fieldValue = ReflectUtil.getFieldValue(model, field); if (fieldValue == null) continue; if (field.isAnnotationPresent(JobField.class)) { JobField jobField = field.getAnnotation(JobField.class);
JobFieldType jobFieldType = jobField.value();
0
2023-11-04 12:36:44+00:00
2k
FTC-ORBIT/14872-2024-CenterStage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Sensors/OrbitGyro.java
[ { "identifier": "PID", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/OrbitUtils/PID.java", "snippet": "public class PID {\n private static final ElapsedTime timer = new ElapsedTime();\n public double kP = 0;\n public double kI = 0;\n public double kD = 0;\n public double kF = 0;\n public double iZone = 0;\n\n public double wanted = 0;\n\n private double integral = 0;\n\n private double prevError = 0;\n private double prevTime = 0;\n\n public PID(final double kP, final double kI, final double kD, final double kF, final double iZone) {\n this.kP = kP;\n this.kI = kI;\n this.kD = kD;\n this.kF = kF;\n this.iZone = iZone;\n }\n\n public void setWanted(final double wanted) {\n this.wanted = wanted;\n }\n\n public double update(final double current) {\n final double currentError = wanted - current;\n final double currentTime = timer.milliseconds();\n final double deltaTime = currentTime - prevTime;\n\n if (Math.abs(currentError) < iZone) {\n if (Math.signum(currentError) != Math.signum(prevError)) {\n integral = 0;\n } else {\n integral += currentError * deltaTime;\n }\n }\n\n final double derivative = deltaTime == 0 ? 0 : (currentError - prevError) / deltaTime;\n\n prevError = currentError;\n prevTime = currentTime;\n\n return kP * currentError + kI * integral + kD * derivative + kF * wanted;\n }\n}" }, { "identifier": "GlobalData", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/robotData/GlobalData.java", "snippet": "public class GlobalData {\n public static RobotState robotState = RobotState.TRAVEL;\n public static boolean hasGamePiece = false;\n public static boolean inAutonomous = false;\n public static float currentTime = 0;\n public static float lastTime = 0;\n public static float deltaTime = 0;\n public static boolean autonomousSide = false; //false = left, true = right\n}" } ]
import com.acmerobotics.dashboard.config.Config; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.robotcore.hardware.HardwareMap; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.teamcode.OrbitUtils.PID; import org.firstinspires.ftc.teamcode.robotData.GlobalData;
774
package org.firstinspires.ftc.teamcode.Sensors; @Config public class OrbitGyro { public static BNO055IMU imu; public static double lastAngle = 0; static double currentAngle = 0; public static double kP = 0; public static double kI = 0; public static double kD = 0;
package org.firstinspires.ftc.teamcode.Sensors; @Config public class OrbitGyro { public static BNO055IMU imu; public static double lastAngle = 0; static double currentAngle = 0; public static double kP = 0; public static double kI = 0; public static double kD = 0;
static PID anglePID = new PID(kP, kI, kD, 0, 0);
0
2023-11-03 13:32:48+00:00
2k
beminder/BeautyMinder
java/src/test/java/app/beautyminder/controller/vision/VisionApiControllerTest.java
[ { "identifier": "VisionController", "path": "java/src/main/java/app/beautyminder/controller/ocr/VisionController.java", "snippet": "@RestController\n@RequestMapping(\"/vision\")\n@RequiredArgsConstructor\npublic class VisionController {\n private final VisionService visionService;\n\n @PostMapping(\"/ocr\")\n public ResponseEntity<VisionResponseDTO> parseImageByGoogleVision(\n @RequestParam(value = \"image\", required = false) MultipartFile image,\n @RequestParam(value = \"url\", required = false) String imageUrl) {\n\n Optional<String> date;\n\n if (image != null && !image.isEmpty()) {\n // Convert MultipartFile to Base64 String\n String base64Image;\n try {\n base64Image = Base64.getEncoder().encodeToString(image.getBytes());\n } catch (IOException e) {\n // Handle the exception, perhaps log it and return an appropriate response\n return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)\n .body(new VisionResponseDTO(\"?\", \"Error processing the image file\"));\n }\n // Handle MultipartFile by passing Base64 string to service\n date = visionService.execute(base64Image);\n } else if (imageUrl != null && !imageUrl.isEmpty()) {\n // Handle URL\n date = visionService.execute(imageUrl);\n } else {\n return ResponseEntity.badRequest()\n .body(new VisionResponseDTO(\"?\", \"No image or URL provided\"));\n }\n\n return date\n .map(d -> ResponseEntity.ok(new VisionResponseDTO(d, \"Success\")))\n .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND)\n .body(new VisionResponseDTO(\"?\", \"No expiration date found or error occurred\")));\n }\n\n}" }, { "identifier": "VisionService", "path": "java/src/main/java/app/beautyminder/service/vision/VisionService.java", "snippet": "@Slf4j\n@Service\npublic class VisionService {\n\n public Optional<String> execute(String input) {\n var img = input.startsWith(\"http\") ? buildImageFromUrl(input) : buildImageFromFile(input);\n return processImage(img);\n }\n\n private Image buildImageFromUrl(String url) {\n var imgSource = ImageSource.newBuilder().setImageUri(url).build();\n return Image.newBuilder().setSource(imgSource).build();\n }\n\n private Image buildImageFromFile(String base64EncodedFile) {\n ByteString imgBytes = ByteString.copyFrom(Base64.getDecoder().decode(base64EncodedFile));\n return Image.newBuilder().setContent(imgBytes).build();\n }\n\n private Optional<String> processImage(Image img) {\n var feat = Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION).build();\n var request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();\n var requests = List.of(request);\n\n try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {\n var response = client.batchAnnotateImages(requests);\n for (var res : response.getResponsesList()) {\n if (res.hasError()) {\n log.error(\"Error: {}\", res.getError().getMessage());\n return Optional.empty();\n }\n\n for (var annotation : res.getTextAnnotationsList()) {\n var ocrResult = annotation.getDescription();\n// for (var line : ocrResult.split(\"\\\\s\")) {\n\n Optional<String> expirationDate = ExpirationDateExtractor.extractExpirationDate(ocrResult);\n if (expirationDate.isPresent()) {\n return expirationDate; // Returns the first found date from the method\n// }\n }\n }\n }\n } catch (Exception exception) {\n log.error(\"Exception occurred: {}\", exception.getMessage());\n return Optional.empty();\n }\n return Optional.empty();\n }\n}" } ]
import app.beautyminder.controller.ocr.VisionController; import app.beautyminder.service.vision.VisionService; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.io.IOException; import java.util.Optional; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
1,104
package app.beautyminder.controller.vision; @Slf4j @ActiveProfiles({"awsBasic", "test"}) public class VisionApiControllerTest { private MockMvc mockMvc; @Mock private VisionService visionService; @InjectMocks
package app.beautyminder.controller.vision; @Slf4j @ActiveProfiles({"awsBasic", "test"}) public class VisionApiControllerTest { private MockMvc mockMvc; @Mock private VisionService visionService; @InjectMocks
private VisionController visionController;
0
2023-11-01 12:37:16+00:00
2k
hacks1ash/keycloak-spring-boot-adapter
src/main/java/io/github/hacks1ash/keycloak/adapter/utils/SecurityContextHelper.java
[ { "identifier": "KeycloakAuthentication", "path": "src/main/java/io/github/hacks1ash/keycloak/adapter/KeycloakAuthentication.java", "snippet": "@Getter\n@Transient\n@EqualsAndHashCode(callSuper = true)\npublic class KeycloakAuthentication<T extends DefaultKeycloakUser> extends JwtAuthenticationToken {\n\n /** The authenticated user details. */\n private final T authenticatedUser;\n\n /**\n * Constructs a KeycloakAuthentication object with the specified parameters.\n *\n * @param jwt The JWT token.\n * @param authorities The collection of granted authorities.\n * @param name The principal name.\n * @param authenticatedUser The authenticated user details.\n */\n public KeycloakAuthentication(\n Jwt jwt,\n Collection<? extends GrantedAuthority> authorities,\n String name,\n T authenticatedUser) {\n super(jwt, authorities, name);\n this.authenticatedUser = authenticatedUser;\n }\n}" }, { "identifier": "DefaultKeycloakUser", "path": "src/main/java/io/github/hacks1ash/keycloak/adapter/model/DefaultKeycloakUser.java", "snippet": "public class DefaultKeycloakUser extends AccessToken {\n\n /**\n * Checks if the current user is a service account.\n *\n * @return true if the user is a service account, false otherwise.\n */\n public boolean isServiceAccount() {\n return this.otherClaims.containsKey(\"clientId\");\n }\n\n /**\n * Retrieves the service account ID if the user is a service account.\n * This method reads the 'clientId' from the otherClaims of the AccessToken.\n *\n * @return The service account ID as a string if available, otherwise null.\n */\n public String getServiceAccountId() {\n Object serviceAccountId = this.getOtherClaims().get(\"clientId\");\n return serviceAccountId != null ? serviceAccountId.toString() : null;\n }\n}" } ]
import io.github.hacks1ash.keycloak.adapter.KeycloakAuthentication; import io.github.hacks1ash.keycloak.adapter.model.DefaultKeycloakUser; import org.springframework.security.core.context.SecurityContextHolder;
654
package io.github.hacks1ash.keycloak.adapter.utils; /** * Helper class for accessing the security context of the current user. Provides utility methods * related to the security context, particularly for Keycloak users. */ public class SecurityContextHelper { private SecurityContextHelper() { throw new IllegalStateException("SecurityContextHelper class"); } /** * Retrieves the current authenticated user from the security context. This method casts the * current authentication object to a KeycloakAuthentication and returns the associated * authenticated user. * * @param <T> The type parameter extending AbstractKeycloakUser. * @return The current authenticated user of type T. * @throws ClassCastException if the current authentication object is not of type * KeycloakAuthentication. */ @SuppressWarnings("unchecked") public static <T extends DefaultKeycloakUser> T getCurrentUser() {
package io.github.hacks1ash.keycloak.adapter.utils; /** * Helper class for accessing the security context of the current user. Provides utility methods * related to the security context, particularly for Keycloak users. */ public class SecurityContextHelper { private SecurityContextHelper() { throw new IllegalStateException("SecurityContextHelper class"); } /** * Retrieves the current authenticated user from the security context. This method casts the * current authentication object to a KeycloakAuthentication and returns the associated * authenticated user. * * @param <T> The type parameter extending AbstractKeycloakUser. * @return The current authenticated user of type T. * @throws ClassCastException if the current authentication object is not of type * KeycloakAuthentication. */ @SuppressWarnings("unchecked") public static <T extends DefaultKeycloakUser> T getCurrentUser() {
return ((KeycloakAuthentication<T>) SecurityContextHolder.getContext().getAuthentication())
0
2023-11-09 09:18:02+00:00
2k
Xrayya/java-cli-pbpu
src/main/java/com/CashierAppUtil/Auth.java
[ { "identifier": "Cashier", "path": "src/main/java/com/Model/Cashier.java", "snippet": "public class Cashier extends Employee {\n public Cashier(UUID employeeID, String name, String username, String password) {\n super(employeeID, name, username, password);\n }\n\n public Cashier(Employee employee) {\n super(employee);\n }\n\n @Override\n public CashierMachine getMachine() {\n return new CashierMachine();\n }\n}" }, { "identifier": "Employee", "path": "src/main/java/com/Model/Employee.java", "snippet": "public abstract class Employee extends EmployeeModel {\n\n public Employee(UUID employeeID, String name, String username, String password) {\n super(employeeID, name, username, password);\n }\n\n public Employee(EmployeeModel employee) {\n super(employee);\n }\n\n public abstract CashierMachine getMachine();\n}" }, { "identifier": "Manager", "path": "src/main/java/com/Model/Manager.java", "snippet": "public class Manager extends Employee {\n public Manager(UUID employeeID, String name, String username, String password) {\n super(employeeID, name, username, password);\n }\n\n public Manager(Employee employee) {\n super(employee);\n }\n\n @Override\n public CashierMachine getMachine() {\n return new ManagerMachine();\n }\n}" }, { "identifier": "Record", "path": "src/main/java/com/RecordUtil/Record.java", "snippet": "public class Record<T> {\n protected File recordFile;\n private Class<T[]> modelClass;\n protected final Gson gson = new GsonBuilder().setPrettyPrinting().create();\n\n /**\n * @param recordFileName name of the file to be accessed. The file should be in the `/RecordFiles` directory with a structure like this project \n * @param modelClass Class object which is the class of this record\n */\n public Record(String recordFileName, Class<T[]> modelClass) {\n this.recordFile = new File(String.format(\"./src/main/java/com/RecordFiles/%s.json\", recordFileName));\n this.modelClass = modelClass;\n }\n\n /**\n * Read record file and return it as type specified\n * \n * @return\n */\n public List<T> readRecordFile() {\n StringBuilder s = new StringBuilder();\n try {\n Scanner sc = new Scanner(this.recordFile);\n while (sc.hasNextLine()) {\n s.append(sc.nextLine());\n }\n sc.close();\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n\n return Arrays.asList(gson.fromJson(s.toString(), modelClass)) ;\n }\n}" } ]
import java.util.List; import com.Model.Cashier; import com.Model.Employee; import com.Model.Manager; import com.RecordUtil.Record;
659
package com.CashierAppUtil; /** * Auth */ public class Auth { public static Employee authenticate(String username, String password) {
package com.CashierAppUtil; /** * Auth */ public class Auth { public static Employee authenticate(String username, String password) {
List<Manager> managers = new Record<Manager>("managers", Manager[].class).readRecordFile();
3
2023-11-09 05:26:20+00:00
2k
FallenDeity/GameEngine2DJava
src/main/java/engine/observers/EventSystem.java
[ { "identifier": "GameObject", "path": "src/main/java/engine/components/GameObject.java", "snippet": "public class GameObject {\n\tprivate static int ID_COUNTER = 0;\n\tprivate final List<Component> components = new ArrayList<>();\n\tpublic transient Transform transform;\n\tprivate String name;\n\tprivate int uid;\n\tprivate boolean serializable = true;\n\tprivate boolean isDestroyed = false;\n\n\tpublic GameObject(String name) {\n\t\tthis.name = name;\n\t\tuid = ID_COUNTER++;\n\t}\n\n\tpublic static void setIdCounter(int id) {\n\t\tID_COUNTER = id;\n\t}\n\n\tpublic <T extends Component> T getComponent(Class<T> componentClass) {\n\t\tfor (Component component : components) {\n\t\t\tif (componentClass.isAssignableFrom(component.getClass())) {\n\t\t\t\ttry {\n\t\t\t\t\treturn componentClass.cast(component);\n\t\t\t\t} catch (ClassCastException e) {\n\t\t\t\t\tLogger logger = Logger.getLogger(name);\n\t\t\t\t\tlogger.severe(e.getMessage());\n\t\t\t\t\tassert false\n\t\t\t\t\t\t\t: \"Error: (GameObject) Could not cast component '\" + componentClass.getName() + \"'\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic <T extends Component> void removeComponent(Class<T> componentClass) {\n\t\tfor (int i = 0; i < components.size(); i++) {\n\t\t\tComponent component = components.get(i);\n\t\t\tif (componentClass.isAssignableFrom(component.getClass())) {\n\t\t\t\tcomponents.remove(component);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic List<Component> getComponents() {\n\t\treturn components;\n\t}\n\n\tpublic void addComponent(Component component) {\n\t\tcomponent.generateUid();\n\t\tcomponents.add(component);\n\t\tcomponent.gameObject = this;\n\t}\n\n\tpublic void editorUpdate(float dt) {\n\t\tcomponents.forEach(component -> component.editorUpdate(dt));\n\t}\n\n\tpublic void update(float dt) {\n\t\tcomponents.forEach(component -> component.update(dt));\n\t}\n\n\tpublic void start() {\n\t\tcomponents.forEach(Component::start);\n\t}\n\n\tpublic void imGui() {\n\t\tcomponents.forEach(component -> {\n\t\t\tif (ImGui.collapsingHeader(component.getClass().getSimpleName())) {\n\t\t\t\tcomponent.imGui();\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void destroy() {\n\t\tif (isDestroyed) return;\n\t\tisDestroyed = true;\n\t\tcomponents.forEach(Component::destroy);\n\t}\n\n\tpublic GameObject copy() {\n\t\tGson gson = new GsonBuilder()\n\t\t\t\t.registerTypeAdapter(Component.class, new ComponentDeserializer())\n\t\t\t\t.registerTypeAdapter(GameObject.class, new GameObjectDeserializer())\n\t\t\t\t.enableComplexMapKeySerialization()\n\t\t\t\t.create();\n\t\tString json = gson.toJson(this);\n\t\tGameObject obj = gson.fromJson(json, GameObject.class);\n\t\tobj.generateUid();\n\t\tobj.getComponents().forEach(Component::generateUid);\n\t\tSpriteRenderer spr = obj.getComponent(SpriteRenderer.class);\n\t\tif (spr != null && spr.getTexture() != null) {\n\t\t\tspr.setTexture(AssetPool.getTexture(spr.getTexture().getFilePath()));\n\t\t}\n\t\treturn obj;\n\t}\n\n\tpublic boolean isDestroyed() {\n\t\treturn isDestroyed;\n\t}\n\n\tpublic void generateUid() {\n\t\tuid = ID_COUNTER++;\n\t}\n\n\tpublic int getUid() {\n\t\treturn uid;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic void setNotSerializable() {\n\t\tserializable = false;\n\t}\n\n\tpublic boolean isSerializable() {\n\t\treturn serializable;\n\t}\n}" }, { "identifier": "Event", "path": "src/main/java/engine/observers/events/Event.java", "snippet": "public class Event {\n\tprivate final EventType eventType;\n\n\tpublic Event(EventType eventType) {\n\t\tthis.eventType = eventType;\n\t}\n\n\tpublic EventType getEventType() {\n\t\treturn eventType;\n\t}\n}" } ]
import engine.components.GameObject; import engine.observers.events.Event; import java.util.ArrayList; import java.util.List;
1,085
package engine.observers; public class EventSystem { private static EventSystem instance = null; private final List<Observer> observers; private EventSystem() { observers = new ArrayList<>(); } public static EventSystem getInstance() { if (instance == null) { instance = new EventSystem(); } return instance; } public void addObserver(Observer observer) { observers.add(observer); } public void removeObserver(Observer observer) { observers.remove(observer); }
package engine.observers; public class EventSystem { private static EventSystem instance = null; private final List<Observer> observers; private EventSystem() { observers = new ArrayList<>(); } public static EventSystem getInstance() { if (instance == null) { instance = new EventSystem(); } return instance; } public void addObserver(Observer observer) { observers.add(observer); } public void removeObserver(Observer observer) { observers.remove(observer); }
public void notify(GameObject gameObject, Event event) {
1
2023-11-04 13:19:21+00:00
2k
RezaGooner/University-food-ordering
Frames/Admin/ProfileManagment/LogHistory.java
[ { "identifier": "icon", "path": "Classes/Pathes/FilesPath.java", "snippet": "public static ImageIcon icon = new ImageIcon(\"Source/icon.png\");\r" }, { "identifier": "errorSound", "path": "Classes/Theme/SoundEffect.java", "snippet": "public static void errorSound() throws IOException, UnsupportedAudioFileException, LineUnavailableException {\r\n Path filePath = Paths.get(ErrorSoundPath);\r\n String absolutePath = filePath.toAbsolutePath().toString();\r\n AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(absolutePath));\r\n\r\n Clip clip = AudioSystem.getClip();\r\n\r\n clip.open(audioInputStream);\r\n\r\n clip.start();\r\n}\r" }, { "identifier": "LogPath", "path": "Classes/Pathes/FilesPath.java", "snippet": "public static String LogPath = \"log.txt\";\r" } ]
import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import static Classes.Pathes.FilesPath.icon; import static Classes.Theme.SoundEffect.errorSound; import static Classes.Pathes.FilesPath.LogPath; import javax.sound.sampled.LineUnavailableException;
1,493
package Frames.Admin.ProfileManagment; /* این کد یک پنجره جدول برای نمایش تاریخچه ورود کاربران به سیستم ایجاد می‌کند. در این پنجره، داده‌های مربوط به فایل log.txt خوانده شده و در جدول نمایش داده می‌شوند. همچنین، امکان جستجو در داده‌های جدول با استفاده از یک JTextField نیز فراهم شده است. در متد سازنده، یک DefaultTableModel ایجاد و ستون‌های مربوط به شناسه، زمان و وضعیت ورود به آن اضافه می‌شوند. سپس، با استفاده از FileInputStream و BufferedReader، داده‌های مربوط به فایل log.txt خوانده شده و به صورت ردیف به جدول اضافه می‌شوند. در پایان، جستجو به پنجره اضافه شده و با استفاده از TableRowSorter، توانایی مرتب‌سازی ردیف‌ها به صورت صعودی و نزولی فراهم شده است. سپس، جدول به پنجره اضافه شده و پنجره نمایش داده می‌شود. ````````````````````````````````````````````````````` This code is a Java class named `LogHistory` that extends the `JFrame` class. It represents a GUI application for displaying and searching log history. Here is a breakdown of the code: 1. The code imports various classes from different packages, including `javax.sound.sampled` for handling audio-related exceptions, `javax.swing` for GUI components, `javax.swing.table` for table-related components, `java.awt.event` for event-related classes, and `java.io` for file-related operations. 2. The `LogHistory` class is defined, which extends the `JFrame` class. 3. The constructor of the `LogHistory` class is defined. It sets up the main frame by setting the title. 4. A `DefaultTableModel` named `tableModel` is created to hold the data for the table. Columns with the headers "شناسه" (ID), "زمان" (Time), and "وضعیت ورود" (Login Status) are added to the table model. 5. The log data is read from a file specified by the `LogPath` and added to the table model. Each line of the file represents a row in the table. 6. A `JTable` named `table` is created using the table model. 7. A search panel (`JPanel`) is created to hold the search field. The search field (`JTextField`) allows users to search for specific entries in the table. When the Enter key is pressed in the search field, an action listener is triggered to filter the table rows based on the entered text. 8. The search panel is added to the north (top) of the frame. 9. A `TableRowSorter` named `sorter` is created using the table model. It allows sorting and filtering of the table rows. 10. The sorter is set on the table using the `setRowSorter()` method. 11. The table is wrapped inside a scroll pane (`JScrollPane`) and added to the frame. 12. A menu bar (`JMenuBar`) is created and added to the frame. 13. A menu (`JMenu`) named "بیشتر" (More) is created and added to the menu bar. 14. A menu item (`JMenuItem`) named "تازه سازی" (Refresh) is created. It adds an action listener to refresh the log history by disposing the current frame and creating a new instance of `LogHistory`. 15. The menu item is added to the menu. 16. The icon image is set for the frame using the `setIconImage()` method. 17. The default close operation is set to dispose the frame when it is closed. 18. The frame is positioned at the center of the screen using the `setLocationRelativeTo()` method. 19. The frame is packed to adjust its size based on the components. 20. The frame is set to be visible. Overall, this code provides a GUI application for displaying log history in a table format. It allows users to search for specific entries and refresh the log history. */ public class LogHistory extends JFrame { private JTable table; private TableRowSorter<DefaultTableModel> sorter; public LogHistory() throws UnsupportedAudioFileException, LineUnavailableException, IOException { super("سابقه ورود"); DefaultTableModel tableModel = new DefaultTableModel(); tableModel.addColumn("شناسه"); tableModel.addColumn("زمان"); tableModel.addColumn("وضعیت ورود"); try (BufferedReader br = new BufferedReader(new FileReader(new File(LogPath)))) { String line; while ((line = br.readLine()) != null) { String[] parts = line.split(" , "); tableModel.addRow(parts); } } catch (Exception e) {
package Frames.Admin.ProfileManagment; /* این کد یک پنجره جدول برای نمایش تاریخچه ورود کاربران به سیستم ایجاد می‌کند. در این پنجره، داده‌های مربوط به فایل log.txt خوانده شده و در جدول نمایش داده می‌شوند. همچنین، امکان جستجو در داده‌های جدول با استفاده از یک JTextField نیز فراهم شده است. در متد سازنده، یک DefaultTableModel ایجاد و ستون‌های مربوط به شناسه، زمان و وضعیت ورود به آن اضافه می‌شوند. سپس، با استفاده از FileInputStream و BufferedReader، داده‌های مربوط به فایل log.txt خوانده شده و به صورت ردیف به جدول اضافه می‌شوند. در پایان، جستجو به پنجره اضافه شده و با استفاده از TableRowSorter، توانایی مرتب‌سازی ردیف‌ها به صورت صعودی و نزولی فراهم شده است. سپس، جدول به پنجره اضافه شده و پنجره نمایش داده می‌شود. ````````````````````````````````````````````````````` This code is a Java class named `LogHistory` that extends the `JFrame` class. It represents a GUI application for displaying and searching log history. Here is a breakdown of the code: 1. The code imports various classes from different packages, including `javax.sound.sampled` for handling audio-related exceptions, `javax.swing` for GUI components, `javax.swing.table` for table-related components, `java.awt.event` for event-related classes, and `java.io` for file-related operations. 2. The `LogHistory` class is defined, which extends the `JFrame` class. 3. The constructor of the `LogHistory` class is defined. It sets up the main frame by setting the title. 4. A `DefaultTableModel` named `tableModel` is created to hold the data for the table. Columns with the headers "شناسه" (ID), "زمان" (Time), and "وضعیت ورود" (Login Status) are added to the table model. 5. The log data is read from a file specified by the `LogPath` and added to the table model. Each line of the file represents a row in the table. 6. A `JTable` named `table` is created using the table model. 7. A search panel (`JPanel`) is created to hold the search field. The search field (`JTextField`) allows users to search for specific entries in the table. When the Enter key is pressed in the search field, an action listener is triggered to filter the table rows based on the entered text. 8. The search panel is added to the north (top) of the frame. 9. A `TableRowSorter` named `sorter` is created using the table model. It allows sorting and filtering of the table rows. 10. The sorter is set on the table using the `setRowSorter()` method. 11. The table is wrapped inside a scroll pane (`JScrollPane`) and added to the frame. 12. A menu bar (`JMenuBar`) is created and added to the frame. 13. A menu (`JMenu`) named "بیشتر" (More) is created and added to the menu bar. 14. A menu item (`JMenuItem`) named "تازه سازی" (Refresh) is created. It adds an action listener to refresh the log history by disposing the current frame and creating a new instance of `LogHistory`. 15. The menu item is added to the menu. 16. The icon image is set for the frame using the `setIconImage()` method. 17. The default close operation is set to dispose the frame when it is closed. 18. The frame is positioned at the center of the screen using the `setLocationRelativeTo()` method. 19. The frame is packed to adjust its size based on the components. 20. The frame is set to be visible. Overall, this code provides a GUI application for displaying log history in a table format. It allows users to search for specific entries and refresh the log history. */ public class LogHistory extends JFrame { private JTable table; private TableRowSorter<DefaultTableModel> sorter; public LogHistory() throws UnsupportedAudioFileException, LineUnavailableException, IOException { super("سابقه ورود"); DefaultTableModel tableModel = new DefaultTableModel(); tableModel.addColumn("شناسه"); tableModel.addColumn("زمان"); tableModel.addColumn("وضعیت ورود"); try (BufferedReader br = new BufferedReader(new FileReader(new File(LogPath)))) { String line; while ((line = br.readLine()) != null) { String[] parts = line.split(" , "); tableModel.addRow(parts); } } catch (Exception e) {
errorSound();
1
2023-11-03 08:35:22+00:00
2k
Celant/PlaytimeSchedule
src/main/java/uk/co/celant/playtimeschedule/Events.java
[ { "identifier": "IPlaytimeCapability", "path": "src/main/java/uk/co/celant/playtimeschedule/capabilities/IPlaytimeCapability.java", "snippet": "public interface IPlaytimeCapability extends INBTSerializable<CompoundTag> {\r\n int getPlaytime();\r\n int getPlaytimeLeft();\r\n String getPlaytimeLeftString();\r\n void incrementPlaytime(boolean save);\r\n void resetPlaytime();\r\n boolean dayHasChanged();\r\n boolean getInFreePlay();\r\n void setInFreePlay(boolean value);\r\n void copy(IPlaytimeCapability playtimeCapability);\r\n}\r" }, { "identifier": "PlaytimeCapability", "path": "src/main/java/uk/co/celant/playtimeschedule/capabilities/PlaytimeCapability.java", "snippet": "public class PlaytimeCapability implements IPlaytimeCapability {\r\n private int curPlaytime = 0;\r\n private long dayMillis = System.currentTimeMillis();\r\n private long lastCheckMillis = System.currentTimeMillis();\r\n private boolean inFreePlay = false;\r\n\r\n @Override\r\n public int getPlaytime() {\r\n return this.curPlaytime;\r\n }\r\n\r\n @Override\r\n public int getPlaytimeLeft() {\r\n if (PlaytimeSchedule.CONFIG.dailyPlaytimeLimit.get() == -1) return -1;\r\n return Math.max(PlaytimeSchedule.CONFIG.dailyPlaytimeLimit.get() - getPlaytime(), 0);\r\n }\r\n\r\n @Override\r\n public String getPlaytimeLeftString() {\r\n int left = this.getPlaytimeLeft();\r\n\r\n String seconds = new DecimalFormat(\"00\").format(Duration.ofSeconds(left).toSecondsPart());\r\n String minutes = new DecimalFormat(\"00\").format(Duration.ofSeconds(left).toMinutesPart());\r\n String hours = new DecimalFormat(\"00\").format(Duration.ofSeconds(left).toHoursPart());\r\n return ChatFormatting.GREEN + \"You have \"\r\n + ChatFormatting.RED + hours + ChatFormatting.GREEN + \" hours, \"\r\n + ChatFormatting.RED + minutes + ChatFormatting.GREEN + \" minutes and \"\r\n + ChatFormatting.RED + seconds + ChatFormatting.GREEN + \" seconds left\";\r\n }\r\n\r\n @Override\r\n public void incrementPlaytime(boolean save) {\r\n if (save) {\r\n this.curPlaytime = this.curPlaytime + deltaTime();\r\n }\r\n this.lastCheckMillis = System.currentTimeMillis();\r\n }\r\n\r\n @Override\r\n public void resetPlaytime() {\r\n this.dayMillis = System.currentTimeMillis();\r\n this.curPlaytime = 0;\r\n }\r\n\r\n @Override\r\n public boolean dayHasChanged() {\r\n long newDayMillis = System.currentTimeMillis();\r\n\r\n Calendar cal = Calendar.getInstance();\r\n cal.setTimeInMillis(this.dayMillis);\r\n int oldDay = cal.get(Calendar.DAY_OF_MONTH);\r\n\r\n cal.setTimeInMillis(newDayMillis);\r\n int newDay = cal.get(Calendar.DAY_OF_MONTH);\r\n\r\n return oldDay != newDay;\r\n }\r\n\r\n @Override\r\n public boolean getInFreePlay() {\r\n return this.inFreePlay;\r\n }\r\n\r\n @Override\r\n public void setInFreePlay(boolean value) {\r\n this.inFreePlay = value;\r\n }\r\n\r\n @Override\r\n public void copy(IPlaytimeCapability playtimeCapability) {\r\n this.curPlaytime = playtimeCapability.getPlaytime();\r\n this.inFreePlay = playtimeCapability.getInFreePlay();\r\n }\r\n\r\n private int deltaTime() {\r\n long newCheckMillis = System.currentTimeMillis();\r\n long diff = newCheckMillis - this.lastCheckMillis;\r\n return Math.round(diff / 1000f);\r\n }\r\n\r\n @Override\r\n public CompoundTag serializeNBT() {\r\n final CompoundTag tag = new CompoundTag();\r\n tag.putInt(\"curPlaytime\", this.curPlaytime);\r\n tag.putLong(\"dayMillis\", this.dayMillis);\r\n return tag;\r\n }\r\n\r\n @Override\r\n public void deserializeNBT(CompoundTag nbt) {\r\n\r\n this.curPlaytime = nbt.getInt(\"curPlaytime\");\r\n this.dayMillis = nbt.getLong(\"dayMillis\");\r\n }\r\n}\r" }, { "identifier": "PlaytimeCapabilityProvider", "path": "src/main/java/uk/co/celant/playtimeschedule/capabilities/PlaytimeCapabilityProvider.java", "snippet": "public class PlaytimeCapabilityProvider implements ICapabilitySerializable<CompoundTag> {\r\n public static final ResourceLocation IDENTIFIER = new ResourceLocation(PlaytimeSchedule.MODID, \"playtime_capability\");\r\n\r\n private final IPlaytimeCapability backend = new PlaytimeCapability();\r\n private final LazyOptional<IPlaytimeCapability> playtimeCapabilityLazyOptional = LazyOptional.of(() -> backend);\r\n\r\n @Override\r\n public <T> @NotNull LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {\r\n return PlaytimeSchedule.PLAYTIME.orEmpty(cap, this.playtimeCapabilityLazyOptional);\r\n }\r\n\r\n void invalidate() {\r\n this.playtimeCapabilityLazyOptional.invalidate();\r\n }\r\n\r\n @Override\r\n public CompoundTag serializeNBT() {\r\n return backend.serializeNBT();\r\n }\r\n\r\n @Override\r\n public void deserializeNBT(CompoundTag nbt) {\r\n backend.deserializeNBT(nbt);\r\n }\r\n}\r" } ]
import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.server.permission.PermissionAPI; import uk.co.celant.playtimeschedule.capabilities.IPlaytimeCapability; import uk.co.celant.playtimeschedule.capabilities.PlaytimeCapability; import uk.co.celant.playtimeschedule.capabilities.PlaytimeCapabilityProvider; import java.text.DecimalFormat; import java.time.Duration; import java.util.Calendar; import java.util.List;
1,495
package uk.co.celant.playtimeschedule; @Mod.EventBusSubscriber(modid = PlaytimeSchedule.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE) public class Events { private int tick; @SubscribeEvent public void registerCapabilities(RegisterCapabilitiesEvent event) { event.register(IPlaytimeCapability.class); } @SubscribeEvent public void attachCapability(AttachCapabilitiesEvent<Entity> event) { if (!(event.getObject() instanceof Player)) return; event.addCapability(PlaytimeCapabilityProvider.IDENTIFIER, new PlaytimeCapabilityProvider()); } @SubscribeEvent public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { Player player = event.getEntity();
package uk.co.celant.playtimeschedule; @Mod.EventBusSubscriber(modid = PlaytimeSchedule.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE) public class Events { private int tick; @SubscribeEvent public void registerCapabilities(RegisterCapabilitiesEvent event) { event.register(IPlaytimeCapability.class); } @SubscribeEvent public void attachCapability(AttachCapabilitiesEvent<Entity> event) { if (!(event.getObject() instanceof Player)) return; event.addCapability(PlaytimeCapabilityProvider.IDENTIFIER, new PlaytimeCapabilityProvider()); } @SubscribeEvent public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { Player player = event.getEntity();
IPlaytimeCapability playtime = player.getCapability(PlaytimeSchedule.PLAYTIME).orElse(new PlaytimeCapability());
1
2023-11-02 12:52:02+00:00
2k
EaindrayFromEarth/Collaborative_Blog_Version_Control_Management-System
java/com/we_write/config/SecurityConfig.java
[ { "identifier": "UserRepository", "path": "java/com/we_write/repository/UserRepository.java", "snippet": "@Repository\r\npublic interface UserRepository extends JpaRepository<User, Long> {\r\n\r\n Optional<User> findByEmail(String email);\r\n\r\n Optional<User> findByUsernameOrEmail(String username, String email);\r\n\r\n Optional<User> findByUsername(User createdBy);\r\n\r\n Boolean existsByUsername(String username);\r\n\r\n Boolean existsByEmail(String email);\r\n\r\n\tOptional<User> findByUsername(String createdBy);\r\n}" }, { "identifier": "JwtAuthenticationEntryPoint", "path": "java/com/we_write/security/JwtAuthenticationEntryPoint.java", "snippet": "@Component\r\npublic class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {\r\n\r\n @Override\r\n public void commence(HttpServletRequest request,\r\n HttpServletResponse response,\r\n AuthenticationException authException) throws IOException, ServletException {\r\n\r\n response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());\r\n }\r\n}" }, { "identifier": "JwtAuthenticationFilter", "path": "java/com/we_write/security/JwtAuthenticationFilter.java", "snippet": "public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {\r\n\r\n private JwtTokenProvider jwtTokenProvider;\r\n\r\n private UserDetailsService userDetailsService;\r\n\r\n\tprivate final AuthenticationManager authenticationManager;\r\n\r\n public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider,AuthenticationManager authenticationManager, UserDetailsService userDetailsService) {\r\n this.jwtTokenProvider = jwtTokenProvider;\r\n this.authenticationManager = authenticationManager;\r\n this.userDetailsService = userDetailsService;\r\n }\r\n\r\n\r\n protected void doFilterInternal(HttpServletRequest request,\r\n HttpServletResponse response,\r\n FilterChain filterChain) throws ServletException, IOException {\r\n\r\n // get JWT token from http request\r\n String token = getTokenFromRequest(request);\r\n\r\n // validate token\r\n if(StringUtils.hasText(token) && jwtTokenProvider.validateToken(token)){\r\n\r\n // get username from token\r\n String username = jwtTokenProvider.getUsername(token);\r\n\r\n // load the user associated with token\r\n UserDetails userDetails = userDetailsService.loadUserByUsername(username);\r\n\r\n UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(\r\n userDetails,\r\n null,\r\n userDetails.getAuthorities()\r\n );\r\n\r\n authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));\r\n\r\n SecurityContextHolder.getContext().setAuthentication(authenticationToken);\r\n\r\n }\r\n\r\n filterChain.doFilter(request, response);\r\n }\r\n\r\n private String getTokenFromRequest(HttpServletRequest request){\r\n\r\n String bearerToken = request.getHeader(\"Authorization\");\r\n\r\n if(StringUtils.hasText(bearerToken) && bearerToken.startsWith(\"Bearer \")){\r\n return bearerToken.substring(7, bearerToken.length());\r\n }\r\n\r\n return null;\r\n }\r\n\r\n}" }, { "identifier": "JwtTokenProvider", "path": "java/com/we_write/security/JwtTokenProvider.java", "snippet": "@Component\r\npublic class JwtTokenProvider {\r\n\r\n @Value(\"${app.jwt-secret}\")\r\n private String jwtSecret;\r\n\r\n @Value(\"${app-jwt-expiration-milliseconds}\")\r\n private long jwtExpirationDate;\r\n\r\n // generate JWT token\r\n public String generateToken(Authentication authentication){\r\n String username = authentication.getName();\r\n\r\n Date currentDate = new Date();\r\n\r\n Date expireDate = new Date(currentDate.getTime() + jwtExpirationDate);\r\n\r\n String token = Jwts.builder()\r\n .setSubject(username)\r\n .setIssuedAt(new Date())\r\n .setExpiration(expireDate)\r\n .signWith(key())\r\n .compact();\r\n return token;\r\n }\r\n\r\n private Key key(){\r\n return Keys.hmacShaKeyFor(\r\n Decoders.BASE64.decode(jwtSecret)\r\n );\r\n }\r\n\r\n // get username from Jwt token\r\n public String getUsername(String token){\r\n Claims claims = Jwts.parserBuilder()\r\n .setSigningKey(key())\r\n .build()\r\n .parseClaimsJws(token)\r\n .getBody();\r\n String username = claims.getSubject();\r\n return username;\r\n }\r\n\r\n // validate Jwt token\r\n public boolean validateToken(String token){\r\n try{\r\n Jwts.parserBuilder()\r\n .setSigningKey(key())\r\n .build()\r\n .parse(token);\r\n return true;\r\n } catch (MalformedJwtException ex) {\r\n throw new BlogAPIException(HttpStatus.BAD_REQUEST, \"Invalid JWT token\");\r\n } catch (ExpiredJwtException ex) {\r\n throw new BlogAPIException(HttpStatus.BAD_REQUEST, \"Expired JWT token\");\r\n } catch (UnsupportedJwtException ex) {\r\n throw new BlogAPIException(HttpStatus.BAD_REQUEST, \"Unsupported JWT token\");\r\n } catch (IllegalArgumentException ex) {\r\n throw new BlogAPIException(HttpStatus.BAD_REQUEST, \"JWT claims string is empty.\");\r\n }\r\n }\r\n\r\n\r\n}" }, { "identifier": "CustomUserDetailsService", "path": "java/com/we_write/service/CustomUserDetailsService.java", "snippet": "@Service\r\npublic class CustomUserDetailsService implements UserDetailsService {\r\n\r\n\t@Autowired\r\n private UserRepository userRepository;\r\n\r\n @Autowired\r\n public CustomUserDetailsService(UserRepository userRepository) {\r\n this.userRepository = userRepository;\r\n }\r\n @Override\r\n public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException {\r\n User user = userRepository.findByUsernameOrEmail(usernameOrEmail, usernameOrEmail)\r\n .orElseThrow(() ->\r\n new UsernameNotFoundException(\"User not found with username or email: \"+ usernameOrEmail));\r\n\r\n Set<GrantedAuthority> authorities = user\r\n .getRoles()\r\n .stream()\r\n .map((role) -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toSet());\r\n\r\n return new org.springframework.security.core.userdetails.User(user.getEmail(),\r\n user.getPassword(),\r\n authorities);\r\n }\r\n}" } ]
import io.swagger.v3.oas.annotations.security.SecurityScheme; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import com.we_write.repository.UserRepository; import com.we_write.security.JwtAuthenticationEntryPoint; import com.we_write.security.JwtAuthenticationFilter; import com.we_write.security.JwtTokenProvider; import com.we_write.service.CustomUserDetailsService; import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
1,598
package com.we_write.config; @Configuration @EnableWebSecurity @EnableMethodSecurity @SecurityScheme( name = "Bear Authentication", type = SecuritySchemeType.HTTP, bearerFormat = "JWT", scheme = "bearer" ) public class SecurityConfig { private JwtAuthenticationEntryPoint authenticationEntryPoint; private JwtAuthenticationFilter authenticationFilter; @Bean public UserDetailsService userDetailsService(UserRepository userRepository) { return new CustomUserDetailsService(userRepository); } @Bean
package com.we_write.config; @Configuration @EnableWebSecurity @EnableMethodSecurity @SecurityScheme( name = "Bear Authentication", type = SecuritySchemeType.HTTP, bearerFormat = "JWT", scheme = "bearer" ) public class SecurityConfig { private JwtAuthenticationEntryPoint authenticationEntryPoint; private JwtAuthenticationFilter authenticationFilter; @Bean public UserDetailsService userDetailsService(UserRepository userRepository) { return new CustomUserDetailsService(userRepository); } @Bean
public JwtAuthenticationFilter customJwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider, AuthenticationManager authenticationManager, UserDetailsService userDetailsService) {
3
2023-11-05 05:44:23+00:00
2k
agomezlucena/merger
src/main/java/io/github/agomezlucena/mergers/Merger.java
[ { "identifier": "ErrorMessageKeys", "path": "src/main/java/io/github/agomezlucena/errors/ErrorMessageKeys.java", "snippet": "public enum ErrorMessageKeys {\n /**\n * Represents the key used when the given collection is null\n */\n COLLECTION_IS_NULL(\"collections.isnull\"),\n /**\n * Represent the key used when the hash function is null\n */\n HASH_FUNCTION_IS_NULL(\"functions.hash.isnull\"),\n /**\n * Represent the key used when the given merger function is null\n */\n MERGER_FUNCTION_IS_NULL(\"functions.merger.isnull\"),\n /**\n * Represent the key used when the given normalizer function is null\n */\n FIRST_NORMALIZER_IS_NULL(\"functions.normalizer.first.isnull\"),\n /**\n * Represent the key used when the given normalizer function is null\n */\n SECOND_NORMALIZER_IS_NULL(\"functions.normalizer.second.isnull\"),\n /**\n * Represent the key used when the given parameter is null\n */\n PARAM_IS_NULL(\"param.isnull\");\n final String key;\n ErrorMessageKeys(String key){\n this.key = key;\n }\n}" }, { "identifier": "ErrorPayload", "path": "src/main/java/io/github/agomezlucena/errors/ErrorPayload.java", "snippet": "public class ErrorPayload {\n private final Class<? extends RuntimeException> errorClass;\n private final ErrorMessageKeys key;\n private final String messageParam;\n\n /**\n * Generates a ErrorPayload object\n *\n * @param key any of the ErrorMessageKeys\n * @param errorClass any RuntimeException\n * @return an ErrorPayload object that later will generate an exception from the given\n * class with the error message referenced by the given key, if the message have any\n * substitution will replace it with null by instance if you have the string\n * <em>'param: %s must not be null'</em> will create the message <em>'param: null must not be null'</em>\n */\n public static ErrorPayload of(ErrorMessageKeys key, Class<? extends RuntimeException> errorClass) {\n return new ErrorPayload(errorClass, key);\n }\n\n /**\n * Generates a ErrorPayload object\n *\n * @param key any of the ErrorMessageKey\n * @param messageParam the string with value that we expect\n * @param errorClass any RuntimeException\n * @return an ErrorPayload object that later will generate an exception from the given class\n * formatting with the message with the string that you pass.\n */\n public static ErrorPayload of(ErrorMessageKeys key, String messageParam, Class<? extends RuntimeException> errorClass) {\n return new ErrorPayload(errorClass, key, messageParam);\n }\n\n private ErrorPayload(Class<? extends RuntimeException> errorClass, ErrorMessageKeys key) {\n this(errorClass, key, null);\n }\n\n private ErrorPayload(Class<? extends RuntimeException> errorClass, ErrorMessageKeys key, String messageParam) {\n this.errorClass = errorClass;\n this.key = key;\n this.messageParam = messageParam;\n }\n\n /**\n * Return the configured exception with the required message based in its error key.\n * @return the expected exception but when can't instantiate the expected exception\n * will return an IllegalStateException with message 'can't create ExceptionName exception'\n */\n public RuntimeException throwException() {\n try {\n return errorClass.getDeclaredConstructor(String.class).newInstance(getMessage());\n } catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) {\n return new IllegalStateException(getMessage(\"errors.exception.instantiate\",errorClass.getSimpleName()),e);\n }\n }\n\n private String getMessage() {\n return getMessage(key.key,messageParam);\n }\n\n private String getMessage(String key,String param){\n String message = ResourceBundle.getBundle(\"errors\").getString(key);\n if (message.contains(\"%s\")) return String.format(message, param);\n return message;\n }\n}" }, { "identifier": "throwIfNull", "path": "src/main/java/io/github/agomezlucena/errors/ThrowingFunctions.java", "snippet": "public static <U> void throwIfNull(U object, ErrorPayload payload) {\n Optional.ofNullable(object)\n .orElseThrow(payload::throwException);\n}" } ]
import io.github.agomezlucena.errors.ErrorMessageKeys; import io.github.agomezlucena.errors.ErrorPayload; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import static io.github.agomezlucena.errors.ThrowingFunctions.throwIfNull;
1,275
package io.github.agomezlucena.mergers; /** * This class allow you to merge two collections based in a hash function to define the identity * and a merger function to execute the merge logic. * By default, if you don't define any hash function will Object.hashCode * * @param <T> the type of the resulting collection. * @param <FC> the type of the first collection. * @param <SC> the type of the second collection. * @author Alejandro Gómez Lucena. */ public abstract class Merger<T, FC, SC> { protected final Collection<FC> firstCollection; protected Collection<SC> secondCollection; protected Function<T, Integer> hashFunction = Object::hashCode; protected BiFunction<T, T, T> mergerFunction; /** * Allows you to create a Merger object with a not null collection of objects of type FC * @param firstCollection not null collection * @throws IllegalArgumentException if firstCollection is null */ protected Merger(Collection<FC> firstCollection) {
package io.github.agomezlucena.mergers; /** * This class allow you to merge two collections based in a hash function to define the identity * and a merger function to execute the merge logic. * By default, if you don't define any hash function will Object.hashCode * * @param <T> the type of the resulting collection. * @param <FC> the type of the first collection. * @param <SC> the type of the second collection. * @author Alejandro Gómez Lucena. */ public abstract class Merger<T, FC, SC> { protected final Collection<FC> firstCollection; protected Collection<SC> secondCollection; protected Function<T, Integer> hashFunction = Object::hashCode; protected BiFunction<T, T, T> mergerFunction; /** * Allows you to create a Merger object with a not null collection of objects of type FC * @param firstCollection not null collection * @throws IllegalArgumentException if firstCollection is null */ protected Merger(Collection<FC> firstCollection) {
throwIfNull(firstCollection, ErrorPayload.of(ErrorMessageKeys.COLLECTION_IS_NULL, IllegalArgumentException.class));
0
2023-11-05 15:29:30+00:00
2k
af19git5/EasyImage
src/main/java/io/github/af19git5/entity/Text.java
[ { "identifier": "PositionX", "path": "src/main/java/io/github/af19git5/type/PositionX.java", "snippet": "@Getter\npublic enum PositionX {\n\n /** 無指定位置 */\n NONE,\n\n /** 置左 */\n LEFT,\n\n /** 置中 */\n MIDDLE,\n\n /** 置右 */\n RIGHT\n}" }, { "identifier": "PositionY", "path": "src/main/java/io/github/af19git5/type/PositionY.java", "snippet": "@Getter\npublic enum PositionY {\n\n /** 無指定位置 */\n NONE,\n\n /** 置頂 */\n TOP,\n\n /** 置中 */\n MIDDLE,\n\n /** 置底 */\n BOTTOM\n}" } ]
import io.github.af19git5.type.PositionX; import io.github.af19git5.type.PositionY; import lombok.Getter; import lombok.NonNull; import java.awt.*;
813
package io.github.af19git5.entity; /** * 插入文字物件 * * @author Jimmy Kang */ @Getter public class Text extends Item { private final String text; private final Color color; private final Font font; /** * @param x 放置x軸位置 * @param y 放置y軸位置 * @param text 文字內容 * @param color 文字顏色 */ public Text(int x, int y, @NonNull String text, @NonNull Color color) { this.setX(x); this.setY(y); this.text = text; this.color = color; this.font = null; } /** * @param x 放置x軸位置 * @param y 放置y軸位置 * @param text 文字內容 * @param colorHex 文字顏色(16進位色碼) */ public Text(int x, int y, @NonNull String text, @NonNull String colorHex) { this.setX(x); this.setY(y); this.text = text; this.color = Color.decode(colorHex); this.font = null; } /** * @param x 放置x軸位置 * @param y 放置y軸位置 * @param text 文字內容 * @param color 文字顏色 * @param font 文字字體 */ public Text(int x, int y, @NonNull String text, @NonNull Color color, Font font) { this.setX(x); this.setY(y); this.text = text; this.color = color; this.font = font; } /** * @param x 放置x軸位置 * @param y 放置y軸位置 * @param text 文字內容 * @param colorHex 文字顏色(16進位色碼) * @param font 文字字體 */ public Text(int x, int y, @NonNull String text, @NonNull String colorHex, Font font) { this.setX(x); this.setY(y); this.text = text; this.color = Color.decode(colorHex); this.font = font; } /** * @param positionX 放置x軸位置 * @param y 放置y軸位置 * @param text 文字內容 * @param color 文字顏色 */
package io.github.af19git5.entity; /** * 插入文字物件 * * @author Jimmy Kang */ @Getter public class Text extends Item { private final String text; private final Color color; private final Font font; /** * @param x 放置x軸位置 * @param y 放置y軸位置 * @param text 文字內容 * @param color 文字顏色 */ public Text(int x, int y, @NonNull String text, @NonNull Color color) { this.setX(x); this.setY(y); this.text = text; this.color = color; this.font = null; } /** * @param x 放置x軸位置 * @param y 放置y軸位置 * @param text 文字內容 * @param colorHex 文字顏色(16進位色碼) */ public Text(int x, int y, @NonNull String text, @NonNull String colorHex) { this.setX(x); this.setY(y); this.text = text; this.color = Color.decode(colorHex); this.font = null; } /** * @param x 放置x軸位置 * @param y 放置y軸位置 * @param text 文字內容 * @param color 文字顏色 * @param font 文字字體 */ public Text(int x, int y, @NonNull String text, @NonNull Color color, Font font) { this.setX(x); this.setY(y); this.text = text; this.color = color; this.font = font; } /** * @param x 放置x軸位置 * @param y 放置y軸位置 * @param text 文字內容 * @param colorHex 文字顏色(16進位色碼) * @param font 文字字體 */ public Text(int x, int y, @NonNull String text, @NonNull String colorHex, Font font) { this.setX(x); this.setY(y); this.text = text; this.color = Color.decode(colorHex); this.font = font; } /** * @param positionX 放置x軸位置 * @param y 放置y軸位置 * @param text 文字內容 * @param color 文字顏色 */
public Text(@NonNull PositionX positionX, int y, @NonNull String text, @NonNull Color color) {
0
2023-11-01 03:55:06+00:00
2k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/utils/ImageUtils.java
[ { "identifier": "Coordinate", "path": "src/main/java/com/chadfield/shogiexplorer/objects/Coordinate.java", "snippet": "public class Coordinate {\n\n private Integer x;\n private Integer y;\n\n public Coordinate() {\n\n }\n\n public Coordinate(Integer x, Integer y) {\n this.x = x;\n this.y = y;\n }\n\n /**\n * @return the x\n */\n public Integer getX() {\n return x;\n }\n\n /**\n * @param x the x to set\n */\n public void setX(Integer x) {\n this.x = x;\n }\n\n /**\n * @return the y\n */\n public Integer getY() {\n return y;\n }\n\n /**\n * @param y the y to set\n */\n public void setY(Integer y) {\n this.y = y;\n }\n\n public boolean sameValue(Coordinate otherCoordinate) {\n return (Objects.equals(this.x, otherCoordinate.getX())) && (Objects.equals(this.y, otherCoordinate.getY()));\n }\n}" }, { "identifier": "Dimension", "path": "src/main/java/com/chadfield/shogiexplorer/objects/Dimension.java", "snippet": "public class Dimension {\n\n private Integer width;\n private Integer height;\n\n public Dimension() {\n\n }\n\n public Dimension(Integer x, Integer y) {\n this.width = x;\n this.height = y;\n }\n\n /**\n * @return the width\n */\n public Integer getWidth() {\n return width;\n }\n\n /**\n * @param width the width to set\n */\n public void setWidth(Integer width) {\n this.width = width;\n }\n\n /**\n * @return the height\n */\n public Integer getHeight() {\n return height;\n }\n\n /**\n * @param height the height to set\n */\n public void setHeight(Integer height) {\n this.height = height;\n }\n}" }, { "identifier": "ImageCache", "path": "src/main/java/com/chadfield/shogiexplorer/objects/ImageCache.java", "snippet": "public class ImageCache {\n\n private Map<String, BaseMultiResolutionImage> imageMap = new HashMap<>();\n\n public void putImage(String identifier, BaseMultiResolutionImage image) {\n getImageMap().put(identifier, image);\n }\n\n public BaseMultiResolutionImage getImage(String identifier) {\n if (getImageMap().containsKey(identifier)) {\n return getImageMap().get(identifier);\n } else {\n return null;\n }\n }\n\n /**\n * @return the imageMap\n */\n public Map<String, BaseMultiResolutionImage> getImageMap() {\n return imageMap;\n }\n\n /**\n * @param imageMap the imageMap to set\n */\n public void setImageMap(Map<String, BaseMultiResolutionImage> imageMap) {\n this.imageMap = imageMap;\n }\n}" } ]
import java.awt.Image; import java.awt.image.BaseMultiResolutionImage; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import com.chadfield.shogiexplorer.objects.Coordinate; import com.chadfield.shogiexplorer.objects.Dimension; import com.chadfield.shogiexplorer.objects.ImageCache; import java.awt.Color; import java.awt.Font; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import org.apache.batik.transcoder.SVGAbstractTranscoder; import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.PNGTranscoder;
1,166
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer 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. Shogi Explorer 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 Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.utils; public class ImageUtils { private static final String OS = System.getProperty("os.name").toLowerCase(); public static final boolean IS_WINDOWS = (OS.contains("win")); public static final boolean IS_MAC = (OS.contains("mac")); public static final boolean IS_LINUX = (OS.contains("nux")); private ImageUtils() { throw new IllegalStateException("Utility class"); }
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer 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. Shogi Explorer 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 Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.utils; public class ImageUtils { private static final String OS = System.getProperty("os.name").toLowerCase(); public static final boolean IS_WINDOWS = (OS.contains("win")); public static final boolean IS_MAC = (OS.contains("mac")); public static final boolean IS_LINUX = (OS.contains("nux")); private ImageUtils() { throw new IllegalStateException("Utility class"); }
public static JLabel getPieceLabelForKoma(Image image, Coordinate boardCoord, Dimension offset, Coordinate imageLocation) {
1
2023-11-08 09:24:57+00:00
2k
F3F5/SpawnAuth
src/main/java/f3f5/SpawnAuth/events/OnPlayerLoginEvent.java
[ { "identifier": "GameHelper", "path": "src/main/java/f3f5/SpawnAuth/helpers/GameHelper.java", "snippet": "public class GameHelper {\r\n public AuthMeApi authMeApi;\r\n public SaveHelper saveHelper;\r\n\r\n public GameHelper(AuthMeApi authMeApi) {\r\n this.authMeApi = authMeApi;\r\n }\r\n\r\n public Location getSpawnLocation(World world) {\r\n int spawnRadius = Integer.parseInt(world.getGameRuleValue(\"spawnRadius\")) <= 10 ? 200 : Integer.parseInt(world.getGameRuleValue(\"spawnRadius\"));\r\n\r\n int x = new Random().nextInt(spawnRadius*2)-spawnRadius;\r\n int z = new Random().nextInt(spawnRadius*2)-spawnRadius;\r\n double y = world.getHighestBlockYAt(x, z);\r\n\r\n return new Location(world, x, y, z);\r\n }\r\n\r\n public void teleport(Player player, Location location){\r\n player.teleport(location);\r\n\r\n if (location.getWorld() == Bukkit.getWorld(\"world_nether\") && player.getLocation().getY() >= 127){\r\n double y = player.getLocation().getY()-saveHelper.getLocation(player.getName()).getY();\r\n player.teleport(new Location(location.getWorld(), location.getX(), player.getLocation().getY()-y , location.getZ()));\r\n }\r\n }\r\n\r\n public void setSaveHelper(SaveHelper saveHelper){\r\n this.saveHelper = saveHelper;\r\n }\r\n}\r" }, { "identifier": "SaveHelper", "path": "src/main/java/f3f5/SpawnAuth/helpers/SaveHelper.java", "snippet": "public class SaveHelper {\r\n private final String dataBaseURL;\r\n\r\n public SaveHelper(File dataBaseFolder) {\r\n this.dataBaseURL = \"jdbc:sqlite:\" + dataBaseFolder + File.separator + \"SpawnAuth.db\";\r\n }\r\n\r\n public void setupDataBase() {\r\n try (Connection connection = DriverManager.getConnection(dataBaseURL)) {\r\n try (PreparedStatement preparedStatement = connection.prepareStatement(\"CREATE TABLE IF NOT EXISTS PlayerLocations (name TEXT NOT NULL, x TEXT NOT NULL, y TEXT NOT NULL, z TEXT NOT NULL, world TEXT NOT NULL)\")) {\r\n preparedStatement.executeUpdate();\r\n }\r\n } catch (SQLException ignored) {\r\n }\r\n }\r\n\r\n public void saveLocation(String name, Location location) {\r\n removeLocation(name);\r\n try (Connection connection = DriverManager.getConnection(dataBaseURL)) {\r\n try (PreparedStatement preparedStatement = connection.prepareStatement(\"INSERT INTO PlayerLocations (name,x,y,z,world) VALUES (?,?,?,?,?)\")) {\r\n preparedStatement.setString(1, name);\r\n preparedStatement.setString(5, location.getWorld().getName());\r\n\r\n preparedStatement.setString(2, String.valueOf(location.getX()));\r\n preparedStatement.setString(3, String.valueOf(location.getY()));\r\n preparedStatement.setString(4, String.valueOf(location.getZ()));\r\n preparedStatement.executeUpdate();\r\n }\r\n } catch (SQLException ignored) {\r\n }\r\n }\r\n\r\n public void removeLocation(String name) {\r\n try (Connection connection = DriverManager.getConnection(dataBaseURL)) {\r\n try (PreparedStatement preparedStatement = connection.prepareStatement(\"DELETE FROM PlayerLocations WHERE name = ?\")) {\r\n preparedStatement.setString(1, name);\r\n preparedStatement.executeUpdate();\r\n }\r\n } catch (SQLException ignored) {\r\n }\r\n }\r\n\r\n public Location getLocation(String name) {\r\n try (Connection connection = DriverManager.getConnection(dataBaseURL)) {\r\n try (PreparedStatement preparedStatement = connection.prepareStatement(\"SELECT * FROM PlayerLocations WHERE name = ?\")) {\r\n preparedStatement.setString(1, name);\r\n ResultSet result = preparedStatement.executeQuery();\r\n if (result.next()) {\r\n return new Location(Bukkit.getWorld(result.getString(\"world\")), Double.parseDouble(result.getString(\"x\")), Double.parseDouble(result.getString(\"y\")), Double.parseDouble(result.getString(\"z\")));\r\n }\r\n }\r\n } catch (SQLException ignored) {\r\n }\r\n return null;\r\n }\r\n public void handleDisable(GameHelper gameHelper) {\r\n try (Connection connection = DriverManager.getConnection(dataBaseURL)) {\r\n try (PreparedStatement preparedStatement = connection.prepareStatement(\"SELECT * FROM PlayerLocations\")) {\r\n ResultSet result = preparedStatement.executeQuery();\r\n while (result.next()) {\r\n try {\r\n Location location = getLocation(result.getString(\"name\"));\r\n Player player = Bukkit.getPlayer(result.getString(\"name\"));\r\n\r\n gameHelper.teleport(player, location);\r\n player.setGravity(true);\r\n removeLocation(player.getName());\r\n } catch (Exception ignored) {}\r\n }\r\n }\r\n } catch (SQLException ignored) {\r\n }\r\n }\r\n\r\n}\r" } ]
import f3f5.SpawnAuth.helpers.GameHelper; import f3f5.SpawnAuth.helpers.SaveHelper; import fr.xephi.authme.events.LoginEvent; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener;
1,089
package f3f5.SpawnAuth.events; public class OnPlayerLoginEvent implements Listener { private final SaveHelper saveHelper;
package f3f5.SpawnAuth.events; public class OnPlayerLoginEvent implements Listener { private final SaveHelper saveHelper;
private final GameHelper gameHelper;
0
2023-11-04 14:43:05+00:00
2k
Akshayp02/Enlight21
app/src/main/java/com/example/enlight21/signupActivity.java
[ { "identifier": "USER_NODE", "path": "app/src/main/java/com/example/enlight21/Utils/Constant.java", "snippet": "public static final String USER_NODE = \"users\";" }, { "identifier": "User", "path": "app/src/main/java/com/example/enlight21/Models/User.java", "snippet": "public class User {\n public String username;\n public String password;\n public String email;\n public String image;\n public String description;\n private boolean following = true;\n\n public User() {\n // Default constructor required for Firebase\n }\n\n public User(String username, String password, String email) {\n this.username = username;\n this.password = password;\n this.email = email;\n }\n\n public User(String username, String password, String email, String image, String description) {\n this.username = username;\n this.password = password;\n this.email = email;\n this.image = image;\n this.description = description;\n }\n\n public User(String username, String description) {\n this.username = username;\n this.description = description;\n }\n\n public User(String username, String password, String email, String image) {\n this.username = username;\n this.password = password;\n this.email = email;\n this.image = image;\n }\n\n public String getEmail() {\n return email;\n }\n\n public String getImage() {\n return image;\n }\n\n public String getName() {\n return username;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setName(String name) {\n this.username = name;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n\n\n\n // Getter and setter for following\n public boolean isFollowing() {\n return following;\n }\n\n public void setFollowing(boolean following) {\n this.following = following;\n }\n\n public void setEmail(String email) {\n this.email =email;\n }\n}" } ]
import static android.content.ContentValues.TAG; import static com.example.enlight21.Utils.Constant.USER_NODE; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.example.enlight21.Models.User; import com.example.enlight21.databinding.ActivitySignupBinding; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.FirebaseFirestore;
1,019
package com.example.enlight21; // ... (other import statements) public class signupActivity extends AppCompatActivity { private ActivitySignupBinding binding; private FirebaseAuth mAuth; FirebaseFirestore db = FirebaseFirestore.getInstance(); @Override protected void onStart() { super.onStart(); // Check if the user is signed in FirebaseUser currentUser = mAuth.getCurrentUser(); if (currentUser != null) { // User is already signed in, navigate to the main activity Intent intent = new Intent(signupActivity.this, MainActivity.class); startActivity(intent); finish(); // Close the current activity to prevent the user from going back } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivitySignupBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance(); binding.signupBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = binding.Email.getText().toString(); String password = validatePassword(binding.Password.getText().toString(), binding.ConfirmPassword.getText().toString()); if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(binding.ConfirmPassword.getText()) || TextUtils.isEmpty(binding.Username.getText())) { Toast.makeText(signupActivity.this, "Please fill the Information", Toast.LENGTH_SHORT).show(); } else { if (password != null) { Task<AuthResult> authResultTask = mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(signupActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { User user = new User( binding.Username.getText().toString(), password,email,null,null); // to strore data in firebase
package com.example.enlight21; // ... (other import statements) public class signupActivity extends AppCompatActivity { private ActivitySignupBinding binding; private FirebaseAuth mAuth; FirebaseFirestore db = FirebaseFirestore.getInstance(); @Override protected void onStart() { super.onStart(); // Check if the user is signed in FirebaseUser currentUser = mAuth.getCurrentUser(); if (currentUser != null) { // User is already signed in, navigate to the main activity Intent intent = new Intent(signupActivity.this, MainActivity.class); startActivity(intent); finish(); // Close the current activity to prevent the user from going back } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivitySignupBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance(); binding.signupBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = binding.Email.getText().toString(); String password = validatePassword(binding.Password.getText().toString(), binding.ConfirmPassword.getText().toString()); if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(binding.ConfirmPassword.getText()) || TextUtils.isEmpty(binding.Username.getText())) { Toast.makeText(signupActivity.this, "Please fill the Information", Toast.LENGTH_SHORT).show(); } else { if (password != null) { Task<AuthResult> authResultTask = mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(signupActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { User user = new User( binding.Username.getText().toString(), password,email,null,null); // to strore data in firebase
db.collection(USER_NODE).document(mAuth.getCurrentUser().getUid()).set(user)
0
2023-11-04 08:22:36+00:00
2k
refrainsclub/npcs
src/main/java/nz/blair/npcs/listeners/PacketInboundListener.java
[ { "identifier": "ClickAction", "path": "src/main/java/nz/blair/npcs/npcs/ClickAction.java", "snippet": "public interface ClickAction {\n void onClick(Player player, ClickType clickType);\n}" }, { "identifier": "ClickType", "path": "src/main/java/nz/blair/npcs/npcs/ClickType.java", "snippet": "public enum ClickType {\n LEFT_CLICK, RIGHT_CLICK;\n\n @Nullable\n public static ClickType fromNms(PacketPlayInUseEntity.EnumEntityUseAction action) {\n switch (action) {\n case ATTACK:\n return LEFT_CLICK;\n case INTERACT_AT:\n return RIGHT_CLICK;\n default:\n return null;\n }\n }\n}" }, { "identifier": "NpcManager", "path": "src/main/java/nz/blair/npcs/npcs/NpcManager.java", "snippet": "public class NpcManager {\n private final Set<Npc> npcs = new HashSet<>();\n\n /**\n * Add an NPC to the manager.\n *\n * @param npc The NPC to add\n * @return Whether the NPC was added\n */\n @SuppressWarnings(\"UnusedReturnValue\") // This return value could be useful in the future\n public boolean addNpc(Npc npc) {\n return npcs.add(npc);\n }\n\n /**\n * Remove an NPC from the manager.\n *\n * @param npc The NPC to remove\n * @return Whether the NPC was removed\n */\n public boolean removeNpc(Npc npc) {\n return npcs.remove(npc);\n }\n\n /**\n * Get a set of all NPCs.\n *\n * @return A set of all NPCs\n */\n public Set<Npc> getNpcs() {\n return Collections.unmodifiableSet(npcs);\n }\n}" }, { "identifier": "NmsUtil", "path": "src/main/java/nz/blair/npcs/utils/NmsUtil.java", "snippet": "public class NmsUtil {\n public static CraftPlayer getCraftPlayer(Player player) {\n return (CraftPlayer) player;\n }\n\n public static EntityPlayer getEntityPlayer(Player player) {\n return getCraftPlayer(player).getHandle();\n }\n\n public static PlayerConnection getPlayerConnection(Player player) {\n return getEntityPlayer(player).playerConnection;\n }\n\n public static ChannelPipeline getChannelPipeline(Player player) {\n PlayerConnection connection = getPlayerConnection(player);\n return connection.networkManager.channel.pipeline();\n }\n\n public static GameProfile getGameProfile(Player player) {\n EntityPlayer entityPlayer = getEntityPlayer(player);\n return entityPlayer.getProfile();\n }\n\n public static CraftWorld getCraftWorld(World world) {\n return (CraftWorld) world;\n }\n\n public static WorldServer getWorldServer(World world) {\n return getCraftWorld(world).getHandle();\n }\n\n public static MinecraftServer getMinecraftServer() {\n return MinecraftServer.getServer();\n }\n\n @Nullable\n public static Object getField(Object object, String name) {\n try {\n Field field = object.getClass().getDeclaredField(name);\n field.setAccessible(true);\n return field.get(object);\n } catch (IllegalAccessException | NoSuchFieldException e) {\n LoggerUtil.warning(\"Failed to get field: \" + name + \" from object: \" + object.getClass().getSimpleName(), e);\n return null;\n }\n }\n\n public static void setField(Object object, String name, Object value) {\n try {\n Field field = object.getClass().getDeclaredField(name);\n field.setAccessible(true);\n field.set(object, value);\n field.setAccessible(false);\n } catch (IllegalAccessException | NoSuchFieldException e) {\n LoggerUtil.warning(\"Failed to set field: \" + name + \" from object: \" + object.getClass().getSimpleName(), e);\n }\n }\n}" } ]
import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity; import nz.blair.npcs.npcs.ClickAction; import nz.blair.npcs.npcs.ClickType; import nz.blair.npcs.npcs.NpcManager; import nz.blair.npcs.utils.NmsUtil; import org.bukkit.entity.Player;
1,196
package nz.blair.npcs.listeners; public class PacketInboundListener { private final NpcManager npcManager; public PacketInboundListener(NpcManager npcManager) { this.npcManager = npcManager; } @SuppressWarnings("SameReturnValue") // Keep the cancel return value for future use public boolean onPacketInbound(Player player, Packet<?> packet) { if (!(packet instanceof PacketPlayInUseEntity)) { return false; } PacketPlayInUseEntity useEntityPacket = (PacketPlayInUseEntity) packet; PacketPlayInUseEntity.EnumEntityUseAction action = useEntityPacket.a(); Object entityIdObj = NmsUtil.getField(useEntityPacket, "a"); if (!(entityIdObj instanceof Integer)) { return false; } int entityId = (int) entityIdObj; npcManager.getNpcs().forEach(npc -> { if (npc.getEntityId() == entityId) { ClickAction clickAction = npc.getClickAction(); if (clickAction == null) { return; }
package nz.blair.npcs.listeners; public class PacketInboundListener { private final NpcManager npcManager; public PacketInboundListener(NpcManager npcManager) { this.npcManager = npcManager; } @SuppressWarnings("SameReturnValue") // Keep the cancel return value for future use public boolean onPacketInbound(Player player, Packet<?> packet) { if (!(packet instanceof PacketPlayInUseEntity)) { return false; } PacketPlayInUseEntity useEntityPacket = (PacketPlayInUseEntity) packet; PacketPlayInUseEntity.EnumEntityUseAction action = useEntityPacket.a(); Object entityIdObj = NmsUtil.getField(useEntityPacket, "a"); if (!(entityIdObj instanceof Integer)) { return false; } int entityId = (int) entityIdObj; npcManager.getNpcs().forEach(npc -> { if (npc.getEntityId() == entityId) { ClickAction clickAction = npc.getClickAction(); if (clickAction == null) { return; }
ClickType clickType = ClickType.fromNms(action);
1
2023-11-01 01:14:41+00:00
2k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/SysUserAuthServiceImpl.java
[ { "identifier": "SysUserAuthDao", "path": "talktime-framework/talktime-dao/src/main/java/com/qingmeng/dao/SysUserAuthDao.java", "snippet": "@Service\npublic class SysUserAuthDao extends ServiceImpl<SysUserAuthMapper, SysUserAuth>{\n\n /**\n * 通过openId查询授权信息\n *\n * @param openId 第三方应用唯一凭证\n * @return {@link SysUserAuth }\n * @author qingmeng\n * @createTime: 2023/11/13 15:05:22\n */\n public SysUserAuth getInfoByOpenId(String openId) {\n LambdaQueryWrapper<SysUserAuth> wrapper = new LambdaQueryWrapper<>();\n wrapper.eq(SysUserAuth::getOpenId, openId);\n return getOne(wrapper);\n }\n}" }, { "identifier": "SysUserAuth", "path": "talktime-framework/talktime-dao/src/main/java/com/qingmeng/entity/SysUserAuth.java", "snippet": "@Data\n@TableName(\"sys_user_auth\")\npublic class SysUserAuth implements Serializable {\n\n private static final long serialVersionUID = -2040348844066255970L;\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 用户id\n */\n private Long userId;\n\n /**\n * 第三方应用登陆类型(微信,qq等)\n */\n private String loginType;\n\n /**\n * 第三方应用的唯一标识\n */\n private String openId;\n}" }, { "identifier": "SysUserAuthService", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/service/SysUserAuthService.java", "snippet": "public interface SysUserAuthService{\n\n /**\n * 使用 Open ID 获取授权信息\n *\n * @param openId 开放 ID\n * @return {@link SysUserAuth }\n * @author qingmeng\n * @createTime: 2023/11/20 08:36:15\n */\n SysUserAuth getAuthInfoWithOpenId(String openId);\n\n /**\n * 保存\n *\n * @param saveUserAuth 保存用户身份验证\n * @author qingmeng\n * @createTime: 2023/11/20 08:41:53\n */\n void save(SysUserAuth saveUserAuth);\n}" } ]
import com.qingmeng.dao.SysUserAuthDao; import com.qingmeng.entity.SysUserAuth; import com.qingmeng.service.SysUserAuthService; import org.springframework.stereotype.Service; import javax.annotation.Resource;
787
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:19:00 */ @Service public class SysUserAuthServiceImpl implements SysUserAuthService { @Resource private SysUserAuthDao sysUserAuthDao; /** * 使用 Open ID 获取授权信息 * * @param openId 开放 ID * @return {@link SysUserAuth } * @author qingmeng * @createTime: 2023/11/20 08:36:15 */ @Override
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:19:00 */ @Service public class SysUserAuthServiceImpl implements SysUserAuthService { @Resource private SysUserAuthDao sysUserAuthDao; /** * 使用 Open ID 获取授权信息 * * @param openId 开放 ID * @return {@link SysUserAuth } * @author qingmeng * @createTime: 2023/11/20 08:36:15 */ @Override
public SysUserAuth getAuthInfoWithOpenId(String openId) {
1
2023-11-07 16:04:55+00:00
2k
TianqiCS/AIChatLib-Fabric
src/main/java/com/citrusmc/aichatlib/client/TextParser.java
[ { "identifier": "ClientConfig", "path": "src/main/java/com/citrusmc/aichatlib/configs/ClientConfig.java", "snippet": "public class ClientConfig extends Config{\n static ClientConfig instance = null;\n\n private ClientConfig() {\n String configFileLocation = \"config/AIChatLib/ClientConfig.yml\";\n this.config = this.loadConfig(configFileLocation, getDefaultConfig());\n }\n\n public static Config getInstance() {\n if (instance == null) {\n instance = new ClientConfig();\n }\n return instance;\n }\n\n\n private ClientConfig(String configLocation, String jarDefault) {\n config = loadConfig(configLocation, jarDefault);\n }\n @Override\n String getDefaultConfig() {\n return String.valueOf(getClass().getClassLoader().getResource(\"configs/ClientConfig.yml\"));\n }\n}" }, { "identifier": "Config", "path": "src/main/java/com/citrusmc/aichatlib/configs/Config.java", "snippet": "public abstract class Config {\n\n protected Map<String, Object> config = null;\n\n public synchronized Map<String, Object> loadConfig(String configFileLocation, String jarDefaultLocation) {\n Map<String, Object> defaults = null;\n\n try (InputStream stream = new URL(jarDefaultLocation).openStream()) {\n defaults = new Yaml().load(stream);\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n Map<String, Object> configsFromFile = new HashMap<>();\n File configFile = new File(configFileLocation);\n\n if (configFile.exists()) {\n try (FileInputStream input = new FileInputStream(configFile)) {\n configsFromFile = new Yaml().load(input);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n for (Map.Entry<String, Object> entry : configsFromFile.entrySet()) {\n\n assert defaults != null;\n if (defaults.containsKey(entry.getKey())) {\n defaults.put(entry.getKey(), entry.getValue());\n }\n }\n\n saveConfig(configFileLocation, defaults);\n\n return defaults;\n }\n\n\n // save config to file location\n public synchronized void saveConfig(String location, Map<String, Object> config) {\n try {\n Files.createDirectories(new File(location).getParentFile().toPath());\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n try (FileWriter writer = new FileWriter(location, StandardCharsets.UTF_8)) {\n DumperOptions options = new DumperOptions();\n options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);\n options.setPrettyFlow(true);\n Yaml yaml = new Yaml(options);\n yaml.dump(config, writer);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n abstract String getDefaultConfig();\n\n // get config entry\n public synchronized Object get(String key) {\n String[] keys = key.split(\"\\\\.\");\n Map<String, Object> childConfig = config;\n for (int i = 0; i < keys.length - 1; i++) {\n Pattern pattern = Pattern.compile(\"([^\\\\[\\\\]]+)(?:\\\\[(\\\\\\\\d+)\\\\])?\");\n Matcher matcher = pattern.matcher(keys[i]);\n if (matcher.find()) {\n String entry = matcher.group(1);\n String entryIndex = matcher.group(2);\n if (entryIndex != null) {\n childConfig = (Map<String, Object>) ((List<Object>) childConfig.get(entry)).get(Integer.parseInt(entryIndex));\n }\n else {\n childConfig = (Map<String, Object>) childConfig.get(entry);\n }\n } else {\n throw new IllegalStateException(\"Invalid config key: \" + key);\n }\n }\n return childConfig.get(keys[keys.length - 1]);\n }\n\n}" } ]
import com.citrusmc.aichatlib.configs.ClientConfig; import com.citrusmc.aichatlib.configs.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
1,028
package com.citrusmc.aichatlib.client; /** * TextParser class * <p> * This class is used to parse the chat message and game message. * <p> */ public class TextParser { private static final Logger LOGGER = LoggerFactory.getLogger("ChatBot-TextParser");
package com.citrusmc.aichatlib.client; /** * TextParser class * <p> * This class is used to parse the chat message and game message. * <p> */ public class TextParser { private static final Logger LOGGER = LoggerFactory.getLogger("ChatBot-TextParser");
private static final Config CONFIG = ClientConfig.getInstance();
0
2023-11-06 00:04:54+00:00
2k
Griefed/AddEmAll
fabric/src/main/java/de/griefed/addemall/FabricRegistrationFactory.java
[ { "identifier": "RegistrationProvider", "path": "common/src/main/java/de/griefed/addemall/registry/RegistrationProvider.java", "snippet": "public interface RegistrationProvider<T> {\n\n /**\n * Gets a provider for specified {@code modId} and {@code resourceKey}. <br>\n * It is <i>recommended</i> to store the resulted provider in a {@code static final} field to\n * the {@link Factory#INSTANCE factory} creating multiple providers for the same resource key and mod id.\n *\n * @param resourceKey the {@link ResourceKey} of the registry of the provider\n * @param modId the mod id that the provider will register objects for\n * @param <T> the type of the provider\n * @return the provider\n */\n static <T> RegistrationProvider<T> get(ResourceKey<? extends Registry<T>> resourceKey, String modId) {\n return Factory.INSTANCE.create(resourceKey, modId);\n }\n\n /**\n * Gets a provider for specified {@code modId} and {@code registry}. <br>\n * It is <i>recommended</i> to store the resulted provider in a {@code static final} field to\n * the {@link Factory#INSTANCE factory} creating multiple providers for the same resource key and mod id.\n *\n * @param registry the {@link Registry} of the provider\n * @param modId the mod id that the provider will register objects for\n * @param <T> the type of the provider\n * @return the provider\n */\n static <T> RegistrationProvider<T> get(Registry<T> registry, String modId) {\n return Factory.INSTANCE.create(registry, modId);\n }\n\n /**\n * Registers an object.\n *\n * @param name the name of the object\n * @param supplier a supplier of the object to register\n * @param <I> the type of the object\n * @return a wrapper containing the lazy registered object. <strong>Calling {@link RegistryObject#get() get} too early\n * on the wrapper might result in crashes!</strong>\n */\n <I extends T> RegistryObject<I> register(String name, Supplier<? extends I> supplier);\n\n /**\n * Gets all the objects currently registered.\n *\n * @return an <strong>immutable</strong> view of all the objects currently registered\n */\n Collection<RegistryObject<T>> getEntries();\n\n /**\n * Gets the mod id that this provider registers objects for.\n *\n * @return the mod id\n */\n String getModId();\n\n /**\n * Factory class for {@link RegistrationProvider registration providers}. <br>\n * This class is loaded using {@link java.util.ServiceLoader Service Loaders}, and only one\n * should exist per mod loader.\n */\n interface Factory {\n\n /**\n * The singleton instance of the {@link Factory}. This is different on each loader.\n */\n Factory INSTANCE = Services.load(Factory.class);\n\n /**\n * Creates a {@link RegistrationProvider}.\n *\n * @param resourceKey the {@link ResourceKey} of the registry to create this provider for\n * @param modId the mod id for which the provider will register objects\n * @param <T> the type of the provider\n * @return the provider\n */\n <T> RegistrationProvider<T> create(ResourceKey<? extends Registry<T>> resourceKey, String modId);\n\n /**\n * Creates a {@link RegistrationProvider}.\n *\n * @param registry the {@link Registry} to create this provider for\n * @param modId the mod id for which the provider will register objects\n * @param <T> the type of the provider\n * @return the provider\n */\n default <T> RegistrationProvider<T> create(Registry<T> registry, String modId) {\n return create(registry.key(), modId);\n }\n }\n}" }, { "identifier": "RegistryObject", "path": "common/src/main/java/de/griefed/addemall/registry/RegistryObject.java", "snippet": "public interface RegistryObject<T> extends Supplier<T> {\n\n /**\n * Gets the {@link ResourceKey} of the registry of the object wrapped.\n *\n * @return the {@link ResourceKey} of the registry\n */\n ResourceKey<T> getResourceKey();\n\n /**\n * Gets the id of the object.\n *\n * @return the id of the object\n */\n ResourceLocation getId();\n\n /**\n * Gets the object behind this wrapper. Calling this method too early\n * might result in crashes.\n *\n * @return the object behind this wrapper\n */\n @Override\n T get();\n\n /**\n * Gets this object wrapped in a vanilla {@link Holder}.\n *\n * @return the holder\n */\n Holder<T> asHolder();\n}" } ]
import de.griefed.addemall.registry.RegistrationProvider; import de.griefed.addemall.registry.RegistryObject; import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.function.Supplier;
1,384
package de.griefed.addemall; public class FabricRegistrationFactory implements RegistrationProvider.Factory { @Override public <T> RegistrationProvider<T> create(ResourceKey<? extends Registry<T>> resourceKey, String modId) { return new Provider<>(modId, resourceKey); } @Override public <T> RegistrationProvider<T> create(Registry<T> registry, String modId) { return new Provider<>(modId, registry); } private static class Provider<T> implements RegistrationProvider<T> { private final String modId; private final Registry<T> registry;
package de.griefed.addemall; public class FabricRegistrationFactory implements RegistrationProvider.Factory { @Override public <T> RegistrationProvider<T> create(ResourceKey<? extends Registry<T>> resourceKey, String modId) { return new Provider<>(modId, resourceKey); } @Override public <T> RegistrationProvider<T> create(Registry<T> registry, String modId) { return new Provider<>(modId, registry); } private static class Provider<T> implements RegistrationProvider<T> { private final String modId; private final Registry<T> registry;
private final Set<RegistryObject<T>> entries = new HashSet<>();
1
2023-11-06 12:50:10+00:00
2k
wicksonZhang/data-structure
10-Map/src/test/java/com/wickson/set/ComparisonTest.java
[ { "identifier": "FileInfo", "path": "9-Set/src/main/java/com/wickson/file/FileInfo.java", "snippet": "public class FileInfo {\n\tprivate int lines;\n\tprivate int files;\n\tprivate String content = \"\";\n\t\n\tpublic String[] words() {\n\t\treturn content.split(\"[^a-zA-Z]+\");\n\t}\n\t\n\tpublic int getFiles() {\n\t\treturn files;\n\t}\n\n\tpublic void setFiles(int files) {\n\t\tthis.files = files;\n\t}\n\n\tpublic int getLines() {\n\t\treturn lines;\n\t}\n\t\n\tpublic void setLines(int lines) {\n\t\tthis.lines = lines;\n\t}\n\t\n\tpublic String getContent() {\n\t\treturn content;\n\t}\n\n\tpublic void setContent(String content) {\n\t\tthis.content = content;\n\t}\n\n\tpublic FileInfo append(FileInfo info) {\n\t\tif (info != null && info.lines > 0) {\n\t\t\tthis.files += info.files;\n\t\t\tthis.lines += info.lines;\n\t\t\tthis.content = new StringBuilder(this.content)\n\t\t\t\t\t.append(\"\\n\")\n\t\t\t\t\t.append(info.content)\n\t\t\t\t\t.toString();\n\t\t}\n\t\treturn this;\n\t}\n}" }, { "identifier": "Files", "path": "9-Set/src/main/java/com/wickson/file/Files.java", "snippet": "public class Files {\n\t\n\t/**\n\t * 读取文件内容\n\t * @param file\n\t * @return\n\t */\n\tpublic static FileInfo read(String file) {\n\t\tif (file == null) return null;\n\t\tFileInfo info = new FileInfo();\n\t\tStringBuilder sb = new StringBuilder();\n\t\ttry (FileReader reader = new FileReader(file);\n\t\t\t\tBufferedReader br = new BufferedReader(reader)) {\n String line;\n while ((line = br.readLine()) != null) {\n \tsb.append(line).append(\"\\n\");\n \tinfo.setLines(info.getLines() + 1);\n }\n int len = sb.length();\n if (len > 0) {\n sb.deleteCharAt(len - 1);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n\t\tinfo.setFiles(info.getFiles() + 1);\n\t\tinfo.setContent(sb.toString());\n\t\treturn info;\n\t}\n\t\n\t/**\n\t * 读取文件夹下面的文件内容\n\t * @param dir\n\t * @param extensions\n\t * @return\n\t */\n\tpublic static FileInfo read(String dir, String[] extensions) {\n\t\tif (dir == null) return null;\n\t\t\n\t\tFile dirFile = new File(dir);\n\t\tif (!dirFile.exists()) return null;\n\n\t\tFileInfo info = new FileInfo();\n\t\tdirFile.listFiles(new FileFilter() {\n\t\t\tpublic boolean accept(File subFile) {\n\t\t\t\tString subFilepath = subFile.getAbsolutePath();\n\t\t\t\tif (subFile.isDirectory()) {\n\t\t\t\t\tinfo.append(read(subFilepath, extensions));\n\t\t\t\t} else if (extensions != null && extensions.length > 0) {\n\t\t\t\t\tfor (String extension : extensions) {\n\t\t\t\t\t\tif (subFilepath.endsWith(\".\" + extension)) {\n\t\t\t\t\t\t\tinfo.append(read(subFilepath));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tinfo.append(read(subFilepath));\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t});\n\t\treturn info;\n\t}\n}" }, { "identifier": "Times", "path": "9-Set/src/main/java/com/wickson/utils/Times.java", "snippet": "public class Times {\n\tprivate static final SimpleDateFormat fmt = new SimpleDateFormat(\"HH:mm:ss.SSS\");\n\t\n\tpublic interface Task {\n\t\tvoid execute();\n\t}\n\t\n\tpublic static void test(String title, Task task) {\n\t\tif (task == null) return;\n\t\ttitle = (title == null) ? \"\" : (\"【\" + title + \"】\");\n\t\tSystem.out.println(title);\n\t\tSystem.out.println(\"开始:\" + fmt.format(new Date()));\n\t\tlong begin = System.currentTimeMillis();\n\t\ttask.execute();\n\t\tlong end = System.currentTimeMillis();\n\t\tSystem.out.println(\"结束:\" + fmt.format(new Date()));\n\t\tdouble delta = (end - begin) / 1000.0;\n\t\tSystem.out.println(\"耗时:\" + delta + \"秒\");\n\t\tSystem.out.println(\"-------------------------------------\");\n\t}\n}" } ]
import com.wickson.file.FileInfo; import com.wickson.file.Files; import com.wickson.utils.Times; import org.junit.jupiter.api.Test;
1,134
package com.wickson.set; /** * 性能对比:红黑树和链表 */ public class ComparisonTest { @Test public void ListSetTest() { Times.test("ListSet", () -> common(new ListSet<>(), file())); } @Test public void treeSetTest() { Times.test("TreeSet", () -> common(new TreeSet<>(), file())); } public String[] file() {
package com.wickson.set; /** * 性能对比:红黑树和链表 */ public class ComparisonTest { @Test public void ListSetTest() { Times.test("ListSet", () -> common(new ListSet<>(), file())); } @Test public void treeSetTest() { Times.test("TreeSet", () -> common(new TreeSet<>(), file())); } public String[] file() {
FileInfo fileInfo = Files.read("C:\\Users\\wicks\\Desktop\\java-source\\java\\util",
0
2023-11-06 16:33:25+00:00
2k
Royal-Code-Master/File-Generation-Spring-Reactive
SendMoney/src/main/java/com/money/app/controller/UserController.java
[ { "identifier": "User", "path": "SendMoney/src/main/java/com/money/app/pojo/User.java", "snippet": "@Document(collection = \"userdetails\")\r\npublic class User {\r\n\r\n\t@Id\r\n\tprivate long uid;\r\n\r\n\t@Indexed(unique = true)\r\n\tprivate String accountNumber;\r\n\r\n\tprivate float amount;\r\n\r\n\tprivate String fullName;\r\n\r\n\t@Indexed(unique = true)\r\n\tprivate String emailAddress;\r\n\r\n\t@Indexed(unique = true)\r\n\tprivate String phoneNumber;\r\n\r\n\tprivate int age;\r\n\r\n\tpublic long getUid() {\r\n\t\treturn uid;\r\n\t}\r\n\r\n\tpublic void setUid(long uid) {\r\n\t\tthis.uid = uid;\r\n\t}\r\n\r\n\tpublic String getAccountNumber() {\r\n\t\treturn accountNumber;\r\n\t}\r\n\r\n\tpublic void setAccountNumber(String accountNumber) {\r\n\t\tthis.accountNumber = accountNumber;\r\n\t}\r\n\r\n\tpublic float getAmount() {\r\n\t\treturn amount;\r\n\t}\r\n\r\n\tpublic void setAmount(float amount) {\r\n\t\tthis.amount = amount;\r\n\t}\r\n\r\n\tpublic String getFullName() {\r\n\t\treturn fullName;\r\n\t}\r\n\r\n\tpublic void setFullName(String fullName) {\r\n\t\tthis.fullName = fullName;\r\n\t}\r\n\r\n\tpublic String getEmailAddress() {\r\n\t\treturn emailAddress;\r\n\t}\r\n\r\n\tpublic void setEmailAddress(String emailAddress) {\r\n\t\tthis.emailAddress = emailAddress;\r\n\t}\r\n\r\n\tpublic String getPhoneNumber() {\r\n\t\treturn phoneNumber;\r\n\t}\r\n\r\n\tpublic void setPhoneNumber(String phoneNumber) {\r\n\t\tthis.phoneNumber = phoneNumber;\r\n\t}\r\n\r\n\tpublic int getAge() {\r\n\t\treturn age;\r\n\t}\r\n\r\n\tpublic void setAge(int age) {\r\n\t\tthis.age = age;\r\n\t}\r\n\r\n\tpublic User(long uid, String accountNumber, float amount, String fullName, String emailAddress, String phoneNumber,int age) {\r\n\t\tsuper();\r\n\t\tthis.uid = uid;\r\n\t\tthis.accountNumber = accountNumber;\r\n\t\tthis.amount = amount;\r\n\t\tthis.fullName = fullName;\r\n\t\tthis.emailAddress = emailAddress;\r\n\t\tthis.phoneNumber = phoneNumber;\r\n\t\tthis.age = age;\r\n\t}\r\n\r\n\tpublic User() {\r\n\t\tsuper();\r\n\t}\r\n\r\n}\r" }, { "identifier": "UserService", "path": "SendMoney/src/main/java/com/money/app/service/UserService.java", "snippet": "@Service\r\npublic class UserService {\r\n\r\n\t@Autowired\r\n\tprivate UserRepo userRepo;\r\n\r\n\t// create new account\r\n\tpublic Mono<User> createAccount(User user) {\r\n\t\tlong userId = user.getUid();\r\n\t\treturn userRepo.findById(userId).flatMap(existingUser -> {\r\n\t\t\tif (existingUser.getAccountNumber().equals(user.getAccountNumber())\r\n\t\t\t\t\t|| existingUser.getEmailAddress().equals(user.getEmailAddress())\r\n\t\t\t\t\t|| existingUser.getPhoneNumber().equals(user.getPhoneNumber())) {\r\n\t\t\t\tString errorMessage = \"User with the same ID or account number, or email or phone number already exists.\";\r\n\t\t\t\tSystem.err.println(errorMessage);\r\n\t\t\t\treturn Mono.error(new RuntimeException(errorMessage));\r\n\t\t\t} else {\r\n\t\t\t\treturn userRepo.insert(user);\r\n\t\t\t}\r\n\t\t}).switchIfEmpty(userRepo.insert(user)).onErrorResume(throwable -> {\r\n\t\t\tif (throwable instanceof RuntimeException) {\r\n\t\t\t\tString errorMessage = \"User with the same ID, account number, or email already exists.\";\r\n\t\t\t\tSystem.err.println(errorMessage);\r\n\t\t\t}\r\n\r\n\t\t\treturn Mono.error(throwable);\r\n\t\t});\r\n\t}\r\n\r\n\t// delete user account by id\r\n\r\n\tpublic Mono<Void> deleteAccount(long uid) {\r\n\t\treturn userRepo.findById(uid)\r\n\t\t\t\t.switchIfEmpty(Mono.error(new RuntimeException(\"User with ID \" + uid + \" does not exist to delete.\")))\r\n\t\t\t\t.flatMap(existingUser -> {\r\n\t\t\t\t\treturn userRepo.deleteById(uid);\r\n\t\t\t\t});\r\n\t}\r\n\r\n\t// update user account data by id\r\n\r\n\tpublic Mono<User> updateAccount(User user) {\r\n\t\tlong userId = user.getUid();\r\n\t\treturn userRepo.findById(userId)\r\n\t\t\t\t.switchIfEmpty(Mono.error(new RuntimeException(\"User with ID \" + userId + \" does not exist.\")))\r\n\t\t\t\t.flatMap(existingUser -> {\r\n\t\t\t\t\texistingUser.setAccountNumber(user.getAccountNumber());\r\n\t\t\t\t\texistingUser.setFullName(user.getFullName());\r\n\t\t\t\t\texistingUser.setEmailAddress(user.getEmailAddress());\r\n\t\t\t\t\texistingUser.setPhoneNumber(user.getPhoneNumber());\r\n\t\t\t\t\texistingUser.setAge(user.getAge());\r\n\t\t\t\t\treturn userRepo.save(existingUser);\r\n\t\t\t\t});\r\n\t}\r\n\r\n\t// get All user details\r\n\tpublic Flux<User> allUsers() {\r\n\t\treturn userRepo.findAll().flatMap(user -> Flux.just(user));\r\n\t}\r\n\r\n}\r" } ]
import org.springframework.beans.factory.annotation.Autowired; 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.money.app.pojo.User; import com.money.app.service.UserService; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
1,232
package com.money.app.controller; @RestController @RequestMapping("/bank") public class UserController { @Autowired private UserService userService; // account creation end point @PostMapping("/newAccount")
package com.money.app.controller; @RestController @RequestMapping("/bank") public class UserController { @Autowired private UserService userService; // account creation end point @PostMapping("/newAccount")
public Mono<User> newAccountEndPoint(@RequestBody User user) {
0
2023-11-09 12:42:24+00:00
2k
arunk140/ollm.chat
app/src/main/java/com/arunk140/ollmchat/SettingsActivity.java
[ { "identifier": "Settings", "path": "app/src/main/java/com/arunk140/ollmchat/Config/Settings.java", "snippet": "public class Settings {\n public int maxTokens = -1;\n public String apiUrl = \"https://api.openai.com/\";\n public String apiKey = \"\";\n public float temperature = 0.7F;\n public String model = \"gpt-3.5-turbo\";\n public String systemPrompt = \"\";\n}" }, { "identifier": "Manager", "path": "app/src/main/java/com/arunk140/ollmchat/DB/Manager.java", "snippet": "public class Manager {\n private Helper dbHelper;\n private Context context;\n private SQLiteDatabase database;\n public Manager(Context c) {\n context = c;\n }\n\n public Manager open() throws SQLException {\n dbHelper = new Helper(context);\n database = dbHelper.getWritableDatabase();\n return this;\n }\n\n public void close() {\n dbHelper.close();\n }\n\n public void setConfigParam(String key, String value) {\n ContentValues contentValue = new ContentValues();\n contentValue.put(Helper.configKeyCol, key);\n contentValue.put(Helper.configValueCol, value);\n database.replace(Helper.configTableName, null, contentValue);\n }\n @SuppressLint(\"Range\")\n public String getConfigParam(String key) {\n String selection = Helper.configKeyCol + \"=?\";\n String[] selectionArgs = { String.valueOf(key) };\n Cursor cursor = database.query(Helper.configTableName, null, selection, selectionArgs, null, null, null);\n if (cursor.moveToFirst()) {\n return cursor.getString(cursor.getColumnIndex(Helper.configValueCol));\n } else {\n return null;\n }\n }\n\n public Settings getSettings() {\n Settings settings = new Settings();\n String apiKey = getConfigParam(\"api_key\");\n int maxTokens = -1; // Default value\n String apiUrl = getConfigParam(\"api_url\");\n String systemPrompt = getConfigParam(\"system_prompt\");\n String model = getConfigParam(\"model\");\n float temperature = 0.7F; // Default value\n try {\n String maxTdb = getConfigParam(\"max_tokens\");\n if (maxTdb != null) {\n maxTokens = Integer.parseInt(getConfigParam(\"max_tokens\"));\n }\n } catch (NumberFormatException e) {\n // Handle invalid maxTokens value\n }\n try {\n String tempDb = getConfigParam(\"temperature\");\n if (tempDb != null) {\n temperature = Float.parseFloat(getConfigParam(\"temperature\"));\n }\n } catch (NumberFormatException e) {\n // Handle invalid temperature value\n }\n if (apiKey != null && !apiKey.isEmpty()) {\n settings.apiKey = apiKey;\n }\n if (model != null && !model.isEmpty()) {\n settings.model = model;\n }\n if (systemPrompt != null && !systemPrompt.isEmpty()) {\n settings.systemPrompt = systemPrompt;\n }\n if (maxTokens > 0) {\n settings.maxTokens = maxTokens;\n }\n if (apiUrl != null && !apiUrl.isEmpty()) {\n if (!apiUrl.endsWith(\"/\")) {\n apiUrl += \"/\";\n }\n settings.apiUrl = apiUrl;\n }\n if (temperature >= 0.0 && temperature <= 1.0) {\n settings.temperature = temperature;\n }\n return settings;\n }\n\n}" } ]
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import com.arunk140.ollmchat.Config.Settings; import com.arunk140.ollmchat.DB.Manager;
1,001
package com.arunk140.ollmchat; public class SettingsActivity extends AppCompatActivity { private EditText apiKeyEditText; private EditText maxTokensEditText; private EditText modelEditText; private EditText apiUrlEditText; private EditText temperatureEditText; private EditText systemPromptMultiLine; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); apiKeyEditText = findViewById(R.id.apiKey); modelEditText = findViewById(R.id.model); maxTokensEditText = findViewById(R.id.maxTokens); apiUrlEditText = findViewById(R.id.apiUrl); temperatureEditText = findViewById(R.id.temperature); systemPromptMultiLine = findViewById(R.id.systemPrompt); Manager manager = new Manager(this); manager.open();
package com.arunk140.ollmchat; public class SettingsActivity extends AppCompatActivity { private EditText apiKeyEditText; private EditText maxTokensEditText; private EditText modelEditText; private EditText apiUrlEditText; private EditText temperatureEditText; private EditText systemPromptMultiLine; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); apiKeyEditText = findViewById(R.id.apiKey); modelEditText = findViewById(R.id.model); maxTokensEditText = findViewById(R.id.maxTokens); apiUrlEditText = findViewById(R.id.apiUrl); temperatureEditText = findViewById(R.id.temperature); systemPromptMultiLine = findViewById(R.id.systemPrompt); Manager manager = new Manager(this); manager.open();
Settings settings = manager.getSettings();
0
2023-11-01 00:44:14+00:00
2k
MonstrousSoftware/Tut3D
core/src/main/java/com/monstrous/tut3d/GameObject.java
[ { "identifier": "Behaviour", "path": "core/src/main/java/com/monstrous/tut3d/behaviours/Behaviour.java", "snippet": "public class Behaviour {\n protected final GameObject go;\n\n protected Behaviour(GameObject go) {\n this.go = go;\n }\n\n public void update(World world, float deltaTime ) { }\n\n // factory for Behaviour instance depending on object type\n public static Behaviour createBehaviour(GameObject go){\n if(go.type.isEnemy)\n return new CookBehaviour(go);\n return null;\n }\n}" }, { "identifier": "PhysicsBody", "path": "core/src/main/java/com/monstrous/tut3d/physics/PhysicsBody.java", "snippet": "public class PhysicsBody {\n\n public final DGeom geom;\n private final Vector3 position; // for convenience, matches geom.getPosition() but converted to Vector3\n private final Quaternion quaternion; // for convenience, matches geom.getQuaternion() but converted to LibGDX Quaternion\n public final ModelInstance debugInstance; // visualisation of collision shape for debug view\n private final DQuaternion tmpQ;\n private final Vector3 linearVelocity;\n\n public PhysicsBody(DGeom geom, ModelInstance debugInstance) {\n this.geom = geom;\n this.debugInstance = debugInstance;\n position = new Vector3();\n linearVelocity = new Vector3();\n quaternion = new Quaternion();\n tmpQ = new DQuaternion();\n }\n\n public Vector3 getPosition() {\n DVector3C pos = geom.getPosition();\n position.x = (float) pos.get0();\n position.y = (float) pos.get1();\n position.z = (float) pos.get2();\n return position;\n }\n\n public void setPosition( Vector3 pos ) {\n geom.setPosition(pos.x, pos.y, pos.z);\n // if the geom is attached to a rigid body it's position will also be changed\n }\n\n public Quaternion getOrientation() {\n DQuaternionC odeQ = geom.getQuaternion();\n float ow = (float) odeQ.get0();\n float ox = (float) odeQ.get1();\n float oy = (float) odeQ.get2();\n float oz = (float) odeQ.get3();\n quaternion.set(ox, oy, oz, ow);\n return quaternion;\n }\n\n // get orientation of rigid body, i.e. without any geom offset rotation\n public Quaternion getBodyOrientation() {\n DQuaternionC odeQ;\n if(geom.getBody() == null) // if geom does not have a body attached, fall back to geom orientation\n odeQ = geom.getQuaternion();\n else\n odeQ = geom.getBody().getQuaternion();\n float ow = (float) odeQ.get0();\n float ox = (float) odeQ.get1();\n float oy = (float) odeQ.get2();\n float oz = (float) odeQ.get3();\n quaternion.set(ox, oy, oz, ow);\n return quaternion;\n }\n\n public void setOrientation( Quaternion q ){\n tmpQ.set(q.w, q.x, q.y, q.z); // convert to ODE quaternion\n geom.setQuaternion(tmpQ);\n // if the geom is attached to a rigid body it's rotation will also be changed\n }\n\n public void applyForce( Vector3 force ){\n DBody rigidBody = geom.getBody();\n rigidBody.addForce(force.x, force.y, force.z);\n }\n\n public void applyForceAtPos( Vector3 force, Vector3 pos ){\n DBody rigidBody = geom.getBody();\n rigidBody.addForceAtPos(force.x, force.y, force.z, pos.x, pos.y, pos.z);\n }\n\n public void applyTorque( Vector3 torque ){\n DBody rigidBody = geom.getBody();\n rigidBody.addTorque(torque.x, torque.y, torque.z);\n }\n\n public Vector3 getVelocity() {\n if(geom.getBody() == null)\n linearVelocity.set(Vector3.Zero);\n else {\n DVector3C v = geom.getBody().getLinearVel();\n linearVelocity.set((float) v.get0(), (float) v.get1(), (float) v.get2());\n }\n return linearVelocity;\n }\n\n // used for player and enemy characters that have capsules for collision geometry\n public void setCapsuleCharacteristics() {\n DBody rigidBody = geom.getBody();\n rigidBody.setDamping(Settings.playerLinearDamping, Settings.playerAngularDamping);\n rigidBody.setAutoDisableFlag(false); // never allow player to get disabled\n rigidBody.setMaxAngularSpeed(0); // keep capsule upright by not allowing rotations\n }\n\n public void destroy() {\n if(geom.getBody() != null)\n geom.getBody().destroy();\n geom.destroy();\n }\n}" } ]
import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Disposable; import com.monstrous.tut3d.behaviours.Behaviour; import com.monstrous.tut3d.physics.PhysicsBody; import net.mgsx.gltf.scene3d.scene.Scene;
1,248
package com.monstrous.tut3d; public class GameObject implements Disposable { public final GameObjectType type; public final Scene scene; public final PhysicsBody body; public final Vector3 direction; public boolean visible; public float health;
package com.monstrous.tut3d; public class GameObject implements Disposable { public final GameObjectType type; public final Scene scene; public final PhysicsBody body; public final Vector3 direction; public boolean visible; public float health;
public Behaviour behaviour;
0
2023-11-04 13:15:48+00:00
2k
DioxideCN/movie-repository
src/main/java/cn/dioxide/movierepository/service/RatingDefinitionService.java
[ { "identifier": "UserHistory", "path": "src/main/java/cn/dioxide/movierepository/entity/UserHistory.java", "snippet": "@Data\npublic class UserHistory {\n\n private Integer movieId; // 电影ID 映射自movies\n\n private String title; // 电影标题 映射自movies\n\n private Integer rating; // 电影评分 映射自movies\n\n private Long timestamp; // 观影时间 映射自rating\n\n private String tag; // 电影前三个标签 映射自genome-tags与tags联表\n\n private List<TagResult> relevance = new ArrayList<>(); // 关联度 映射自genome-scores\n\n}" }, { "identifier": "PageResult", "path": "src/main/java/cn/dioxide/movierepository/infra/PageResult.java", "snippet": "@Data\npublic class PageResult<T> {\n\n private final List<T> results;\n\n private final Long pageNumber, pageSize, totalPage, totalRow;\n\n private PageResult(List<T> results, Page<?> page) {\n this.results = results;\n this.pageNumber = page.getPageNumber();\n this.pageSize = page.getPageSize();\n this.totalPage = page.getTotalPage();\n this.totalRow = page.getTotalRow();\n }\n\n public static <U> PageResult<U> of(List<U> results, Page<?> page) {\n return new PageResult<>(results, page);\n }\n\n}" }, { "identifier": "TagResultMapper", "path": "src/main/java/cn/dioxide/movierepository/mapper/TagResultMapper.java", "snippet": "@Mapper\npublic interface TagResultMapper extends BaseMapper<TagResult> {\n}" }, { "identifier": "UserHistoryMapper", "path": "src/main/java/cn/dioxide/movierepository/mapper/UserHistoryMapper.java", "snippet": "@Mapper\npublic interface UserHistoryMapper extends BaseMapper<UserHistory> {\n List<UserHistory> userIdSearchPage(Integer userId);\n}" }, { "identifier": "IRatingDefinitionService", "path": "src/main/java/cn/dioxide/movierepository/service/impl/IRatingDefinitionService.java", "snippet": "@Service\npublic interface IRatingDefinitionService {\n Mono<PageResult<?>> ratingResultSearch(Integer id,\n Integer page,\n Integer size);\n}" } ]
import cn.dioxide.movierepository.entity.UserHistory; import cn.dioxide.movierepository.infra.PageResult; import cn.dioxide.movierepository.mapper.TagResultMapper; import cn.dioxide.movierepository.mapper.UserHistoryMapper; import cn.dioxide.movierepository.service.impl.IRatingDefinitionService; import com.mybatisflex.core.paginate.Page; import com.mybatisflex.core.query.QueryColumn; import com.mybatisflex.core.query.QueryTable; import com.mybatisflex.core.query.QueryWrapper; import jakarta.annotation.Resource; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
734
package cn.dioxide.movierepository.service; /** * 采用异步并行流优化 * @author Dioxide.CN * @date 2023/11/28 * @since 1.0 */ @Service public class RatingDefinitionService implements IRatingDefinitionService { @Resource
package cn.dioxide.movierepository.service; /** * 采用异步并行流优化 * @author Dioxide.CN * @date 2023/11/28 * @since 1.0 */ @Service public class RatingDefinitionService implements IRatingDefinitionService { @Resource
UserHistoryMapper userHistoryMapper;
3
2023-11-09 01:58:58+00:00
2k
Einzieg/EinziegCloud
src/test/java/com/cloud/LogTest.java
[ { "identifier": "Log", "path": "src/main/java/com/cloud/entity/Log.java", "snippet": "@Data\n@Builder\n@TableName(\"cloud_log\")\npublic class Log {\n\n\t/**\n\t * 主键\n\t */\n\t@TableId(value = \"ID\", type = IdType.AUTO)\n\tprivate Long id;\n\n\t/**\n\t * 运行结果\n\t */\n\t@TableField(value = \"OUTCOME\")\n\tprivate String outcome;\n\n\t/**\n\t * 创建时间\n\t */\n\t@TableField(value = \"CREATE_TIME\")\n\tprivate Date createTime;\n\n\t/**\n\t * 耗时\n\t */\n\t@TableField(value = \"TAKE_TIME\")\n\tprivate Long takeTime;\n\n\t/**\n\t * http请求方法\n\t */\n\t@TableField(value = \"HTTP_METHOD\")\n\tprivate String httpMethod;\n\n\t/**\n\t * 类方法\n\t */\n\t@TableField(value = \"CLASS_METHOD\")\n\tprivate String classMethod;\n\n\t/**\n\t * 请求URL\n\t */\n\t@TableField(value = \"REQUEST_URL\")\n\tprivate String requestUrl;\n\n\t/**\n\t * 请求IP\n\t */\n\t@TableField(value = \"IP\")\n\tprivate String ip;\n\n\t/**\n\t * 用户\n\t */\n\t@TableField(value = \"USER\")\n\tprivate String user;\n\n\t/**\n\t * 模块\n\t */\n\t@TableField(value = \"MODEL\")\n\tprivate String model;\n\n\t/**\n\t * 说明\n\t */\n\t@TableField(value = \"DETAIL\")\n\tprivate String detail;\n\n\t@TableField(value = \"RETURN_BODY\")\n\tprivate String returnBody;\n}" }, { "identifier": "LogServiceImpl", "path": "src/main/java/com/cloud/service/impl/LogServiceImpl.java", "snippet": "@Slf4j\n@Service\n@RequiredArgsConstructor\npublic class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements ILogService {\n\n\t@Override\n\tpublic void saveLog(ProceedingJoinPoint joinPoint, String outcome, Long currentTime, Object returnBody) {\n\t\tLong takeTime = System.currentTimeMillis() - currentTime;\n\t\tHttpServletRequest request = HttpUtil.getHttpServletRequest();\n\t\tMethodSignature signature = (MethodSignature) joinPoint.getSignature();\n\t\tOLog oLog = signature.getMethod().getAnnotation(OLog.class);\n\t\t// 方法名\n\t\tString methodName = joinPoint.getSignature().getName();\n\t\tassert request != null;\n\t\tString name = switch (methodName) {\n\t\t\tcase \"login\", \"register\" -> JSONObject.parseObject(JSONObject.toJSONString(List.of(joinPoint.getArgs()).get(0))).getString(\"username\");\n\t\t\tcase \"logout\" -> JwtUtil.extractUsername(request.getHeader(\"Authorization\").substring(7));\n\t\t\tcase \"mail\" -> Arrays.asList(joinPoint.getArgs()).get(0).toString();\n\t\t\tdefault -> SecurityContextHolder.getContext().getAuthentication().getName();\n\t\t};\n\t\tLog olog = Log.builder()\n\t\t\t\t.outcome(outcome)\n\t\t\t\t.createTime(new Date())\n\t\t\t\t.takeTime(takeTime)\n\t\t\t\t.httpMethod(request.getMethod())\n\t\t\t\t.classMethod(joinPoint.getSignature().getDeclaringTypeName() + \".\" + methodName)\n\t\t\t\t.requestUrl(request.getRequestURI())\n\t\t\t\t.ip(IPUtil.getIpAddr())\n\t\t\t\t.user(name)\n\t\t\t\t.model(oLog.model())\n\t\t\t\t.detail(oLog.detail())\n\t\t\t\t.returnBody(returnBody.toString())\n\t\t\t\t.build();\n\n\t\tlog.debug(\"log: {}\", olog);\n\t\tthis.save(olog);\n\t}\n\n\tpublic Msg<?> getLogs(Log olog, Integer current, Integer size) {\n\t\treturn Msg.success(\n\t\t\t\tthis.page(\n\t\t\t\t\t\tnew Page<>(current, size),\n\t\t\t\t\t\tnew QueryWrapper<>(olog).orderByDesc(\"CREATE_TIME\")\n\t\t\t\t)\n\t\t);\n\t}\n\n}" } ]
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.cloud.entity.Log; import com.cloud.service.impl.LogServiceImpl; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner;
1,021
package com.cloud; @Slf4j @SpringBootTest(classes = EinziegCloudApplication.class) @RunWith(SpringRunner.class) public class LogTest { @Resource
package com.cloud; @Slf4j @SpringBootTest(classes = EinziegCloudApplication.class) @RunWith(SpringRunner.class) public class LogTest { @Resource
LogServiceImpl logServiceImpl;
1
2023-11-07 07:27:53+00:00
2k
Bergerk1/Big-Data-Analytics
src/main/java/de/ddm/actors/profiling/InputReader.java
[ { "identifier": "AkkaSerializable", "path": "src/main/java/de/ddm/serialization/AkkaSerializable.java", "snippet": "@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)\npublic interface AkkaSerializable extends Serializable {\n}" }, { "identifier": "DomainConfigurationSingleton", "path": "src/main/java/de/ddm/singletons/DomainConfigurationSingleton.java", "snippet": "public class DomainConfigurationSingleton {\n\n\tprivate static DomainConfiguration singleton = new DomainConfiguration();\n\n\tpublic static DomainConfiguration get() {\n\t\treturn singleton;\n\t}\n\n\tpublic static void set(DomainConfiguration instance) {\n\t\tsingleton = instance;\n\t}\n}" }, { "identifier": "InputConfigurationSingleton", "path": "src/main/java/de/ddm/singletons/InputConfigurationSingleton.java", "snippet": "public class InputConfigurationSingleton {\n\n\tprivate static InputConfiguration singleton = new InputConfiguration();\n\n\tpublic static InputConfiguration get() {\n\t\treturn singleton;\n\t}\n\n\tpublic static void set(InputConfiguration instance) {\n\t\tsingleton = instance;\n\t}\n}" } ]
import akka.actor.typed.ActorRef; import akka.actor.typed.Behavior; import akka.actor.typed.PostStop; import akka.actor.typed.javadsl.AbstractBehavior; import akka.actor.typed.javadsl.ActorContext; import akka.actor.typed.javadsl.Behaviors; import akka.actor.typed.javadsl.Receive; import com.opencsv.CSVReader; import com.opencsv.exceptions.CsvValidationException; import de.ddm.serialization.AkkaSerializable; import de.ddm.singletons.DomainConfigurationSingleton; import de.ddm.singletons.InputConfigurationSingleton; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List;
682
package de.ddm.actors.profiling; public class InputReader extends AbstractBehavior<InputReader.Message> { //////////////////// // Actor Messages // //////////////////// public interface Message extends AkkaSerializable { } @Getter @NoArgsConstructor @AllArgsConstructor public static class ReadHeaderMessage implements Message { private static final long serialVersionUID = 1729062814525657711L; ActorRef<DependencyMiner.Message> replyTo; } @Getter @NoArgsConstructor @AllArgsConstructor public static class ReadBatchMessage implements Message { private static final long serialVersionUID = -7915854043207237318L; ActorRef<DependencyMiner.Message> replyTo; } //////////////////////// // Actor Construction // //////////////////////// public static final String DEFAULT_NAME = "inputReader"; public static Behavior<Message> create(final int id, final File inputFile) { return Behaviors.setup(context -> new InputReader(context, id, inputFile)); } private InputReader(ActorContext<Message> context, final int id, final File inputFile) throws IOException, CsvValidationException { super(context); this.id = id; this.reader = InputConfigurationSingleton.get().createCSVReader(inputFile); this.header = InputConfigurationSingleton.get().getHeader(inputFile); if (InputConfigurationSingleton.get().isFileHasHeader()) this.reader.readNext(); } ///////////////// // Actor State // ///////////////// private final int id;
package de.ddm.actors.profiling; public class InputReader extends AbstractBehavior<InputReader.Message> { //////////////////// // Actor Messages // //////////////////// public interface Message extends AkkaSerializable { } @Getter @NoArgsConstructor @AllArgsConstructor public static class ReadHeaderMessage implements Message { private static final long serialVersionUID = 1729062814525657711L; ActorRef<DependencyMiner.Message> replyTo; } @Getter @NoArgsConstructor @AllArgsConstructor public static class ReadBatchMessage implements Message { private static final long serialVersionUID = -7915854043207237318L; ActorRef<DependencyMiner.Message> replyTo; } //////////////////////// // Actor Construction // //////////////////////// public static final String DEFAULT_NAME = "inputReader"; public static Behavior<Message> create(final int id, final File inputFile) { return Behaviors.setup(context -> new InputReader(context, id, inputFile)); } private InputReader(ActorContext<Message> context, final int id, final File inputFile) throws IOException, CsvValidationException { super(context); this.id = id; this.reader = InputConfigurationSingleton.get().createCSVReader(inputFile); this.header = InputConfigurationSingleton.get().getHeader(inputFile); if (InputConfigurationSingleton.get().isFileHasHeader()) this.reader.readNext(); } ///////////////// // Actor State // ///////////////// private final int id;
private final int batchSize = DomainConfigurationSingleton.get().getInputReaderBatchSize();
1
2023-11-01 11:57:53+00:00
2k
20dinosaurs/BassScript
src/main/java/miro/bassscript/functionutils/Function.java
[ { "identifier": "BSLogger", "path": "src/main/java/miro/bassscript/BSLogger.java", "snippet": "public class BSLogger {\n\n private final Logger LOGGER;\n\n public BSLogger() {\n LOGGER = LoggerFactory.getLogger(\"bassscript\");\n }\n\n public void logDebug(String s) {\n LOGGER.debug(s);\n }\n\n public void logInfo(String s) {\n LOGGER.info(s);\n }\n\n public void logWarning(String s) {\n LOGGER.warn(s);\n }\n}" }, { "identifier": "BassScript", "path": "src/main/java/miro/bassscript/BassScript.java", "snippet": "public class BassScript implements ClientModInitializer {\n\n\tprivate BSLogger logger;\n\tprivate FunctionStack functionStack;\n\tprivate BaritoneHandler baritoneHandler;\n\n\n\t@Override\n\tpublic void onInitializeClient() {\n\t\tClientLifecycleEvents.CLIENT_STARTED.register((client) -> onInitializeReady());\n\n\t\tClientTickEvents.START_CLIENT_TICK.register((client) -> onStartTick());\n\t\tClientSendMessageEvents.ALLOW_CHAT.register(this::onChat);\n\t}\n\n\tprivate void onInitializeReady() {\n\t\tlogger = new BSLogger();\n\t\tbaritoneHandler = new BaritoneHandler(this);\n\t\tfunctionStack = new FunctionStack(this, false);\n\n\t\tbaritoneHandler.initSettings();\n\n\t\tgetLogger().logDebug(\"BassScript ready\");\n\t}\n\n\tprivate void onStartTick() {\n\t\tfunctionStack.tick();\n\t}\n\n\tprivate boolean onChat(String message) {\n\t\tif (message.equals(\"gaeming\")) {\n\t\t\tSimpleItemCollection items = new SimpleItemCollection();\n\t\t\titems.addItem(Items.DIRT, 32);\n\t\t\titems.addItem(Items.OAK_LOG, 32);\n\n\t\t\tfunctionStack.addFunction(new MineBlocksFunction(this, functionStack, items));\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic MinecraftClient getMinecraft() {\n\t\treturn MinecraftClient.getInstance();\n\t}\n\n\tpublic ClientPlayerEntity getPlayer() {\n\t\treturn MinecraftClient.getInstance().player;\n\t}\n\n\tpublic ClientWorld getWorld() {\n\t\treturn MinecraftClient.getInstance().world;\n\t}\n\n\tpublic BSLogger getLogger() {\n\t\treturn logger;\n\t}\n\n\tpublic BaritoneHandler getBaritoneHandler() {\n\t\treturn baritoneHandler;\n\t}\n\n\tpublic IBaritone getBaritone() {\n\t\treturn baritoneHandler.getBaritone();\n\t}\n\n\tpublic FunctionStack getFunctionStack() {\n\t\treturn functionStack;\n\t}\n}" }, { "identifier": "ITimeable", "path": "src/main/java/miro/bassscript/ITimeable.java", "snippet": "public interface ITimeable {\n Double getEstimatedTicks();\n}" } ]
import miro.bassscript.BSLogger; import miro.bassscript.BassScript; import miro.bassscript.ITimeable; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.client.world.ClientWorld;
774
package miro.bassscript.functionutils; /** * All Functions extend this class. * Provides access to the Function's {@link BassScript} instance. */ public abstract class Function implements ITimeable { /** * The current instance of BassScript. */ protected BassScript bassScript; /** * The logger. */
package miro.bassscript.functionutils; /** * All Functions extend this class. * Provides access to the Function's {@link BassScript} instance. */ public abstract class Function implements ITimeable { /** * The current instance of BassScript. */ protected BassScript bassScript; /** * The logger. */
protected BSLogger logger;
0
2023-11-08 05:28:18+00:00
2k
hlysine/create_power_loader
src/main/java/com/hlysine/create_power_loader/content/ContraptionRenderer.java
[ { "identifier": "AndesiteChunkLoaderRenderer", "path": "src/main/java/com/hlysine/create_power_loader/content/andesitechunkloader/AndesiteChunkLoaderRenderer.java", "snippet": "public class AndesiteChunkLoaderRenderer extends AbstractChunkLoaderRenderer {\n\n public AndesiteChunkLoaderRenderer(BlockEntityRendererProvider.Context context) {\n super(context);\n }\n\n @Override\n protected PartialModel getCorePartial(boolean attached, boolean active) {\n if (attached) {\n return active\n ? CPLPartialModels.ANDESITE_CORE_ATTACHED_ACTIVE\n : CPLPartialModels.ANDESITE_CORE_ATTACHED_INACTIVE;\n } else {\n return active\n ? CPLPartialModels.ANDESITE_CORE_ACTIVE\n : CPLPartialModels.ANDESITE_CORE_INACTIVE;\n }\n }\n\n @Override\n protected boolean shouldFunctionOnContraption(MovementContext context) {\n return CPLConfigs.server().andesiteOnContraption.get() &&\n !context.contraption.isActorTypeDisabled(CPLBlocks.ANDESITE_CHUNK_LOADER.asStack()) &&\n !context.contraption.isActorTypeDisabled(ItemStack.EMPTY);\n }\n}" }, { "identifier": "BrassChunkLoaderRenderer", "path": "src/main/java/com/hlysine/create_power_loader/content/brasschunkloader/BrassChunkLoaderRenderer.java", "snippet": "public class BrassChunkLoaderRenderer extends AbstractChunkLoaderRenderer {\n\n public BrassChunkLoaderRenderer(BlockEntityRendererProvider.Context context) {\n super(context);\n }\n\n @Override\n protected PartialModel getCorePartial(boolean attached, boolean active) {\n if (attached) {\n return active\n ? CPLPartialModels.BRASS_CORE_ATTACHED_ACTIVE\n : CPLPartialModels.BRASS_CORE_ATTACHED_INACTIVE;\n } else {\n return active\n ? CPLPartialModels.BRASS_CORE_ACTIVE\n : CPLPartialModels.BRASS_CORE_INACTIVE;\n }\n }\n\n @Override\n protected boolean shouldFunctionOnContraption(MovementContext context) {\n return CPLConfigs.server().brassOnContraption.get() &&\n !context.contraption.isActorTypeDisabled(CPLBlocks.BRASS_CHUNK_LOADER.asStack()) &&\n !context.contraption.isActorTypeDisabled(ItemStack.EMPTY);\n }\n}" } ]
import com.hlysine.create_power_loader.content.andesitechunkloader.AndesiteChunkLoaderRenderer; import com.hlysine.create_power_loader.content.brasschunkloader.BrassChunkLoaderRenderer; import com.jozufozu.flywheel.core.virtual.VirtualRenderWorld; import com.simibubi.create.content.contraptions.behaviour.MovementContext; import com.simibubi.create.content.contraptions.render.ContraptionMatrices; import net.minecraft.client.renderer.MultiBufferSource;
670
package com.hlysine.create_power_loader.content; public class ContraptionRenderer { private static final AndesiteChunkLoaderRenderer ANDESITE_RENDERER = new AndesiteChunkLoaderRenderer(null);
package com.hlysine.create_power_loader.content; public class ContraptionRenderer { private static final AndesiteChunkLoaderRenderer ANDESITE_RENDERER = new AndesiteChunkLoaderRenderer(null);
private static final BrassChunkLoaderRenderer BRASS_RENDERER = new BrassChunkLoaderRenderer(null);
1
2023-11-09 04:29:33+00:00
2k
dingodb/dingo-expr
runtime/src/main/java/io/dingodb/expr/runtime/op/mathematical/AbsCheckFun.java
[ { "identifier": "ExprEvaluatingException", "path": "runtime/src/main/java/io/dingodb/expr/runtime/exception/ExprEvaluatingException.java", "snippet": "public class ExprEvaluatingException extends RuntimeException {\n private static final long serialVersionUID = 3903309327153427907L;\n\n /**\n * Exception thrown when there are errors in evaluating.\n *\n * @param message the error message\n */\n public ExprEvaluatingException(String message) {\n super(message);\n }\n\n /**\n * Exception thrown when there are errors in evaluating.\n *\n * @param cause the cause of the exception\n */\n public ExprEvaluatingException(Throwable cause) {\n super(cause);\n }\n\n /**\n * Exception thrown when there are errors in evaluating.\n *\n * @param cause the cause of the exception\n * @param message the error message\n */\n public ExprEvaluatingException(String message, Throwable cause) {\n super(message, cause);\n }\n}" }, { "identifier": "UnaryNumericOp", "path": "runtime/src/main/java/io/dingodb/expr/runtime/op/UnaryNumericOp.java", "snippet": "public abstract class UnaryNumericOp extends UnaryOp {\n private static final long serialVersionUID = -336042269536007913L;\n\n @Override\n public Object bestKeyOf(@NonNull Type @NonNull [] types) {\n Type best = Types.bestType(types[0]);\n if (best != null) {\n Arrays.fill(types, best);\n }\n return best;\n }\n}" }, { "identifier": "ExceptionUtils", "path": "runtime/src/main/java/io/dingodb/expr/runtime/utils/ExceptionUtils.java", "snippet": "public final class ExceptionUtils {\n private ExceptionUtils() {\n }\n\n public static @NonNull ArithmeticException exceedsIntRange() {\n return new ArithmeticException(\n \"Value exceeds limits of INT, which is from \"\n + Integer.MIN_VALUE + \" to \" + Integer.MAX_VALUE + \".\"\n );\n }\n\n public static @NonNull ArithmeticException exceedsLongRange() {\n return new ArithmeticException(\n \"Value exceeds limits of LONG, which is from \"\n + Long.MIN_VALUE + \" to \" + Long.MAX_VALUE + \".\"\n );\n }\n\n public static @NonNull Object nonNullElement(Object value) {\n if (value != null) {\n return value;\n }\n throw new NullElementsNotAllowed();\n }\n}" } ]
import io.dingodb.expr.annotations.Operators; import io.dingodb.expr.runtime.exception.ExprEvaluatingException; import io.dingodb.expr.runtime.op.UnaryNumericOp; import io.dingodb.expr.runtime.utils.ExceptionUtils; import org.checkerframework.checker.nullness.qual.NonNull; import java.math.BigDecimal;
837
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.runtime.op.mathematical; @Operators abstract class AbsCheckFun extends UnaryNumericOp { public static final String NAME = "ABS"; private static final long serialVersionUID = 6834907753646404442L; static int abs(int num) { if (num == Integer.MIN_VALUE) {
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.runtime.op.mathematical; @Operators abstract class AbsCheckFun extends UnaryNumericOp { public static final String NAME = "ABS"; private static final long serialVersionUID = 6834907753646404442L; static int abs(int num) { if (num == Integer.MIN_VALUE) {
throw new ExprEvaluatingException(ExceptionUtils.exceedsIntRange());
0
2023-11-04 08:43:49+00:00
2k
sesamecare/stripe-mock
src/main/java/com/sesame/oss/stripemock/entities/RefundManager.java
[ { "identifier": "QueryParameters", "path": "src/main/java/com/sesame/oss/stripemock/http/QueryParameters.java", "snippet": "public class QueryParameters {\n private final String wholeQueryParameterString;\n private final Map<String, List<String>> keyValuePairs = new HashMap<>();\n\n public QueryParameters(String wholeQueryParameterString) {\n this.wholeQueryParameterString = wholeQueryParameterString;\n if (wholeQueryParameterString != null) {\n for (String pair : wholeQueryParameterString.split(\"&\")) {\n String[] pairParts = pair.split(\"=\");\n List<String> values = keyValuePairs.computeIfAbsent(pairParts[0], ignored -> new ArrayList<>());\n if (pairParts.length == 2) {\n values.add(pairParts[1]);\n }\n }\n }\n }\n\n public Collection<String> getParameters() {\n return Collections.unmodifiableSet(keyValuePairs.keySet());\n }\n\n public Optional<String> getFirst(String key) {\n List<String> values = keyValuePairs.get(key);\n if (values == null) {\n return Optional.empty();\n }\n if (!values.isEmpty()) {\n return Optional.ofNullable(values.getFirst());\n } else {\n return Optional.empty();\n }\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n QueryParameters that = (QueryParameters) o;\n return Objects.equals(wholeQueryParameterString, that.wholeQueryParameterString);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(wholeQueryParameterString);\n }\n\n @Override\n public String toString() {\n return wholeQueryParameterString == null ? \"\" : \"?\" + wholeQueryParameterString;\n }\n}" }, { "identifier": "ResponseCodeException", "path": "src/main/java/com/sesame/oss/stripemock/http/ResponseCodeException.java", "snippet": "public class ResponseCodeException extends Exception {\n private final int responseCode;\n private final String errorMessage;\n private final String code;\n private final String errorType;\n private final String declineCode;\n\n public ResponseCodeException(int responseCode, String errorMessage) {\n this(responseCode, errorMessage, null, null, null);\n }\n\n public ResponseCodeException(int responseCode, String errorMessage, String code, String errorType, String declineCode) {\n super(errorMessage);\n this.responseCode = responseCode;\n this.errorMessage = errorMessage;\n this.code = code;\n this.errorType = errorType;\n this.declineCode = declineCode;\n }\n\n public int getResponseCode() {\n return responseCode;\n }\n\n public String getErrorMessage() {\n return errorMessage;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getErrorType() {\n return errorType;\n }\n\n public String getDeclineCode() {\n return declineCode;\n }\n\n public static ResponseCodeException noSuchEntity(int code, String entityType, String entityId) {\n return new ResponseCodeException(code, String.format(\"No such %s: '%s'\", entityType, entityId), \"resource_missing\", \"invalid_request_error\", null);\n }\n}" } ]
import com.sesame.oss.stripemock.http.QueryParameters; import com.sesame.oss.stripemock.http.ResponseCodeException; import com.stripe.model.PaymentIntent; import com.stripe.model.Refund; import java.time.Clock; import java.util.List; import java.util.Map;
1,401
package com.sesame.oss.stripemock.entities; class RefundManager extends AbstractEntityManager<Refund> { private final StripeEntities stripeEntities; protected RefundManager(Clock clock, StripeEntities stripeEntities) { super(clock, Refund.class, "re", 24); this.stripeEntities = stripeEntities; } @Override protected Refund initialize(Refund refund, Map<String, Object> formData) throws ResponseCodeException { refund.setStatus("succeeded"); if (refund.getAmount() == null && refund.getPaymentIntent() != null) { refund.setAmount(stripeEntities.getEntityManager(PaymentIntent.class) .get(refund.getPaymentIntent()) .orElseThrow(() -> ResponseCodeException.noSuchEntity(400, "payment_intent", refund.getPaymentIntent())) .getAmount()); } return refund; } @Override protected void validate(Refund refund) throws ResponseCodeException { super.validate(refund); String paymentIntentId = refund.getPaymentIntent(); if (paymentIntentId == null && refund.getCharge() == null) { throw new ResponseCodeException(400, "One of the following params should be provided for this request: payment_intent or charge."); } // todo: support charges too PaymentIntent paymentIntent = stripeEntities.getEntityManager(PaymentIntent.class) .get(paymentIntentId) .orElseThrow(() -> ResponseCodeException.noSuchEntity(400, "payment_intent", paymentIntentId)); if (!paymentIntent.getStatus() .equals("succeeded")) { throw new ResponseCodeException(400, String.format("This PaymentIntent (%s) does not have a successful charge to refund.", paymentIntentId)); } } @Override protected Refund perform(Refund existingRefund, Refund updatedRefund, String operation, Map<String, Object> formData) throws ResponseCodeException { if (operation.equals("cancel")) { String status = updatedRefund.getStatus(); if (status.equals("pending")) { updatedRefund.setStatus("canceled"); } else if (status.equals("canceled")) { // Already canceled, nothing to be done } else { throw new ResponseCodeException(400, "Can't cancel a refund that is in status: " + status); } return updatedRefund; } return super.perform(existingRefund, updatedRefund, operation, formData); } @Override public boolean canPerformOperation(String operation) { return operation.equals("cancel"); } @Override
package com.sesame.oss.stripemock.entities; class RefundManager extends AbstractEntityManager<Refund> { private final StripeEntities stripeEntities; protected RefundManager(Clock clock, StripeEntities stripeEntities) { super(clock, Refund.class, "re", 24); this.stripeEntities = stripeEntities; } @Override protected Refund initialize(Refund refund, Map<String, Object> formData) throws ResponseCodeException { refund.setStatus("succeeded"); if (refund.getAmount() == null && refund.getPaymentIntent() != null) { refund.setAmount(stripeEntities.getEntityManager(PaymentIntent.class) .get(refund.getPaymentIntent()) .orElseThrow(() -> ResponseCodeException.noSuchEntity(400, "payment_intent", refund.getPaymentIntent())) .getAmount()); } return refund; } @Override protected void validate(Refund refund) throws ResponseCodeException { super.validate(refund); String paymentIntentId = refund.getPaymentIntent(); if (paymentIntentId == null && refund.getCharge() == null) { throw new ResponseCodeException(400, "One of the following params should be provided for this request: payment_intent or charge."); } // todo: support charges too PaymentIntent paymentIntent = stripeEntities.getEntityManager(PaymentIntent.class) .get(paymentIntentId) .orElseThrow(() -> ResponseCodeException.noSuchEntity(400, "payment_intent", paymentIntentId)); if (!paymentIntent.getStatus() .equals("succeeded")) { throw new ResponseCodeException(400, String.format("This PaymentIntent (%s) does not have a successful charge to refund.", paymentIntentId)); } } @Override protected Refund perform(Refund existingRefund, Refund updatedRefund, String operation, Map<String, Object> formData) throws ResponseCodeException { if (operation.equals("cancel")) { String status = updatedRefund.getStatus(); if (status.equals("pending")) { updatedRefund.setStatus("canceled"); } else if (status.equals("canceled")) { // Already canceled, nothing to be done } else { throw new ResponseCodeException(400, "Can't cancel a refund that is in status: " + status); } return updatedRefund; } return super.perform(existingRefund, updatedRefund, operation, formData); } @Override public boolean canPerformOperation(String operation) { return operation.equals("cancel"); } @Override
public List<Refund> list(QueryParameters query) {
0
2023-11-03 08:51:13+00:00
2k
Bo-Vane/Chatbot-api
chatbot-api-interface/src/test/java/com/bo/chatbot/api/test/SpringBootRunTest.java
[ { "identifier": "IOpenAI", "path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/ai/IOpenAI.java", "snippet": "public interface IOpenAI {\n String doChatGLM(String question) throws IOException;\n}" }, { "identifier": "IZsxqApi", "path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/zsxq/IZsxqApi.java", "snippet": "public interface IZsxqApi {\n\n QuestionAggregates queryQuestion(String groupId, String cookie) throws IOException;\n\n boolean answer(String groupId,String cookie,String topicId,String text) throws IOException;\n}" }, { "identifier": "QuestionAggregates", "path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/zsxq/aggregates/QuestionAggregates.java", "snippet": "public class QuestionAggregates {\n\n private boolean succeeded;\n private Resp_data resp_data;\n\n public QuestionAggregates(boolean succeeded, Resp_data resp_data) {\n this.succeeded = succeeded;\n this.resp_data = resp_data;\n }\n\n public boolean isSucceeded() {\n return succeeded;\n }\n\n public void setSucceeded(boolean succeeded) {\n this.succeeded = succeeded;\n }\n\n public Resp_data getResp_data() {\n return resp_data;\n }\n\n public void setResp_data(Resp_data resp_data) {\n this.resp_data = resp_data;\n }\n}" }, { "identifier": "Favorites", "path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/zsxq/vo/Favorites.java", "snippet": "public class Favorites\n{\n private String favor_time;\n\n private Topic topic;\n\n public void setFavor_time(String favor_time){\n this.favor_time = favor_time;\n }\n public String getFavor_time(){\n return this.favor_time;\n }\n public void setTopic(Topic topic){\n this.topic = topic;\n }\n public Topic getTopic(){\n return this.topic;\n }\n}" }, { "identifier": "Topic", "path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/zsxq/vo/Topic.java", "snippet": "public class Topic\n{\n private String topic_id;\n\n private Group group;\n\n private String type;\n\n private Task task;\n\n private Statistics statistics;\n\n private boolean enabled_task;\n\n private boolean show_solutions;\n\n private List<Show_comments> show_comments;\n\n private int likes_count;\n\n private int rewards_count;\n\n private int comments_count;\n\n private int reading_count;\n\n private int readers_count;\n\n private boolean digested;\n\n private boolean sticky;\n\n private String create_time;\n\n private User_specific user_specific;\n\n public void setTopic_id(String topic_id){\n this.topic_id = topic_id;\n }\n public String getTopic_id(){\n return this.topic_id;\n }\n public void setGroup(Group group){\n this.group = group;\n }\n public Group getGroup(){\n return this.group;\n }\n public void setType(String type){\n this.type = type;\n }\n public String getType(){\n return this.type;\n }\n public void setTask(Task task){\n this.task = task;\n }\n public Task getTask(){\n return this.task;\n }\n public void setStatistics(Statistics statistics){\n this.statistics = statistics;\n }\n public Statistics getStatistics(){\n return this.statistics;\n }\n public void setEnabled_task(boolean enabled_task){\n this.enabled_task = enabled_task;\n }\n public boolean getEnabled_task(){\n return this.enabled_task;\n }\n public void setShow_solutions(boolean show_solutions){\n this.show_solutions = show_solutions;\n }\n public boolean getShow_solutions(){\n return this.show_solutions;\n }\n public void setShow_comments(List<Show_comments> show_comments){\n this.show_comments = show_comments;\n }\n public List<Show_comments> getShow_comments(){\n return this.show_comments;\n }\n public void setLikes_count(int likes_count){\n this.likes_count = likes_count;\n }\n public int getLikes_count(){\n return this.likes_count;\n }\n public void setRewards_count(int rewards_count){\n this.rewards_count = rewards_count;\n }\n public int getRewards_count(){\n return this.rewards_count;\n }\n public void setComments_count(int comments_count){\n this.comments_count = comments_count;\n }\n public int getComments_count(){\n return this.comments_count;\n }\n public void setReading_count(int reading_count){\n this.reading_count = reading_count;\n }\n public int getReading_count(){\n return this.reading_count;\n }\n public void setReaders_count(int readers_count){\n this.readers_count = readers_count;\n }\n public int getReaders_count(){\n return this.readers_count;\n }\n public void setDigested(boolean digested){\n this.digested = digested;\n }\n public boolean getDigested(){\n return this.digested;\n }\n public void setSticky(boolean sticky){\n this.sticky = sticky;\n }\n public boolean getSticky(){\n return this.sticky;\n }\n public void setCreate_time(String create_time){\n this.create_time = create_time;\n }\n public String getCreate_time(){\n return this.create_time;\n }\n public void setUser_specific(User_specific user_specific){\n this.user_specific = user_specific;\n }\n public User_specific getUser_specific(){\n return this.user_specific;\n }\n}" } ]
import com.alibaba.fastjson.JSON; import com.bo.chatbot.api.domain.ai.IOpenAI; import com.bo.chatbot.api.domain.zsxq.IZsxqApi; import com.bo.chatbot.api.domain.zsxq.aggregates.QuestionAggregates; import com.bo.chatbot.api.domain.zsxq.vo.Favorites; import com.bo.chatbot.api.domain.zsxq.vo.Topic; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.io.IOException;
1,597
package com.bo.chatbot.api.test; @SpringBootTest @RunWith(SpringRunner.class) public class SpringBootRunTest { private Logger logger = LoggerFactory.getLogger(SpringBootRunTest.class); @Value("${chatbot-api.groupId}") private String groupId; @Value("${chatbot-api.cookie}") private String cookie; @Resource private IZsxqApi zsxqApi; @Resource private IOpenAI openAI; @Test public void test_zsxqApi() throws IOException {
package com.bo.chatbot.api.test; @SpringBootTest @RunWith(SpringRunner.class) public class SpringBootRunTest { private Logger logger = LoggerFactory.getLogger(SpringBootRunTest.class); @Value("${chatbot-api.groupId}") private String groupId; @Value("${chatbot-api.cookie}") private String cookie; @Resource private IZsxqApi zsxqApi; @Resource private IOpenAI openAI; @Test public void test_zsxqApi() throws IOException {
QuestionAggregates questionAggregates = zsxqApi.queryQuestion(groupId, cookie);
2
2023-11-06 08:52:38+00:00
2k
Arborsm/ArborCore
src/main/java/org/arbor/gtnn/api/recipe/PlantCasingCondition.java
[ { "identifier": "IChemicalPlantReceiver", "path": "src/main/java/org/arbor/gtnn/api/capability/IChemicalPlantReceiver.java", "snippet": "public interface IChemicalPlantReceiver {\n /**\n * @return the cleanroom the machine is receiving from\n */\n @Nullable\n IChemicalPlantProvider getChemicalPlant();\n}" }, { "identifier": "IChemicalPlantProvider", "path": "src/main/java/org/arbor/gtnn/api/machine/feature/IChemicalPlantProvider.java", "snippet": "public interface IChemicalPlantProvider extends IMachineFeature {\n}" }, { "identifier": "PlantCasingBlock", "path": "src/main/java/org/arbor/gtnn/block/PlantCasingBlock.java", "snippet": "public class PlantCasingBlock extends Block {\n private static final Map<String, PlantCasing> All_PlantCasing = new Object2ObjectOpenHashMap<>();\n private static final Map<Integer, PlantCasing> All_PlantCasing_Tier = new Object2ObjectOpenHashMap<>();\n\n public PlantCasingBlock(Properties properties) {\n super(properties);\n }\n\n public enum PlantCasing implements PlantCasingType {\n BRONZE(TIER0, CASING_BRONZE_BRICKS, \"Bronze\", GTCEu.id(\"block/casings/solid/machine_casing_bronze_plated_bricks\")),\n STEEL(TIER1, CASING_STEEL_SOLID, \"Steel\", GTCEu.id(\"block/casings/solid/machine_casing_solid_steel\")),\n ALUMINIUM(TIER2, CASING_ALUMINIUM_FROSTPROOF, \"Aluminium\", GTCEu.id(\"block/casings/solid/machine_casing_frost_proof\")),\n STAINLESS(TIER3, CASING_STAINLESS_CLEAN, \"Stainless\", GTCEu.id(\"block/casings/solid/machine_casing_clean_stainless_steel\")),\n TITANIUM(TIER4, CASING_TITANIUM_STABLE, \"Titanium\", GTCEu.id(\"block/casings/solid/machine_casing_stable_titanium\")),\n TUNGSTENSTEEL(TIER5, CASING_TUNGSTENSTEEL_ROBUST, \"Tungstensteel\", GTCEu.id(\"block/casings/solid/machine_casing_robust_tungstensteel\")),\n CHROME(TIER6, CASING_TUNGSTENSTEEL_ROBUST, \"Chrome\", GTCEu.id(\"block/casings/solid/machine_casing_robust_tungstensteel\")),\n IRIDIUM(TIER7, CASING_TUNGSTENSTEEL_ROBUST, \"Iridium\", GTCEu.id(\"block/casings/solid/machine_casing_robust_tungstensteel\"));\n\n private final ITier tier;\n private final BlockEntry<Block> plantCasing;\n private final String name;\n private final ResourceLocation resourceLocation;\n\n PlantCasing(ITier tier, BlockEntry<Block> plantCasing, String name, ResourceLocation resourceLocation) {\n this.tier = tier;\n this.plantCasing = plantCasing;\n this.name = name;\n this.resourceLocation = resourceLocation;\n All_PlantCasing.put(name, this);\n All_PlantCasing_Tier.put(tier.tier(), this);\n }\n public static PlantCasing getByTier(int tier){\n return All_PlantCasing_Tier.get(tier);\n }\n\n @Nullable\n public static PlantCasing getByName(@Nullable String name) {\n return All_PlantCasing.get(name);\n }\n\n @Nonnull\n public static PlantCasing getByNameOrDefault(@Nullable String name) {\n var type = getByName(name);\n if (type == null) {\n return BRONZE;\n }\n return type;\n }\n\n public PlantCasingType plantCasingType() {\n return this;\n }\n\n @Override\n public String getName() {\n return this.name;\n }\n\n @Override\n public int getTier() {\n return tier.tier();\n }\n\n @Override\n public BlockEntry<Block> getPlantCasing() {\n return plantCasing;\n }\n\n public BlockEntry<Block> getPlantCasing(int tier) {\n return PlantCasing.values()[tier].getPlantCasing();\n }\n\n @Override\n public ResourceLocation getResourceLocation() {\n return resourceLocation;\n }\n }\n}" } ]
import com.google.gson.JsonObject; import com.gregtechceu.gtceu.api.machine.MetaMachine; import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMultiController; import com.gregtechceu.gtceu.api.machine.trait.RecipeLogic; import com.gregtechceu.gtceu.api.recipe.GTRecipe; import com.gregtechceu.gtceu.api.recipe.RecipeCondition; import lombok.Getter; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.util.GsonHelper; import org.arbor.gtnn.api.capability.IChemicalPlantReceiver; import org.arbor.gtnn.api.machine.feature.IChemicalPlantProvider; import org.arbor.gtnn.block.PlantCasingBlock; import org.jetbrains.annotations.NotNull;
1,235
package org.arbor.gtnn.api.recipe; @Getter public class PlantCasingCondition extends RecipeCondition { public final static PlantCasingCondition INSTANCE = new PlantCasingCondition();
package org.arbor.gtnn.api.recipe; @Getter public class PlantCasingCondition extends RecipeCondition { public final static PlantCasingCondition INSTANCE = new PlantCasingCondition();
private PlantCasingBlock.PlantCasing plantCasing = PlantCasingBlock.PlantCasing.BRONZE;
2
2023-11-04 07:59:02+00:00
2k
satisfyu/HerbalBrews
common/src/main/java/satisfyu/herbalbrews/compat/rei/display/TeaKettleDisplay.java
[ { "identifier": "TeaKettleCategory", "path": "common/src/main/java/satisfyu/herbalbrews/compat/rei/category/TeaKettleCategory.java", "snippet": "public class TeaKettleCategory implements DisplayCategory<TeaKettleDisplay> {\n\n\n public static final CategoryIdentifier<TeaKettleDisplay> COOKING_CAULDRON_DISPLAY = CategoryIdentifier.of(HerbalBrews.MOD_ID, \"tea_kettle_display\");\n\n @Override\n public CategoryIdentifier<TeaKettleDisplay> getCategoryIdentifier() {\n return COOKING_CAULDRON_DISPLAY;\n }\n\n @Override\n public Component getTitle() {\n return Component.translatable(\"rei.herbalbrews.tea_kettle_category\");\n }\n\n @Override\n public Renderer getIcon() {\n return EntryStacks.of(ObjectRegistry.TEA_KETTLE.get());\n }\n\n @Override\n public int getDisplayHeight() {\n return 64;\n }\n\n @Override\n public List<Widget> setupDisplay(TeaKettleDisplay display, Rectangle bounds) {\n Point startPoint = new Point(bounds.getX() + 16, bounds.getCenterY() - 18);\n List<Widget> widgets = Lists.newArrayList();\n widgets.add(Widgets.createRecipeBase(bounds));\n widgets.add(Widgets.createArrow(new Point(startPoint.x + 60, startPoint.y + 9)).animationDurationTicks(TeaKettleBlockEntity.MAX_COOKING_TIME));\n\n widgets.add(Widgets.createResultSlotBackground(new Point(startPoint.x + 96, startPoint.y + 9)));\n widgets.add(Widgets.createSlot(new Point(startPoint.x + 96, startPoint.y + 9)).entries(display.getOutputEntries().get(0)).disableBackground().markOutput());\n\n for (int slot = 0; slot < 6; slot++) {\n if (display.getInputEntries().size() < slot + 1)\n widgets.add(Widgets.createSlotBackground(new Point(startPoint.x + 18 * (slot % 3), startPoint.y + 18 * (slot / 3))));\n else\n widgets.add(Widgets.createSlot(new Point(startPoint.x + 18 * (slot % 3), startPoint.y + 18 * (slot / 3))).entries(display.getInputEntries().get(slot)).markInput());\n }\n\n return widgets;\n }\n}" }, { "identifier": "TeaKettleRecipe", "path": "common/src/main/java/satisfyu/herbalbrews/recipe/TeaKettleRecipe.java", "snippet": "public class TeaKettleRecipe implements Recipe<Container> {\n\n final ResourceLocation id;\n private final NonNullList<Ingredient> inputs;\n private final ItemStack output;\n\n public TeaKettleRecipe(ResourceLocation id, NonNullList<Ingredient> inputs, ItemStack output) {\n this.id = id;\n this.inputs = inputs;\n this.output = output;\n }\n\n @Override\n public boolean matches(Container inventory, Level world) {\n return GeneralUtil.matchesRecipe(inventory, inputs, 0, 6);\n }\n\n public ItemStack assemble() {\n return assemble(null, null);\n }\n\n @Override\n public ItemStack assemble(Container inventory, RegistryAccess registryManager) {\n return this.output.copy();\n }\n\n @Override\n public boolean canCraftInDimensions(int width, int height) {\n return false;\n }\n\n public ItemStack getResultItem() {\n return getResultItem(null);\n }\n\n @Override\n public ItemStack getResultItem(RegistryAccess registryManager) {\n return this.output;\n }\n\n @Override\n public ResourceLocation getId() {\n return id;\n }\n\n @Override\n public RecipeSerializer<?> getSerializer() {\n return RecipeTypeRegistry.TEAK_KETTLE_RECIPE_SERIALIZER.get();\n }\n\n @Override\n public RecipeType<?> getType() {\n return RecipeTypeRegistry.TEA_KETTLE_RECIPE_TYPE.get();\n }\n\n @Override\n public NonNullList<Ingredient> getIngredients() {\n return this.inputs;\n }\n\n @Override\n public boolean isSpecial() {\n return true;\n }\n\n public static class Serializer implements RecipeSerializer<TeaKettleRecipe> {\n\n @Override\n public TeaKettleRecipe fromJson(ResourceLocation id, JsonObject json) {\n final var ingredients = GeneralUtil.deserializeIngredients(GsonHelper.getAsJsonArray(json, \"ingredients\"));\n if (ingredients.isEmpty()) {\n throw new JsonParseException(\"No ingredients for Tea Kettle Recipe\");\n } else if (ingredients.size() > 6) {\n throw new JsonParseException(\"Too many ingredients for Tea Kettle Recipe\");\n } else {\n return new TeaKettleRecipe(id, ingredients, ShapedRecipe.itemStackFromJson(GsonHelper.getAsJsonObject(json, \"result\")));\n }\n }\n\n @Override\n public TeaKettleRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf buf) {\n final var ingredients = NonNullList.withSize(buf.readVarInt(), Ingredient.EMPTY);\n ingredients.replaceAll(ignored -> Ingredient.fromNetwork(buf));\n return new TeaKettleRecipe(id, ingredients, buf.readItem());\n }\n\n @Override\n public void toNetwork(FriendlyByteBuf buf, TeaKettleRecipe recipe) {\n buf.writeVarInt(recipe.inputs.size());\n recipe.inputs.forEach(entry -> entry.toNetwork(buf));\n buf.writeItem(recipe.output);\n }\n }\n\n public static class Type implements RecipeType<TeaKettleRecipe> {\n private Type() {\n }\n\n public static final Type INSTANCE = new Type();\n\n public static final String ID = \"cooking\";\n }\n}" } ]
import me.shedaniel.rei.api.common.category.CategoryIdentifier; import me.shedaniel.rei.api.common.display.basic.BasicDisplay; import me.shedaniel.rei.api.common.entry.EntryIngredient; import me.shedaniel.rei.api.common.util.EntryIngredients; import net.minecraft.resources.ResourceLocation; import satisfyu.herbalbrews.compat.rei.category.TeaKettleCategory; import satisfyu.herbalbrews.recipe.TeaKettleRecipe; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional;
1,583
package satisfyu.herbalbrews.compat.rei.display; public class TeaKettleDisplay extends BasicDisplay { public TeaKettleDisplay(TeaKettleRecipe recipe) { this(EntryIngredients.ofIngredients(new ArrayList<>(recipe.getIngredients())), Collections.singletonList(EntryIngredients.of(recipe.getResultItem(BasicDisplay.registryAccess()))), Optional.ofNullable(recipe.getId())); } public TeaKettleDisplay(List<EntryIngredient> inputs, List<EntryIngredient> outputs, Optional<ResourceLocation> location) { super(inputs, outputs, location); } @Override public CategoryIdentifier<?> getCategoryIdentifier() {
package satisfyu.herbalbrews.compat.rei.display; public class TeaKettleDisplay extends BasicDisplay { public TeaKettleDisplay(TeaKettleRecipe recipe) { this(EntryIngredients.ofIngredients(new ArrayList<>(recipe.getIngredients())), Collections.singletonList(EntryIngredients.of(recipe.getResultItem(BasicDisplay.registryAccess()))), Optional.ofNullable(recipe.getId())); } public TeaKettleDisplay(List<EntryIngredient> inputs, List<EntryIngredient> outputs, Optional<ResourceLocation> location) { super(inputs, outputs, location); } @Override public CategoryIdentifier<?> getCategoryIdentifier() {
return TeaKettleCategory.COOKING_CAULDRON_DISPLAY;
0
2023-11-05 16:46:52+00:00
2k
sizdshi/download-server
server/common/src/main/java/com/example/utils/ResultUtils.java
[ { "identifier": "ErrorCode", "path": "server/common/src/main/java/com/example/common/ErrorCode.java", "snippet": "public enum ErrorCode {\r\n /**\r\n * 成功\r\n */\r\n SUCCESS(0, \"ok\"),\r\n /**\r\n * 请求参数错误\r\n */\r\n PARAMS_ERROR(40000, \"请求参数错误\"),\r\n /**\r\n * 未登录\r\n */\r\n NOT_LOGIN_ERROR(40100, \"未登录\"),\r\n /**\r\n * 无权限\r\n */\r\n NO_AUTH_ERROR(40101, \"无权限\"),\r\n /**\r\n * 账号已封禁\r\n */\r\n PROHIBITED(40001, \"账号已封禁\"),\r\n /**\r\n * 请求数据不存在\r\n */\r\n NOT_FOUND_ERROR(40400, \"请求数据不存在\"),\r\n /**\r\n * 禁止访问\r\n */\r\n FORBIDDEN_ERROR(40300, \"禁止访问\"),\r\n /**\r\n * 系统内部异常\r\n */\r\n SYSTEM_ERROR(50000, \"系统内部异常\"),\r\n /**\r\n * 操作错误\r\n */\r\n FILE_ERROR(40500, \"下载失败,文件过大,请下载2GB以下文件\"),\r\n /**\r\n * 操作错误\r\n */\r\n OPERATION_ERROR(50001, \"操作失败\");\r\n\r\n\r\n\r\n /**\r\n * 状态码\r\n */\r\n private final int code;\r\n\r\n /**\r\n * 信息\r\n */\r\n private final String message;\r\n\r\n ErrorCode(int code, String message) {\r\n this.code = code;\r\n this.message = message;\r\n }\r\n\r\n public int getCode() {\r\n return code;\r\n }\r\n\r\n public String getMessage() {\r\n return message;\r\n }\r\n}\r" }, { "identifier": "BaseResponse", "path": "server/common/src/main/java/com/example/model/BaseResponse.java", "snippet": "@Data\r\npublic class BaseResponse<T> implements Serializable {\r\n\r\n private static final long serialVersionUID = -1693660536490703953L;\r\n private int code;\r\n\r\n private T data;\r\n\r\n private String message;\r\n\r\n public BaseResponse(int code, T data, String message) {\r\n this.code = code;\r\n this.data = data;\r\n this.message = message;\r\n }\r\n\r\n public BaseResponse(int code, T data) {\r\n this(code, data, \"\");\r\n }\r\n\r\n public BaseResponse(ErrorCode errorCode) {\r\n this(errorCode.getCode(), null, errorCode.getMessage());\r\n }\r\n}\r" } ]
import com.example.common.ErrorCode; import com.example.model.BaseResponse;
745
package com.example.utils; /** * @Author: Kenneth shi * @Description: **/ public class ResultUtils { /** * 成功 * * @param data 数据 * @return {@link BaseResponse}<{@link T}> */ public static <T> BaseResponse<T> success(T data) { return new BaseResponse<>(0, data, "ok"); } /** * 错误 * 失败 * * @param errorCode 错误代码 * @return {@link BaseResponse} */
package com.example.utils; /** * @Author: Kenneth shi * @Description: **/ public class ResultUtils { /** * 成功 * * @param data 数据 * @return {@link BaseResponse}<{@link T}> */ public static <T> BaseResponse<T> success(T data) { return new BaseResponse<>(0, data, "ok"); } /** * 错误 * 失败 * * @param errorCode 错误代码 * @return {@link BaseResponse} */
public static <T> BaseResponse<T> error(ErrorCode errorCode) {
0
2023-11-02 06:09:03+00:00
2k
RapierXbox/Benium-Client
src/main/java/net/rapierxbox/beniumclient/hacks/KillAura.java
[ { "identifier": "Hack", "path": "src/main/java/net/rapierxbox/beniumclient/util/Hack.java", "snippet": "public class Hack {\r\n private final String name;\r\n\r\n private static boolean enabled;\r\n public Hack(String name)\r\n {\r\n this.name = name;\r\n }\r\n\r\n public static final boolean isEnabled()\r\n {\r\n return enabled;\r\n }\r\n\r\n public String getName() {return this.name;}\r\n\r\n public final void setEnabled(boolean enabled)\r\n {\r\n if (this.enabled == enabled){\r\n return;\r\n }\r\n this.enabled = enabled;\r\n\r\n if (enabled) {\r\n onEnable();\r\n } else {\r\n onDisable();\r\n }\r\n }\r\n\r\n public final String getEnabledString() {\r\n if (enabled) {\r\n return name + \" enabled\";\r\n } else {\r\n return name + \" disabled\";\r\n }\r\n }\r\n\r\n public final void toggle() {\r\n setEnabled(!enabled);\r\n }\r\n\r\n protected void onEnable()\r\n {\r\n\r\n }\r\n\r\n protected void onDisable()\r\n {\r\n\r\n }\r\n\r\n protected void tick(MinecraftClient client) {\r\n\r\n }\r\n}\r" }, { "identifier": "BUtil", "path": "src/main/java/net/rapierxbox/beniumclient/util/BUtil.java", "snippet": "public class BUtil {\r\n public static Entity getNearestEntity(MinecraftClient client) {\r\n Entity best_entity = null;\r\n Double best_dis = 6.0;\r\n\r\n for (Entity entity : client.world.getEntities()) {\r\n if (!entity.isPlayer() && entity.isAttackable() && entity.isAlive()) {\r\n if (BMath.getdistance(client.player.getPos(), entity.getPos()) < best_dis) {\r\n best_entity = entity;\r\n best_dis = BMath.getdistance(client.player.getPos(), entity.getPos());\r\n }\r\n }\r\n }\r\n return best_entity;\r\n }\r\n\r\n public static Entity getNearestEntity(MinecraftClient client, BlockPos pos) {\r\n Entity best_entity = null;\r\n Double best_dis = 5.0;\r\n\r\n for (Entity entity : client.world.getEntities()) {\r\n if (!entity.isPlayer() && entity.isAttackable() && entity.isAlive()) {\r\n if (BMath.getdistance(new Vec3d(pos.getX(), pos.getY(), pos.getZ()), entity.getPos()) < best_dis) {\r\n best_entity = entity;\r\n best_dis = BMath.getdistance(new Vec3d(pos.getX(), pos.getY(), pos.getZ()), entity.getPos());\r\n }\r\n }\r\n }\r\n return best_entity;\r\n }\r\n}\r" } ]
import net.minecraft.client.MinecraftClient; import net.minecraft.entity.Entity; import net.minecraft.util.Hand; import net.rapierxbox.beniumclient.util.Hack; import net.rapierxbox.beniumclient.util.BUtil; import java.util.Random;
746
package net.rapierxbox.beniumclient.hacks; public class KillAura extends Hack { public KillAura() { super("KillAura"); } private Entity target; private static int cooldown = 5; @Override protected void tick(MinecraftClient client) {
package net.rapierxbox.beniumclient.hacks; public class KillAura extends Hack { public KillAura() { super("KillAura"); } private Entity target; private static int cooldown = 5; @Override protected void tick(MinecraftClient client) {
if (BUtil.getNearestEntity(client) != null && cooldown <= 0) {
1
2023-11-09 13:23:48+00:00
2k
SatyaRajAwasth1/smart-credit-manager
src/main/java/np/com/satyarajawasthi/smartcreditmanager/controller/CredentialDialogController.java
[ { "identifier": "Credential", "path": "src/main/java/np/com/satyarajawasthi/smartcreditmanager/model/Credential.java", "snippet": "public class Credential {\n\n private int id;\n private String toolName;\n private String username;\n private String password;\n private String email;\n private String remarks;\n\n public Credential() {\n }\n\n public Credential(int id, String toolName, String username, String password, String email, String remarks) {\n this.id = id;\n this.toolName = toolName;\n this.username = username;\n this.password = password;\n this.email = email;\n this.remarks = remarks;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getToolName() {\n return toolName;\n }\n\n public void setToolName(String toolName) {\n this.toolName = toolName;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getRemarks() {\n return remarks;\n }\n\n public void setRemarks(String remarks) {\n this.remarks = remarks;\n }\n}" }, { "identifier": "CredentialManager", "path": "src/main/java/np/com/satyarajawasthi/smartcreditmanager/manager/CredentialManager.java", "snippet": "public class CredentialManager {\n private final CredentialRepository credentialRepository;\n private final String encryptionKey;\n\n public CredentialManager() {\n credentialRepository = new CredentialRepository();\n encryptionKey = \"5a98beed71b7d65e10d914d3456f25b1\";\n }\n\n public ObservableList<Credential> getAllCredentials() {\n List<Credential> credentialList = credentialRepository.getAllCredentials(encryptionKey);\n return FXCollections.observableArrayList(credentialList);\n }\n\n public void addCredential(Credential credential) {\n credentialRepository.addCredential(credential, encryptionKey);\n }\n\n public void editCredential(Credential credential) {\n credentialRepository.editCredential(credential, encryptionKey);\n }\n\n public void deleteCredential(int credentialId) {\n credentialRepository.deleteCredential(credentialId);\n }\n\n}" } ]
import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.stage.Stage; import javafx.util.Duration; import np.com.satyarajawasthi.smartcreditmanager.model.Credential; import np.com.satyarajawasthi.smartcreditmanager.manager.CredentialManager;
816
package np.com.satyarajawasthi.smartcreditmanager.controller; public class CredentialDialogController { @FXML private TextField toolNameField; @FXML private TextField usernameField; @FXML private TextField passwordField; @FXML private TextField emailField; @FXML private TextField remarksField; @FXML private DialogPane dialogPane; private CredentialManager credentialManager; private Stage dialogStage;
package np.com.satyarajawasthi.smartcreditmanager.controller; public class CredentialDialogController { @FXML private TextField toolNameField; @FXML private TextField usernameField; @FXML private TextField passwordField; @FXML private TextField emailField; @FXML private TextField remarksField; @FXML private DialogPane dialogPane; private CredentialManager credentialManager; private Stage dialogStage;
private Credential credential; // For storing the credential to edit
0
2023-11-05 03:53:02+00:00
2k
AmokDev/DeathNote
src/main/java/dev/amok/DeathNote/Plugin.java
[ { "identifier": "SQLite", "path": "src/main/java/dev/amok/DeathNote/Database/SQLite.java", "snippet": "public class SQLite {\n static Connection dbConnection;\n\n public static void getConnection() throws SQLException {\n dbConnection = DriverManager.getConnection(String.format(\"jdbc:sqlite:%s\\\\data.db\", getInstance().getDataFolder()));\n }\n\n public static void closeConnection() throws SQLException {\n dbConnection.close();\n }\n\n public static void createDB() throws SQLException {\n Statement statement = dbConnection.createStatement();\n statement.setQueryTimeout(30);\n\n statement.executeUpdate(\"CREATE TABLE IF NOT EXISTS players (name TEXT, unix INTEGER)\");\n }\n\n public static void addPlayer(String name) throws SQLException {\n Statement statement = dbConnection.createStatement();\n statement.setQueryTimeout(30);\n\n statement.executeUpdate(String.format(\"INSERT INTO players VALUES('%s', 0)\", name));\n }\n\n public static void updatePlayerData(String name, long unix) throws SQLException {\n Statement statement = dbConnection.createStatement();\n statement.setQueryTimeout(30);\n statement.executeUpdate(String.format(\"UPDATE players SET unix = %d WHERE name = '%s'\", unix, name));\n }\n\n public static long getPlayerUnix(String name) throws SQLException {\n Statement statement = dbConnection.createStatement();\n statement.setQueryTimeout(30);\n ResultSet rs = statement.executeQuery(String.format(\"SELECT * FROM players WHERE name = '%s'\", name));\n long data = 0;\n while (rs.next())\n data = rs.getLong(\"unix\");\n return data;\n }\n\n public static int getPlayerIsRegistered(String name) throws SQLException {\n Statement statement = dbConnection.createStatement();\n statement.setQueryTimeout(30);\n ResultSet rs = statement.executeQuery(String.format(\"SELECT * FROM players WHERE name = '%s'\", name));\n String data = \"\";\n while (rs.next())\n data = rs.getString(\"name\");\n\n if (data == null) {\n return 0;\n } else if (!data.equals(name)) {\n return 0;\n }\n return 1;\n }\n}" }, { "identifier": "CommandInit", "path": "src/main/java/dev/amok/DeathNote/Initializers/CommandInit.java", "snippet": "public class CommandInit {\n\n\tpublic static void init() {\n\t\ttry {\n\t\t\tClassPath cp = ClassPath.from(CommandInit.class.getClassLoader());\n\t\t\tfor (ClassInfo classInfo : cp.getTopLevelClassesRecursive(\"dev.amok.DeathNote.Commands\")) {\n\t\t\t\tClass<?> clazz = Class.forName(classInfo.getName());\n\t\t\t\ttry {\n\t\t\t\t\tif (CommandExecutor.class.isAssignableFrom(clazz)) {\n\t\t\t\t\t\tCommandExecutor command = (CommandExecutor) clazz.getDeclaredConstructor().newInstance();\n\t\t\t\t\t\tString commandName = classInfo.getSimpleName().replace(\"Command\", \"\");\n\t\t\t\t\t\tPlugin.plugin.getCommand(commandName).setExecutor(command);\n\t\t\t\t\t}\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n }\n}" }, { "identifier": "EventInit", "path": "src/main/java/dev/amok/DeathNote/Initializers/EventInit.java", "snippet": "public class EventInit {\n public static void init() {\n\t\ttry {\n\t\t\tClassPath cp = ClassPath.from(CommandInit.class.getClassLoader());\n\t\t\tfor (ClassInfo classInfo : cp.getTopLevelClassesRecursive(\"dev.amok.DeathNote.Events\")) {\n\t\t\t\tClass<?> clazz = Class.forName(classInfo.getName());\n\t\t\t\ttry {\n\t\t\t\t\tif (Listener.class.isAssignableFrom(clazz)) {\n\t\t\t\t\t\tListener event = (Listener) clazz.getDeclaredConstructor().newInstance();\n\t\t\t\t\t\t// String eventName = classInfo.getSimpleName().replace(\"Event\", \"\");\n\t\t\t\t\t\tPlugin.plugin.getServer().getPluginManager().registerEvents(event, Plugin.plugin);\n\t\t\t\t\t}\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n }\n}" } ]
import java.sql.SQLException; import org.bukkit.plugin.java.JavaPlugin; import dev.amok.DeathNote.Database.SQLite; import dev.amok.DeathNote.Initializers.CommandInit; import dev.amok.DeathNote.Initializers.EventInit;
1,063
package dev.amok.DeathNote; public class Plugin extends JavaPlugin { public static JavaPlugin plugin; private static Plugin instance; @Override public void onEnable() { Plugin.plugin = this; instance = this; getLogger().info("Loading config..."); this.saveDefaultConfig(); getLogger().info("Loading database..."); try { SQLite.getConnection(); } catch (SQLException e) { e.printStackTrace(); } try { SQLite.createDB(); } catch (SQLException e) { e.printStackTrace(); } CommandInit.init();
package dev.amok.DeathNote; public class Plugin extends JavaPlugin { public static JavaPlugin plugin; private static Plugin instance; @Override public void onEnable() { Plugin.plugin = this; instance = this; getLogger().info("Loading config..."); this.saveDefaultConfig(); getLogger().info("Loading database..."); try { SQLite.getConnection(); } catch (SQLException e) { e.printStackTrace(); } try { SQLite.createDB(); } catch (SQLException e) { e.printStackTrace(); } CommandInit.init();
EventInit.init();
2
2023-11-03 09:03:34+00:00
2k
wqj666666/embyboot
src/main/java/com/emby/boot/controller/EmbyUserController.java
[ { "identifier": "EmbyUser", "path": "src/main/java/com/emby/boot/dao/entity/EmbyUser.java", "snippet": "@Schema(description = \"emby用户成员变量\")\n@Data\n@TableName(\"user\")\npublic class EmbyUser {\n @Schema(description = \"电报用户id\",example = \"123\")\n private String chatid;\n\n @Schema(description = \"emby用户id\",example = \"123\")\n private String embyUserid;\n\n}" }, { "identifier": "EmbyUserInfoResp", "path": "src/main/java/com/emby/boot/dto/resp/EmbyUserInfoResp.java", "snippet": "@Schema(description = \"emby用户个人信息成员变量\")\n@Data\npublic class EmbyUserInfoResp {\n @Schema(description = \"电报用户id\",example = \"123\")\n private String chatid;\n\n @Schema(description = \"emby用户id\",example = \"123\")\n private String embyUserid;\n\n @Schema(description = \"emby用户名称\",example = \"123\")\n private String embyName;\n}" }, { "identifier": "RestResp", "path": "src/main/java/com/emby/boot/dto/resp/RestResp.java", "snippet": "@Getter\npublic class RestResp<T> {\n\n /**\n * 响应码\n */\n private String code;\n\n /**\n * 响应消息\n */\n private String message;\n\n /**\n * 响应数据\n */\n private T data;\n\n private RestResp() {\n this.code = ErrorCodeEnum.OK.getCode();\n this.message = ErrorCodeEnum.OK.getMessage();\n }\n\n private RestResp(ErrorCodeEnum errorCode) {\n this.code = errorCode.getCode();\n this.message = errorCode.getMessage();\n }\n\n private RestResp(T data) {\n this();\n this.data = data;\n }\n\n /**\n * 业务处理成功,无数据返回\n */\n public static RestResp<Void> ok() {\n return new RestResp<>();\n }\n\n /**\n * 业务处理成功,有数据返回\n */\n public static <T> RestResp<T> ok(T data) {\n return new RestResp<>(data);\n }\n\n /**\n * 业务处理失败\n */\n public static RestResp<Void> fail(ErrorCodeEnum errorCode) {\n return new RestResp<>(errorCode);\n }\n\n\n /**\n * 系统错误\n */\n public static RestResp<Void> error() {\n return new RestResp<>(ErrorCodeEnum.SYSTEM_ERROR);\n }\n\n /**\n * 判断是否成功\n */\n public boolean isOk() {\n return Objects.equals(this.code, ErrorCodeEnum.OK.getCode());\n }\n\n}" }, { "identifier": "EmbyUserService", "path": "src/main/java/com/emby/boot/service/EmbyUserService.java", "snippet": "public interface EmbyUserService {\n /**\n * emby新建用户\n * @param name 用户名称\n * @param chatid 电报id\n * @return\n */\n RestResp<EmbyUser> userNew(String name,String chatid);\n\n /**\n * emby删除用户\n * @param chatid 电报id\n * @return\n */\n RestResp<Void> userDelete(String chatid);\n\n /**\n * emby去除密码\n * @param chatid 电报id\n * @return\n */\n RestResp<Void> userPassword(String chatid);\n\n /**\n * emby个人信息\n * @param chatid 电报id\n * @return\n */\n RestResp<EmbyUserInfoResp> userInfo(String chatid);\n}" } ]
import com.emby.boot.dao.entity.EmbyUser; import com.emby.boot.dto.resp.EmbyUserInfoResp; import com.emby.boot.dto.resp.RestResp; import com.emby.boot.service.EmbyUserService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
1,109
package com.emby.boot.controller; /** * @author laojian * @date 2023/10/9 17:32 */ @Tag(name = "EmbyUserController",description = "emby用户控制类") @RestController @RequestMapping("/emby") @RequiredArgsConstructor public class EmbyUserController { private final EmbyUserService embyUserService; /** * emby用户注册接口 * @param name * @return */ @Operation(summary = "emby用户注册接口") @PostMapping("/userNew")
package com.emby.boot.controller; /** * @author laojian * @date 2023/10/9 17:32 */ @Tag(name = "EmbyUserController",description = "emby用户控制类") @RestController @RequestMapping("/emby") @RequiredArgsConstructor public class EmbyUserController { private final EmbyUserService embyUserService; /** * emby用户注册接口 * @param name * @return */ @Operation(summary = "emby用户注册接口") @PostMapping("/userNew")
public RestResp<EmbyUser> userNew(String name, String chatid){
0
2023-11-09 17:15:57+00:00
2k
BaderTim/minecraft-measurement-mod
src/main/java/io/github/mmm/renderer/SurveyRenderer.java
[ { "identifier": "Edge", "path": "src/main/java/io/github/mmm/measurement/survey/objects/graph/Edge.java", "snippet": "public class Edge {\n\n private Vertex startVertex;\n private Vertex endVertex;\n private int index;\n\n public Edge(Vertex startVertex, Vertex endVertex, int index) {\n this.startVertex = startVertex;\n this.endVertex = endVertex;\n this.index = index;\n }\n\n public Vertex getStartVertex() {\n return startVertex;\n }\n\n public Vertex getEndVertex() {\n return endVertex;\n }\n\n public int getIndex() {\n return index;\n }\n}" }, { "identifier": "Vertex", "path": "src/main/java/io/github/mmm/measurement/survey/objects/graph/Vertex.java", "snippet": "public class Vertex {\n\n private Vector3f position;\n private int index;\n\n public Vertex(Vector3f vec, int index) {\n this.position = vec;\n this.index = index;\n }\n\n public Vector3f getPosition() {\n return position;\n }\n\n public int getIndex() {\n return index;\n }\n}" }, { "identifier": "SURVEY_CONTROLLER", "path": "src/main/java/io/github/mmm/MMM.java", "snippet": "public static final SurveyController SURVEY_CONTROLLER = new SurveyController();" } ]
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; import io.github.mmm.measurement.survey.objects.graph.Edge; import io.github.mmm.measurement.survey.objects.graph.Vertex; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.client.renderer.entity.DisplayRenderer; import net.minecraft.client.renderer.entity.EntityRenderer; import net.minecraft.client.renderer.entity.EntityRenderers; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; import net.minecraftforge.client.event.RenderGuiOverlayEvent; import net.minecraftforge.client.event.RenderLevelStageEvent; import org.joml.Quaternionf; import org.joml.Vector3f; import java.awt.*; import static io.github.mmm.MMM.SURVEY_CONTROLLER;
681
package io.github.mmm.renderer; public class SurveyRenderer { private Tesselator tesselator; private BufferBuilder buffer; private VertexBuffer vertexBuffer; private Color edgeColor; private Color vertexColor; public SurveyRenderer() { this.edgeColor = Color.RED; this.vertexColor = Color.WHITE; } public void renderGraph(RenderLevelStageEvent event) { renderVerticesNew(event); beginRender(); renderEdges(); endRender(event); } private void renderVerticesNew(RenderLevelStageEvent event) { Font fontRenderer = Minecraft.getInstance().font; PoseStack matrixStack = event.getPoseStack(); Vec3 viewerPos = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition(); Quaternionf viewerRot = Minecraft.getInstance().gameRenderer.getMainCamera().rotation();
package io.github.mmm.renderer; public class SurveyRenderer { private Tesselator tesselator; private BufferBuilder buffer; private VertexBuffer vertexBuffer; private Color edgeColor; private Color vertexColor; public SurveyRenderer() { this.edgeColor = Color.RED; this.vertexColor = Color.WHITE; } public void renderGraph(RenderLevelStageEvent event) { renderVerticesNew(event); beginRender(); renderEdges(); endRender(event); } private void renderVerticesNew(RenderLevelStageEvent event) { Font fontRenderer = Minecraft.getInstance().font; PoseStack matrixStack = event.getPoseStack(); Vec3 viewerPos = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition(); Quaternionf viewerRot = Minecraft.getInstance().gameRenderer.getMainCamera().rotation();
for(Vertex vertex : SURVEY_CONTROLLER.getSurvey().getVertices()) {
2
2023-11-06 16:56:46+00:00
2k
Guzz-drk/api_gestao_vagas
src/main/java/br/com/guzz/gestao_vagas/modules/candidate/useCases/CreateCandidateUseCase.java
[ { "identifier": "UserFoundException", "path": "src/main/java/br/com/guzz/gestao_vagas/exceptions/UserFoundException.java", "snippet": "public class UserFoundException extends RuntimeException{\n \n public UserFoundException(){\n super(\"Usuário já existe!\");\n }\n}" }, { "identifier": "CandidateEntity", "path": "src/main/java/br/com/guzz/gestao_vagas/modules/candidate/entity/CandidateEntity.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n\n@Entity(name = \"candidate\")\npublic class CandidateEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID id;\n\n @Schema(example = \"Gustavo\", description = \"Nome do candidato\")\n private String name;\n\n @NotBlank\n @Pattern(regexp = \"\\\\S+\", message = \"O campo [username] não deve conter espaço\")\n @Schema(example = \"guzz-drk\", description = \"Username do candidato\")\n private String username;\n\n @Email(message = \"O campo [email] deve conter um e-mail válido\")\n @Schema(example = \"gwprkg@gmail.com\", description = \"E-mail do candidato\")\n private String email;\n\n @Length(min = 5, max = 100, message = \"O campo [password] deve conter entre (5) e (100) caracteres\")\n @Schema(example = \"@@@adfsa#$##\", minLength = 5, maxLength = 100, requiredMode = RequiredMode.REQUIRED, description = \"Senha do candidato\")\n private String password;\n\n @Schema(example = \"Amante de programação\", description = \"Descrição do candidato\")\n private String description;\n\n private String curriculum;\n\n @CreationTimestamp\n private LocalDateTime createdAt;\n}" }, { "identifier": "CandidateRepository", "path": "src/main/java/br/com/guzz/gestao_vagas/modules/candidate/repository/CandidateRepository.java", "snippet": "public interface CandidateRepository extends JpaRepository<CandidateEntity, UUID> {\n\n Optional<CandidateEntity> findByUsernameOrEmail(String username, String email);\n Optional<CandidateEntity> findByUsername(String username);\n}" } ]
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import br.com.guzz.gestao_vagas.exceptions.UserFoundException; import br.com.guzz.gestao_vagas.modules.candidate.entity.CandidateEntity; import br.com.guzz.gestao_vagas.modules.candidate.repository.CandidateRepository;
659
package br.com.guzz.gestao_vagas.modules.candidate.useCases; @Service public class CreateCandidateUseCase { @Autowired private CandidateRepository candidateRepository; @Autowired private PasswordEncoder passwordEncoder; public CandidateEntity execute(CandidateEntity candidateEntity) { this.candidateRepository.findByUsernameOrEmail(candidateEntity.getUsername(), candidateEntity.getEmail()) .ifPresent((user) -> {
package br.com.guzz.gestao_vagas.modules.candidate.useCases; @Service public class CreateCandidateUseCase { @Autowired private CandidateRepository candidateRepository; @Autowired private PasswordEncoder passwordEncoder; public CandidateEntity execute(CandidateEntity candidateEntity) { this.candidateRepository.findByUsernameOrEmail(candidateEntity.getUsername(), candidateEntity.getEmail()) .ifPresent((user) -> {
throw new UserFoundException();
0
2023-11-05 13:45:16+00:00
2k
alejandalb/metaIoT-operation-manager-service
src/main/java/com/upv/alalca3/metaIoT/operationmanager/controllers/rest/OperationController.java
[ { "identifier": "Operation", "path": "src/main/java/com/upv/alalca3/metaIoT/operationmanager/model/Operation.java", "snippet": "@Entity\npublic class Operation {\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\n\tprivate String type;\n\tprivate String parameters;\n\tprivate String status;\n\n\t@OneToMany(mappedBy = \"operation\")\n\tprivate Set<Message> messages;\n\n\t/**\n\t * @return the id\n\t */\n\tpublic Long getId() {\n\t\treturn this.id;\n\t}\n\n\t/**\n\t * @param id the id to set\n\t */\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the type\n\t */\n\tpublic String getType() {\n\t\treturn this.type;\n\t}\n\n\t/**\n\t * @param type the type to set\n\t */\n\tpublic void setType(String type) {\n\t\tthis.type = type;\n\t}\n\n\t/**\n\t * @return the parameters\n\t */\n\tpublic String getParameters() {\n\t\treturn this.parameters;\n\t}\n\n\t/**\n\t * @param parameters the parameters to set\n\t */\n\tpublic void setParameters(String parameters) {\n\t\tthis.parameters = parameters;\n\t}\n\n\t/**\n\t * @return the status\n\t */\n\tpublic String getStatus() {\n\t\treturn this.status;\n\t}\n\n\t/**\n\t * @param status the status to set\n\t */\n\tpublic void setStatus(String status) {\n\t\tthis.status = status;\n\t}\n\n\t/**\n\t * @return the messages\n\t */\n\tpublic Set<Message> getMessages() {\n\t\treturn this.messages;\n\t}\n\n\t/**\n\t * @param messages the messages to set\n\t */\n\tpublic void setMessages(Set<Message> messages) {\n\t\tthis.messages = messages;\n\t}\n\n}" }, { "identifier": "IMqttService", "path": "src/main/java/com/upv/alalca3/metaIoT/operationmanager/service/IMqttService.java", "snippet": "public interface IMqttService {\n\n\tvoid publishOperation(String additionalPath, String message);\n\n\tvoid subscribeToAckTopic(MqttCallback callback);\n\n\tvoid subscribeToCompletionTopic(MqttCallback callback);\n\n\tvoid subscribeToRejectionTopic(MqttCallback callback);\n\n\t/**\n\t * Subscribes to the specified MQTT topics.\n\t *\n\t * @param topics the topics to subscribe to\n\t */\n\tvoid subscribe();\n\n}" }, { "identifier": "OperationServiceImpl", "path": "src/main/java/com/upv/alalca3/metaIoT/operationmanager/service/impl/OperationServiceImpl.java", "snippet": "@Service\npublic class OperationServiceImpl {\n\t@Autowired\n\tprivate IMqttService mqttService;\n\t@Autowired\n\tprivate OperationRepository repo;\n\n\tpublic void handleNewOperation(Operation operation) throws JsonProcessingException {\n\t\toperation = this.repo.save(operation);\n\t\tthis.publishOperation(operation);\n\t}\n\n\tprivate void publishOperation(Operation operation) throws JsonProcessingException {\n\t\tObjectMapper mapper = new ObjectMapper();\n\t\tthis.mqttService.publishOperation(operation.getType() + \"/\" + operation.getId().toString(),\n\t\t\t\tmapper.writeValueAsString(operation));\n\t}\n}" } ]
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.core.JsonProcessingException; import com.upv.alalca3.metaIoT.operationmanager.model.Operation; import com.upv.alalca3.metaIoT.operationmanager.service.IMqttService; import com.upv.alalca3.metaIoT.operationmanager.service.impl.OperationServiceImpl;
936
/** * */ package com.upv.alalca3.metaIoT.operationmanager.controllers.rest; /** * */ @RestController public class OperationController { @Autowired private IMqttService mqttService; @Autowired
/** * */ package com.upv.alalca3.metaIoT.operationmanager.controllers.rest; /** * */ @RestController public class OperationController { @Autowired private IMqttService mqttService; @Autowired
private OperationServiceImpl opService;
2
2023-11-06 18:25:36+00:00
2k
hoffmann-g/trabalho-final-poo
src/main/java/application/tabs/RentalTab.java
[ { "identifier": "DataAccessObject", "path": "src/main/java/model/dao/DataAccessObject.java", "snippet": "public interface DataAccessObject<T> {\n\n List<T> readRows();\n void insertRow(T t);\n void deleteRow(T t);\n boolean contains(T t);\n}" }, { "identifier": "CarRental", "path": "src/main/java/model/entities/CarRental.java", "snippet": "public class CarRental {\n\n private LocalDateTime start;\n private LocalDateTime finish;\n\n private Vehicle vehicle;\n private Invoice invoice;\n\n public CarRental(LocalDateTime start, LocalDateTime finish, Vehicle vehicle) {\n this.start = start;\n this.finish = finish;\n this.vehicle = vehicle;\n }\n\n public LocalDateTime getStart() {\n return start;\n }\n\n public void setStart(LocalDateTime start) {\n this.start = start;\n }\n\n public LocalDateTime getFinish() {\n return finish;\n }\n\n public void setFinish(LocalDateTime finish) {\n this.finish = finish;\n }\n\n public Vehicle getVehicle() {\n return vehicle;\n }\n\n public void setVehicle(Vehicle vehicle) {\n this.vehicle = vehicle;\n }\n\n public Invoice getInvoice() {\n return invoice;\n }\n\n public void setInvoice(Invoice invoice) {\n this.invoice = invoice;\n }\n\n @Override\n public String toString() {\n return vehicle + \" - \" + start.format(DateTimeFormatter.ofPattern(\"dd/MM/yyyy HH:mm\"));\n }\n}" }, { "identifier": "Vehicle", "path": "src/main/java/model/entities/Vehicle.java", "snippet": "public class Vehicle {\n\n private String model;\n\n public Vehicle(String model) {\n this.model = model;\n }\n\n public String getModel() {\n return model;\n }\n\n public void setModel(String model) {\n this.model = model;\n }\n\n @Override\n public String toString() {\n return model;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Vehicle vehicle = (Vehicle) o;\n return Objects.equals(model, vehicle.model);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(model);\n }\n}" }, { "identifier": "RentalService", "path": "src/main/java/model/services/RentalService.java", "snippet": "public class RentalService {\n\n private Double pricePerHour;\n private Double pricePerDay;\n\n private TaxService taxService;\n\n public RentalService(Double pricePerHour, Double pricePerDay, TaxService taxService) {\n this.pricePerHour = pricePerHour;\n this.pricePerDay = pricePerDay;\n this.taxService = taxService;\n }\n\n public void processInvoice(CarRental carRental){\n double minutes = Duration.between(carRental.getStart(), carRental.getFinish()).toMinutes();\n double hours = minutes / 60;\n double basicPayment;\n\n if (hours <= 12){\n basicPayment = pricePerHour * Math.ceil(hours);\n } else {\n basicPayment = pricePerDay * Math.ceil(hours/24);\n }\n\n double tax = taxService.tax(basicPayment);\n carRental.setInvoice(new Invoice(basicPayment, tax));\n }\n}" } ]
import model.dao.DataAccessObject; import model.entities.CarRental; import model.entities.Vehicle; import model.services.RentalService; import javax.swing.*; import java.security.InvalidParameterException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List;
907
package application.tabs; public class RentalTab extends Tab<CarRental>{ private final InvoiceTab invoiceTab; private final DataAccessObject<CarRental> carRentalDao; private final DataAccessObject<Vehicle> vehicleDao;
package application.tabs; public class RentalTab extends Tab<CarRental>{ private final InvoiceTab invoiceTab; private final DataAccessObject<CarRental> carRentalDao; private final DataAccessObject<Vehicle> vehicleDao;
private final RentalService rentalService;
3
2023-11-08 15:22:05+00:00
2k
InfantinoAndrea00/polimi-software-engineering-project-2022
src/main/java/it/polimi/ingsw/server/controller/states/Initialize.java
[ { "identifier": "Server", "path": "src/main/java/it/polimi/ingsw/server/Server.java", "snippet": "public class Server {\n public static final int PORT = 5555;\n public static ViewObserver viewObserver;\n public static AtomicBoolean creatingGame;\n public static Game game;\n\n public static void main(String[] args) {\n ServerSocket socket;\n creatingGame = new AtomicBoolean(true);\n viewObserver = new ViewObserver();\n try {\n socket = new ServerSocket(PORT);\n } catch (IOException e) {\n System.out.println(\"cannot open server socket\");\n System.exit(1);\n return;\n }\n\n while (true) {\n try {\n Socket client = socket.accept();\n ClientHandler clientHandler = new ClientHandler(client);\n Thread thread = new Thread(clientHandler, \"Eryantis_Server - \" + client.getInetAddress());\n thread.start();\n } catch (IOException e) {\n System.out.println(\"connection dropped\");\n }\n }\n }\n}" }, { "identifier": "GameController", "path": "src/main/java/it/polimi/ingsw/server/controller/GameController.java", "snippet": "public class GameController {\n private GameControllerState state;\n\n /**\n * constructor\n */\n public GameController() {\n state = new StartGame();\n }\n\n /**\n * request of the state in which the controller is\n * @return current state\n */\n public GameControllerState getState() {\n return state;\n }\n\n /**\n * set the state of the controller\n * @param state state to be set\n */\n public void setState(GameControllerState state) {\n this.state = state;\n }\n\n /**\n * method that sets the next state of the FSA\n */\n public void nextState() {\n state.nextState(this);\n }\n\n /**\n * method that changes the model through the action of every state\n * @param o1 generic object that will be casted\n * @param o2 generic object that will be casted\n */\n public void changeModel(Object o1, Object o2) {\n state.Action(o1, o2);\n }\n\n}" }, { "identifier": "GameControllerState", "path": "src/main/java/it/polimi/ingsw/server/controller/GameControllerState.java", "snippet": "public interface GameControllerState {\n void nextState(GameController g);\n void Action(Object o1, Object o2);\n\n}" }, { "identifier": "GameRound", "path": "src/main/java/it/polimi/ingsw/server/model/GameRound.java", "snippet": "public class GameRound {\n private List<Integer> order;\n private Map<Integer, AssistantCard> assistantCardsPlayed;\n public int roundCounter;\n public PlayerTurn currentTurn;\n\n /**\n * constructor\n * @param order a list representing players' order inside that turn\n */\n public GameRound (List<Integer> order){\n this.order = order;\n assistantCardsPlayed = new HashMap<>();\n roundCounter = 0;\n }\n\n /**\n * request for the players order in that turn\n * @return the players order in that turn\n */\n public List<Integer> getOrder(){\n return order;\n }\n\n /**\n * remove all the cards played in the previous round\n */\n public void resetCardsPlayed(){\n assistantCardsPlayed = new HashMap<>();\n }\n\n /**\n * set the order in the turn\n * @param order the order in the turn\n */\n public void setOrder(List<Integer> order){\n this.order = order;\n }\n\n /**\n * request for assistant cards already played by a player\n * @return the assistant cards already played by a player\n */\n public Map<Integer, AssistantCard> getAssistantCardsPlayed(){\n return assistantCardsPlayed;\n }\n\n /**\n * method that return every card that the player can play in this turn\n * @param player the player that is next to play\n * @return a list of integer representing every card that the player inserted as parameter can play in this turn\n */\n public List<Integer> playableCards(Player player){\n List<AssistantCard> canPlayCards = new ArrayList<>(player.getDeck());\n List<AssistantCard> toRemove = new ArrayList<>();\n for (AssistantCard ac : canPlayCards)\n for (AssistantCard a : assistantCardsPlayed.values())\n if (ac.getSpeedValue() == a.getSpeedValue())\n toRemove.add(ac);\n canPlayCards.removeAll(toRemove);\n if (canPlayCards.isEmpty())\n canPlayCards = new ArrayList<>(player.getDeck());\n List <Integer> canPlayCardIds = new ArrayList<>();\n for(AssistantCard card : canPlayCards)\n canPlayCardIds.add(card.getSpeedValue());\n return canPlayCardIds;\n }\n\n}" } ]
import it.polimi.ingsw.server.Server; import it.polimi.ingsw.server.controller.GameController; import it.polimi.ingsw.server.controller.GameControllerState; import it.polimi.ingsw.server.model.GameRound; import java.util.ArrayList; import java.util.List;
1,354
package it.polimi.ingsw.server.controller.states; /** * Class in which the game is initialized */ public class Initialize implements GameControllerState { @Override public void nextState(GameController g) { g.setState(new RefillCloudTiles()); } @Override public void Action(Object nullObject1, Object nullObject2) { int firstPlayerId = (int) (Math.random() * Server.game.getPlayerNumber()); List<Integer> currentRound = new ArrayList<>(); int i; for(i=firstPlayerId; i<Server.game.getPlayerNumber(); i++) currentRound.add(i); for(i=0; i<firstPlayerId; i++) currentRound.add(i);
package it.polimi.ingsw.server.controller.states; /** * Class in which the game is initialized */ public class Initialize implements GameControllerState { @Override public void nextState(GameController g) { g.setState(new RefillCloudTiles()); } @Override public void Action(Object nullObject1, Object nullObject2) { int firstPlayerId = (int) (Math.random() * Server.game.getPlayerNumber()); List<Integer> currentRound = new ArrayList<>(); int i; for(i=firstPlayerId; i<Server.game.getPlayerNumber(); i++) currentRound.add(i); for(i=0; i<firstPlayerId; i++) currentRound.add(i);
Server.game.currentRound = new GameRound(currentRound);
3
2023-11-06 00:50:18+00:00
2k
Space-shooter-III/game
game/src/main/java/com/github/spaceshooteriii/game/display/compoments/GamePanel.java
[ { "identifier": "Game", "path": "game/src/main/java/com/github/spaceshooteriii/game/Game.java", "snippet": "public class Game {\n\n private JFrame frame;\n private GamePanel gamePanel;\n private static @Getter GameState state;\n\n public static final int WIDTH = 820;\n public static final int HEIGHT = 724;\n\n public static BufferedImageLoader TEXTRA_ALICE_LOADER = null;\n public static TextraAlice TEXTRA_ALICE = null;\n public static Font GAME_FONT = null;\n\n private static Logger LOGGER = LogManager.getLogger(\"Game\");\n\n public Game() {\n Game.LOGGER.info(\"Starting...\");\n this.frame = new JFrame();\n this.gamePanel = new GamePanel();\n Game.state = new GameState();\n\n this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n this.frame.setLocationRelativeTo(null);\n this.frame.setSize(Game.WIDTH, Game.HEIGHT);\n this.frame.setTitle(\"Space shooter III\");\n this.frame.setResizable(false);\n this.frame.setMinimumSize(new Dimension(Game.WIDTH, Game.HEIGHT));\n this.frame.setMaximumSize(new Dimension(Game.WIDTH, Game.HEIGHT));\n\n this.gamePanel.setPreferredSize(new Dimension(Game.WIDTH, Game.HEIGHT));\n this.frame.add(this.gamePanel);\n\n\n this.frame.setPreferredSize(new Dimension(Game.WIDTH, Game.HEIGHT));\n this.frame.setVisible(true);\n\n this.gamePanel.startGameLoop();\n Game.LOGGER.info(\"Started\");\n }\n\n}" }, { "identifier": "KeyBoardEventListener", "path": "game/src/main/java/com/github/spaceshooteriii/game/event/listeners/KeyBoardEventListener.java", "snippet": "public class KeyBoardEventListener implements KeyListener {\n @Override\n public void keyTyped(KeyEvent e) {\n Game.getState().getGameStateModeManager().keyTyped(e);\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n Game.getState().getGameStateModeManager().keyPressed(e);\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n Game.getState().getGameStateModeManager().keyReleased(e);\n }\n}" }, { "identifier": "MouseEventListener", "path": "game/src/main/java/com/github/spaceshooteriii/game/event/listeners/MouseEventListener.java", "snippet": "public class MouseEventListener implements MouseListener {\n @Override\n public void mouseClicked(MouseEvent e) {\n Game.getState().getGameStateModeManager().mouseClicked(e);\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n Game.getState().getGameStateModeManager().mousePressed(e);\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n Game.getState().getGameStateModeManager().mouseReleased(e);\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n Game.getState().getGameStateModeManager().mouseEntered(e);\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n Game.getState().getGameStateModeManager().mouseExited(e);\n }\n}" }, { "identifier": "MouseMotionEventListener", "path": "game/src/main/java/com/github/spaceshooteriii/game/event/listeners/MouseMotionEventListener.java", "snippet": "public class MouseMotionEventListener implements MouseMotionListener {\n @Override\n public void mouseDragged(MouseEvent e) {\n Game.getState().getGameStateModeManager().mouseDragged(e);\n }\n\n @Override\n public void mouseMoved(MouseEvent e) {\n Game.getState().getGameStateModeManager().mouseMoved(e);\n }\n}" }, { "identifier": "MouseWheelEventListener", "path": "game/src/main/java/com/github/spaceshooteriii/game/event/listeners/MouseWheelEventListener.java", "snippet": "public class MouseWheelEventListener implements MouseWheelListener {\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n Game.getState().getGameStateModeManager().mouseWheelMoved(e);\n }\n}" } ]
import com.github.spaceshooteriii.game.Game; import com.github.spaceshooteriii.game.event.listeners.KeyBoardEventListener; import com.github.spaceshooteriii.game.event.listeners.MouseEventListener; import com.github.spaceshooteriii.game.event.listeners.MouseMotionEventListener; import com.github.spaceshooteriii.game.event.listeners.MouseWheelEventListener; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.swing.JPanel; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints;
1,024
package com.github.spaceshooteriii.game.display.compoments; public class GamePanel extends JPanel implements Runnable { private Thread gameThread; private final int FPS;
package com.github.spaceshooteriii.game.display.compoments; public class GamePanel extends JPanel implements Runnable { private Thread gameThread; private final int FPS;
private KeyBoardEventListener keyListener;
1
2023-11-03 11:18:00+00:00
2k
conductor-oss/conductor
core/src/main/java/com/netflix/conductor/core/storage/DummyPayloadStorage.java
[ { "identifier": "ExternalStorageLocation", "path": "common/src/main/java/com/netflix/conductor/common/run/ExternalStorageLocation.java", "snippet": "public class ExternalStorageLocation {\n\n private String uri;\n private String path;\n\n public String getUri() {\n return uri;\n }\n\n public void setUri(String uri) {\n this.uri = uri;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n @Override\n public String toString() {\n return \"ExternalStorageLocation{\" + \"uri='\" + uri + '\\'' + \", path='\" + path + '\\'' + '}';\n }\n}" }, { "identifier": "ExternalPayloadStorage", "path": "common/src/main/java/com/netflix/conductor/common/utils/ExternalPayloadStorage.java", "snippet": "public interface ExternalPayloadStorage {\n\n enum Operation {\n READ,\n WRITE\n }\n\n enum PayloadType {\n WORKFLOW_INPUT,\n WORKFLOW_OUTPUT,\n TASK_INPUT,\n TASK_OUTPUT\n }\n\n /**\n * Obtain a uri used to store/access a json payload in external storage.\n *\n * @param operation the type of {@link Operation} to be performed with the uri\n * @param payloadType the {@link PayloadType} that is being accessed at the uri\n * @param path (optional) the relative path for which the external storage location object is to\n * be populated. If path is not specified, it will be computed and populated.\n * @return a {@link ExternalStorageLocation} object which contains the uri and the path for the\n * json payload\n */\n ExternalStorageLocation getLocation(Operation operation, PayloadType payloadType, String path);\n\n /**\n * Obtain an uri used to store/access a json payload in external storage with deduplication of\n * data based on payloadBytes digest.\n *\n * @param operation the type of {@link Operation} to be performed with the uri\n * @param payloadType the {@link PayloadType} that is being accessed at the uri\n * @param path (optional) the relative path for which the external storage location object is to\n * be populated. If path is not specified, it will be computed and populated.\n * @param payloadBytes for calculating digest which is used for objectKey\n * @return a {@link ExternalStorageLocation} object which contains the uri and the path for the\n * json payload\n */\n default ExternalStorageLocation getLocation(\n Operation operation, PayloadType payloadType, String path, byte[] payloadBytes) {\n return getLocation(operation, payloadType, path);\n }\n\n /**\n * Upload a json payload to the specified external storage location.\n *\n * @param path the location to which the object is to be uploaded\n * @param payload an {@link InputStream} containing the json payload which is to be uploaded\n * @param payloadSize the size of the json payload in bytes\n */\n void upload(String path, InputStream payload, long payloadSize);\n\n /**\n * Download the json payload from the specified external storage location.\n *\n * @param path the location from where the object is to be downloaded\n * @return an {@link InputStream} of the json payload at the specified location\n */\n InputStream download(String path);\n}" } ]
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.UUID; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.common.run.ExternalStorageLocation; import com.netflix.conductor.common.utils.ExternalPayloadStorage; import com.fasterxml.jackson.databind.ObjectMapper;
1,184
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <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.netflix.conductor.core.storage; /** * A dummy implementation of {@link ExternalPayloadStorage} used when no external payload is * configured */ public class DummyPayloadStorage implements ExternalPayloadStorage { private static final Logger LOGGER = LoggerFactory.getLogger(DummyPayloadStorage.class); private ObjectMapper objectMapper; private File payloadDir; public DummyPayloadStorage() { try { this.objectMapper = new ObjectMapper(); this.payloadDir = Files.createTempDirectory("payloads").toFile(); LOGGER.info( "{} initialized in directory: {}", this.getClass().getSimpleName(), payloadDir.getAbsolutePath()); } catch (IOException ioException) { LOGGER.error( "Exception encountered while creating payloads directory : {}", ioException.getMessage()); } } @Override
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <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.netflix.conductor.core.storage; /** * A dummy implementation of {@link ExternalPayloadStorage} used when no external payload is * configured */ public class DummyPayloadStorage implements ExternalPayloadStorage { private static final Logger LOGGER = LoggerFactory.getLogger(DummyPayloadStorage.class); private ObjectMapper objectMapper; private File payloadDir; public DummyPayloadStorage() { try { this.objectMapper = new ObjectMapper(); this.payloadDir = Files.createTempDirectory("payloads").toFile(); LOGGER.info( "{} initialized in directory: {}", this.getClass().getSimpleName(), payloadDir.getAbsolutePath()); } catch (IOException ioException) { LOGGER.error( "Exception encountered while creating payloads directory : {}", ioException.getMessage()); } } @Override
public ExternalStorageLocation getLocation(
0
2023-12-08 06:06:09+00:00
2k
specmock/specmock
specmock/src/test/java/io/specmock/core/HttpExchangeTest.java
[ { "identifier": "Example1Request", "path": "specmock/src/test/java/io/specmock/core/example/Example1Request.java", "snippet": "public class Example1Request {\n private String stringValue;\n private Integer integerValue;\n private Long longValue;\n private BigDecimal bigDecimalValue;\n\n /**\n * Empty constructor for ExampleRequest.\n */\n public Example1Request() {\n }\n\n /**\n * Constructs an ExampleRequest with specified values.\n *\n * @param stringValue The string value.\n * @param integerValue The integer value.\n * @param longValue The long value.\n * @param bigDecimalValue The BigDecimal value.\n */\n public Example1Request(\n String stringValue,\n Integer integerValue,\n Long longValue,\n BigDecimal bigDecimalValue\n ) {\n this.stringValue = stringValue;\n this.integerValue = integerValue;\n this.longValue = longValue;\n this.bigDecimalValue = bigDecimalValue;\n }\n\n /**\n * Retrieves the string value.\n *\n * @return The string value.\n */\n public String getStringValue() {\n return stringValue;\n }\n\n /**\n * Retrieves the integer value.\n *\n * @return The integer value.\n */\n public Integer getIntegerValue() {\n return integerValue;\n }\n\n /**\n * Retrieves the long value.\n *\n * @return The long value.\n */\n public Long getLongValue() {\n return longValue;\n }\n\n /**\n * Retrieves the BigDecimal value.\n *\n * @return The BigDecimal value.\n */\n public BigDecimal getBigDecimalValue() {\n return bigDecimalValue;\n }\n}" }, { "identifier": "Example1Response", "path": "specmock/src/test/java/io/specmock/core/example/Example1Response.java", "snippet": "public class Example1Response {\n private String stringValue;\n\n /**\n * Empty constructor for ExampleResponse.\n */\n public Example1Response() {\n }\n\n /**\n * Constructs an ExampleResponse with the specified string value.\n *\n * @param stringValue The string value.\n */\n public Example1Response(String stringValue) {\n this.stringValue = stringValue;\n }\n\n /**\n * Retrieves the string value.\n *\n * @return The string value.\n */\n public String getStringValue() {\n return stringValue;\n }\n\n /**\n * Sets the string value.\n *\n * @param stringValue The string value to set.\n */\n public void setStringValue(String stringValue) {\n this.stringValue = stringValue;\n }\n}" }, { "identifier": "Example3Response", "path": "specmock/src/test/java/io/specmock/core/example/Example3Response.java", "snippet": "public class Example3Response {\n private String stringValue;\n\n /**\n * Empty constructor for ExampleResponse.\n */\n public Example3Response() {\n }\n\n /**\n * Constructs an ExampleResponse with the specified string value.\n *\n * @param stringValue The string value.\n */\n public Example3Response(String stringValue) {\n this.stringValue = stringValue;\n }\n\n /**\n * Retrieves the string value.\n *\n * @return The string value.\n */\n public String getStringValue() {\n return stringValue;\n }\n\n /**\n * Sets the string value.\n *\n * @param stringValue The string value to set.\n */\n public void setStringValue(String stringValue) {\n this.stringValue = stringValue;\n }\n}" } ]
import static org.assertj.core.api.Assertions.assertThat; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import io.specmock.core.example.Example1Request; import io.specmock.core.example.Example1Response; import io.specmock.core.example.Example3Response;
1,193
/* * Copyright 2023 SpecMock * (c) 2023 SpecMock Contributors * SPDX-License-Identifier: Apache-2.0 * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.specmock.core; class HttpExchangeTest { private final Example1Request exampleRequest = new Example1Request("REQ", 1, 1L, BigDecimal.ONE); private final Example1Response exampleResponse = new Example1Response("RES"); @Test void matchRequest() { final HttpExchange exchange = HttpExchange.builder() .requestObject(exampleRequest) .responseStatus(HttpStatus.OK) .responseObject(exampleResponse) .build(); // Correct Class assertThat(exchange.isMatchRequest(Example1Request.class, Example1Response.class)).isTrue(); assertThat(exchange.isNotMatchRequest(Example1Request.class, Example1Response.class)).isFalse(); // Incorrect Class
/* * Copyright 2023 SpecMock * (c) 2023 SpecMock Contributors * SPDX-License-Identifier: Apache-2.0 * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.specmock.core; class HttpExchangeTest { private final Example1Request exampleRequest = new Example1Request("REQ", 1, 1L, BigDecimal.ONE); private final Example1Response exampleResponse = new Example1Response("RES"); @Test void matchRequest() { final HttpExchange exchange = HttpExchange.builder() .requestObject(exampleRequest) .responseStatus(HttpStatus.OK) .responseObject(exampleResponse) .build(); // Correct Class assertThat(exchange.isMatchRequest(Example1Request.class, Example1Response.class)).isTrue(); assertThat(exchange.isNotMatchRequest(Example1Request.class, Example1Response.class)).isFalse(); // Incorrect Class
assertThat(exchange.isMatchRequest(Example1Request.class, Example3Response.class)).isFalse();
2
2023-12-13 10:43:07+00:00
2k
kdhrubo/db2rest
src/main/java/com/homihq/db2rest/rsql/parser/MyBatisFilterVisitor.java
[ { "identifier": "OperatorV2", "path": "src/main/java/com/homihq/db2rest/rsql/operators/OperatorV2.java", "snippet": "public interface OperatorV2 {\n\n SqlCriterion handle(SqlColumn<Object> column, String value, Class type);\n\n default SqlCriterion handle(SqlColumn<Object> column, List<String> value, Class type) {\n return handle(column, value.get(0), type);\n }\n\n default Object parseValue(String value, Class type) {\n\n if (String.class == type) {\n return value;\n }\n else if (Boolean.class == type || boolean.class == type) {\n return Boolean.valueOf(value);\n }\n else if (Integer.class == type || int.class == type) {\n return Integer.valueOf(value);\n }\n\n else {\n return value;\n }\n\n }\n\n}" }, { "identifier": "RSQLOperatorHandlers", "path": "src/main/java/com/homihq/db2rest/rsql/operators/RSQLOperatorHandlers.java", "snippet": "public class RSQLOperatorHandlers {\n\n private static final Map<String, OperatorV2> OPERATOR_HANDLER_MAP = new HashMap<>();\n\n static {\n OPERATOR_HANDLER_MAP.put(EQUAL.getSymbol(), new EqualToOperator());\n OPERATOR_HANDLER_MAP.put(GREATER_THAN.getSymbol(), new GreaterThanOperator());\n OPERATOR_HANDLER_MAP.put(GREATER_THAN_OR_EQUAL.getSymbol(), new GreaterThanEqualToOperator());\n OPERATOR_HANDLER_MAP.put(LESS_THAN.getSymbol(), new LessThanOperator());\n OPERATOR_HANDLER_MAP.put(LESS_THAN_OR_EQUAL.getSymbol(), new LessThanEqualToOperator());\n OPERATOR_HANDLER_MAP.put(NOT_EQUAL.getSymbol(), new NotEqualToOperator());\n OPERATOR_HANDLER_MAP.put(LIKE.getSymbol(), new LikeOperator());\n OPERATOR_HANDLER_MAP.put(END_WITH.getSymbol(), new EndWithOperator());\n }\n\n public static OperatorV2 getOperatorHandler(String symbol) {\n return OPERATOR_HANDLER_MAP.get(symbol);\n }\n}" } ]
import static org.mybatis.dynamic.sql.SqlBuilder.*; import java.util.ArrayList; import java.util.List; import com.homihq.db2rest.rsql.operators.OperatorV2; import com.homihq.db2rest.rsql.operators.RSQLOperatorHandlers; import cz.jirutka.rsql.parser.ast.*; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.mybatis.dynamic.sql.*;
772
package com.homihq.db2rest.rsql.parser; @RequiredArgsConstructor @Slf4j public class MyBatisFilterVisitor implements RSQLVisitor<SqlCriterion, Object> { private final SqlTable sqlTable; @Override public SqlCriterion visit(AndNode node, Object optionalParameter) { List<AndOrCriteriaGroup> criterionList = new ArrayList<>(); for (Node child : node.getChildren()) { criterionList.add(and(child.accept(this, optionalParameter))); } return processCriteriaGroup(criterionList); } @Override public SqlCriterion visit(OrNode node, Object optionalParameter) { List<AndOrCriteriaGroup> criterionList = new ArrayList<>(); for (Node child : node.getChildren()) { criterionList.add(or(child.accept(this, optionalParameter))); } return processCriteriaGroup(criterionList); } @Override public SqlCriterion visit(ComparisonNode comparisonNode, Object optionalParameter) { ComparisonOperator op = comparisonNode.getOperator(); String columnName = comparisonNode.getSelector();
package com.homihq.db2rest.rsql.parser; @RequiredArgsConstructor @Slf4j public class MyBatisFilterVisitor implements RSQLVisitor<SqlCriterion, Object> { private final SqlTable sqlTable; @Override public SqlCriterion visit(AndNode node, Object optionalParameter) { List<AndOrCriteriaGroup> criterionList = new ArrayList<>(); for (Node child : node.getChildren()) { criterionList.add(and(child.accept(this, optionalParameter))); } return processCriteriaGroup(criterionList); } @Override public SqlCriterion visit(OrNode node, Object optionalParameter) { List<AndOrCriteriaGroup> criterionList = new ArrayList<>(); for (Node child : node.getChildren()) { criterionList.add(or(child.accept(this, optionalParameter))); } return processCriteriaGroup(criterionList); } @Override public SqlCriterion visit(ComparisonNode comparisonNode, Object optionalParameter) { ComparisonOperator op = comparisonNode.getOperator(); String columnName = comparisonNode.getSelector();
OperatorV2 operatorHandler = RSQLOperatorHandlers.getOperatorHandler(op.getSymbol());
0
2023-12-14 19:26:05+00:00
2k
kaifangqian/open-sign
src/main/java/com/resrun/service/verify/SignVerifyService.java
[ { "identifier": "SignPdfInfoVo", "path": "src/main/java/com/resrun/service/pojo/SignPdfInfoVo.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@ApiModel(\"数字签名信息返回对象\")\npublic class SignPdfInfoVo {\n /**\n * PDF名称\n */\n @ApiModelProperty(value = \"PDF名称\")\n private String pdfName;\n /**\n * PDF大小\n */\n @ApiModelProperty(value = \"PDF大小\")\n private String pdfSize;\n\n /**\n * 文件签名结果\n */\n @ApiModelProperty(value = \"文件签名结果\")\n private Integer pdfSingResult;\n\n @ApiModelProperty(value = \"数字签名详细集合\")\n private List<SignatureDetail> signatureDetails = new ArrayList<>();\n\n public static class SignatureDetail {\n /**\n * 数字签名名称\n */\n @ApiModelProperty(value = \"数字签名名称\")\n public String signName;\n /**\n * 签名日期时间\n */\n @ApiModelProperty(value = \"签名日期时间\")\n public Date signTime;\n /**\n * 有效期开始时间\n */\n @ApiModelProperty(value = \"有效期开始时间\")\n public Date validStartTime;\n /**\n * 有效期结束时间\n */\n @ApiModelProperty(value = \"有效期结束时间\")\n public Date validEndTime;\n /**\n * 证书名称\n */\n @ApiModelProperty(value = \"证书名称\")\n public String certName;\n /**\n * 证书序列号\n */\n @ApiModelProperty(value = \"证书序列号\")\n public String serialNumber;\n /**\n * 证书公钥\n */\n @ApiModelProperty(value = \"证书公钥\")\n public String publicKey;\n /**\n * 证书格式\n */\n @ApiModelProperty(value = \"证书格式\")\n public String pubKeyFormat;\n /**\n * 证书签名算法\n */\n @ApiModelProperty(value = \"证书签名算法\")\n public String sigAlgName;\n /**\n * 证书颁发者\n */\n @ApiModelProperty(value = \"证书颁发者\")\n public String userDnName;\n /**\n * 是否被篡改\n */\n @ApiModelProperty(value = \"是否被篡改\")\n public boolean validate;\n\n @ApiModelProperty(value = \"图片内容\")\n public String imageContent;\n /**\n * 图片路径\n */\n @ApiModelProperty(value = \"图片路径\")\n public String imagePath;\n\n /**\n * 签名位置\n */\n @ApiModelProperty(value = \"签名位置\")\n public String reason;\n /**\n * 签名类型\n */\n @ApiModelProperty(value = \"签名类型\")\n public String location;\n\n /**\n * 签名页面\n */\n @ApiModelProperty(value = \"签名页面\")\n public int pageNum;\n\n /**\n * 图片的base64编码\n */\n @ApiModelProperty(value = \"图片的base64编码\")\n public String sealBase64;\n\n /**\n * 文件摘要\n */\n @ApiModelProperty(value = \"文件摘要\")\n public String fileDigest;\n\n public float llx, lly, urx, ury;\n /**\n * 文件路径\n */\n // public String filePath;\n }\n\n}" }, { "identifier": "VerifyResponse", "path": "src/main/java/com/resrun/controller/vo/response/VerifyResponse.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@ApiModel(\"文件验签-返回对象\")\npublic class VerifyResponse implements Serializable {\n\n private static final long serialVersionUID = -1498109564641142303L;\n\n @ApiModelProperty(\"返回信息\")\n private String msg ;\n\n @ApiModelProperty(\"详细数据\")\n private SignPdfInfoVo vo ;\n\n}" } ]
import com.resrun.service.pojo.SignPdfInfoVo; import com.resrun.controller.vo.response.VerifyResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service;
1,125
package com.resrun.service.verify; /** * @Description: 在线签名验签服务实现类 * @Package: com.resrun.service.verify * @ClassName: SignVerifyServiceImpl * @copyright 北京资源律动科技有限公司 */ @Slf4j @Service public class SignVerifyService{ /** * 获取pdf签名图片信息 * @return 提取结果 */ public VerifyResponse getImageFromPdf(byte[] bytes, String fileName) { VerifyResponse response = new VerifyResponse();
package com.resrun.service.verify; /** * @Description: 在线签名验签服务实现类 * @Package: com.resrun.service.verify * @ClassName: SignVerifyServiceImpl * @copyright 北京资源律动科技有限公司 */ @Slf4j @Service public class SignVerifyService{ /** * 获取pdf签名图片信息 * @return 提取结果 */ public VerifyResponse getImageFromPdf(byte[] bytes, String fileName) { VerifyResponse response = new VerifyResponse();
SignPdfInfoVo signPdfInfo = new SignPdfInfoVo();
0
2023-12-14 06:53:32+00:00
2k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/config/RPrefs.java
[ { "identifier": "EXCLUDED_PREFS_FROM_BACKUP", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static Set<String> EXCLUDED_PREFS_FROM_BACKUP = new HashSet<>(\n Arrays.asList(\n PREF_WORKING_METHOD,\n MONET_LAST_UPDATED\n )\n);" }, { "identifier": "ColorBlendr", "path": "app/src/main/java/com/drdisagree/colorblendr/ColorBlendr.java", "snippet": "public class ColorBlendr extends Application {\n\n private static ColorBlendr instance;\n private static WeakReference<Context> contextReference;\n\n public void onCreate() {\n super.onCreate();\n instance = this;\n contextReference = new WeakReference<>(getApplicationContext());\n DynamicColors.applyToActivitiesIfAvailable(this);\n }\n\n public static Context getAppContext() {\n if (contextReference == null || contextReference.get() == null) {\n contextReference = new WeakReference<>(ColorBlendr.getInstance().getApplicationContext());\n }\n return contextReference.get();\n }\n\n private static ColorBlendr getInstance() {\n if (instance == null) {\n instance = new ColorBlendr();\n }\n return instance;\n }\n\n public static IRootService getRootService() {\n return RootServiceProvider.getRootServiceProvider();\n }\n}" }, { "identifier": "Const", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public class Const {\n\n // Preferences file\n public static final String SharedPrefs = BuildConfig.APPLICATION_ID + \"_preferences\";\n\n // System packages\n public static final String FRAMEWORK_PACKAGE = \"android\";\n public static final String SYSTEMUI_PACKAGE = \"com.android.systemui\";\n\n // General preferences\n public static final String FIRST_RUN = \"firstRun\";\n public static final String THEMING_ENABLED = \"themingEnabled\";\n public static final String MONET_STYLE = \"customMonetStyle\";\n public static final String MONET_ACCENT_SATURATION = \"monetAccentSaturationValue\";\n public static final String MONET_BACKGROUND_SATURATION = \"monetBackgroundSaturationValue\";\n public static final String MONET_BACKGROUND_LIGHTNESS = \"monetBackgroundLightnessValue\";\n public static final String MONET_ACCURATE_SHADES = \"monetAccurateShades\";\n public static final String MONET_PITCH_BLACK_THEME = \"monetPitchBlackTheme\";\n public static final String MONET_SEED_COLOR = \"monetSeedColor\";\n public static final String MONET_SEED_COLOR_ENABLED = \"monetSeedColorEnabled\";\n public static final String MANUAL_OVERRIDE_COLORS = \"manualOverrideColors\";\n public static final String MONET_LAST_UPDATED = \"monetLastUpdated\";\n public static final String FABRICATED_OVERLAY_SOURCE_PACKAGE = FRAMEWORK_PACKAGE;\n public static final String FABRICATED_OVERLAY_NAME_SYSTEM = BuildConfig.APPLICATION_ID + \"_dynamic_theme\";\n public static final String FABRICATED_OVERLAY_NAME_APPS = BuildConfig.APPLICATION_ID + \".%s_dynamic_theme\";\n public static final String WALLPAPER_COLOR_LIST = \"wallpaperColorList\";\n public static final String FABRICATED_OVERLAY_FOR_APPS_STATE = \"fabricatedOverlayForAppsState\";\n public static final String SHOW_PER_APP_THEME_WARN = \"showPerAppThemeWarn\";\n public static final String TINT_TEXT_COLOR = \"tintTextColor\";\n\n // Service preferences\n public static final Gson GSON = new Gson();\n public static final String PREF_WORKING_METHOD = \"workingMethod\";\n\n public static Set<String> EXCLUDED_PREFS_FROM_BACKUP = new HashSet<>(\n Arrays.asList(\n PREF_WORKING_METHOD,\n MONET_LAST_UPDATED\n )\n );\n\n public static void saveSelectedFabricatedApps(HashMap<String, Boolean> selectedApps) {\n RPrefs.putString(FABRICATED_OVERLAY_FOR_APPS_STATE, Const.GSON.toJson(selectedApps));\n }\n\n public static HashMap<String, Boolean> getSelectedFabricatedApps() {\n String selectedApps = RPrefs.getString(FABRICATED_OVERLAY_FOR_APPS_STATE, null);\n if (selectedApps == null || selectedApps.isEmpty()) {\n return new HashMap<>();\n }\n\n return Const.GSON.fromJson(selectedApps, new TypeToken<HashMap<String, Boolean>>() {\n }.getType());\n }\n}" } ]
import static android.content.Context.MODE_PRIVATE; import static com.drdisagree.colorblendr.common.Const.EXCLUDED_PREFS_FROM_BACKUP; import android.content.SharedPreferences; import android.util.Log; import androidx.annotation.NonNull; import com.drdisagree.colorblendr.ColorBlendr; import com.drdisagree.colorblendr.common.Const; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map;
1,120
package com.drdisagree.colorblendr.config; @SuppressWarnings("unused") public class RPrefs { private static final String TAG = RPrefs.class.getSimpleName();
package com.drdisagree.colorblendr.config; @SuppressWarnings("unused") public class RPrefs { private static final String TAG = RPrefs.class.getSimpleName();
public static SharedPreferences prefs = ColorBlendr.getAppContext().createDeviceProtectedStorageContext().getSharedPreferences(Const.SharedPrefs, MODE_PRIVATE);
1
2023-12-06 13:20:16+00:00
2k
bzvs1992/spring-boot-holiday-starter
src/main/java/cn/bzvs/holiday/util/HolidayFix.java
[ { "identifier": "ConstantData", "path": "src/main/java/cn/bzvs/holiday/autoconfigure/ConstantData.java", "snippet": "public class ConstantData {\n\n /**\n * 所有日期数据\n */\n private static final Map<String, CalendarVO> ALL_DATE_MAP = new ConcurrentHashMap<>();\n\n /**\n * 初始化,并设置数据\n * @param calendarVOList 对象列表\n */\n public static void init(List<CalendarVO> calendarVOList) {\n ALL_DATE_MAP.clear();\n setDayInfoAll(calendarVOList);\n }\n\n /**\n * 设置数据\n * @param calendarVOList 对象列表\n */\n public static void setDayInfoAll(List<CalendarVO> calendarVOList) {\n Map<String, CalendarVO> allMap = calendarVOList.stream().collect(Collectors.toMap(CalendarVO::getDate, Function.identity()));\n ALL_DATE_MAP.putAll(allMap);\n }\n\n /**\n * 获取所有日历数据\n * @return Map<String, CalendarVO> 对象MAP\n */\n public static Map<String, CalendarVO> getAllDateMap() {\n return new ConcurrentHashMap<>(ALL_DATE_MAP);\n }\n}" }, { "identifier": "HolidayProperties", "path": "src/main/java/cn/bzvs/holiday/autoconfigure/properties/HolidayProperties.java", "snippet": "@Data\n@ConfigurationProperties(prefix = \"holiday\")\npublic class HolidayProperties {\n\n /**\n * 类型:在线模式:network, 本地模式:local\n */\n private String type = \"network\";\n\n /**\n * 配置 在线获取 模式下,数据获取的年份\n */\n private Set<Integer> years;\n /**\n * 配置 本地获取 模式下,数据路径\n */\n private String path = \"/config/holiday.json\";\n}" }, { "identifier": "CalendarVO", "path": "src/main/java/cn/bzvs/holiday/entity/vo/CalendarVO.java", "snippet": "@Data\npublic class CalendarVO {\n\n /**\n * 主键\n * 日期yyyy-MM-dd\n * isNullAble:0\n */\n private String date;\n /**\n * 0普通工作日1周末2需要补班的工作日3法定节假日\n * isNullAble:1,defaultVal:0\n */\n private Integer status;\n}" } ]
import cn.bzvs.holiday.autoconfigure.ConstantData; import cn.bzvs.holiday.autoconfigure.properties.HolidayProperties; import cn.bzvs.holiday.entity.vo.CalendarVO; import cn.hutool.core.io.FileUtil; import com.alibaba.fastjson2.JSON; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.List;
828
package cn.bzvs.holiday.util; /** * 节假日修复工具 * * @author bzvs * @date 2024/12/04 * @since 1.0.0 */ @Slf4j public class HolidayFix { private HolidayFix() { } /** * 重置数据 * * @param file JSON文件 * @return boolean */ public static boolean reset(@NonNull File file) { String json = FileUtil.readString(file, StandardCharsets.UTF_8); return reset(json); } /** * 重置数据 * * @param json JSON数据 * @return boolean */ public static boolean reset(String json) { try {
package cn.bzvs.holiday.util; /** * 节假日修复工具 * * @author bzvs * @date 2024/12/04 * @since 1.0.0 */ @Slf4j public class HolidayFix { private HolidayFix() { } /** * 重置数据 * * @param file JSON文件 * @return boolean */ public static boolean reset(@NonNull File file) { String json = FileUtil.readString(file, StandardCharsets.UTF_8); return reset(json); } /** * 重置数据 * * @param json JSON数据 * @return boolean */ public static boolean reset(String json) { try {
List<CalendarVO> calendarVOList = JSON.parseArray(json, CalendarVO.class);
2
2023-12-05 10:59:02+00:00
2k
HelpChat/DeluxeMenus
src/main/java/com/extendedclip/deluxemenus/utils/ItemUtils.java
[ { "identifier": "INVENTORY_ITEM_ACCESSORS", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final Map<String, Function<PlayerInventory, ItemStack>> INVENTORY_ITEM_ACCESSORS = ImmutableMap.<String, Function<PlayerInventory, ItemStack>>builder()\r\n .put(MAIN_HAND, PlayerInventory::getItemInMainHand)\r\n .put(OFF_HAND, PlayerInventory::getItemInOffHand)\r\n .put(HELMET, PlayerInventory::getHelmet)\r\n .put(CHESTPLATE, PlayerInventory::getChestplate)\r\n .put(LEGGINGS, PlayerInventory::getLeggings)\r\n .put(BOOTS, PlayerInventory::getBoots)\r\n .build();\r" }, { "identifier": "ITEMSADDER_PREFIX", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final String ITEMSADDER_PREFIX = \"itemsadder-\";\r" }, { "identifier": "MMOITEMS_PREFIX", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final String MMOITEMS_PREFIX = \"mmoitems-\";\r" }, { "identifier": "ORAXEN_PREFIX", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final String ORAXEN_PREFIX = \"oraxen-\";\r" }, { "identifier": "PLACEHOLDER_PREFIX", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final String PLACEHOLDER_PREFIX = \"placeholder-\";\r" }, { "identifier": "WATER_BOTTLE", "path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java", "snippet": "public static final String WATER_BOTTLE = \"water_bottle\";\r" } ]
import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionType; import org.jetbrains.annotations.NotNull; import static com.extendedclip.deluxemenus.utils.Constants.INVENTORY_ITEM_ACCESSORS; import static com.extendedclip.deluxemenus.utils.Constants.ITEMSADDER_PREFIX; import static com.extendedclip.deluxemenus.utils.Constants.MMOITEMS_PREFIX; import static com.extendedclip.deluxemenus.utils.Constants.ORAXEN_PREFIX; import static com.extendedclip.deluxemenus.utils.Constants.PLACEHOLDER_PREFIX; import static com.extendedclip.deluxemenus.utils.Constants.WATER_BOTTLE;
999
package com.extendedclip.deluxemenus.utils; public final class ItemUtils { private ItemUtils() { throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); } /** * Checks if the string starts with the substring "placeholder-". The check is case-sensitive. * * @param material The string to check * @return true if the string starts with "placeholder-", false otherwise */ public static boolean isPlaceholderMaterial(@NotNull final String material) { return material.startsWith(PLACEHOLDER_PREFIX); } /** * Checks if the string is a player item. The check is case-sensitive. * Player items are: "main_hand", "off_hand", "armor_helmet", "armor_chestplate", "armor_leggings", "armor_boots" * * @param material The string to check * @return true if the string is a player item, false otherwise */ public static boolean isPlayerItem(@NotNull final String material) { return INVENTORY_ITEM_ACCESSORS.containsKey(material); } /** * Checks if the string is an ItemsAdder item. The check is case-sensitive. * ItemsAdder items are: "itemsadder-{namespace:name}" * * @param material The string to check * @return true if the string is an ItemsAdder item, false otherwise */ public static boolean isItemsAdderItem(@NotNull final String material) { return material.startsWith(ITEMSADDER_PREFIX); } /** * Checks if the string is an Oraxen item. The check is case-sensitive. * Oraxen items are: "oraxen-{namespace:name}" * * @param material The string to check * @return true if the string is an Oraxen item, false otherwise */ public static boolean isOraxenItem(@NotNull final String material) { return material.startsWith(ORAXEN_PREFIX); } /** * Checks if the string is an MMOItems item. The check is case-sensitive. * MMOItems items are: "mmoitems-{namespace:name}" * * @param material The string to check * @return true if the string is an MMOItem item, false otherwise */ public static boolean isMMOItemsItem(@NotNull final String material) {
package com.extendedclip.deluxemenus.utils; public final class ItemUtils { private ItemUtils() { throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); } /** * Checks if the string starts with the substring "placeholder-". The check is case-sensitive. * * @param material The string to check * @return true if the string starts with "placeholder-", false otherwise */ public static boolean isPlaceholderMaterial(@NotNull final String material) { return material.startsWith(PLACEHOLDER_PREFIX); } /** * Checks if the string is a player item. The check is case-sensitive. * Player items are: "main_hand", "off_hand", "armor_helmet", "armor_chestplate", "armor_leggings", "armor_boots" * * @param material The string to check * @return true if the string is a player item, false otherwise */ public static boolean isPlayerItem(@NotNull final String material) { return INVENTORY_ITEM_ACCESSORS.containsKey(material); } /** * Checks if the string is an ItemsAdder item. The check is case-sensitive. * ItemsAdder items are: "itemsadder-{namespace:name}" * * @param material The string to check * @return true if the string is an ItemsAdder item, false otherwise */ public static boolean isItemsAdderItem(@NotNull final String material) { return material.startsWith(ITEMSADDER_PREFIX); } /** * Checks if the string is an Oraxen item. The check is case-sensitive. * Oraxen items are: "oraxen-{namespace:name}" * * @param material The string to check * @return true if the string is an Oraxen item, false otherwise */ public static boolean isOraxenItem(@NotNull final String material) { return material.startsWith(ORAXEN_PREFIX); } /** * Checks if the string is an MMOItems item. The check is case-sensitive. * MMOItems items are: "mmoitems-{namespace:name}" * * @param material The string to check * @return true if the string is an MMOItem item, false otherwise */ public static boolean isMMOItemsItem(@NotNull final String material) {
return material.startsWith(MMOITEMS_PREFIX);
2
2023-12-14 23:41:07+00:00
2k
lxs2601055687/contextAdminRuoYi
ruoyi-common/src/main/java/com/ruoyi/common/jackson/SensitiveJsonSerializer.java
[ { "identifier": "SensitiveService", "path": "ruoyi-common/src/main/java/com/ruoyi/common/core/service/SensitiveService.java", "snippet": "public interface SensitiveService {\n\n /**\n * 是否脱敏\n */\n boolean isSensitive();\n\n}" }, { "identifier": "SensitiveStrategy", "path": "ruoyi-common/src/main/java/com/ruoyi/common/enums/SensitiveStrategy.java", "snippet": "@AllArgsConstructor\npublic enum SensitiveStrategy {\n\n /**\n * 身份证脱敏\n */\n ID_CARD(s -> DesensitizedUtil.idCardNum(s, 3, 4)),\n\n /**\n * 手机号脱敏\n */\n PHONE(DesensitizedUtil::mobilePhone),\n\n /**\n * 地址脱敏\n */\n ADDRESS(s -> DesensitizedUtil.address(s, 8)),\n\n /**\n * 邮箱脱敏\n */\n EMAIL(DesensitizedUtil::email),\n\n /**\n * 银行卡\n */\n BANK_CARD(DesensitizedUtil::bankCard);\n\n //可自行添加其他脱敏策略\n\n private final Function<String, String> desensitizer;\n\n public Function<String, String> desensitizer() {\n return desensitizer;\n }\n}" }, { "identifier": "SpringUtils", "path": "ruoyi-common/src/main/java/com/ruoyi/common/utils/spring/SpringUtils.java", "snippet": "@Component\npublic final class SpringUtils extends SpringUtil {\n\n /**\n * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true\n *\n * @param name\n * @return boolean\n */\n public static boolean containsBean(String name) {\n return getBeanFactory().containsBean(name);\n }\n\n /**\n * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。\n * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)\n *\n * @param name\n * @return boolean\n */\n public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {\n return getBeanFactory().isSingleton(name);\n }\n\n /**\n * @param name\n * @return Class 注册对象的类型\n */\n public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {\n return getBeanFactory().getType(name);\n }\n\n /**\n * 如果给定的bean名字在bean定义中有别名,则返回这些别名\n *\n * @param name\n */\n public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {\n return getBeanFactory().getAliases(name);\n }\n\n /**\n * 获取aop代理对象\n *\n * @param invoker\n * @return\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> T getAopProxy(T invoker) {\n return (T) AopContext.currentProxy();\n }\n\n\n /**\n * 获取spring上下文\n */\n public static ApplicationContext context() {\n return getApplicationContext();\n }\n\n}" } ]
import cn.hutool.core.util.ObjectUtil; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.ContextualSerializer; import com.ruoyi.common.annotation.Sensitive; import com.ruoyi.common.core.service.SensitiveService; import com.ruoyi.common.enums.SensitiveStrategy; import com.ruoyi.common.utils.spring.SpringUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import java.io.IOException; import java.util.Objects;
1,000
package com.ruoyi.common.jackson; /** * 数据脱敏json序列化工具 * * @author Yjoioooo */ @Slf4j public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {
package com.ruoyi.common.jackson; /** * 数据脱敏json序列化工具 * * @author Yjoioooo */ @Slf4j public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {
private SensitiveStrategy strategy;
1
2023-12-07 12:06:21+00:00
2k
DHBin/isme-java-serve
src/main/java/cn/dhbin/isme/pms/service/RoleService.java
[ { "identifier": "Page", "path": "src/main/java/cn/dhbin/isme/common/response/Page.java", "snippet": "@Data\npublic class Page<T> {\n\n private List<T> pageData;\n\n private Long total;\n\n\n /**\n * mpPage转成Page\n *\n * @param mpPage mp的分页结果\n * @param <T> 类型\n * @return page\n */\n public static <T> Page<T> convert(IPage<T> mpPage) {\n Page<T> page = new Page<>();\n page.setPageData(mpPage.getRecords());\n page.setTotal(mpPage.getTotal());\n return page;\n }\n}" }, { "identifier": "PermissionDto", "path": "src/main/java/cn/dhbin/isme/pms/domain/dto/PermissionDto.java", "snippet": "@Data\npublic class PermissionDto {\n\n private Long id;\n\n private String name;\n\n private String code;\n\n private String type;\n\n private Long parentId;\n\n private String path;\n\n private String redirect;\n\n private String icon;\n\n private String component;\n\n private String layout;\n\n private Boolean keepalive;\n\n private String method;\n\n private String description;\n\n private Boolean show;\n\n private Boolean enable;\n\n private Integer order;\n\n}" }, { "identifier": "RolePageDto", "path": "src/main/java/cn/dhbin/isme/pms/domain/dto/RolePageDto.java", "snippet": "@Data\npublic class RolePageDto {\n\n private Long id;\n\n private String code;\n\n private String name;\n\n private Boolean enable;\n\n private List<Long> permissionIds;\n\n}" }, { "identifier": "Role", "path": "src/main/java/cn/dhbin/isme/pms/domain/entity/Role.java", "snippet": "@Data\n@TableName(\"role\")\npublic class Role implements Convert {\n\n @TableId(type = IdType.AUTO)\n private Long id;\n\n private String code;\n\n private String name;\n\n private Boolean enable;\n\n}" }, { "identifier": "AddRolePermissionsRequest", "path": "src/main/java/cn/dhbin/isme/pms/domain/request/AddRolePermissionsRequest.java", "snippet": "@Data\npublic class AddRolePermissionsRequest {\n\n private Long id;\n\n private List<Long> permissionIds;\n}" }, { "identifier": "AddRoleUsersRequest", "path": "src/main/java/cn/dhbin/isme/pms/domain/request/AddRoleUsersRequest.java", "snippet": "@Data\npublic class AddRoleUsersRequest {\n\n private List<Long> userIds;\n\n}" }, { "identifier": "CreateRoleRequest", "path": "src/main/java/cn/dhbin/isme/pms/domain/request/CreateRoleRequest.java", "snippet": "@Data\npublic class CreateRoleRequest implements Convert {\n\n @NotBlank(message = \"角色编码不能为空\")\n private String code;\n\n @NotBlank(message = \"角色名不能为空\")\n private String name;\n\n private List<Long> permissionIds;\n\n private Boolean enable;\n\n}" }, { "identifier": "RemoveRoleUsersRequest", "path": "src/main/java/cn/dhbin/isme/pms/domain/request/RemoveRoleUsersRequest.java", "snippet": "@Data\npublic class RemoveRoleUsersRequest {\n\n private List<Long> userIds;\n\n}" }, { "identifier": "RolePageRequest", "path": "src/main/java/cn/dhbin/isme/pms/domain/request/RolePageRequest.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class RolePageRequest extends PageRequest {\n\n private String name;\n\n private Boolean enable;\n\n}" }, { "identifier": "UpdateRoleRequest", "path": "src/main/java/cn/dhbin/isme/pms/domain/request/UpdateRoleRequest.java", "snippet": "@Data\npublic class UpdateRoleRequest {\n\n private String name;\n\n private Boolean enable;\n\n private List<Long> permissionIds;\n\n\n}" } ]
import cn.dhbin.isme.common.response.Page; import cn.dhbin.isme.pms.domain.dto.PermissionDto; import cn.dhbin.isme.pms.domain.dto.RolePageDto; import cn.dhbin.isme.pms.domain.entity.Role; import cn.dhbin.isme.pms.domain.request.AddRolePermissionsRequest; import cn.dhbin.isme.pms.domain.request.AddRoleUsersRequest; import cn.dhbin.isme.pms.domain.request.CreateRoleRequest; import cn.dhbin.isme.pms.domain.request.RemoveRoleUsersRequest; import cn.dhbin.isme.pms.domain.request.RolePageRequest; import cn.dhbin.isme.pms.domain.request.UpdateRoleRequest; import cn.hutool.core.lang.tree.Tree; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List;
1,522
package cn.dhbin.isme.pms.service; /** * RoleService * * @author dhb */ public interface RoleService extends IService<Role> { /** * 根据用户id查询角色 * * @param userId 用户id * @return 用户角色列表 */ List<Role> findRolesByUserId(Long userId); /** * 根据角色编码获取权限树 * * @param roleCode 角色编码 * @return 权限树 */ List<Tree<Long>> findRolePermissionsTree(String roleCode); /** * 根据角色编码获取角色 * * @param roleCode 角色编码 * @return 角色 */ Role findByCode(String roleCode); /** * 创建角色 * * @param request req */ void createRole(CreateRoleRequest request); /** * 分页查询 * * @param request 请求 * @return dto */ Page<RolePageDto> queryPage(RolePageRequest request); /** * 查询角色权限 * * @param id 角色id * @return 角色权限 */ List<PermissionDto> findRolePermissions(Long id); /** * 更新角色,当角色标识是管理员时,不给修改 * * @param id 角色id * @param request req */ void updateRole(Long id, UpdateRoleRequest request); /** * 删除角色,不能删除管理员 * * @param id 角色id */ void removeRole(Long id); /** * 给角色添加权限 * * @param request req */ void addRolePermissions(AddRolePermissionsRequest request); /** * 给角色分配用户 * * @param roleId 角色id * @param request req */
package cn.dhbin.isme.pms.service; /** * RoleService * * @author dhb */ public interface RoleService extends IService<Role> { /** * 根据用户id查询角色 * * @param userId 用户id * @return 用户角色列表 */ List<Role> findRolesByUserId(Long userId); /** * 根据角色编码获取权限树 * * @param roleCode 角色编码 * @return 权限树 */ List<Tree<Long>> findRolePermissionsTree(String roleCode); /** * 根据角色编码获取角色 * * @param roleCode 角色编码 * @return 角色 */ Role findByCode(String roleCode); /** * 创建角色 * * @param request req */ void createRole(CreateRoleRequest request); /** * 分页查询 * * @param request 请求 * @return dto */ Page<RolePageDto> queryPage(RolePageRequest request); /** * 查询角色权限 * * @param id 角色id * @return 角色权限 */ List<PermissionDto> findRolePermissions(Long id); /** * 更新角色,当角色标识是管理员时,不给修改 * * @param id 角色id * @param request req */ void updateRole(Long id, UpdateRoleRequest request); /** * 删除角色,不能删除管理员 * * @param id 角色id */ void removeRole(Long id); /** * 给角色添加权限 * * @param request req */ void addRolePermissions(AddRolePermissionsRequest request); /** * 给角色分配用户 * * @param roleId 角色id * @param request req */
void addRoleUsers(Long roleId, AddRoleUsersRequest request);
5
2023-12-13 17:21:04+00:00
2k
Earthcomputer/ModCompatChecker
root/src/main/java/net/earthcomputer/modcompatchecker/util/InheritanceUtil.java
[ { "identifier": "IResolvedClass", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/indexer/IResolvedClass.java", "snippet": "public sealed interface IResolvedClass permits ClassIndex, ClasspathClass {\n AccessFlags getAccess();\n @Nullable\n String getSuperclass();\n List<String> getInterfaces();\n Collection<ClassMember> getFields();\n Collection<ClassMember> getMethods();\n Collection<String> getPermittedSubclasses();\n @Nullable\n String getNestHost();\n Collection<String> getNestMembers();\n}" }, { "identifier": "Index", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/indexer/Index.java", "snippet": "public final class Index {\n private final Map<String, ClassIndex> classes = new HashMap<>();\n private final Map<String, ClasspathClass> classpathClassCache = new ConcurrentHashMap<>();\n\n @Nullable\n public ClassIndex addClass(String name, AccessFlags access, String superclass, List<String> interfaces) {\n ClassIndex classIndex = new ClassIndex(access, superclass, interfaces);\n for (Plugin plugin : PluginLoader.plugins()) {\n classIndex = plugin.onIndexClass(this, name, classIndex);\n if (classIndex == null) {\n return null;\n }\n }\n classes.put(name, classIndex);\n return classIndex;\n }\n\n @Nullable\n public IResolvedClass findClass(@Nullable String name) {\n if (name == null) {\n return null;\n }\n\n if (AsmUtil.OBJECT.equals(name)) {\n return ClasspathClass.OBJECT;\n }\n\n ClassIndex classIndex = classes.get(name);\n if (classIndex != null) {\n return classIndex;\n }\n\n ClasspathClass classpathClass = classpathClassCache.get(name);\n if (classpathClass != null) {\n return classpathClass;\n }\n\n try {\n Class<?> classpathCls = Class.forName(Type.getObjectType(name).getClassName(), false, ClassLoader.getPlatformClassLoader());\n if (classpathClassCache.size() >= 200) {\n // periodically clear the cache to stop it getting out of hand\n classpathClassCache.clear();\n }\n classpathClass = new ClasspathClass(classpathCls);\n classpathClassCache.put(name, classpathClass);\n return classpathClass;\n } catch (ClassNotFoundException e) {\n return null;\n }\n }\n\n public void serialize(PrintWriter writer) {\n var entries = new ArrayList<>(classes.entrySet());\n entries.sort(Map.Entry.comparingByKey());\n for (var entry : entries) {\n ClassIndex clazz = entry.getValue();\n writer.printf(\"class %s %s %s%s%s\\n\", clazz.getAccess(), entry.getKey(), clazz.getSuperclass(), clazz.getInterfaces().isEmpty() ? \"\" : \" \", String.join(\" \", clazz.getInterfaces()));\n clazz.serialize(writer);\n }\n }\n\n public void deserializeFrom(BufferedReader reader) throws IOException {\n String line;\n while ((line = reader.readLine()) != null) {\n String[] parts = line.split(\" \");\n if (parts.length < 4) {\n throw new IOException(\"Incomplete line: \" + line);\n }\n\n String classType = parts[0];\n if (!\"class\".equals(classType)) {\n throw new IOException(\"Invalid line start: \" + line);\n }\n\n String key = parts[2];\n String superclass = parts[3];\n List<String> interfaces = new ArrayList<>(Arrays.asList(parts).subList(4, parts.length));\n\n AccessFlags access = AccessFlags.parse(parts[1]);\n if (access == null) {\n throw new IOException(\"Invalid access flags: \" + parts[1]);\n }\n\n ClassIndex classIndex = new ClassIndex(access, superclass, interfaces);\n\n for (Plugin plugin : PluginLoader.plugins()) {\n classIndex = plugin.onIndexClass(this, key, classIndex);\n if (classIndex == null) {\n break;\n }\n }\n\n if (classIndex != null) {\n classIndex.deserializeFrom(key, reader);\n classes.put(key, classIndex);\n }\n }\n }\n}" } ]
import net.earthcomputer.modcompatchecker.indexer.IResolvedClass; import net.earthcomputer.modcompatchecker.indexer.Index; import org.jetbrains.annotations.Nullable; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set;
1,253
package net.earthcomputer.modcompatchecker.util; public final class InheritanceUtil { private InheritanceUtil() { } public static boolean canOverride(String subclass, String superclass, AccessFlags superMethodAccess) { // JVMS 21 §5.4.5, assumes no intermediate subclasses between `subclass` and `superclass` which contain methods // that can override the super method. if (superMethodAccess.isStatic()) { return false; } return switch (superMethodAccess.accessLevel()) { case PUBLIC, PROTECTED -> true; case PACKAGE -> AsmUtil.areSamePackage(subclass, superclass); case PRIVATE -> false; }; } @Nullable public static OwnedClassMember lookupField(Index index, String owner, String name, String desc) { // JVMS 21 §5.4.3.2 field resolution, 1-4 (field lookup)
package net.earthcomputer.modcompatchecker.util; public final class InheritanceUtil { private InheritanceUtil() { } public static boolean canOverride(String subclass, String superclass, AccessFlags superMethodAccess) { // JVMS 21 §5.4.5, assumes no intermediate subclasses between `subclass` and `superclass` which contain methods // that can override the super method. if (superMethodAccess.isStatic()) { return false; } return switch (superMethodAccess.accessLevel()) { case PUBLIC, PROTECTED -> true; case PACKAGE -> AsmUtil.areSamePackage(subclass, superclass); case PRIVATE -> false; }; } @Nullable public static OwnedClassMember lookupField(Index index, String owner, String name, String desc) { // JVMS 21 §5.4.3.2 field resolution, 1-4 (field lookup)
for (IResolvedClass resolvedClass = index.findClass(owner); resolvedClass != null; resolvedClass = index.findClass(owner = resolvedClass.getSuperclass())) {
0
2023-12-11 00:48:12+00:00
2k
wkgcass/jdkman
src/main/java/io/vproxy/jdkman/action/InitAction.java
[ { "identifier": "JDKManConfig", "path": "src/main/java/io/vproxy/jdkman/entity/JDKManConfig.java", "snippet": "public class JDKManConfig implements JSONObject {\n private String defaultJDK;\n private List<JDKInfo> jdks;\n\n public static final Rule<JDKManConfig> rule = new ObjectRule<>(() -> new JDKManConfig(null))\n .put(\"defaultJDK\", JDKManConfig::setDefaultJDK, NullableStringRule.get())\n .put(\"jdks\", JDKManConfig::setJdks, new ArrayRule<>(ArrayList::new, List::add, JDKInfo.rule));\n\n @Override\n public JSON.Object toJson() {\n return new ObjectBuilder()\n .put(\"defaultJDK\", defaultJDK)\n .putArray(\"jdks\", a -> jdks.forEach(e -> a.addInst(e.toJson())))\n .build();\n }\n\n public JDKManConfig() {\n jdks = new ArrayList<>();\n }\n\n private JDKManConfig(@SuppressWarnings(\"unused\") Void unused) {\n }\n\n public String getDefaultJDK() {\n return defaultJDK;\n }\n\n public void setDefaultJDK(String defaultJDK) {\n this.defaultJDK = defaultJDK;\n }\n\n public List<JDKInfo> getJdks() {\n return jdks;\n }\n\n public void setJdks(List<JDKInfo> jdks) {\n this.jdks = jdks;\n }\n}" }, { "identifier": "ErrorResult", "path": "src/main/java/io/vproxy/jdkman/ex/ErrorResult.java", "snippet": "public class ErrorResult extends Exception {\n public ErrorResult(String message) {\n super(message);\n }\n}" }, { "identifier": "ResConsts", "path": "src/main/java/io/vproxy/jdkman/res/ResConsts.java", "snippet": "public class ResConsts {\n private ResConsts() {\n }\n\n public static final String MD5_JDKMAN_PROXY_WINDOWS_X86_64 = \"dc1dd297823a73c64cf17d62b789c34e\";\n}" } ]
import io.vproxy.base.util.LogType; import io.vproxy.base.util.Logger; import io.vproxy.base.util.OS; import io.vproxy.base.util.Utils; import io.vproxy.jdkman.entity.JDKManConfig; import io.vproxy.jdkman.ex.ErrorResult; import io.vproxy.jdkman.res.ResConsts; import vjson.Stringifier; import vjson.simple.SimpleString; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.HashSet; import java.util.Set;
1,063
package io.vproxy.jdkman.action; public class InitAction implements Action { private static final Set<String> EXECUTABLES = new HashSet<>() {{ addAll(Arrays.asList( "jar", "jarsigner", "java", "javac", "javadoc", "javap", "jcmd", "jconsole", "jdb", "jdeprscan", "jdeps", "jfr", "jhsdb", "jimage", "jinfo", "jlink", "jmap", "jmod", "jpackage", "jps", "jrunscript", "jshell", "jstack", "jstat", "jstatd", "jwebserver", "keytool", "rmiregistry", "serialver")); addAll(Arrays.asList( "jaotc", "jpackager" )); addAll(Arrays.asList( "appletviewer", "extcheck", "idlj", "javafxpackager", "javah", "javapackager", "jhat", "jjs", "jmc", "jsadebugd", "jvisualvm", "native2ascii", "orbd", "pack200", "policytool", "rmic", "rmid", "schemagen", "servertool", "tnameserv", "unpack200", "wsgen", "wsimport", "xjc")); addAll(Arrays.asList( "javaws", "jcontrol", "jweblauncher" )); }}; @Override public String validate(String[] options) { if (options.length != 0 && options.length != 1) { return STR."unknown options for `init`: \{Arrays.toString(options)}"; } if (options.length > 0 && !Set.of("sh", "pwsh").contains(options[0])) { return STR."the first option must be 'sh|pwsh': \{options[0]}"; } return null; } private enum ShellType { shell, pwsh, } @Override
package io.vproxy.jdkman.action; public class InitAction implements Action { private static final Set<String> EXECUTABLES = new HashSet<>() {{ addAll(Arrays.asList( "jar", "jarsigner", "java", "javac", "javadoc", "javap", "jcmd", "jconsole", "jdb", "jdeprscan", "jdeps", "jfr", "jhsdb", "jimage", "jinfo", "jlink", "jmap", "jmod", "jpackage", "jps", "jrunscript", "jshell", "jstack", "jstat", "jstatd", "jwebserver", "keytool", "rmiregistry", "serialver")); addAll(Arrays.asList( "jaotc", "jpackager" )); addAll(Arrays.asList( "appletviewer", "extcheck", "idlj", "javafxpackager", "javah", "javapackager", "jhat", "jjs", "jmc", "jsadebugd", "jvisualvm", "native2ascii", "orbd", "pack200", "policytool", "rmic", "rmid", "schemagen", "servertool", "tnameserv", "unpack200", "wsgen", "wsimport", "xjc")); addAll(Arrays.asList( "javaws", "jcontrol", "jweblauncher" )); }}; @Override public String validate(String[] options) { if (options.length != 0 && options.length != 1) { return STR."unknown options for `init`: \{Arrays.toString(options)}"; } if (options.length > 0 && !Set.of("sh", "pwsh").contains(options[0])) { return STR."the first option must be 'sh|pwsh': \{options[0]}"; } return null; } private enum ShellType { shell, pwsh, } @Override
public boolean execute(JDKManConfig config, String[] options) throws Exception {
0
2023-12-07 04:55:35+00:00
2k
DantSu/studio
driver/src/main/java/studio/driver/model/fs/FsDeviceInfos.java
[ { "identifier": "SecurityUtils", "path": "core/src/main/java/studio/core/v1/utils/SecurityUtils.java", "snippet": "public class SecurityUtils {\n\n private static final Logger LOGGER = LogManager.getLogger(SecurityUtils.class);\n\n private static final byte[] HEX_ARRAY = \"0123456789abcdef\".getBytes(StandardCharsets.US_ASCII);\n\n private SecurityUtils() {\n throw new IllegalStateException(\"Utility class\");\n }\n\n /**\n * Compute the sha1 of a byte array in Hex string\n * \n * @param input byte array\n * @return sha1 String\n */\n public static String sha1Hex(byte[] array) {\n try {\n byte[] digest = MessageDigest.getInstance(\"SHA1\").digest(array);\n return encodeHex(digest);\n } catch (NoSuchAlgorithmException e) {\n LOGGER.error(\"sha1 not supported\", e);\n return null;\n }\n }\n\n /**\n * Compute the sha1 of a String in Hex string\n * \n * @param input UTF-8 string\n * @return sha1 String\n */\n public static String sha1Hex(String s) {\n return sha1Hex(s.getBytes(StandardCharsets.UTF_8));\n }\n\n /**\n * Convert byte array to (lowercase) Hex String\n * \n * @param bytes byte array\n * @return hexadecimal string\n */\n public static String encodeHex(byte[] bytes) {\n byte[] hexChars = new byte[bytes.length * 2];\n for (int j = 0; j < bytes.length; j++) {\n int v = bytes[j] & 0xFF;\n hexChars[j * 2] = HEX_ARRAY[v >>> 4];\n hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];\n }\n return new String(hexChars, StandardCharsets.UTF_8);\n }\n\n /**\n * Convert UTF-8 String to (lowercase) Hex String\n * \n * @param s String\n * @return hexadecimal string\n */\n public static String encodeHex(String s) {\n return encodeHex(s.getBytes(StandardCharsets.UTF_8));\n }\n\n /**\n * Convert Hex String to byte array.\n * \n * @param s hexadecimal string\n * @return byte array\n */\n public static byte[] decodeHex(String s) {\n int len = s.length();\n if (len % 2 != 0) {\n throw new IllegalArgumentException(\"Invalid hex string (length % 2 != 0)\");\n }\n byte[] arr = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n arr[i / 2] = Integer.valueOf(s.substring(i, i + 2), 16).byteValue();\n }\n return arr;\n }\n\n}" }, { "identifier": "DeviceInfos", "path": "driver/src/main/java/studio/driver/model/DeviceInfos.java", "snippet": "public abstract class DeviceInfos {\n\n private short firmwareMajor;\n private short firmwareMinor;\n private String serialNumber;\n\n public short getFirmwareMajor() {\n return firmwareMajor;\n }\n\n public void setFirmwareMajor(short firmwareMajor) {\n this.firmwareMajor = firmwareMajor;\n }\n\n public short getFirmwareMinor() {\n return firmwareMinor;\n }\n\n public void setFirmwareMinor(short firmwareMinor) {\n this.firmwareMinor = firmwareMinor;\n }\n\n public String getSerialNumber() {\n return serialNumber;\n }\n\n public void setSerialNumber(String serialNumber) {\n this.serialNumber = serialNumber;\n }\n\n}" } ]
import studio.core.v1.utils.SecurityUtils; import studio.driver.model.DeviceInfos;
1,159
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.driver.model.fs; public class FsDeviceInfos extends DeviceInfos { private byte[] deviceKey; private long sdCardSizeInBytes; private long usedSpaceInBytes; public byte[] getDeviceKey() { return deviceKey; } public void setDeviceKey(byte[] deviceId) { this.deviceKey = deviceId; } public long getSdCardSizeInBytes() { return sdCardSizeInBytes; } public void setSdCardSizeInBytes(long sdCardSizeInBytes) { this.sdCardSizeInBytes = sdCardSizeInBytes; } public long getUsedSpaceInBytes() { return usedSpaceInBytes; } public void setUsedSpaceInBytes(long usedSpaceInBytes) { this.usedSpaceInBytes = usedSpaceInBytes; } @Override public String toString() {
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.driver.model.fs; public class FsDeviceInfos extends DeviceInfos { private byte[] deviceKey; private long sdCardSizeInBytes; private long usedSpaceInBytes; public byte[] getDeviceKey() { return deviceKey; } public void setDeviceKey(byte[] deviceId) { this.deviceKey = deviceId; } public long getSdCardSizeInBytes() { return sdCardSizeInBytes; } public void setSdCardSizeInBytes(long sdCardSizeInBytes) { this.sdCardSizeInBytes = sdCardSizeInBytes; } public long getUsedSpaceInBytes() { return usedSpaceInBytes; } public void setUsedSpaceInBytes(long usedSpaceInBytes) { this.usedSpaceInBytes = usedSpaceInBytes; } @Override public String toString() {
return "FsDeviceInfos{" + "uuid=" + SecurityUtils.encodeHex(deviceKey) + ", firmwareMajor=" + getFirmwareMajor()
0
2023-12-14 15:08:35+00:00
2k
cworld1/notie
app/src/main/java/com/cworld/notie/fragment/SettingsFragment.java
[ { "identifier": "AboutActivity", "path": "app/src/main/java/com/cworld/notie/AboutActivity.java", "snippet": "public class AboutActivity extends AppCompatActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n EdgeToEdge.enable(this);\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_about);\n\n initTopAppBar(findViewById(R.id.topAppBar));\n initButtons();\n\n // filling the version text\n try {\n PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n String version = packageInfo.versionName;\n String versionFormat = getString(R.string.version_format);\n TextView versionTextview = findViewById(R.id.app_version_textview);\n versionTextview.setText(String.format(versionFormat, version));\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n }\n }\n\n private void initButtons() {\n // about app\n findViewById(R.id.btn_github).setOnClickListener(v ->\n startActivity(new Intent(Intent.ACTION_VIEW,\n Uri.parse(\"https://github.com/cworld1/notie\")))\n );\n findViewById(R.id.btn_email).setOnClickListener(v ->\n startActivity(new Intent(Intent.ACTION_SENDTO,\n Uri.parse(\"mailto:cworld0@qq.com\")))\n );\n\n // donate\n findViewById(R.id.btn_alipay).setOnClickListener(v ->\n startActivity(new Intent(Intent.ACTION_VIEW,\n Uri.parse(\"https://qr.alipay.com/fkx13845ccfsdjyuhvokt47\")))\n );\n\n // author\n findViewById(R.id.author_cworld).setOnClickListener(v ->\n startActivity(new Intent(Intent.ACTION_VIEW,\n Uri.parse(\"http://blog.cworld.top\")))\n );\n }\n\n private void initTopAppBar(@NonNull MaterialToolbar topAppBar) {\n // set click listener\n topAppBar.setNavigationOnClickListener(v -> finish());\n }\n}" }, { "identifier": "PreferenceHelper", "path": "app/src/main/java/com/cworld/notie/util/PreferenceHelper.java", "snippet": "public class PreferenceHelper {\r\n private final SharedPreferences sharedPreferences;\r\n\r\n public PreferenceHelper(Context context) {\r\n sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\r\n }\r\n\r\n // editor\r\n public final int getLineHeight() {\r\n return sharedPreferences.getInt(\"line_height\", 10);\r\n }\r\n\r\n // markdown\r\n public final boolean getPreviewEnabled() {\r\n return sharedPreferences.getBoolean(\"markdown_preview\", false);\r\n }\r\n\r\n public final boolean getHighlightEnabled() {\r\n return sharedPreferences.getBoolean(\"markdown_highlight\", true);\r\n }\r\n\r\n // languages\r\n public static void setApplicationLanguage(@NonNull String language) {\r\n // follow system language\r\n if (language.equals(\"system\"))\r\n language = Locale.getDefault().toLanguageTag();\r\n\r\n // set language\r\n LocaleListCompat appLocale = LocaleListCompat.forLanguageTags(language);\r\n // Call this on the main thread as it may require Activity.restart()\r\n AppCompatDelegate.setApplicationLocales(appLocale);\r\n }\r\n\r\n // others\r\n public static void clickItem(@NonNull Preference preference, Context context, Class<?> cls) {\r\n preference.setOnPreferenceClickListener(preference1 -> {\r\n context.startActivity(new Intent(context, cls));\r\n return true;\r\n });\r\n }\r\n\r\n public static void clickItem(@NonNull Preference preference, Context context, String url) {\r\n preference.setOnPreferenceClickListener(preference1 -> {\r\n context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));\r\n return true;\r\n });\r\n }\r\n}\r" } ]
import android.os.Bundle; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import com.cworld.notie.AboutActivity; import com.cworld.notie.R; import com.cworld.notie.util.PreferenceHelper; import java.util.Objects;
909
package com.cworld.notie.fragment; public class SettingsFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.preferences, rootKey); // click repo
package com.cworld.notie.fragment; public class SettingsFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.preferences, rootKey); // click repo
PreferenceHelper.clickItem(
1
2023-12-09 16:22:05+00:00
2k
wuhit/slash
src/main/java/com/wuhit/core/SshClient.java
[ { "identifier": "Logger", "path": "src/main/java/com/wuhit/Logger.java", "snippet": "public final class Logger {\n\n private String ruciaHome;\n\n private String fileName;\n\n private String separator;\n\n private FileWriter fileWriter;\n\n private void initFileWriter() {\n String parentDir =\n ruciaHome + separator + \"logs\" + separator + LocalDate.now().format(DTFUtil.YYYY_MM_DD);\n File parentDirFile = Paths.get(parentDir).toFile();\n if (parentDirFile.exists() == false) {\n parentDirFile.mkdirs();\n }\n\n String logPath = parentDir + separator + fileName + \".log\";\n\n File logFile = Paths.get(logPath).toFile();\n\n if (logFile.exists() == false) {\n try {\n logFile.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n try {\n fileWriter = new FileWriter(logFile, true);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void write(String log) {\n try {\n fileWriter.write(log + \"\\n\");\n fileWriter.flush();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public void info(String log) {\n log = LocalDateTime.now().format(DTFUtil.YYYY_MM_DD_HH_MM_SS_SSS) + \": \" + log;\n System.out.println(log);\n this.write(log);\n }\n\n public void error(String log) {\n log = LocalDateTime.now().format(DTFUtil.YYYY_MM_DD_HH_MM_SS_SSS) + \": \" + log;\n System.err.println(log);\n this.write(log);\n }\n\n public void destroy() {\n try {\n fileWriter.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public Logger(String ruciaHome, String fileName, String separator) {\n this.ruciaHome = ruciaHome;\n this.fileName = fileName;\n this.separator = separator;\n this.initFileWriter();\n }\n}" }, { "identifier": "SlashException", "path": "src/main/java/com/wuhit/SlashException.java", "snippet": "public class SlashException extends RuntimeException {\n public SlashException(String message) {\n super(message);\n }\n}" }, { "identifier": "StringUtils", "path": "src/main/java/com/wuhit/StringUtils.java", "snippet": "public final class StringUtils {\n public static boolean isNotBlank(String value) {\n return value != null && !value.trim().isEmpty();\n }\n\n public static boolean isBlank(String value) {\n return value == null || value.trim().isEmpty();\n }\n}" }, { "identifier": "UserInfo", "path": "src/main/java/com/wuhit/configure/UserInfo.java", "snippet": "public class UserInfo implements com.jcraft.jsch.UserInfo, UIKeyboardInteractive {\n\n private BaseMFA mfa;\n\n @Override\n public String[] promptKeyboardInteractive(\n String destination, String name, String instruction, String[] prompt, boolean[] echo) {\n\n\n if ((prompt[0].contains(\"OTP Code\") || prompt[0].contains(\"Verification code\")) && mfa != null) {\n System.out.println(STR.\"\\u001B[32m\\{destination} \\{prompt[0]}\\u001B[0m\");\n String otpCode = mfa.otpCode();\n\n String prevOtpCode = OTPCodeStore.get();\n\n if (StringUtils.isBlank(prevOtpCode) || prevOtpCode.equals(otpCode) == false) {\n System.out.println(STR.\"\\u001B[32m\\{otpCode}\\u001B[0m\");\n OTPCodeStore.set(otpCode);\n return new String[]{otpCode};\n }\n }\n\n\n Scanner scanner = new Scanner(System.in);\n System.out.println(STR.\"\\u001B[32m\\{destination} \\{prompt[0]}\\u001B[0m\");\n String input = scanner.nextLine().trim();\n\n return new String[]{input};\n\n }\n\n @Override\n public String getPassphrase() {\n return null;\n }\n\n @Override\n public String getPassword() {\n return null;\n }\n\n @Override\n public boolean promptPassword(String message) {\n return true;\n }\n\n @Override\n public boolean promptPassphrase(String message) {\n return true;\n }\n\n @Override\n public boolean promptYesNo(String message) {\n return true;\n }\n\n @Override\n public void showMessage(String message) {\n System.err.println(message);\n }\n\n public UserInfo(BaseMFA mfa) {\n this.mfa = mfa;\n }\n\n private UserInfo() {\n }\n}" }, { "identifier": "BaseMFA", "path": "src/main/java/com/wuhit/mfa/BaseMFA.java", "snippet": "public abstract class BaseMFA {\n\n private String secret;\n\n\n public abstract String otpCode();\n\n\n public BaseMFA(String secret) {\n this.secret = secret;\n }\n\n private BaseMFA() {\n\n }\n}" }, { "identifier": "GoogleMFA", "path": "src/main/java/com/wuhit/mfa/GoogleMFA.java", "snippet": "public class GoogleMFA extends BaseMFA {\n\n private GoogleAuthenticatorKey key;\n private GoogleAuthenticator auth = new GoogleAuthenticator();\n\n public GoogleMFA(String secret) {\n super(secret);\n key = new GoogleAuthenticatorKey.Builder(secret).build();\n }\n\n public String otpCode() {\n return String.valueOf(auth.getTotpPassword(key.getKey()));\n }\n}" } ]
import com.jcraft.jsch.*; import com.wuhit.Logger; import com.wuhit.SlashException; import com.wuhit.StringUtils; import com.wuhit.configure.*; import com.wuhit.configure.UserInfo; import com.wuhit.mfa.BaseMFA; import com.wuhit.mfa.GoogleMFA; import java.io.ByteArrayOutputStream; import java.io.File; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
1,475
package com.wuhit.core; public class SshClient { private Ssh ssh;
package com.wuhit.core; public class SshClient { private Ssh ssh;
private Logger logger;
0
2023-12-13 03:35:39+00:00
2k
conductor-oss/conductor-community
persistence/mysql-persistence/src/test/java/com/netflix/conductor/mysql/dao/MySQLMetadataDAOTest.java
[ { "identifier": "TestObjectMapperConfiguration", "path": "test-util/src/test/java/com/netflix/conductor/common/config/TestObjectMapperConfiguration.java", "snippet": "@Configuration\npublic class TestObjectMapperConfiguration {\n\n @Bean\n public ObjectMapper testObjectMapper() {\n return new ObjectMapperProvider().getObjectMapper();\n }\n}" }, { "identifier": "MySQLConfiguration", "path": "persistence/mysql-persistence/src/main/java/com/netflix/conductor/mysql/config/MySQLConfiguration.java", "snippet": "@Configuration(proxyBeanMethods = false)\n@EnableConfigurationProperties(MySQLProperties.class)\n@ConditionalOnProperty(name = \"conductor.db.type\", havingValue = \"mysql\")\n// Import the DataSourceAutoConfiguration when mysql database is selected.\n// By default the datasource configuration is excluded in the main module.\n@Import(DataSourceAutoConfiguration.class)\npublic class MySQLConfiguration {\n\n @Bean\n @DependsOn({\"flyway\", \"flywayInitializer\"})\n public MySQLMetadataDAO mySqlMetadataDAO(\n @Qualifier(\"mysqlRetryTemplate\") RetryTemplate retryTemplate,\n ObjectMapper objectMapper,\n DataSource dataSource,\n MySQLProperties properties) {\n return new MySQLMetadataDAO(retryTemplate, objectMapper, dataSource, properties);\n }\n\n @Bean\n @DependsOn({\"flyway\", \"flywayInitializer\"})\n public MySQLExecutionDAO mySqlExecutionDAO(\n @Qualifier(\"mysqlRetryTemplate\") RetryTemplate retryTemplate,\n ObjectMapper objectMapper,\n DataSource dataSource) {\n return new MySQLExecutionDAO(retryTemplate, objectMapper, dataSource);\n }\n\n @Bean\n @DependsOn({\"flyway\", \"flywayInitializer\"})\n public MySQLQueueDAO mySqlQueueDAO(\n @Qualifier(\"mysqlRetryTemplate\") RetryTemplate retryTemplate,\n ObjectMapper objectMapper,\n DataSource dataSource) {\n return new MySQLQueueDAO(retryTemplate, objectMapper, dataSource);\n }\n\n @Bean\n public RetryTemplate mysqlRetryTemplate(MySQLProperties properties) {\n SimpleRetryPolicy retryPolicy = new CustomRetryPolicy();\n retryPolicy.setMaxAttempts(properties.getDeadlockRetryMax());\n\n RetryTemplate retryTemplate = new RetryTemplate();\n retryTemplate.setRetryPolicy(retryPolicy);\n retryTemplate.setBackOffPolicy(new NoBackOffPolicy());\n return retryTemplate;\n }\n\n public static class CustomRetryPolicy extends SimpleRetryPolicy {\n\n @Override\n public boolean canRetry(final RetryContext context) {\n final Optional<Throwable> lastThrowable =\n Optional.ofNullable(context.getLastThrowable());\n return lastThrowable\n .map(throwable -> super.canRetry(context) && isDeadLockError(throwable))\n .orElseGet(() -> super.canRetry(context));\n }\n\n private boolean isDeadLockError(Throwable throwable) {\n SQLException sqlException = findCauseSQLException(throwable);\n if (sqlException == null) {\n return false;\n }\n return ER_LOCK_DEADLOCK == sqlException.getErrorCode();\n }\n\n private SQLException findCauseSQLException(Throwable throwable) {\n Throwable causeException = throwable;\n while (null != causeException && !(causeException instanceof SQLException)) {\n causeException = causeException.getCause();\n }\n return (SQLException) causeException;\n }\n }\n}" } ]
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.lang3.builder.EqualsBuilder; import org.flywaydb.core.Flyway; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.events.EventHandler; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.core.exception.NonTransientException; import com.netflix.conductor.mysql.config.MySQLConfiguration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue;
1,120
/* * <p> * 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 * <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.netflix.conductor.mysql.dao; @ContextConfiguration( classes = {
/* * <p> * 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 * <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.netflix.conductor.mysql.dao; @ContextConfiguration( classes = {
TestObjectMapperConfiguration.class,
0
2023-12-08 06:06:20+00:00
2k
zhouyqxy/aurora_Lite
src/main/java/com/aurora/controller/PhotoController.java
[ { "identifier": "FilePathEnum", "path": "src/main/java/com/aurora/enums/FilePathEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum FilePathEnum {\n\n AVATAR(\"aurora/avatar/\", \"头像路径\"),\n\n ARTICLE(\"aurora/articles/\", \"文章图片路径\"),\n\n VOICE(\"aurora/voice/\", \"音频路径\"),\n\n PHOTO(\"aurora/photos/\", \"相册路径\"),\n\n CONFIG(\"aurora/config/\", \"配置图片路径\"),\n\n TALK(\"aurora/talks/\", \"配置图片路径\"),\n\n MD(\"aurora/markdown/\", \"md文件路径\");\n\n private final String path;\n\n private final String desc;\n\n}" }, { "identifier": "PageResultDTO", "path": "src/main/java/com/aurora/model/dto/PageResultDTO.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class PageResultDTO<T> {\n\n private List<T> records;\n\n private Integer count;\n\n}" }, { "identifier": "PhotoAdminDTO", "path": "src/main/java/com/aurora/model/dto/PhotoAdminDTO.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class PhotoAdminDTO {\n\n private Integer id;\n\n private String photoName;\n\n private String photoDesc;\n\n private String photoSrc;\n\n}" }, { "identifier": "PhotoDTO", "path": "src/main/java/com/aurora/model/dto/PhotoDTO.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class PhotoDTO {\n\n private String photoAlbumCover;\n\n private String photoAlbumName;\n\n private List<String> photos;\n\n}" }, { "identifier": "PhotoService", "path": "src/main/java/com/aurora/service/PhotoService.java", "snippet": "public interface PhotoService extends IService<Photo> {\n\n PageResultDTO<PhotoAdminDTO> listPhotos(ConditionVO conditionVO);\n\n void updatePhoto(PhotoInfoVO photoInfoVO);\n\n void savePhotos(PhotoVO photoVO);\n\n void updatePhotosAlbum(PhotoVO photoVO);\n\n void updatePhotoDelete(DeleteVO deleteVO);\n\n void deletePhotos(List<Integer> photoIds);\n\n PhotoDTO listPhotosByAlbumId(Integer albumId);\n\n}" }, { "identifier": "UploadStrategyContext", "path": "src/main/java/com/aurora/strategy/context/UploadStrategyContext.java", "snippet": "@Service\npublic class UploadStrategyContext {\n\n @Value(\"${upload.mode}\")\n private String uploadMode;\n\n @Autowired\n private Map<String, UploadStrategy> uploadStrategyMap;\n\n public String executeUploadStrategy(MultipartFile file, String path) {\n return uploadStrategyMap.get(getStrategy(uploadMode)).uploadFile(file, path);\n }\n\n public String executeUploadStrategy(String fileName, InputStream inputStream, String path) {\n return uploadStrategyMap.get(getStrategy(uploadMode)).uploadFile(fileName, inputStream, path);\n }\n\n}" }, { "identifier": "OptTypeConstant", "path": "src/main/java/com/aurora/constant/OptTypeConstant.java", "snippet": "public interface OptTypeConstant {\n\n String SAVE_OR_UPDATE = \"新增或修改\";\n\n String SAVE = \"新增\";\n\n String UPDATE = \"修改\";\n\n String DELETE = \"删除\";\n\n String UPLOAD = \"上传\";\n\n String EXPORT = \"导出\";\n\n}" } ]
import com.aurora.annotation.OptLog; import com.aurora.enums.FilePathEnum; import com.aurora.model.dto.PageResultDTO; import com.aurora.model.dto.PhotoAdminDTO; import com.aurora.model.dto.PhotoDTO; import com.aurora.service.PhotoService; import com.aurora.model.vo.*; import com.aurora.strategy.context.UploadStrategyContext; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import java.util.List; import static com.aurora.constant.OptTypeConstant.*;
1,043
package com.aurora.controller; @Api(tags = "照片模块") @RestController public class PhotoController { @Autowired private PhotoService photoService; @Autowired private UploadStrategyContext uploadStrategyContext; @OptLog(optType = UPLOAD) @ApiOperation(value = "上传照片") @ApiImplicitParam(name = "file", value = "照片", required = true, dataType = "MultipartFile") @PostMapping("/admin/photos/upload") public ResultVO<String> savePhotoAlbumCover(MultipartFile file) {
package com.aurora.controller; @Api(tags = "照片模块") @RestController public class PhotoController { @Autowired private PhotoService photoService; @Autowired private UploadStrategyContext uploadStrategyContext; @OptLog(optType = UPLOAD) @ApiOperation(value = "上传照片") @ApiImplicitParam(name = "file", value = "照片", required = true, dataType = "MultipartFile") @PostMapping("/admin/photos/upload") public ResultVO<String> savePhotoAlbumCover(MultipartFile file) {
return ResultVO.ok(uploadStrategyContext.executeUploadStrategy(file, FilePathEnum.PHOTO.getPath()));
0
2023-12-05 03:38:51+00:00
2k
khaHesham/Match-Reservation-System
Api/src/main/java/com/premierleague/reservation/api/service/UserService.java
[ { "identifier": "UserDTO", "path": "Api/src/main/java/com/premierleague/reservation/api/dtos/UserDTO.java", "snippet": "@Setter\n@Getter\npublic class UserDTO implements Serializable {\n\n @Setter\n private Long id;\n\n @Setter\n private String username;\n\n @Setter\n private String firstName;\n\n @Setter\n private String lastName;\n\n @Setter\n private String email;\n\n @Setter\n private String city;\n\n @Setter\n private String birthDate;\n\n @Setter\n private Role role;\n\n @Setter\n private String Address;\n \n}" }, { "identifier": "UnauthorizedException", "path": "Api/src/main/java/com/premierleague/reservation/api/exceptions/UnauthorizedException.java", "snippet": "public class UnauthorizedException extends RuntimeException{\n public UnauthorizedException(String message) {\n super(message);\n }\n}" }, { "identifier": "UserMapper", "path": "Api/src/main/java/com/premierleague/reservation/api/mappers/UserMapper.java", "snippet": "@Mapper(componentModel = \"spring\")\npublic interface UserMapper {\n\n User toEntity(UserDTO userDTO);\n\n UserDTO toDTO(User user);\n\n List<UserDTO> toDTOs(List<User> users);\n}" }, { "identifier": "User", "path": "Api/src/main/java/com/premierleague/reservation/api/models/User.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"users\")\npublic class User implements UserDetails {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id\", nullable = false)\n private Long id;\n\n @Column(name = \"username\", unique = true)\n private String username;\n\n @Column(name = \"first_name\")\n private String firstName;\n\n @Column(name = \"last_name\")\n private String lastName;\n\n @Column(name = \"password\")\n private String password;\n\n @Column(name = \"email\",unique = true)\n private String email;\n\n @Column(name = \"city\")\n private String city;\n\n @Column(name = \"requested_role\")\n private boolean requestedRole = false;\n\n @Column(name = \"birth_date\")\n private String birthDate;\n\n @Column(name = \"address\")\n private String Address;\n\n @Enumerated(EnumType.STRING)\n private Role role;\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return List.of(new SimpleGrantedAuthority(role.name()));\n }\n\n @Override\n public String getPassword() {\n return password;\n }\n\n @Override\n public String getUsername() {\n return username;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n}" }, { "identifier": "Role", "path": "Api/src/main/java/com/premierleague/reservation/api/models/enums/Role.java", "snippet": "@RequiredArgsConstructor\npublic enum Role {\n ADMIN(\n Set.of(\n ADMIN_READ,\n ADMIN_UPDATE,\n ADMIN_DELETE,\n ADMIN_CREATE,\n MANAGER_READ,\n MANAGER_UPDATE,\n MANAGER_DELETE,\n MANAGER_CREATE\n )\n ),\n EFA_MANAGER(\n Set.of(\n MANAGER_READ,\n MANAGER_UPDATE,\n MANAGER_DELETE,\n MANAGER_CREATE\n )\n ),\n GUEST(\n Set.of(\n GUEST_READ\n )\n ),\n USER(\n Set.of(\n USER_READ,\n USER_UPDATE,\n USER_DELETE,\n USER_CREATE\n )\n );\n\n @Getter\n private final Set<Permission> permissions;\n\n public List<SimpleGrantedAuthority> getAuthorities() {\n var authorities = getPermissions()\n .stream()\n .map(permission -> new SimpleGrantedAuthority(permission.getPermission()))\n .collect(Collectors.toList());\n authorities.add(new SimpleGrantedAuthority(\"ROLE_\" + this.name()));\n return authorities;\n }\n\n}" }, { "identifier": "UserRepository", "path": "Api/src/main/java/com/premierleague/reservation/api/repositories/UserRepository.java", "snippet": "@Repository\npublic interface UserRepository extends JpaRepository<User, Long> {\n Optional<User> findUserByUsername(String username);\n Optional<User> findUserByEmail(String email);\n}" } ]
import com.premierleague.reservation.api.dtos.UserDTO; import com.premierleague.reservation.api.exceptions.UnauthorizedException; import com.premierleague.reservation.api.mappers.UserMapper; import com.premierleague.reservation.api.models.User; import com.premierleague.reservation.api.models.enums.Role; import com.premierleague.reservation.api.repositories.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Optional;
1,250
package com.premierleague.reservation.api.service; @Service public class UserService { @Autowired private UserRepository userRepository; @Autowired private UserMapper userMapper; @Autowired private AuthenticationService authenticationService;
package com.premierleague.reservation.api.service; @Service public class UserService { @Autowired private UserRepository userRepository; @Autowired private UserMapper userMapper; @Autowired private AuthenticationService authenticationService;
public UserDTO userProfile(String username) {
0
2023-12-05 18:40:40+00:00
2k
h1alexbel/cdit
src/it/postgres/src/test/java/EntryTest.java
[ { "identifier": "Env", "path": "src/main/java/org/cdit/Env.java", "snippet": "public final class Env implements Scalar<String> {\n\n /**\n * Name.\n */\n private final String name;\n\n /**\n * Value.\n */\n private final String value;\n\n /**\n * Ctor.\n *\n * @param nm Name\n * @param val Value\n */\n public Env(final String nm, final String val) {\n this.name = nm;\n this.value = val;\n }\n\n @Override\n public String value() {\n return \"%s:%s\".formatted(this.name, this.value);\n }\n}" }, { "identifier": "Postgres", "path": "src/main/java/org/cdit/containers/Postgres.java", "snippet": "public final class Postgres extends ContainerEnvelope {\n\n /**\n * Ctor.\n *\n * @param tag Image Tag\n * @param vars Environment Variables\n */\n public Postgres(final String tag, final Env... vars) {\n super(\"postgres:%s\".formatted(tag), vars);\n }\n\n /**\n * Ctor.\n *\n * @param tag Image Tag\n * @param vars Environment Variables\n */\n public Postgres(final String tag, final List<Env> vars) {\n super(\"postgres:%s\".formatted(tag), vars);\n }\n}" } ]
import org.cdit.Env; import org.cdit.containers.Postgres; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer;
861
/* * Copyright (c) 2023 Aliaksei Bialiauski * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO 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. */ /** * Test suite for {@link Postgres}. * * @since 0.0.0 */ final class EntryTest { @Test void runs() { MatcherAssert.assertThat( "Container is not running", new Postgres("16").run() .isRunning(), new IsEqual<>(true) ); } @Test void checksImageName() { MatcherAssert.assertThat( "PostgreSQL image is not in the right format", new Postgres("16.0-bullseye").run().getImage().get(), new IsEqual<>("postgres:16.0-bullseye") ); } @Test void stops() { final GenericContainer<?> started = new Postgres("latest").run(); started.stop(); MatcherAssert.assertThat( "Container is not stopped", started.isRunning(), new IsEqual<>(false) ); } @Test void checksEnvs() { MatcherAssert.assertThat( "Environment Variables are not in the right format", new Postgres( "latest",
/* * Copyright (c) 2023 Aliaksei Bialiauski * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO 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. */ /** * Test suite for {@link Postgres}. * * @since 0.0.0 */ final class EntryTest { @Test void runs() { MatcherAssert.assertThat( "Container is not running", new Postgres("16").run() .isRunning(), new IsEqual<>(true) ); } @Test void checksImageName() { MatcherAssert.assertThat( "PostgreSQL image is not in the right format", new Postgres("16.0-bullseye").run().getImage().get(), new IsEqual<>("postgres:16.0-bullseye") ); } @Test void stops() { final GenericContainer<?> started = new Postgres("latest").run(); started.stop(); MatcherAssert.assertThat( "Container is not stopped", started.isRunning(), new IsEqual<>(false) ); } @Test void checksEnvs() { MatcherAssert.assertThat( "Environment Variables are not in the right format", new Postgres( "latest",
new Env("POSTGRES_USER", "user"),
0
2023-12-06 10:29:59+00:00
2k
blueokanna/ReverseCoin
src/main/java/ReverseCoinBlockChainGeneration/BlockChainConfig.java
[ { "identifier": "ReverseCoinBlock", "path": "src/main/java/BlockModel/ReverseCoinBlock.java", "snippet": "public class ReverseCoinBlock implements Serializable, ReverseCoinBlockInterface {\n\n private static final long serialVersionUID = 1145141919810L;\n private byte version;\n private int index;\n private String PreviousHash;\n private CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsData;\n private String TransactionHash;\n private long TimeStamp;\n private long nonce;\n private int difficulty;\n private String thisBlockHash;\n\n @Override\n public byte getVersion() {\n return version;\n }\n\n @Override\n public void setVersion(byte version) {\n this.version = version;\n }\n\n @Override\n public int getIndex() {\n return index;\n }\n\n @Override\n public void setIndex(int index) {\n this.index = index;\n }\n\n @Override\n public String getPreviousHash() {\n return PreviousHash;\n }\n\n @Override\n public void setPreviousHash(String PreviousHash) {\n this.PreviousHash = PreviousHash;\n }\n\n @Override\n public String getTransactionHash() {\n return TransactionHash;\n }\n\n @Override\n public void setTransactionHash(String TransactionHash) {\n this.TransactionHash = TransactionHash;\n } \n\n @Override\n public CopyOnWriteArrayList<ReverseCoinTransaction> getTransactionsData() {\n return TransactionsData;\n }\n\n @Override\n public void setTransactionsData(CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsData) {\n this.TransactionsData = TransactionsData;\n }\n\n @Override\n public long getTimeStamp() {\n return TimeStamp;\n }\n\n @Override\n public void setTimeStamp(long TimeStamp) {\n this.TimeStamp = TimeStamp;\n }\n\n @Override\n public int getDifficulty() {\n return difficulty;\n }\n\n @Override\n public void setDifficulty(int difficulty) {\n this.difficulty = difficulty;\n }\n\n @Override\n public long getNonce() {\n return nonce;\n }\n\n @Override\n public void setNonce(long nonce) {\n this.nonce = nonce;\n }\n\n @Override\n public String getThisBlockHash() {\n return thisBlockHash;\n }\n\n @Override\n public void setThisBlockHash(String thisBlockHash) {\n this.thisBlockHash = thisBlockHash;\n }\n\n @Override\n public String toBlockJsonString(ReverseCoinBlock blocks) {\n return new GsonBuilder().create().toJson(blocks);\n }\n\n}" }, { "identifier": "ReverseCoinTransaction", "path": "src/main/java/BlockModel/ReverseCoinTransaction.java", "snippet": "public class ReverseCoinTransaction implements Serializable ,TransactionInterface{\n\n private static final long serialVersionUID = 1145141919810L;\n private String Sender;\n private String receiver;\n private double amount;\n private double Txfee;\n private String signature;\n\n public ReverseCoinTransaction() {\n\n }\n public ReverseCoinTransaction(String Sender, String receiver, double amount, double Txfee) {\n this.Sender = Sender;\n this.receiver = receiver;\n this.amount = amount;\n this.Txfee = Txfee;\n }\n public ReverseCoinTransaction(String Sender, String receiver, double amount, double Txfee, String signature) {\n this.Sender = Sender;\n this.receiver = receiver;\n this.amount = amount;\n this.Txfee = Txfee;\n this.signature = signature;\n }\n\n private LinkedHashMap<String, Object> JsonMap() {\n LinkedHashMap<String, Object> map = new LinkedHashMap<>();\n map.put(\"Sender\", Sender);\n map.put(\"Receiver\", receiver);\n map.put(\"Amount\", amount);\n map.put(\"GasFee\", Txfee);\n map.put(\"Signature\", signature);\n return map;\n }\n\n @Override\n public String getSender() {\n return Sender;\n }\n\n @Override\n public void setSender(String Sender) {\n this.Sender = Sender;\n }\n\n @Override\n public String getReceiver() {\n return receiver;\n }\n\n @Override\n public void setReceiver(String receiver) {\n this.receiver = receiver;\n }\n\n @Override\n public double getAmount() {\n return amount;\n }\n\n @Override\n public void setAmount(double amount) {\n this.amount = amount;\n }\n\n @Override\n public double getTxfee() {\n return Txfee;\n }\n\n @Override\n public void setTxfee(double Txfee) {\n this.Txfee = Txfee;\n }\n\n @Override\n public String getSignature() {\n return signature;\n }\n\n @Override\n public void setSignature(String signature) {\n this.signature = signature;\n }\n\n @Override\n public String toJsonTransactionString() {\n Gson gson = new GsonBuilder().setPrettyPrinting().create();\n return gson.toJson(JsonMap());\n }\n\n}" }, { "identifier": "ReverseCoinChainConfigInterface", "path": "src/main/java/ConnectionAPI/ReverseCoinChainConfigInterface.java", "snippet": "public interface ReverseCoinChainConfigInterface {\n\n int getDifficulty();\n\n int getPorts();\n\n String getAddressPort();\n\n CopyOnWriteArrayList<ReverseCoinBlock> getBlockList();\n\n CopyOnWriteArrayList<ReverseCoinTransaction> getTransactionsList();\n\n CopyOnWriteArrayList<WebSocket> getSocketsList();\n\n ReverseCoinBlock getLatestBlock();\n \n String SHA3with256Hash(String input);\n\n void setDifficulty(int difficulty);\n\n void setPorts(int ports);\n\n void setAddressPort(String AddressPort);\n\n void setBlockList(CopyOnWriteArrayList<ReverseCoinBlock> BlockList);\n\n void setTransactionsList(CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsList);\n\n void setSocketsList(CopyOnWriteArrayList<WebSocket> socketsList);\n}" } ]
import BlockModel.ReverseCoinBlock; import BlockModel.ReverseCoinTransaction; import org.bouncycastle.crypto.digests.SHA3Digest; import org.bouncycastle.util.encoders.Hex; import org.java_websocket.WebSocket; import java.util.concurrent.CopyOnWriteArrayList; import ConnectionAPI.ReverseCoinChainConfigInterface;
1,593
package ReverseCoinBlockChainGeneration; public class BlockChainConfig implements ReverseCoinChainConfigInterface { private volatile CopyOnWriteArrayList<ReverseCoinBlock> BlockList = new CopyOnWriteArrayList<>();
package ReverseCoinBlockChainGeneration; public class BlockChainConfig implements ReverseCoinChainConfigInterface { private volatile CopyOnWriteArrayList<ReverseCoinBlock> BlockList = new CopyOnWriteArrayList<>();
private volatile CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsList = new CopyOnWriteArrayList<>();
1
2023-12-11 05:18:04+00:00
2k
Patbox/PolyDecorations
src/main/java/eu/pb4/polydecorations/polydex/PolydexCompatImpl.java
[ { "identifier": "GuiTextures", "path": "src/main/java/eu/pb4/polydecorations/ui/GuiTextures.java", "snippet": "public class GuiTextures {\n public static final GuiElement EMPTY = icon16(\"empty\").get().build();\n public static final Function<Text, Text> SHELF = background(\"shelf\");\n\n public static final Supplier<GuiElementBuilder> POLYDEX_BUTTON = icon32(\"polydex\");\n\n public static void register() {\n PolydexTextures.register();\n }\n\n\n public record Progress(GuiElement[] elements) {\n\n public GuiElement get(float progress) {\n return elements[Math.min((int) (progress * elements.length), elements.length - 1)];\n }\n\n public static Progress createVertical(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = verticalProgress16(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress16(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal32(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress32(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal32Right(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress32Right(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n public static Progress createVertical32Right(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = verticalProgress32Right(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n }\n\n}" }, { "identifier": "GuiUtils", "path": "src/main/java/eu/pb4/polydecorations/ui/GuiUtils.java", "snippet": "public class GuiUtils {\n public static final GuiElement EMPTY = GuiElement.EMPTY;\n\n public static final void playClickSound(ServerPlayerEntity player) {\n player.playSound(SoundEvents.UI_BUTTON_CLICK.value(), SoundCategory.MASTER, 0.5f, 1);\n }\n}" } ]
import eu.pb4.polydex.api.v1.recipe.*; import eu.pb4.factorytools.api.recipe.CountedIngredient; import eu.pb4.factorytools.api.recipe.OutputStack; import eu.pb4.polydecorations.ui.GuiTextures; import eu.pb4.polydecorations.ui.GuiUtils; import eu.pb4.sgui.api.elements.GuiElement; import net.minecraft.recipe.RecipeType; import net.minecraft.text.Text; import java.util.ArrayList; import java.util.List;
1,018
package eu.pb4.polydecorations.polydex; public class PolydexCompatImpl { public static void register() { } public static GuiElement getButton(RecipeType<?> type) { var category = PolydexCategory.of(type);
package eu.pb4.polydecorations.polydex; public class PolydexCompatImpl { public static void register() { } public static GuiElement getButton(RecipeType<?> type) { var category = PolydexCategory.of(type);
return GuiTextures.POLYDEX_BUTTON.get()
0
2023-12-10 16:20:36+00:00
2k
i-moonlight/Suricate
src/main/java/com/michelin/suricate/controllers/AssetController.java
[ { "identifier": "ApiErrorDto", "path": "src/main/java/com/michelin/suricate/model/dto/api/error/ApiErrorDto.java", "snippet": "@Data\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = false)\n@Schema(description = \"Api error response\")\npublic class ApiErrorDto extends AbstractDto {\n @Schema(description = \"Error message\")\n private String message;\n\n @Schema(description = \"Error key\")\n private String key;\n\n @Schema(description = \"HttpStatus number\", example = \"1\")\n private int status;\n\n @Schema(description = \"Date of the error\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private Date timestamp;\n\n /**\n * Constructor.\n *\n * @param apiErrorEnum The api error enum\n */\n public ApiErrorDto(ApiErrorEnum apiErrorEnum) {\n this.message = apiErrorEnum.getMessage();\n this.key = apiErrorEnum.getKey();\n this.timestamp = new Date();\n this.status = apiErrorEnum.getStatus().value();\n }\n\n public ApiErrorDto(String message, ApiErrorEnum apiError) {\n this(apiError);\n this.message = StringUtils.isBlank(message) ? apiError.getMessage() : message;\n }\n}" }, { "identifier": "Asset", "path": "src/main/java/com/michelin/suricate/model/entities/Asset.java", "snippet": "@Entity\n@Getter\n@Setter\n@ToString(callSuper = true)\n@NoArgsConstructor\npublic class Asset extends AbstractAuditingEntity<Long> {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @ToString.Exclude\n @JdbcTypeCode(Types.BINARY)\n @Basic(fetch = FetchType.LAZY)\n @Column(nullable = false)\n private byte[] content;\n\n @Column(length = 100)\n private String contentType;\n\n @Column\n private long size;\n\n public void setContent(byte[] content) {\n this.content = content;\n this.size = content.length;\n }\n\n /**\n * Hashcode method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Hashcode method\n *\n * @return The hash code\n */\n @Override\n public int hashCode() {\n return super.hashCode();\n }\n\n /**\n * Equals method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Equals method\n *\n * @param other The other object to compare\n * @return true if equals, false otherwise\n */\n @Override\n public boolean equals(Object other) {\n return super.equals(other);\n }\n}" }, { "identifier": "AssetService", "path": "src/main/java/com/michelin/suricate/services/api/AssetService.java", "snippet": "@Service\npublic class AssetService {\n @Autowired\n private AssetRepository assetRepository;\n\n /**\n * Find an asset by ID.\n *\n * @param token the asset token used to identify the asset\n * @return The related asset\n */\n public Asset getAssetById(final String token) {\n Optional<Asset> assetOptional = assetRepository.findById(IdUtils.decrypt(token));\n\n if (assetOptional.isEmpty()) {\n throw new ObjectNotFoundException(Asset.class, token);\n }\n\n return assetOptional.get();\n }\n\n /**\n * Save an asset.\n *\n * @param asset The asset to save\n * @return The saved asset\n */\n public Asset save(Asset asset) {\n return assetRepository.save(asset);\n }\n}" } ]
import com.michelin.suricate.model.dto.api.error.ApiErrorDto; import com.michelin.suricate.model.entities.Asset; import com.michelin.suricate.services.api.AssetService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.CacheControl; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest;
1,251
/* * * * Copyright 2012-2021 the original author or authors. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * 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.michelin.suricate.controllers; /** * Asset controller. */ @RestController @RequestMapping("/api")
/* * * * Copyright 2012-2021 the original author or authors. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * 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.michelin.suricate.controllers; /** * Asset controller. */ @RestController @RequestMapping("/api")
@Tag(name = "Asset", description = "Asset Controller")
1
2023-12-11 11:28:37+00:00
2k
NaerQAQ/js4bukkit
src/main/java/org/js4bukkit/io/config/ConfigManager.java
[ { "identifier": "Js4Bukkit", "path": "src/main/java/org/js4bukkit/Js4Bukkit.java", "snippet": "public class Js4Bukkit extends JavaPlugin {\n /**\n * 实例。\n */\n @Getter\n @Setter\n private static Js4Bukkit instance;\n\n /**\n * 服务器版本。\n */\n @Getter\n @Setter\n private static Double serverVersion;\n\n /**\n * 插件配置文件夹路径。\n */\n @Getter\n @Setter\n private static String dataFolderAbsolutePath;\n\n @Getter\n @Setter\n private static String nmsVersion;\n\n /**\n * 插件开启。\n *\n * @author 2000000\n */\n @Override\n @SneakyThrows\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n public void onEnable() {\n setInstance(this);\n setDataFolderAbsolutePath(getDataFolder().getAbsolutePath());\n\n String serverPackage =\n getServer().getClass().getPackage().getName();\n\n setNmsVersion(\n serverPackage.replace(\".\", \",\").split(\",\")[3]\n );\n\n String[] arrayVersion = StringUtils.substringsBetween(\n serverPackage, \".v\", \"_R\"\n );\n\n String stringVersion = Arrays.toString(arrayVersion)\n .replace(\"_\", \"0\")\n .replace(\"[\", \"\")\n .replace(\"]\", \"\");\n\n setServerVersion(\n Double.parseDouble(stringVersion)\n );\n\n // 配置文件与注解处理\n ConfigManager.getConfig();\n AnnotatedClassProcessor.processAnnotatedClasses();\n\n // Maven 依赖与外部依赖加载\n MavenDependencyLoader.download();\n ThirdPartyJarLoader.load();\n\n // 脚本注册\n ScriptHandler.registerScripts();\n }\n\n /**\n * 插件卸载。\n *\n * @author 2000000\n */\n @Override\n public void onDisable() {\n ScriptHandler.unloadScripts();\n\n QuickUtils.sendMessage(\n ConsoleMessageTypeEnum.NORMAL,\n \"Plugin has been disabled.\"\n );\n }\n}" }, { "identifier": "YamlManager", "path": "src/main/java/org/js4bukkit/io/file/impl/YamlManager.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class YamlManager implements FileManagerInterface<Yaml> {\n /**\n * {@link YamlManager} 实例。\n *\n * <p>\n * 此处使用 {@link Getter} 注解生成对应 getter 方法。\n * </p>\n */\n @Getter\n private static final YamlManager instance = new YamlManager();\n\n /**\n * {@code Yaml} 文件后缀常量。\n */\n private static final String YAML_FILE_EXTENSION = \".yml\";\n\n /**\n * 通过文件名与路径获取一个 {@link Yaml} 对象。\n *\n * <p>\n * 使用此方法生成的 {@link Yaml} 对象其重载属性为 {@link ReloadSettings#AUTOMATICALLY},将会在内容更改后自动重载。\n * </p>\n *\n * @param name 文件名\n * @param path 文件路径\n * @param inputStreamFromResource 是否从资源内获取输入流\n * @return {@link Yaml}\n */\n @Override\n public Yaml get(String name, String path, boolean inputStreamFromResource) {\n if (name.contains(YAML_FILE_EXTENSION)) {\n name = name.split(YAML_FILE_EXTENSION)[0];\n }\n\n File file = new File(path, name + YAML_FILE_EXTENSION);\n\n if (file.exists() && inputStreamFromResource) {\n inputStreamFromResource = false;\n }\n\n SimplixBuilder simplixBuilder = SimplixBuilder.fromFile(file)\n .setDataType(DataType.SORTED)\n .setConfigSettings(ConfigSettings.PRESERVE_COMMENTS)\n .setReloadSettings(ReloadSettings.AUTOMATICALLY);\n\n if (inputStreamFromResource) {\n simplixBuilder.addInputStreamFromResource(name + YAML_FILE_EXTENSION);\n }\n\n return simplixBuilder.createYaml();\n }\n}" } ]
import de.leonhard.storage.Yaml; import lombok.*; import org.apache.commons.io.FileUtils; import org.js4bukkit.Js4Bukkit; import org.js4bukkit.io.file.impl.YamlManager; import java.io.File; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile;
1,227
package org.js4bukkit.io.config; /** * 配置文件管理类。 * * <p> * 该类提供配置文件的创建、获取等等。 * </p> * * @author NaerQAQ * @version 1.0 * @since 2023/7/29 */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ConfigManager { static { loadConfigs("configs"); loadConfigs("plugins"); } /** * {@code config.yml} 配置文件实例。 */ @Getter
package org.js4bukkit.io.config; /** * 配置文件管理类。 * * <p> * 该类提供配置文件的创建、获取等等。 * </p> * * @author NaerQAQ * @version 1.0 * @since 2023/7/29 */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ConfigManager { static { loadConfigs("configs"); loadConfigs("plugins"); } /** * {@code config.yml} 配置文件实例。 */ @Getter
private static final Yaml config = YamlManager.getInstance().get(
1
2023-12-14 13:50:24+00:00
2k
Rainnny7/Feather
src/main/java/me/braydon/feather/database/Repository.java
[ { "identifier": "FeatherSettings", "path": "src/main/java/me/braydon/feather/FeatherSettings.java", "snippet": "public final class FeatherSettings {\n /**\n * The {@link Gson} instance to use for serialization.\n */\n @Setter @Getter private static Gson gson = new GsonBuilder()\n .serializeNulls()\n .create();\n}" }, { "identifier": "FieldUtils", "path": "src/main/java/me/braydon/feather/common/FieldUtils.java", "snippet": "@UtilityClass\npublic final class FieldUtils {\n /**\n * Extract the key to use for the given field.\n *\n * @param field the field to get the key from\n * @return the key for the field\n */\n @NonNull\n public static String extractKey(@NonNull Field field) {\n boolean idField = field.isAnnotationPresent(Id.class); // Is this field annotated with @Id?\n me.braydon.feather.annotation.Field annotation = field.getAnnotation(me.braydon.feather.annotation.Field.class); // Get the @Field annotation\n String key = idField ? field.getAnnotation(Id.class).key() : annotation.key(); // The key of the database field\n if (key.isEmpty()) { // No field in the annotation, use the field name\n key = field.getName();\n }\n return key;\n }\n}" } ]
import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NonNull; import me.braydon.feather.FeatherSettings; import me.braydon.feather.annotation.Serializable; import me.braydon.feather.common.FieldUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; import java.util.UUID;
1,080
/* * Copyright (c) 2023 Braydon (Rainnny). All rights reserved. * * For inquiries, please contact braydonrainnny@gmail.com */ package me.braydon.feather.database; /** * A repository belonging to a {@link IDatabase}. * * @author Braydon * @param <D> the database this repository uses * @param <ID> the identifier for type for entities * @param <E> the entity type this repository stores */ @AllArgsConstructor @Getter(AccessLevel.PROTECTED) public abstract class Repository<D extends IDatabase<?, ?>, ID, E> { /** * The database this repository belongs to. * * @see D for database */ @NonNull private final D database; /** * The class for the entity this repository uses. * * @see E for entity */ @NonNull private final Class<? extends E> entityClass; /** * Get the entity with the given id. * * @param id the entity id * @return the entity with the id, null if none * @see ID for id * @see E for entity */ public abstract E find(@NonNull ID id); /** * Get all entities within this repository. * * @return the entities * @see E for entity */ public abstract List<E> findAll(); /** * Save the given entity to the database. * * @param entity the entity to save * @see E for entity */ public void save(@NonNull E entity) { saveAll(entity); } /** * Save the given entities. * * @param entities the entities to save * @see E for entity */ public abstract void saveAll(@NonNull E... entities); /** * Get the amount of stored entities. * * @return the amount of stored entities * @see E for entity */ public abstract long count(); /** * Drop the entity with the given id. * * @param id the entity id to drop * @see ID for id * @see E for entity */ public abstract void dropById(@NonNull ID id); /** * Drop the given entity. * * @param entity the entity to drop * @see E for entity */ public abstract void drop(@NonNull E entity); /** * Construct a new entity from the given mapped data. * * @param mappedData the mapped data to parse * @return the created entity, null if none * @see E for entity */ protected final E newEntity(Map<String, ?> mappedData) { if (mappedData == null) { // No mapped data given return null; } try { Constructor<? extends E> constructor = entityClass.getConstructor(); // Get the no args constructor E entity = constructor.newInstance(); // Create the entity // Get the field tagged with @Id for (Field field : entityClass.getDeclaredFields()) {
/* * Copyright (c) 2023 Braydon (Rainnny). All rights reserved. * * For inquiries, please contact braydonrainnny@gmail.com */ package me.braydon.feather.database; /** * A repository belonging to a {@link IDatabase}. * * @author Braydon * @param <D> the database this repository uses * @param <ID> the identifier for type for entities * @param <E> the entity type this repository stores */ @AllArgsConstructor @Getter(AccessLevel.PROTECTED) public abstract class Repository<D extends IDatabase<?, ?>, ID, E> { /** * The database this repository belongs to. * * @see D for database */ @NonNull private final D database; /** * The class for the entity this repository uses. * * @see E for entity */ @NonNull private final Class<? extends E> entityClass; /** * Get the entity with the given id. * * @param id the entity id * @return the entity with the id, null if none * @see ID for id * @see E for entity */ public abstract E find(@NonNull ID id); /** * Get all entities within this repository. * * @return the entities * @see E for entity */ public abstract List<E> findAll(); /** * Save the given entity to the database. * * @param entity the entity to save * @see E for entity */ public void save(@NonNull E entity) { saveAll(entity); } /** * Save the given entities. * * @param entities the entities to save * @see E for entity */ public abstract void saveAll(@NonNull E... entities); /** * Get the amount of stored entities. * * @return the amount of stored entities * @see E for entity */ public abstract long count(); /** * Drop the entity with the given id. * * @param id the entity id to drop * @see ID for id * @see E for entity */ public abstract void dropById(@NonNull ID id); /** * Drop the given entity. * * @param entity the entity to drop * @see E for entity */ public abstract void drop(@NonNull E entity); /** * Construct a new entity from the given mapped data. * * @param mappedData the mapped data to parse * @return the created entity, null if none * @see E for entity */ protected final E newEntity(Map<String, ?> mappedData) { if (mappedData == null) { // No mapped data given return null; } try { Constructor<? extends E> constructor = entityClass.getConstructor(); // Get the no args constructor E entity = constructor.newInstance(); // Create the entity // Get the field tagged with @Id for (Field field : entityClass.getDeclaredFields()) {
String key = FieldUtils.extractKey(field); // The key of the database field
1
2023-12-12 04:20:32+00:00
2k
xyzbtw/boze-anti-6b6t
src/main/java/com/example/addon/ExampleAddon.java
[ { "identifier": "ExampleAddonDispatcher", "path": "src/main/java/com/example/addon/impl/ExampleAddonDispatcher.java", "snippet": "public class ExampleAddonDispatcher implements AddonDispatcher {\n private final CommandDispatcher<CommandSource> DISPATCHER = new CommandDispatcher<>();\n\n @Override\n public CommandDispatcher<CommandSource> getDispatcher() {\n return DISPATCHER;\n }\n\n @Override\n public String getPrefix() {\n return \"example\";\n }\n}" }, { "identifier": "ExampleAddonModule", "path": "src/main/java/com/example/addon/impl/ExampleAddonModule.java", "snippet": "public abstract class ExampleAddonModule implements AddonModule, ModuleInfo, Serializable<ExampleAddonModule> {\n\n private boolean state;\n private Bind bind;\n\n private final String name;\n private String title;\n private final String description;\n\n protected final ArrayList<AddonElement> elements = new ArrayList<>();\n\n public ExampleAddonModule(String name, String title, String description) {\n this.name = name;\n this.title = title;\n this.description = description;\n\n this.state = false;\n this.bind = new ExampleAddonBind(-1, false);\n }\n\n @Override\n public ModuleInfo getInfo() {\n return this;\n }\n\n @Override\n public List<AddonElement> getElements() {\n return elements;\n }\n\n @Override\n public JsonObject toJson() {\n JsonObject object = new JsonObject();\n object.addProperty(\"title\", name);\n\n for (AddonElement element : elements) {\n if (element instanceof Serializable) {\n object.add(element.getName(), ((Serializable<?>) element).toJson());\n }\n }\n\n return object;\n }\n\n @Override\n public ExampleAddonModule fromJson(JsonObject jsonObject) {\n title = jsonObject.get(\"title\").getAsString();\n\n for (AddonElement element : elements) {\n if (element instanceof Serializable) {\n ((Serializable<?>) element).fromJson(jsonObject.get(element.getName()).getAsJsonObject());\n }\n }\n\n return this;\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public String getTitle() {\n return title;\n }\n\n @Override\n public String getDescription() {\n return description;\n }\n\n @Override\n public boolean getState() {\n return state;\n }\n\n @Override\n public boolean setState(boolean newState) {\n if (state != newState) {\n state = newState;\n\n if (state) {\n BozeInstance.INSTANCE.subscribe(this);\n } else {\n BozeInstance.INSTANCE.unsubscribe(this);\n }\n\n return true;\n }\n return false;\n }\n\n @Override\n public Bind getBind() {\n return bind;\n }\n\n @Override\n public void setBind(Bind bind) {\n this.bind = bind;\n }\n}" } ]
import com.example.addon.impl.ExampleAddonDispatcher; import com.example.addon.impl.ExampleAddonModule; import com.google.gson.JsonObject; import dev.boze.api.BozeInstance; import dev.boze.api.Globals; import dev.boze.api.addon.Addon; import dev.boze.api.addon.AddonMetadata; import dev.boze.api.addon.AddonVersion; import dev.boze.api.addon.command.AddonDispatcher; import dev.boze.api.addon.module.AddonModule; import dev.boze.api.config.Serializable; import dev.boze.api.exception.AddonInitializationException; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.impl.util.log.Log; import net.fabricmc.loader.impl.util.log.LogCategory; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ServerInfo; import net.minecraft.client.option.ServerList; import java.util.ArrayList; import java.util.List;
990
package com.example.addon; public class ExampleAddon implements ModInitializer, Addon, Serializable<ExampleAddon> { public final AddonMetadata metadata = new AddonMetadata( "example-addon", "Example Addon", "An example addon for Boze", new AddonVersion(1, 0, 0)); private final ArrayList<AddonModule> modules = new ArrayList<>();
package com.example.addon; public class ExampleAddon implements ModInitializer, Addon, Serializable<ExampleAddon> { public final AddonMetadata metadata = new AddonMetadata( "example-addon", "Example Addon", "An example addon for Boze", new AddonVersion(1, 0, 0)); private final ArrayList<AddonModule> modules = new ArrayList<>();
private ExampleAddonDispatcher dispatcher;
0
2023-12-06 21:02:03+00:00
2k
litongjava/ai-server
whisper-asr/whisper-asr-service/src/main/java/com/litongjava/ai/server/single/LocalWhisper.java
[ { "identifier": "WhisperSegment", "path": "whisper-asr/whisper-asr-service/src/main/java/com/litongjava/ai/server/model/WhisperSegment.java", "snippet": "public class WhisperSegment {\n private long start, end;\n private String sentence;\n\n public WhisperSegment() {\n }\n\n public WhisperSegment(long start, long end, String sentence) {\n this.start = start;\n this.end = end;\n this.sentence = sentence;\n }\n\n public long getStart() {\n return start;\n }\n\n public long getEnd() {\n return end;\n }\n\n public String getSentence() {\n return sentence;\n }\n\n public void setStart(long start) {\n this.start = start;\n }\n\n public void setEnd(long end) {\n this.end = end;\n }\n\n public void setSentence(String sentence) {\n this.sentence = sentence;\n }\n\n @Override\n public String toString() {\n return \"[\" + start + \" --> \" + end + \"]:\" + sentence;\n }\n}" }, { "identifier": "WhiserAsrProperties", "path": "whisper-asr/whisper-asr-service/src/main/java/com/litongjava/ai/server/property/WhiserAsrProperties.java", "snippet": "@Data\n@NoArgsConstructor\npublic class WhiserAsrProperties {\n private String modelName = \"ggml-base.en.bin\";\n}" }, { "identifier": "WhisperCppJni", "path": "whisper-asr/whisper-asr-service/src/main/java/com/litongjava/ai/server/service/WhisperCppJni.java", "snippet": "public class WhisperCppJni {\n\n private WhisperJNI whisper = null;\n private WhisperContext ctx = null;\n\n public void initContext(Path path) throws IOException {\n whisper = new WhisperJNI();\n ctx = whisper.init(path);\n }\n\n public List<WhisperSegment> fullTranscribeWithTime(WhisperFullParams params, float[] samples, int numSamples) {\n int result = whisper.full(ctx, params, samples, numSamples);\n if (result != 0) {\n throw new RuntimeException(\"Transcription failed with code \" + result);\n }\n int numSegments = whisper.fullNSegments(ctx);\n ArrayList<WhisperSegment> segments = new ArrayList<WhisperSegment>(numSegments);\n\n for (int i = 0; i < numSegments; i++) {\n String text = whisper.fullGetSegmentText(ctx, i);\n long start = whisper.fullGetSegmentTimestamp0(ctx, i);\n long end = whisper.fullGetSegmentTimestamp1(ctx, i);\n segments.add(new WhisperSegment(start, end, text));\n }\n return segments;\n }\n\n public void close() {\n ctx.close();\n }\n}" } ]
import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import com.litongjava.ai.server.model.WhisperSegment; import com.litongjava.ai.server.property.WhiserAsrProperties; import com.litongjava.ai.server.service.WhisperCppJni; import com.litongjava.ai.server.utils.WhisperExecutorServiceUtils; import com.litongjava.jfinal.aop.Aop; import io.github.givimad.whisperjni.WhisperFullParams; import io.github.givimad.whisperjni.WhisperJNI; import lombok.extern.slf4j.Slf4j;
1,024
package com.litongjava.ai.server.single; @Slf4j public enum LocalWhisper { INSTANCE; private ThreadLocal<WhisperCppJni> threadLocalWhisper; private WhisperFullParams defaultPararams = new WhisperFullParams(); LocalWhisper() { try { WhisperJNI.loadLibrary(); } catch (IOException e1) { e1.printStackTrace(); } // C:\Users\Administrator\.cache\whisper String userHome = System.getProperty("user.home"); String modelName = Aop.get(WhiserAsrProperties.class).getModelName(); Path path = Paths.get(userHome, ".cache", "whisper", modelName); threadLocalWhisper = ThreadLocal.withInitial(() -> { WhisperCppJni whisper = new WhisperCppJni(); try { whisper.initContext(path); } catch (IOException e) { e.printStackTrace(); } return whisper; }); defaultPararams.printProgress = false; }
package com.litongjava.ai.server.single; @Slf4j public enum LocalWhisper { INSTANCE; private ThreadLocal<WhisperCppJni> threadLocalWhisper; private WhisperFullParams defaultPararams = new WhisperFullParams(); LocalWhisper() { try { WhisperJNI.loadLibrary(); } catch (IOException e1) { e1.printStackTrace(); } // C:\Users\Administrator\.cache\whisper String userHome = System.getProperty("user.home"); String modelName = Aop.get(WhiserAsrProperties.class).getModelName(); Path path = Paths.get(userHome, ".cache", "whisper", modelName); threadLocalWhisper = ThreadLocal.withInitial(() -> { WhisperCppJni whisper = new WhisperCppJni(); try { whisper.initContext(path); } catch (IOException e) { e.printStackTrace(); } return whisper; }); defaultPararams.printProgress = false; }
public List<WhisperSegment> fullTranscribeWithTime(float[] audioData, int numSamples, WhisperFullParams params) {
0
2023-12-13 15:12:36+00:00
2k
i-moonlight/Beluga
server/src/main/java/com/amnesica/belugaproject/services/data/RangeDataService.java
[ { "identifier": "StaticValues", "path": "server/src/main/java/com/amnesica/belugaproject/config/StaticValues.java", "snippet": "public class StaticValues {\n // Lokale Feeder - Scheduler\n public static final int INTERVAL_UPDATE_LOCAL_FEEDER = 2000; // 2 Sekunden\n public static final int INTERVAL_LOCAL_PLANES_TO_HISTORY = 600000; // 10 Minuten\n public static final int INTERVAL_REMOVE_OLD_TRAILS_LOCAL = 600000; // 10 Minuten\n public static final long INTERVAL_REMOVE_OLD_DATA = 2592000000L; // 30 Tage\n public static final String INTERVAL_REMOVE_OLD_TRAILS_FROM_HISTORY = \"0 0 2 * * ?\"; // cron expression: every day at 02:00 a.m.\n public static final int RETENTION_DAYS_TRAILS_IN_HISTORY = 2; // 2 Tage\n public static final String INTERVAL_REMOVE_OLD_AIRCRAFT_FROM_HISTORY = \"0 0 1 * * ?\"; // cron expression: every day at 01:00 a.m.\n public static final int RETENTION_DAYS_AIRCRAFT_IN_HISTORY = 30; // 30 Tage\n\n // Opensky-Network - Scheduler\n public static final int INTERVAL_UPDATE_OPENSKY = 5000; // 5 Sekunden\n public static final int INTERVAL_REMOVE_OLD_PLANES_OPENSKY = 600000; // 10 Minuten\n\n // ISS - Scheduler\n public static final int INTERVAL_UPDATE_ISS = 2000; // 2 Sekunden\n public static final int INTERVAL_REMOVE_OLD_TRAILS_ISS = 600000; // 10 Minuten\n}" }, { "identifier": "Aircraft", "path": "server/src/main/java/com/amnesica/belugaproject/entities/aircraft/Aircraft.java", "snippet": "@Entity\n@Table(name = \"aircraft\")\npublic class Aircraft extends AircraftSuperclass {\n\n public Aircraft() {\n // Benötiger, leerer Konstruktor\n }\n\n public Aircraft(String hex, Double latitude, Double longitude) {\n super(hex, latitude, longitude);\n }\n}" }, { "identifier": "RangeData", "path": "server/src/main/java/com/amnesica/belugaproject/entities/data/RangeData.java", "snippet": "@Data\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@Entity\npublic class RangeData {\n\n @Id\n @GeneratedValue\n private long id;\n private String hex;\n private Double latitude;\n private Double longitude;\n private Double distance;\n private Integer altitude;\n private String type;\n private String category;\n private String registration;\n private String flightId;\n private Long timestamp;\n\n // Liste mit Feeder, welches Flugzeug zur Zeit empfangen\n @Type(type = \"list-array\")\n @Column(name = \"feeder_list\", columnDefinition = \"text[]\")\n private List<String> feederList;\n\n // Quelle (ADS-B oder MLAT)\n @Type(type = \"list-array\")\n @Column(name = \"source_list\", columnDefinition = \"text[]\")\n private List<String> sourceList;\n\n public RangeData(String hex, Double latitude, Double longitude, Double distance, Integer altitude, String type, String category, String registration, String flightId, Long timestamp, List<String> feederList, List<String> sourceList) {\n this.hex = hex;\n this.latitude = latitude;\n this.longitude = longitude;\n this.distance = distance;\n this.altitude = altitude;\n this.type = type;\n this.category = category;\n this.registration = registration;\n this.flightId = flightId;\n this.timestamp = timestamp;\n this.feederList = feederList;\n this.sourceList = sourceList;\n }\n\n public RangeData() {\n // Benötigter, leerer Konstruktor\n }\n}" }, { "identifier": "RangeDataRepository", "path": "server/src/main/java/com/amnesica/belugaproject/repositories/data/RangeDataRepository.java", "snippet": "@Repository\npublic interface RangeDataRepository extends CrudRepository<RangeData, String> {\n\n List<RangeData> findAllByTimestampBetween(long startTime, long endTime);\n\n @Transactional\n @Modifying\n @Query(value = \"delete from range_data rd where rd.timestamp <= (extract('epoch' from (current_timestamp - interval '?1 days')) * 1000)\", nativeQuery = true)\n void deleteAllByTimestampLessThanEqual(long time);\n}" } ]
import com.amnesica.belugaproject.config.StaticValues; import com.amnesica.belugaproject.entities.aircraft.Aircraft; import com.amnesica.belugaproject.entities.data.RangeData; import com.amnesica.belugaproject.repositories.data.RangeDataRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.text.DateFormat; import java.util.Date; import java.util.List;
1,244
package com.amnesica.belugaproject.services.data; @Slf4j @Service public class RangeDataService { @Autowired private RangeDataRepository rangeDataRepository; /** * Gibt eine Liste mit Range-Data, Start- und Endpunkt von Flugzeugen, * welche in dem Zeitslot empfangen wurden * * @param startTime long * @param endTime long * @return List<RangeData> */
package com.amnesica.belugaproject.services.data; @Slf4j @Service public class RangeDataService { @Autowired private RangeDataRepository rangeDataRepository; /** * Gibt eine Liste mit Range-Data, Start- und Endpunkt von Flugzeugen, * welche in dem Zeitslot empfangen wurden * * @param startTime long * @param endTime long * @return List<RangeData> */
public List<RangeData> getRangeDataBetweenTimestamps(long startTime, long endTime) {
2
2023-12-11 11:37:46+00:00
2k
fiber-net-gateway/fiber-net-gateway
fiber-gateway-common/src/main/java/io/fiber/net/common/async/internal/MappedSingle.java
[ { "identifier": "Disposable", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/async/Disposable.java", "snippet": "public interface Disposable {\n boolean isDisposed();\n\n boolean dispose();\n}" }, { "identifier": "Function", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/async/Function.java", "snippet": "@FunctionalInterface\npublic interface Function<T, R> {\n R invoke(T t) throws Throwable;\n}" }, { "identifier": "Scheduler", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/async/Scheduler.java", "snippet": "public class Scheduler {\n private static final FastThreadLocal<Scheduler> TH = new FastThreadLocal<>();\n\n public static void assertInIoThread() {\n if (ThreadExecutorMap.currentExecutor() == null) {\n throw new IllegalStateException(\"not in io thread??\");\n }\n }\n\n public static boolean isInIOThread() {\n return ThreadExecutorMap.currentExecutor() != null;\n }\n\n public static boolean isInIOThread(EventLoopGroup group) {\n EventExecutor executor = ThreadExecutorMap.currentExecutor();\n return executor != null && executor.parent() == group;\n }\n\n public static Scheduler current() {\n Scheduler scheduler = TH.getIfExists();\n if (scheduler == null) {\n EventExecutor currentExecutor = ThreadExecutorMap.currentExecutor();\n if (currentExecutor == null) {\n throw new IllegalStateException(\"not in io thread??\");\n }\n scheduler = new Scheduler(currentExecutor);\n TH.set(scheduler);\n }\n\n return scheduler;\n }\n\n public static void __setCurrentScheduler(Scheduler scheduler) {\n TH.set(scheduler);\n }\n\n private final EventExecutor eventExecutor;\n\n public Scheduler(EventExecutor eventExecutor) {\n this.eventExecutor = eventExecutor;\n }\n\n public void execute(Runnable runnable) {\n eventExecutor.execute(runnable);\n }\n\n public ScheduledFuture<?> schedule(Runnable task, long timeoutMs) {\n return eventExecutor.schedule(task, timeoutMs, TimeUnit.MILLISECONDS);\n }\n\n public boolean inLoop() {\n return eventExecutor.inEventLoop();\n }\n\n public EventExecutor getEventExecutor() {\n return eventExecutor;\n }\n}" }, { "identifier": "Single", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/async/Single.java", "snippet": "public interface Single<T> {\n\n interface Observer<T> {\n\n void onSubscribe(Disposable d);\n\n void onSuccess(T t);\n\n void onError(Throwable e);\n\n Scheduler scheduler();\n }\n\n interface Emitter<T> {\n\n void onSuccess(T t);\n\n void onError(Throwable t);\n\n boolean isDisposed();\n\n }\n\n interface OnSubscribe<T> {\n void subscribe(Emitter<T> emitter) throws Throwable;\n }\n\n static <T> Single<T> create(OnSubscribe<T> onSubscribe) {\n return new SingleCreate<>(onSubscribe);\n }\n\n static <T> Single<T> just(T t) {\n return new JustSingle<>(t);\n }\n\n void subscribe(Observer<? super T> observer);\n\n default Disposable subscribe(java.util.function.BiConsumer<T, Throwable> com) {\n SingleConsumeOb<T> ob = new SingleConsumeOb<>(com);\n subscribe(ob);\n return ob.getD();\n }\n\n default <R> Single<R> flatMap(Function<? super T, Single<? extends R>> map) {\n return new FlatMappedSingle<>(map, this);\n }\n\n default <R> Single<R> map(Function<? super T, ? extends R> map) {\n return new MappedSingle<>(map, this);\n }\n\n}" } ]
import io.fiber.net.common.async.Disposable; import io.fiber.net.common.async.Function; import io.fiber.net.common.async.Scheduler; import io.fiber.net.common.async.Single;
1,108
package io.fiber.net.common.async.internal; public class MappedSingle<T, U> implements Single<U> { private final Function<? super T, ? extends U> map; private final Single<T> source; public MappedSingle(Function<? super T, ? extends U> fc, Single<T> source) { this.map = fc; this.source = source; } @Override public void subscribe(Observer<? super U> observer) { source.subscribe(new MapOb<>(map, observer)); } private static class MapOb<T, U> implements Observer<T> { private final Function<? super T, ? extends U> map; private final Observer<? super U> c; private MapOb(Function<T, U> map, Observer<? super U> c) { this.map = map; this.c = c; } @Override
package io.fiber.net.common.async.internal; public class MappedSingle<T, U> implements Single<U> { private final Function<? super T, ? extends U> map; private final Single<T> source; public MappedSingle(Function<? super T, ? extends U> fc, Single<T> source) { this.map = fc; this.source = source; } @Override public void subscribe(Observer<? super U> observer) { source.subscribe(new MapOb<>(map, observer)); } private static class MapOb<T, U> implements Observer<T> { private final Function<? super T, ? extends U> map; private final Observer<? super U> c; private MapOb(Function<T, U> map, Observer<? super U> c) { this.map = map; this.c = c; } @Override
public void onSubscribe(Disposable d) {
0
2023-12-08 15:18:05+00:00
2k
i-moonlight/IPFS_Gateway_Checker
ipfs-status-service/src/main/java/com/fooock/ipfs/status/task/GatewayCheckWritableTask.java
[ { "identifier": "Gateway", "path": "ipfs-status-service/src/main/java/com/fooock/ipfs/status/model/Gateway.java", "snippet": "@Data\n@RequiredArgsConstructor\n@EqualsAndHashCode(doNotUseGetters = true, exclude = {\"startTime\", \"latency\", \"lastUpdate\"})\npublic class Gateway {\n public static final int GATEWAY_WRITABLE = 0;\n public static final int GATEWAY_NO_WRITABLE = 1;\n public static final int GATEWAY_WRITABLE_UNKNOWN = 2;\n\n private final String name;\n private final String url;\n\n private long startTime;\n private long lastUpdate;\n private long latency;\n\n public void calculateLatency() {\n lastUpdate = System.currentTimeMillis();\n latency = lastUpdate - startTime;\n }\n}" }, { "identifier": "Report", "path": "ipfs-status-service/src/main/java/com/fooock/ipfs/status/model/Report.java", "snippet": "@Data\n@NoArgsConstructor\n@EqualsAndHashCode(doNotUseGetters = true)\npublic class Report {\n private long latency;\n private long lastUpdate;\n\n private int statusCode;\n private int writable = Gateway.GATEWAY_WRITABLE_UNKNOWN;\n\n private String name;\n private String url;\n\n private List<String> cors;\n}" }, { "identifier": "ReportMemoryRepository", "path": "ipfs-status-service/src/main/java/com/fooock/ipfs/status/repository/ReportMemoryRepository.java", "snippet": "@Repository\npublic class ReportMemoryRepository {\n private final Map<String, Report> reportMap = Collections.synchronizedMap(new HashMap<>());\n\n public synchronized Report save(String key, Report report) {\n if (reportMap.containsKey(key)) {\n return reportMap.replace(key, report);\n }\n return reportMap.put(key, report);\n }\n\n public Collection<Report> all() {\n return reportMap.values();\n }\n\n public List<Report> findOnline() {\n List<Report> onlineGateways = new ArrayList<>();\n for (Report report : reportMap.values()) {\n if (report.getStatusCode() == 200) onlineGateways.add(report);\n }\n return onlineGateways;\n }\n\n public boolean exists(String key) {\n return reportMap.containsKey(key);\n }\n\n public Report get(String key) {\n return reportMap.get(key);\n }\n\n public void updateWritableState(String key, int state) {\n reportMap.get(key).setWritable(state);\n }\n}" } ]
import com.fooock.ipfs.status.model.Gateway; import com.fooock.ipfs.status.model.Report; import com.fooock.ipfs.status.repository.ReportMemoryRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import java.util.List;
965
package com.fooock.ipfs.status.task; /** * Check if the public gateway has public writable access */ @Configuration @EnableScheduling @Slf4j public class GatewayCheckWritableTask { private final static long THREE_HOURS = 60 * 60 * 1000 * 3; private final static long ONE_MINUTE = 60000; private final ReportMemoryRepository reportMemoryRepository; private final WebClient webClient; public GatewayCheckWritableTask(ReportMemoryRepository reportMemoryRepository, WebClient webClient) { this.reportMemoryRepository = reportMemoryRepository; this.webClient = webClient; } /** * Execute check every three hours and save result to repository. */ @Scheduled(fixedRate = THREE_HOURS, initialDelay = ONE_MINUTE) public void checkWritable() { log.debug("Prepared to check writable nodes..."); List<Report> online = reportMemoryRepository.findOnline(); if (online.isEmpty()) { log.warn("No online gateways..."); return; } log.info("Check writable state of {} gateways...", online.size()); online.forEach(gateway -> { Mono<ClientResponse> clientResponse = webClient.post() .uri(buildPostUrl(gateway.getName())) .exchange(); clientResponse.subscribe(s -> checkGatewayResponse(gateway, s),
package com.fooock.ipfs.status.task; /** * Check if the public gateway has public writable access */ @Configuration @EnableScheduling @Slf4j public class GatewayCheckWritableTask { private final static long THREE_HOURS = 60 * 60 * 1000 * 3; private final static long ONE_MINUTE = 60000; private final ReportMemoryRepository reportMemoryRepository; private final WebClient webClient; public GatewayCheckWritableTask(ReportMemoryRepository reportMemoryRepository, WebClient webClient) { this.reportMemoryRepository = reportMemoryRepository; this.webClient = webClient; } /** * Execute check every three hours and save result to repository. */ @Scheduled(fixedRate = THREE_HOURS, initialDelay = ONE_MINUTE) public void checkWritable() { log.debug("Prepared to check writable nodes..."); List<Report> online = reportMemoryRepository.findOnline(); if (online.isEmpty()) { log.warn("No online gateways..."); return; } log.info("Check writable state of {} gateways...", online.size()); online.forEach(gateway -> { Mono<ClientResponse> clientResponse = webClient.post() .uri(buildPostUrl(gateway.getName())) .exchange(); clientResponse.subscribe(s -> checkGatewayResponse(gateway, s),
throwable -> updateWritableState(gateway, Gateway.GATEWAY_NO_WRITABLE));
0
2023-12-11 10:11:41+00:00
2k
sigbla/sigbla-pds
src/main/java/sigbla/app/pds/collection/internal/adapter/Adapters.java
[ { "identifier": "Function", "path": "src/main/java/sigbla/app/pds/collection/Function.java", "snippet": "public interface Function<P, R> {\n R invoke(P parameter);\n}" }, { "identifier": "Traversable", "path": "src/main/java/sigbla/app/pds/collection/Traversable.java", "snippet": "public interface Traversable<E> {\n /**\n * All collection methods can be built upon this {@code forEach} definition.\n */\n @SuppressWarnings(\"NullableProblems\")\n <U> void forEach(@NotNull Function<E, U> f);\n\n /**\n * Returns the size of the collection.\n * <p/>\n * <p>Warning: infinite collections are possible, as are collections that require traversal to calculate the\n * size.\n */\n int size();\n\n /**\n * Returns true if this collection is empty.\n */\n boolean isEmpty();\n\n /**\n * Returns this collection converted to a string by joining elements together with the specified {@code separator}.\n */\n @NotNull\n String makeString(@NotNull String separator);\n\n /**\n * Returns this collection converted to a string.\n *\n * @param separator Specifies the joining character\n * @param prefix Specifies a prefix to the string\n * @param postfix Species a postfix to the string\n * @param limit Specifies the maximum number of elements to join. If the limit is exceeded, additional elements are ignored.\n * @param truncated If the limit is reached, the {@code truncated} value will be appended to indicate the limit was reached.\n */\n @NotNull\n String makeString(@NotNull String separator, @NotNull String prefix, @NotNull String postfix, int limit, @NotNull String truncated);\n\n /**\n * Converts this collection to another collection using a builder.\n */\n @NotNull\n <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder);\n\n /**\n * Converts this collection to a set.\n */\n @NotNull\n Set<E> toSet();\n\n /**\n * Converts this collection to a sorted set.\n */\n @NotNull\n SortedSet<E> toSortedSet(Comparator<? super E> comparator);\n\n /**\n * Converts this collection to an indexed list.\n */\n @NotNull\n IndexedList<E> toIndexedList();\n\n /**\n * Converts this collection to an array of objects.\n */\n @NotNull\n Object[] toArray();\n\n /**\n * Converts this collection to an array of objects of the correct type.\n */\n @NotNull\n E[] toArray(E[] array);\n}" }, { "identifier": "Break", "path": "src/main/java/sigbla/app/pds/collection/internal/base/Break.java", "snippet": "public final class Break extends RuntimeException {\n public static final Break instance = new Break();\n}" } ]
import sigbla.app.pds.collection.Function; import sigbla.app.pds.collection.Traversable; import sigbla.app.pds.collection.internal.base.Break; import org.jetbrains.annotations.NotNull; import java.util.Collection;
1,055
/* * Copyright (c) 2014 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO 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. */ package sigbla.app.pds.collection.internal.adapter; /** * */ public class Adapters { public static <E> boolean containsAll(@NotNull Traversable<E> traversable, @NotNull Collection<?> c) { for (Object e : c) { if (!contains(traversable, e)) { return false; } } return true; } @SuppressWarnings("unchecked") public static <E> boolean contains(@NotNull Traversable<E> traversable, final Object o) { try {
/* * Copyright (c) 2014 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO 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. */ package sigbla.app.pds.collection.internal.adapter; /** * */ public class Adapters { public static <E> boolean containsAll(@NotNull Traversable<E> traversable, @NotNull Collection<?> c) { for (Object e : c) { if (!contains(traversable, e)) { return false; } } return true; } @SuppressWarnings("unchecked") public static <E> boolean contains(@NotNull Traversable<E> traversable, final Object o) { try {
traversable.forEach(new Function<E, Object>() {
0
2023-12-10 15:10:13+00:00
2k
AdanJoGoHe/sunandbeach
src/main/java/com/serex/beachandsun/items/HoneyRumItem.java
[ { "identifier": "ItemInit", "path": "src/main/java/com/serex/beachandsun/ItemInit.java", "snippet": "public class ItemInit {\n public static final Item TROPICAL_CAN = registerItem(\"tropical\", new TropicalCanItem(new FabricItemSettings()));\n public static final Item EMPTY_TROPICAL_CAN = registerItem(\"empty_tropical\", new Item(new FabricItemSettings()));\n public static final Item TIRMA = registerItem(\"tirma\", new TirmaItem(new FabricItemSettings()));\n public static final Item GOFIO_BAG = registerItem(\"gofio_bag\", new GofioBagItem(new FabricItemSettings()));\n public static final Item VODKA = registerItem(\"vodka\", new VodkaItem(new FabricItemSettings()));\n public static final Item MALIBU = registerItem(\"malibu\", new MalibuItem(new FabricItemSettings()));\n public static final Item JUGGERNOG_DRINK = registerItem(\"juggernog_drink\", new JuggernogDrinkItem(new FabricItemSettings()));\n public static final Item REUSABLE_POTION = registerItem(\"reusable_potion\", new ReusablePotionItem(new FabricItemSettings()));\n public static final Item HONEY_RUM = registerItem(\"honey_rum\", new HoneyRumItem(new FabricItemSettings()));\n public static final Item MIRACLE_SWORD = registerItem(\"miracle_sword\", new MiracleSword(MIRACLE_SWORD_MATERIAL, 25, (float) -1.8 , new Item.Settings()));\n public static final Item WOODEN_MACE = registerItem(\"wooden_mace\", new WoodenMace(WOODEN_MACE_MATERIAL, 25, (float) -1.8 , new Item.Settings()));\n public static final Item GREEN_CHURRO = registerItem(\"green_churro\", new GreenChurroSword(GREEN_CHURRO_SWORD_MATERIAL, 3, (float) -1.8 , new Item.Settings()));\n public static final Item BLUE_CHURRO = registerItem(\"blue_churro\", new BlueChurroSword(BLUE_CHURRO_SWORD_MATERIAL, 3, (float) -1.8 , new Item.Settings()));\n\n public static final Item CANDELABRO = registerItem(\"candelabro\", new Candelabro(new FabricItemSettings()));\n\n private static void addItemsToMiscItemGroup(FabricItemGroupEntries entries){\n entries.add(TROPICAL_CAN);\n entries.add(TIRMA);\n entries.add(GOFIO_BAG);\n entries.add(EMPTY_TROPICAL_CAN);\n entries.add(VODKA);\n entries.add(MIRACLE_SWORD);\n entries.add(MALIBU);\n entries.add(WOODEN_MACE);\n entries.add(GREEN_CHURRO);\n entries.add(BLUE_CHURRO);\n entries.add(HONEY_RUM);\n entries.add(REUSABLE_POTION);\n entries.add(CANDELABRO);\n }\n\n private static Item registerItem(String name, Item item) {\n return Registry.register(Registries.ITEM, new Identifier(MODIDEF, name), item);\n }\n\n public static void registerItems(){\n BeachAndSun.LOGGER.info(\"Registering Mod items for {}\", MODIDEF);\n ItemGroupEvents.modifyEntriesEvent(ItemGroups.INGREDIENTS).register(ItemInit::addItemsToMiscItemGroup);\n }\n}" }, { "identifier": "ModSounds", "path": "src/main/java/com/serex/beachandsun/sound/ModSounds.java", "snippet": "public class ModSounds {\n public static SoundEvent VODKA_FINISH_SOUND = registerSoundEvent(\"vodka_finish_drink\");\n public static SoundEvent LC_SHOP_SONG = registerSoundEvent(\"lc_shop_song\");\n public static SoundEvent QUICK_REVIVE_SOUND = registerSoundEvent(\"quick_revive_sound\");\n\n private static SoundEvent registerSoundEvent(String name){\n Identifier id = new Identifier(Constants.MODIDEF, name);\n return Registry.register(Registries.SOUND_EVENT, id, SoundEvent.of(id));\n }\n\n public static void registerSounds(){\n BeachAndSun.LOGGER.info(\"Registering Mod Sounds for {}\", MODIDEF);\n }\n}" } ]
import com.serex.beachandsun.ItemInit; import com.serex.beachandsun.sound.ModSounds; import java.util.List; import net.minecraft.advancement.criterion.Criteria; import net.minecraft.client.item.TooltipContext; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.entity.effect.StatusEffects; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUsage; import net.minecraft.potion.PotionUtil; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.stat.Stats; import net.minecraft.text.Text; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.util.UseAction; import net.minecraft.world.World; import net.minecraft.world.event.GameEvent; import org.jetbrains.annotations.Nullable;
1,444
package com.serex.beachandsun.items; public class HoneyRumItem extends Item { public HoneyRumItem(Settings settings) { super(settings); } public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) { return ItemUsage.consumeHeldItem(world, user, hand); } @Override public UseAction getUseAction(ItemStack stack) { return UseAction.DRINK; } @Override public int getMaxUseTime(ItemStack stack) { return 32; } @Override public ItemStack finishUsing(ItemStack stack, World world, LivingEntity user) { PlayerEntity playerEntity; PlayerEntity playerEntity2 = playerEntity = user instanceof PlayerEntity ? (PlayerEntity)user : null; if (playerEntity instanceof ServerPlayerEntity) { Criteria.CONSUME_ITEM.trigger((ServerPlayerEntity)playerEntity, stack); } if (!world.isClient) { List<StatusEffectInstance> list = PotionUtil.getPotionEffects(stack); for (StatusEffectInstance statusEffectInstance : list) { if (statusEffectInstance.getEffectType().isInstant()) { statusEffectInstance.getEffectType().applyInstantEffect(playerEntity, playerEntity, user, statusEffectInstance.getAmplifier(), 1.0); continue; } user.addStatusEffect(new StatusEffectInstance(statusEffectInstance)); } } if (playerEntity == null || !playerEntity.getAbilities().creativeMode) {
package com.serex.beachandsun.items; public class HoneyRumItem extends Item { public HoneyRumItem(Settings settings) { super(settings); } public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) { return ItemUsage.consumeHeldItem(world, user, hand); } @Override public UseAction getUseAction(ItemStack stack) { return UseAction.DRINK; } @Override public int getMaxUseTime(ItemStack stack) { return 32; } @Override public ItemStack finishUsing(ItemStack stack, World world, LivingEntity user) { PlayerEntity playerEntity; PlayerEntity playerEntity2 = playerEntity = user instanceof PlayerEntity ? (PlayerEntity)user : null; if (playerEntity instanceof ServerPlayerEntity) { Criteria.CONSUME_ITEM.trigger((ServerPlayerEntity)playerEntity, stack); } if (!world.isClient) { List<StatusEffectInstance> list = PotionUtil.getPotionEffects(stack); for (StatusEffectInstance statusEffectInstance : list) { if (statusEffectInstance.getEffectType().isInstant()) { statusEffectInstance.getEffectType().applyInstantEffect(playerEntity, playerEntity, user, statusEffectInstance.getAmplifier(), 1.0); continue; } user.addStatusEffect(new StatusEffectInstance(statusEffectInstance)); } } if (playerEntity == null || !playerEntity.getAbilities().creativeMode) {
playerEntity.playSound(ModSounds.QUICK_REVIVE_SOUND,100,1);
1
2023-12-06 10:53:54+00:00
2k
netty/netty-incubator-codec-ohttp
codec-ohttp/src/main/java/io/netty/incubator/codec/ohttp/OHttpServerPublicKeys.java
[ { "identifier": "CryptoException", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/CryptoException.java", "snippet": "public final class CryptoException extends Exception {\n\n public CryptoException(String message) {\n super(message);\n }\n\n public CryptoException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public CryptoException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "AEAD", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AEAD.java", "snippet": "public enum AEAD {\n AES_GCM128((short) 0x0001, 16, 12),\n AES_GCM256((short) 0x0002, 32, 12),\n CHACHA20_POLY1305((short) 0x0003, 32, 12);\n\n public static AEAD forId(short id) {\n for (AEAD val : values()) {\n if (val.id == id) {\n return val;\n }\n }\n throw new IllegalArgumentException(\"unknown AEAD id \" + id);\n }\n\n private final short id;\n private final int nk;\n private final int nn;\n\n AEAD(short id, int nk, int nn) {\n this.id = id;\n this.nk = nk;\n this.nn = nn;\n }\n\n public short id() {\n return id;\n }\n\n public int nk() {\n return nk;\n }\n\n public int nn() {\n return nn;\n }\n}" }, { "identifier": "KDF", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/KDF.java", "snippet": "public enum KDF {\n HKDF_SHA256((short) 0x0001),\n HKDF_SHA384((short) 0x0002),\n HKDF_SHA512((short) 0x0003);\n\n public static KDF forId(short id) {\n for (KDF val : values()) {\n if (val.id == id) {\n return val;\n }\n }\n throw new IllegalArgumentException(\"unknown KDF id \" + id);\n }\n\n private final short id;\n\n KDF(short id) {\n this.id = id;\n }\n\n public short id() {\n return id;\n }\n}" }, { "identifier": "KEM", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/KEM.java", "snippet": "public enum KEM {\n P256_SHA256((short) 16, 65, 65),\n P384_SHA348((short) 17, 97, 97),\n P521_SHA512((short) 18, 133, 133),\n X25519_SHA256((short) 32, 32, 32),\n X448_SHA512((short) 33, 56, 56);\n\n public static KEM forId(short id) {\n for (KEM val : values()) {\n if (val.id == id) {\n return val;\n }\n }\n throw new IllegalArgumentException(\"unknown KEM id \" + id);\n }\n\n KEM(short id, int nenc, int npk) {\n this.id = id;\n this.nenc = nenc;\n this.npk = npk;\n }\n\n private final short id;\n private final int nenc;\n private final int npk;\n\n public short id() {\n return id;\n }\n\n public int nenc() {\n return nenc;\n }\n\n public int npk() {\n return npk;\n }\n}" } ]
import io.netty.incubator.codec.hpke.KDF; import io.netty.incubator.codec.hpke.KEM; import static java.util.Objects.requireNonNull; import io.netty.incubator.codec.hpke.CryptoException; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import io.netty.incubator.codec.hpke.AEAD;
1,535
/* * Copyright 2023 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; /** * Set of server public keys and cipher suites for a OHTTP client. */ public final class OHttpServerPublicKeys implements Iterable<Map.Entry<Byte, OHttpKey.PublicKey>> { private final Map<Byte, OHttpKey.PublicKey> keys; public OHttpServerPublicKeys(Map<Byte, OHttpKey.PublicKey> keys) { this.keys = Collections.unmodifiableMap(requireNonNull(keys, "keys")); } /** * Return all {@link OHttpKey.PublicKey}s. * * @return keys. */ public Collection<OHttpKey.PublicKey> keys() { return keys.values(); } /** * Return the {@link OHttpKey.PublicKey} for the given id or {@code null} if there is no key for the id. * * @param keyId the id of the key. * @return key the key. */ public OHttpKey.PublicKey key(byte keyId) { return keys.get(keyId); } @Override public Iterator<Map.Entry<Byte, OHttpKey.PublicKey>> iterator() { return keys.entrySet().iterator(); } @Override public String toString() { return keys.values() .stream() .map(k -> "{ciphers=" + k.ciphersuites().stream() .map(OHttpCiphersuite::toString) .collect(Collectors.joining(", ", "[", "]")) + ", publicKey=" + ByteBufUtil.hexDump(k.pkEncoded()) + "}") .collect(Collectors.joining(", ", "[", "]")); } /* * Decode a serialized {@link ServerPublicKeys} on the client. */
/* * Copyright 2023 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; /** * Set of server public keys and cipher suites for a OHTTP client. */ public final class OHttpServerPublicKeys implements Iterable<Map.Entry<Byte, OHttpKey.PublicKey>> { private final Map<Byte, OHttpKey.PublicKey> keys; public OHttpServerPublicKeys(Map<Byte, OHttpKey.PublicKey> keys) { this.keys = Collections.unmodifiableMap(requireNonNull(keys, "keys")); } /** * Return all {@link OHttpKey.PublicKey}s. * * @return keys. */ public Collection<OHttpKey.PublicKey> keys() { return keys.values(); } /** * Return the {@link OHttpKey.PublicKey} for the given id or {@code null} if there is no key for the id. * * @param keyId the id of the key. * @return key the key. */ public OHttpKey.PublicKey key(byte keyId) { return keys.get(keyId); } @Override public Iterator<Map.Entry<Byte, OHttpKey.PublicKey>> iterator() { return keys.entrySet().iterator(); } @Override public String toString() { return keys.values() .stream() .map(k -> "{ciphers=" + k.ciphersuites().stream() .map(OHttpCiphersuite::toString) .collect(Collectors.joining(", ", "[", "]")) + ", publicKey=" + ByteBufUtil.hexDump(k.pkEncoded()) + "}") .collect(Collectors.joining(", ", "[", "]")); } /* * Decode a serialized {@link ServerPublicKeys} on the client. */
public static OHttpServerPublicKeys decode(ByteBuf input) throws CryptoException {
0
2023-12-06 09:14:09+00:00
2k
xia0ne/NotificationTools
src/main/java/com/example/notificationtools/controller/RedisController.java
[ { "identifier": "RedisServiceImpl", "path": "src/main/java/com/example/notificationtools/service/impl/RedisServiceImpl.java", "snippet": "@Service\n@Log\npublic class RedisServiceImpl implements RedisService {\n\t@Resource\n\tprivate RedisTemplate<String, Object> redisTemplate;\n\n\t/*\n\t-1 custom\n\t0 drink\n\t1 tig\n\t */\n\t@Override\n\tpublic boolean setCount(int taskId) {\n\t\ttry {\n\t\t\tredisTemplate.opsForValue().increment(\"count:\" + taskId);\n\t\t\treturn true;\n\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic List<HashMap<Integer, Object>> getCount() {\n\t\ttry {\n\t\t\tList<Integer> taskId = TaskConfig.getTaskId();\n\t\t\tList<String> keys = taskId.stream().map(id -> \"count:\" + id).toList();\n\t\t\tList<Object> counts = redisTemplate.opsForValue().multiGet(keys);\n\t\t\tList<HashMap<Integer, Object>> result = new ArrayList<>();\n\t\t\tfor (int i = 0; i < taskId.size(); i++) {\n\t\t\t\tif (counts.get(i) != null) {\n\t\t\t\t\tresult.add(new HashMap<>(Map.of(taskId.get(i), counts.get(i))));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\n\t@Override\n\tpublic boolean setLog(String logs) {\n\t\tlog.info(\"setLog \" + logs);\n\t\ttry {\n\t\t\tredisTemplate.opsForList().rightPush(\"logs\", logs);\n\t\t\tLong size = redisTemplate.opsForList().size(\"logs\");\n\t\t\tif (size > 10) {\n\t\t\t\tredisTemplate.opsForList().trim(\"log\", size - 10, size);\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic List<Object> getLogs(int index, int offset) {\n\t\treturn redisTemplate.opsForList().range(\"logs\", index, Math.min(index + offset - 1, index + 9)).stream()\n\t\t\t\t\t\t.map(Object::toString)\n\t\t\t\t\t\t.collect(Collectors.toList());\n\t}\n}" }, { "identifier": "ResponseResult", "path": "src/main/java/com/example/notificationtools/utils/ResponseResult.java", "snippet": "@Data\n@Builder\npublic class ResponseResult<T>{\n\tprivate long timestamp;\n\tprivate String status;\n\tprivate String message;\n\tprivate T data;\n\n\tpublic static <T> ResponseResult<T> success(){\n\t\treturn success(null);\n\t}\n\n\tpublic static <T> ResponseResult<T> success(T data){\n\t\treturn ResponseResult.<T>builder().data(data)\n\t\t\t\t\t\t.message(ResponeseStatus.SUCCESS.getDescription())\n\t\t\t\t\t\t.status(ResponeseStatus.SUCCESS.getResponeseCode())\n\t\t\t\t\t\t.timestamp(System.currentTimeMillis())\n\t\t\t\t\t\t.build();\n\t}\n\n\tpublic static <T> ResponseResult<T> fail(String message){\n\t\treturn fail(null, message);\n\t}\n\n\tpublic static <T> ResponseResult<T> fail(T data, String message){\n\t\treturn ResponseResult.<T>builder().data(data)\n\t\t\t\t\t\t.message(message)\n\t\t\t\t\t\t.status(ResponeseStatus.FAIL.getResponeseCode())\n\t\t\t\t\t\t.timestamp(System.currentTimeMillis())\n\t\t\t\t\t\t.build();\n\t}\n}" } ]
import com.example.notificationtools.service.impl.RedisServiceImpl; import com.example.notificationtools.utils.ResponseResult; import jakarta.annotation.Resource; import lombok.extern.java.Log; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List;
902
package com.example.notificationtools.controller; @RestController @RequestMapping("/logs") @Log public class RedisController { @Resource
package com.example.notificationtools.controller; @RestController @RequestMapping("/logs") @Log public class RedisController { @Resource
RedisServiceImpl redisService;
0
2023-12-05 06:46:58+00:00
2k
Ender-Cube/Endercube
Parkour/src/main/java/net/endercube/Parkour/listeners/MinigamePlayerJoin.java
[ { "identifier": "MinigamePlayerJoinEvent", "path": "Common/src/main/java/net/endercube/Common/events/MinigamePlayerJoinEvent.java", "snippet": "public class MinigamePlayerJoinEvent implements PlayerMinigameEvent {\n\n private final String minigame;\n private final EndercubePlayer player;\n private final String map;\n\n public MinigamePlayerJoinEvent(String minigame, EndercubePlayer player, String map) {\n this.minigame = minigame;\n this.player = player;\n this.map = map;\n\n player.setCurrentMinigame(minigame);\n }\n\n @Override\n public @NotNull String getMinigame() {\n return minigame;\n }\n\n public @NotNull EndercubePlayer getPlayer() {\n return player;\n }\n public @NotNull String getMap() {\n return map;\n }\n}" }, { "identifier": "EndercubePlayer", "path": "Common/src/main/java/net/endercube/Common/players/EndercubePlayer.java", "snippet": "public class EndercubePlayer extends Player {\n public EndercubePlayer(@NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) {\n super(uuid, username, playerConnection);\n }\n\n /**\n * Get the current minigame\n * @return the name of the minigame or \"hub\" if in the hub\n */\n public String getCurrentMinigame() {\n return this.getTag(Tag.String(\"minigame\"));\n }\n\n /**\n * Sets the player's current minigame\n */\n public void setCurrentMinigame(String minigame) {\n this.setTag(Tag.String(\"minigame\"), minigame);\n }\n\n /**\n * Teleport the player to the hub\n */\n public void gotoHub() {\n if (Objects.equals(this.getCurrentMinigame(), \"hub\")) {\n this.sendMessage(\"Sending you to the hub spawn\");\n this.teleport(this.getInstance().getTag(Tag.Transient(\"spawnPos\")));\n return;\n }\n this.sendMessage(\"Sending you to the hub\");\n MinecraftServer.getGlobalEventHandler().call(new MinigamePlayerLeaveEvent(this.getCurrentMinigame(), this));\n MinecraftServer.getGlobalEventHandler().call(new MinigamePlayerJoinEvent(\"hub\", this, null));\n }\n}" }, { "identifier": "InventoryItems", "path": "Parkour/src/main/java/net/endercube/Parkour/InventoryItems.java", "snippet": "public class InventoryItems {\n public static final ItemStack CHECKPOINT_ITEM = ItemStack.builder(Material.ARROW)\n .displayName(Component.text(\"Teleport to current checkpoint\"))\n .build()\n .withTag(Tag.String(\"action\"), \"checkpoint\");\n public static final ItemStack RESTART_ITEM = ItemStack.builder(Material.BLAZE_POWDER)\n .displayName(Component.text(\"Restart the whole map!\"))\n .build()\n .withTag(Tag.String(\"action\"), \"restart\");\n public static final ItemStack HUB_ITEM = ItemStack.builder(Material.RED_BED)\n .displayName(Component.text(\"Teleport back to hub\"))\n .build()\n .withTag(Tag.String(\"action\"), \"hub\");\n public static final ItemStack VISIBILITY_ITEM_VISIBLE = ItemStack.builder(Material.ENDER_EYE)\n .displayName(Component.text(\"Click to hide players\"))\n .build()\n .withTag(Tag.String(\"action\"), \"hidePlayers\");\n public static final ItemStack VISIBILITY_ITEM_INVISIBLE = ItemStack.builder(Material.ENDER_PEARL)\n .displayName(Component.text(\"Click to show players\"))\n .build()\n .withTag(Tag.String(\"action\"), \"showPlayers\");\n public static final ItemStack GRIND_MODE_HUB = ItemStack.builder(Material.YELLOW_BED)\n .displayName(Component.text(\"Click to toggle grind mode\"))\n .lore(\n Component.text(\"→ Go To Hub\").color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD),\n Component.text(\" Open map menu\").color(NamedTextColor.GRAY),\n Component.text(\" Restart map\").color(NamedTextColor.GRAY)\n )\n .build()\n .withTag(Tag.String(\"action\"), \"set_grindMode_menu\");\n\n public static final ItemStack GRIND_MODE_MENU = ItemStack.builder(Material.PAINTING)\n .displayName(Component.text(\"Click to toggle grind mode\"))\n .lore(\n Component.text(\" Go To Hub\").color(NamedTextColor.GRAY),\n Component.text(\"→ Open map menu\").color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD),\n Component.text(\" Restart map\").color(NamedTextColor.GRAY)\n )\n .build()\n .withTag(Tag.String(\"action\"), \"set_grindMode_restart\");\n\n public static final ItemStack GRIND_MODE_RESTART = ItemStack.builder(Material.BLAZE_POWDER)\n .displayName(Component.text(\"Click to toggle grind mode\"))\n .lore(\n Component.text(\" Go To Hub\").color(NamedTextColor.GRAY),\n Component.text(\" Open map menu\").color(NamedTextColor.GRAY),\n Component.text(\"→ Restart map\").color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD)\n )\n .build()\n .withTag(Tag.String(\"action\"), \"set_grindMode_hub\");\n}" }, { "identifier": "logger", "path": "Common/src/main/java/net/endercube/Common/EndercubeMinigame.java", "snippet": "public static final Logger logger;" }, { "identifier": "database", "path": "Parkour/src/main/java/net/endercube/Parkour/ParkourMinigame.java", "snippet": "public static ParkourDatabase database;" }, { "identifier": "parkourMinigame", "path": "Parkour/src/main/java/net/endercube/Parkour/ParkourMinigame.java", "snippet": "public static ParkourMinigame parkourMinigame;" } ]
import net.endercube.Common.events.MinigamePlayerJoinEvent; import net.endercube.Common.players.EndercubePlayer; import net.endercube.Parkour.InventoryItems; import net.minestom.server.MinecraftServer; import net.minestom.server.event.EventListener; import net.minestom.server.instance.InstanceContainer; import net.minestom.server.tag.Tag; import org.jetbrains.annotations.NotNull; import static net.endercube.Common.EndercubeMinigame.logger; import static net.endercube.Parkour.ParkourMinigame.database; import static net.endercube.Parkour.ParkourMinigame.parkourMinigame;
1,502
package net.endercube.Parkour.listeners; public class MinigamePlayerJoin implements EventListener<MinigamePlayerJoinEvent> { @Override public @NotNull Class<MinigamePlayerJoinEvent> eventType() { return MinigamePlayerJoinEvent.class; } @Override public @NotNull Result run(@NotNull MinigamePlayerJoinEvent event) {
package net.endercube.Parkour.listeners; public class MinigamePlayerJoin implements EventListener<MinigamePlayerJoinEvent> { @Override public @NotNull Class<MinigamePlayerJoinEvent> eventType() { return MinigamePlayerJoinEvent.class; } @Override public @NotNull Result run(@NotNull MinigamePlayerJoinEvent event) {
EndercubePlayer player = event.getPlayer();
1
2023-12-10 12:08:18+00:00
2k
lukebemishprojects/Tempest
common/src/main/java/dev/lukebemish/tempest/impl/mixin/LevelMixin.java
[ { "identifier": "Services", "path": "common/src/main/java/dev/lukebemish/tempest/impl/Services.java", "snippet": "public final class Services {\n private Services() {}\n\n public static final Platform PLATFORM = load(Platform.class);\n\n private static final List<Snower> SNOWERS;\n private static final List<Melter> MELTERS;\n\n public static boolean snow(ServerLevel level, BlockPos pos, BlockState original) {\n for (var snower : SNOWERS) {\n if (snower.snow(level, pos, original)) {\n return true;\n }\n }\n return false;\n }\n\n public static boolean melt(ServerLevel level, BlockPos pos, BlockState original) {\n for (var melter : MELTERS) {\n if (melter.melt(level, pos, original)) {\n return true;\n }\n }\n return false;\n }\n\n public static <T> T load(Class<T> clazz) {\n return ServiceLoader.load(clazz)\n .findFirst()\n .orElseThrow(() -> new NullPointerException(\"Failed to load service for \" + clazz.getName()));\n }\n\n static {\n var melters = new ArrayList<Melter>();\n var snowers = new ArrayList<Snower>();\n for (var provider : ServiceLoader.load(CompatProvider.class)) {\n if (provider.shouldLoad()) {\n var compat = provider.compat();\n melters.add(new Melter() {\n boolean valid = true;\n\n @Override\n public boolean melt(ServerLevel level, BlockPos pos, BlockState original) {\n if (valid) {\n try {\n return compat.melt(level, pos, original);\n } catch (Throwable t) {\n valid = false;\n Constants.LOGGER.error(\"Failed to melt block at {} with provider {}\", pos, provider.getClass().getName(), t);\n }\n }\n return false;\n }\n });\n snowers.add(new Snower() {\n boolean valid = true;\n\n @Override\n public boolean snow(ServerLevel level, BlockPos pos, BlockState original) {\n if (valid) {\n try {\n return compat.snow(level, pos, original);\n } catch (Throwable t) {\n valid = false;\n Constants.LOGGER.error(\"Failed to snow block at {} with provider {}\", pos, provider.getClass().getName(), t);\n }\n }\n return false;\n }\n });\n }\n }\n MELTERS = List.copyOf(melters);\n SNOWERS = List.copyOf(snowers);\n }\n\n public interface Platform {\n WeatherChunkData getChunkData(LevelChunk chunk);\n <S, T extends S> Supplier<T> register(Supplier<T> supplier, ResourceLocation location, Registry<S> registry);\n\n boolean modLoaded(String modId);\n }\n\n @FunctionalInterface\n private interface Melter {\n boolean melt(ServerLevel level, BlockPos pos, BlockState original);\n }\n\n @FunctionalInterface\n private interface Snower {\n boolean snow(ServerLevel level, BlockPos pos, BlockState original);\n }\n\n public interface Compat {\n boolean melt(ServerLevel level, BlockPos pos, BlockState original);\n boolean snow(ServerLevel level, BlockPos pos, BlockState original);\n }\n\n public interface CompatProvider {\n Compat compat();\n\n boolean shouldLoad();\n }\n}" }, { "identifier": "WeatherCategory", "path": "common/src/main/java/dev/lukebemish/tempest/impl/data/WeatherCategory.java", "snippet": "public enum WeatherCategory {\n SNOW(new ResourceLocation(\"textures/environment/snow.png\"), false, 1.0f),\n RAIN(new ResourceLocation(\"textures/environment/rain.png\"), true, 0.2f),\n SLEET(Constants.id(\"textures/environment/sleet.png\"), true, 0.5f),\n HAIL(Constants.id(\"textures/environment/hail.png\"), true, 0.5f);\n\n public final ResourceLocation location;\n public final boolean fastFalling;\n private final float swirlMult;\n\n WeatherCategory(ResourceLocation location, boolean fastFalling, float swirlMult) {\n this.location = location;\n this.fastFalling = fastFalling;\n this.swirlMult = swirlMult;\n }\n\n public static class WeatherStatus {\n public final WeatherCategory category;\n public final float intensity;\n public final float swirl;\n public final float windX;\n public final float windZ;\n public final float speed;\n public final float thunder;\n\n public WeatherStatus(WeatherCategory category, float intensity, float windX, float windZ, float thunder) {\n this.category = category;\n float i = Mth.sqrt(intensity);\n this.intensity = 1 - (0.7f * (1 - i));\n this.speed = Mth.sqrt(windX * windX + windZ * windZ);\n this.swirl = (1 - speed * speed) * this.category.swirlMult;\n this.windX = windX / this.speed;\n this.windZ = windZ / this.speed;\n this.thunder = thunder;\n }\n }\n}" } ]
import dev.lukebemish.tempest.impl.Services; import dev.lukebemish.tempest.impl.data.WeatherCategory; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
1,417
package dev.lukebemish.tempest.impl.mixin; @Mixin(Level.class) public class LevelMixin { @Inject( method = "isRainingAt(Lnet/minecraft/core/BlockPos;)Z", at = @At("HEAD"), cancellable = true ) private void tempest$isRainingAt(BlockPos pos, CallbackInfoReturnable<Boolean> cir) { //noinspection DataFlowIssue var level = (Level) (Object) this;
package dev.lukebemish.tempest.impl.mixin; @Mixin(Level.class) public class LevelMixin { @Inject( method = "isRainingAt(Lnet/minecraft/core/BlockPos;)Z", at = @At("HEAD"), cancellable = true ) private void tempest$isRainingAt(BlockPos pos, CallbackInfoReturnable<Boolean> cir) { //noinspection DataFlowIssue var level = (Level) (Object) this;
var data = Services.PLATFORM.getChunkData(level.getChunkAt(pos));
0
2023-12-06 23:23:31+00:00
2k
aws-samples/codecatalyst-java-workflow-sample
src/main/java/com/example/calculator/restcalculator/rest/SumController.java
[ { "identifier": "ResultDto", "path": "src/main/java/com/example/calculator/restcalculator/dto/ResultDto.java", "snippet": "public class ResultDto {\n\n private String result;\n\n public String getResult() {\n return result;\n }\n\n public void setResult(String result) {\n this.result = result;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n ResultDto resultDto = (ResultDto) o;\n return result.equals(resultDto.result);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(result);\n }\n\n @Override\n public String toString() {\n return \"ResultDto{\" +\n \"result='\" + result + '\\'' +\n '}';\n }\n}" }, { "identifier": "SumDto", "path": "src/main/java/com/example/calculator/restcalculator/dto/SumDto.java", "snippet": "public class SumDto {\n\n private String firstAdding;\n private String secondAdding;\n\n public String getFirstAdding() {\n return firstAdding;\n }\n\n public void setFirstAdding(String firstAdding) {\n this.firstAdding = firstAdding;\n }\n\n public String getSecondAdding() {\n return secondAdding;\n }\n\n public void setSecondAdding(String secondAdding) {\n this.secondAdding = secondAdding;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n SumDto sumDto = (SumDto) o;\n return firstAdding.equals(sumDto.firstAdding) && secondAdding.equals(sumDto.secondAdding);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(firstAdding, secondAdding);\n }\n\n @Override\n public String toString() {\n return \"SumDto{\" +\n \"firstAdding='\" + firstAdding + '\\'' +\n \", secondAdding='\" + secondAdding + '\\'' +\n '}';\n }\n}" }, { "identifier": "Calculator", "path": "src/main/java/com/example/calculator/restcalculator/service/Calculator.java", "snippet": "@Component\npublic class Calculator {\n\n public String calculateSum(String firstAdding, String secondAdding) {\n if (!isInteger(firstAdding) || !isInteger(secondAdding)) {\n throw new RuntimeException(\"Operation supports only integer numbers\");\n }\n\n Integer result = Integer.parseInt(firstAdding) + Integer.parseInt(secondAdding);\n return String.valueOf(result);\n }\n\n private boolean isInteger(String number) {\n try {\n Integer.parseInt(number);\n return true;\n } catch (Exception exc) {\n return false;\n }\n }\n\n}" } ]
import com.example.calculator.restcalculator.dto.ResultDto; import com.example.calculator.restcalculator.dto.SumDto; import com.example.calculator.restcalculator.service.Calculator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController;
756
package com.example.calculator.restcalculator.rest; @RestController public class SumController { @Autowired
package com.example.calculator.restcalculator.rest; @RestController public class SumController { @Autowired
private Calculator calculator;
2
2023-12-14 10:24:15+00:00
2k
RennanMendes/healthnove-backend
src/test/java/com/healthnove/schedulingHealthNove/domain/service/DoctorServiceTest.java
[ { "identifier": "Gender", "path": "src/main/java/com/healthnove/schedulingHealthNove/domain/enumerated/Gender.java", "snippet": "public enum Gender {\n MALE, FEMALE\n}" }, { "identifier": "Speciality", "path": "src/main/java/com/healthnove/schedulingHealthNove/domain/enumerated/Speciality.java", "snippet": "public enum Speciality {\n CARDIOLOGY, MEDICAL_CLINIC, DERMATOLOGY, GASTROENTEROLOGIST, GYNECOLOGY, PEDIATRICS, PNEUMOLOGY\n}" }, { "identifier": "UserType", "path": "src/main/java/com/healthnove/schedulingHealthNove/domain/enumerated/UserType.java", "snippet": "public enum UserType {\n DOCTOR, PATIENT\n}" }, { "identifier": "DoctorAlreadyRegisteredException", "path": "src/main/java/com/healthnove/schedulingHealthNove/domain/exception/DoctorAlreadyRegisteredException.java", "snippet": "public class DoctorAlreadyRegisteredException extends RuntimeException {\n public DoctorAlreadyRegisteredException() {\n super(\"Médico já cadastrado!\");\n }\n}" }, { "identifier": "DoctorNotFoundException", "path": "src/main/java/com/healthnove/schedulingHealthNove/domain/exception/DoctorNotFoundException.java", "snippet": "public class DoctorNotFoundException extends RuntimeException {\n public DoctorNotFoundException() {\n super(\"Médico não encontrado!\");\n }\n}" }, { "identifier": "Doctor", "path": "src/main/java/com/healthnove/schedulingHealthNove/domain/model/Doctor.java", "snippet": "@Entity\n@Table(name = \"tb_doctor\")\n@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@EqualsAndHashCode(of = \"id\")\npublic class Doctor {\n\n @Id\n private Long id;\n\n @Column(unique = true)\n private String crm;\n\n @Enumerated(EnumType.STRING)\n private Speciality speciality;\n private boolean active;\n\n @OneToOne\n @JoinColumn(name = \"id_user\")\n private User user;\n\n public Doctor(User user, DoctorRequestDto requestDto) {\n this.id = user.getId();\n this.crm = requestDto.crm();\n this.speciality = requestDto.speciality();\n this.active = true;\n this.user = user;\n }\n\n public void setSpeciality(Speciality speciality) {\n this.speciality = speciality;\n }\n\n public void setActive(boolean active) {\n this.active = active;\n }\n\n}" }, { "identifier": "User", "path": "src/main/java/com/healthnove/schedulingHealthNove/domain/model/User.java", "snippet": "@Entity\n@Table(name = \"tb_user\")\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\n@EqualsAndHashCode(of = \"id\")\npublic class User implements UserDetails {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String firstName;\n private String lastName;\n\n @Column(unique = true)\n private String cpf;\n private String phone;\n private Date birthDate;\n\n @Enumerated(EnumType.STRING)\n private Gender gender;\n\n @Column(unique = true)\n private String email;\n private String password;\n\n @Enumerated(EnumType.STRING)\n private UserType userType;\n private boolean active;\n\n public User(UserRequestDto userData) {\n this.firstName = userData.name();\n this.lastName = userData.lastName();\n this.cpf = userData.cpf();\n this.phone = userData.phone();\n this.birthDate = userData.birthDate();\n this.gender = userData.gender();\n this.email = userData.email();\n this.password = userData.password();\n\n this.userType = UserType.PATIENT;\n this.active = true;\n }\n\n public void update(UserUpdateDto userData) {\n this.firstName = userData.firstName();\n this.lastName = userData.lastName();\n this.phone = userData.phone();\n this.email = userData.email();\n }\n\n public void setUserType(UserType userType) {\n this.userType = userType;\n }\n\n public void delete() {\n this.active = false;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return List.of(new SimpleGrantedAuthority(\"ROLE_USER\"));\n }\n\n @Override\n public String getUsername() {\n return email;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n}" }, { "identifier": "DoctorRepository", "path": "src/main/java/com/healthnove/schedulingHealthNove/domain/repository/DoctorRepository.java", "snippet": "public interface DoctorRepository extends JpaRepository<Doctor, Long> {\n boolean existsByIdAndActiveTrue(Long id);\n\n Optional<Doctor> findByIdAndActiveTrue(Long id);\n\n Page<Doctor> findBySpecialityAndActiveTrue(Pageable page, Speciality speciality);\n\n Page<Doctor> findByActiveTrue(Pageable page);\n}" } ]
import com.healthnove.schedulingHealthNove.domain.dto.doctor.DoctorRequestDto; import com.healthnove.schedulingHealthNove.domain.dto.doctor.DoctorResponseDto; import com.healthnove.schedulingHealthNove.domain.dto.doctor.DoctorUpdateDto; import com.healthnove.schedulingHealthNove.domain.enumerated.Gender; import com.healthnove.schedulingHealthNove.domain.enumerated.Speciality; import com.healthnove.schedulingHealthNove.domain.enumerated.UserType; import com.healthnove.schedulingHealthNove.domain.exception.DoctorAlreadyRegisteredException; import com.healthnove.schedulingHealthNove.domain.exception.DoctorNotFoundException; import com.healthnove.schedulingHealthNove.domain.model.Doctor; import com.healthnove.schedulingHealthNove.domain.model.User; import com.healthnove.schedulingHealthNove.domain.repository.DoctorRepository; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Optional; import static org.mockito.ArgumentMatchers.any; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when;
1,546
package com.healthnove.schedulingHealthNove.domain.service; @SpringBootTest class DoctorServiceTest { private static final Long ID = 1L; @InjectMocks private DoctorService doctorService; @Mock
package com.healthnove.schedulingHealthNove.domain.service; @SpringBootTest class DoctorServiceTest { private static final Long ID = 1L; @InjectMocks private DoctorService doctorService; @Mock
private DoctorRepository repository;
7
2023-12-14 21:54:29+00:00
2k
xhtcode/xht-cloud-parent
xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/poetry/service/ISysDictPoetryService.java
[ { "identifier": "PageResponse", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java", "snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @Schema(description = \"当前页\")\n private long current;\n\n /**\n * 每页显示条数\n */\n @Schema(description = \"每页显示条数\")\n private long size;\n\n /**\n * 总页数\n */\n @Schema(description = \"总页数\")\n private long pages;\n\n /**\n * 总条目数\n */\n @Schema(description = \"总条目数\")\n private long total;\n\n /**\n * 结果集\n */\n @Schema(description = \"结果集\")\n private List<T> list;\n\n}" }, { "identifier": "SysDictPoetryAddRequest", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/poetry/controller/request/SysDictPoetryAddRequest.java", "snippet": "@Data\n@Schema(name = \"SysDictPoetryRequest(-增加请求信息)\", description = \"-增加请求信息\")\npublic class SysDictPoetryAddRequest extends SysDictPoetryRequest {\n\n}" }, { "identifier": "SysDictPoetryQueryRequest", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/poetry/controller/request/SysDictPoetryQueryRequest.java", "snippet": "@Data\n@Schema(name = \"SysDictPoetryRequest(-查询请求信息)\", description = \"-查询请求信息\")\npublic class SysDictPoetryQueryRequest extends SysDictPoetryRequest {\n\n}" }, { "identifier": "SysDictPoetryUpdateRequest", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/poetry/controller/request/SysDictPoetryUpdateRequest.java", "snippet": "@Data\n@Schema(name = \"SysDictPoetryRequest(-修改请求信息)\", description = \"-修改请求信息\")\npublic class SysDictPoetryUpdateRequest extends SysDictPoetryRequest {\n\n /**\n * id\n */\n @Schema(description = \"id\")\n @NotBlank(message = \"id `id` 校验不通过\", groups = {Create.class, Update.class})\n private String id;\n\n}" }, { "identifier": "SysDictPoetryResponse", "path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/poetry/controller/response/SysDictPoetryResponse.java", "snippet": "@Data\n@Schema(name = \"SysDictPoetryResponse(-响应信息)\", description = \"\")\npublic class SysDictPoetryResponse extends Response {\n\n /**\n * id\n */\n @Schema(description = \"id\")\n private String id;\n\n /**\n * 作者\n */\n @Schema(description = \"作者\")\n private String author;\n\n /**\n * 作者简介\n */\n @Schema(description = \"作者简介\")\n private String authorDesc;\n\n /**\n * 类型\n */\n @Schema(description = \"类型\")\n private String type;\n\n /**\n * 简介\n */\n @Schema(description = \"简介\")\n private String typeDesc;\n\n /**\n * 作品名字\n */\n @Schema(description = \"作品名字\")\n private String title;\n\n /**\n * 作品名字简介\n */\n @Schema(description = \"作品名字简介\")\n private String tilteDesc;\n\n /**\n * 作品内容\n */\n @Schema(description = \"作品内容\")\n private String context;\n\n /**\n * 作品内容简介\n */\n @Schema(description = \"作品内容简介\")\n private String contextDesc;\n\n}" } ]
import com.xht.cloud.framework.core.api.response.PageResponse; import com.xht.cloud.system.module.poetry.controller.request.SysDictPoetryAddRequest; import com.xht.cloud.system.module.poetry.controller.request.SysDictPoetryQueryRequest; import com.xht.cloud.system.module.poetry.controller.request.SysDictPoetryUpdateRequest; import com.xht.cloud.system.module.poetry.controller.response.SysDictPoetryResponse; import java.util.List;
1,228
package com.xht.cloud.system.module.poetry.service; /** * 描述 : * * @author : xht **/ public interface ISysDictPoetryService{ /** * 创建 * * @param addRequest {@link SysDictPoetryAddRequest} * @return {@link String} 主键 */ String create(SysDictPoetryAddRequest addRequest); /** * 根据id修改 * * @param updateRequest {@link SysDictPoetryUpdateRequest} */ void update(SysDictPoetryUpdateRequest updateRequest); /** * 删除 * * @param ids {@link List<String>} id集合 */ void remove(List<String> ids); /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link SysDictPoetryResponse} */
package com.xht.cloud.system.module.poetry.service; /** * 描述 : * * @author : xht **/ public interface ISysDictPoetryService{ /** * 创建 * * @param addRequest {@link SysDictPoetryAddRequest} * @return {@link String} 主键 */ String create(SysDictPoetryAddRequest addRequest); /** * 根据id修改 * * @param updateRequest {@link SysDictPoetryUpdateRequest} */ void update(SysDictPoetryUpdateRequest updateRequest); /** * 删除 * * @param ids {@link List<String>} id集合 */ void remove(List<String> ids); /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link SysDictPoetryResponse} */
SysDictPoetryResponse findById(String id);
4
2023-12-12 08:16:30+00:00
2k
Utils4J/JavaUtils
src/test/java/CustomTableTest.java
[ { "identifier": "CustomTable", "path": "src/test/java/data/CustomTable.java", "snippet": "public interface CustomTable extends Table<TestClass> {\n\t@NotNull\n\t@Override\n\tCustomTable createTable();\n\n\tdefault List<TestClass> select2() {\n\t\treturn selectAll(Order.empty().limit(2));\n\t}\n}" }, { "identifier": "TestClass", "path": "src/test/java/data/TestClass.java", "snippet": "public class TestClass implements DataClass<TestClass> {\n\tprivate final Table<TestClass> table;\n\n\t@NotNull\n\t@Override\n\tpublic Table<TestClass> getTable() {\n\t\treturn table;\n\t}\n\n\t@Column(key = true)\n\tpublic ID id;\n\n\t@Column\n\tpublic TE enumTest;\n\n\t@Column\n\tpublic EnumSet<TE> enums;\n\n\tpublic TestClass(Table<TestClass> table) {\n\t\tthis.table = table;\n\t}\n\n\tpublic TestClass(Table<TestClass> table, TE e, EnumSet<TE> enums) {\n\t\tthis.table = table;\n\t\tthis.enumTest = e;\n\t\tthis.enums = enums;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn id.asString() + \": \" + enumTest + \", \" + enums + \" (\" + (id.getTimeCreated().toEpochMilli() - System.currentTimeMillis()) + \")\";\n\t}\n}" }, { "identifier": "DatabaseManager", "path": "src/main/java/de/mineking/javautils/database/DatabaseManager.java", "snippet": "public class DatabaseManager {\n\tpublic final static Logger logger = LoggerFactory.getLogger(DatabaseManager.class);\n\n\tprivate final Map<String, Object> data = new HashMap<>();\n\n\tfinal List<TypeMapper<?, ?>> mappers = new ArrayList<>();\n\tfinal Jdbi db;\n\n\tpublic DatabaseManager(@NotNull String host, @NotNull String user, @NotNull String password) {\n\t\tdb = Jdbi.create(host, user, password);\n\n\t\tmappers.add(TypeMapper.JSON);\n\t\tmappers.add(TypeMapper.SERIAL);\n\t\tmappers.add(TypeMapper.INTEGER);\n\t\tmappers.add(TypeMapper.LONG);\n\t\tmappers.add(TypeMapper.DOUBLE);\n\t\tmappers.add(TypeMapper.BOOLEAN);\n\t\tmappers.add(TypeMapper.STRING);\n\t\tmappers.add(TypeMapper.TIMESTAMP);\n\t\tmappers.add(TypeMapper.MKID);\n\t\tmappers.add(TypeMapper.OPTIONAL);\n\t\tmappers.add(TypeMapper.ENUM);\n\t\tmappers.add(TypeMapper.ARRAY);\n\t}\n\n\t@NotNull\n\tpublic Jdbi getDriver() {\n\t\treturn db;\n\t}\n\n\t@NotNull\n\tpublic DatabaseManager addMapper(@NotNull TypeMapper<?, ?> mapper) {\n\t\tmappers.add(0, mapper);\n\t\treturn this;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@NotNull\n\tpublic <T, R> TypeMapper<T, R> getMapper(@NotNull Type type, @NotNull Field f) {\n\t\treturn (TypeMapper<T, R>) mappers.stream()\n\t\t\t\t.filter(m -> m.accepts(this, type, f))\n\t\t\t\t.findFirst().orElseThrow(() -> new IllegalStateException(\"No mapper found for \" + type));\n\t}\n\n\t@NotNull\n\tpublic DataType getType(@NotNull Type type, @NotNull Field field) {\n\t\treturn getMapper(type, field).getType(this, type, field);\n\t}\n\n\t@Nullable\n\tpublic <T> Argument getArgument(@NotNull Type type, @NotNull Field field, @Nullable T value) {\n\t\tvar mapper = getMapper(type, field);\n\t\treturn mapper.createArgument(this, type, field, mapper.format(this, type, field, value));\n\t}\n\n\t@Nullable\n\tpublic Object format(@NotNull Type type, @NotNull Field field, @Nullable Object obj) {\n\t\treturn getMapper(type, field).format(this, type, field, obj);\n\t}\n\n\t@Nullable\n\tpublic Object extract(@NotNull Type type, @NotNull Field field, @NotNull String name, @NotNull ResultSet set) throws SQLException {\n\t\treturn getMapper(type, field).extract(set, name, type);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Nullable\n\tpublic <T, R> R parse(@NotNull Type type, @NotNull Field field, T value) {\n\t\treturn (R) getMapper(type, field).parse(this, type, field, value);\n\t}\n\n\tprivate class TableBuilder<O, T extends Table<O>> {\n\t\tprivate final T table;\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic TableBuilder(Class<T> table, Class<O> type, Supplier<O> instance, String name) {\n\t\t\tthis.table = (T) Proxy.newProxyInstance(\n\t\t\t\t\tgetClass().getClassLoader(),\n\t\t\t\t\tnew Class<?>[]{table},\n\t\t\t\t\tnew TableImpl<>(DatabaseManager.this, this::getTable, type, instance, name)\n\t\t\t);\n\t\t}\n\n\t\tprivate T getTable() {\n\t\t\treturn table;\n\t\t}\n\t}\n\n\t@NotNull\n\tpublic <O, T extends Table<O>> T getTable(@NotNull Class<T> table, @NotNull Class<O> type, @NotNull Supplier<O> instance, @NotNull String name) {\n\t\treturn new TableBuilder<>(table, type, instance, name).getTable();\n\t}\n\n\t@NotNull\n\tpublic <O, T extends Table<O>> T getTable(@NotNull Class<T> table, @NotNull Class<O> type, @NotNull Supplier<O> instance) {\n\t\treturn getTable(table, type, instance, type.getSimpleName().toLowerCase());\n\t}\n\n\t@NotNull\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <O> Table<O> getTable(@NotNull Class<O> type, @NotNull Supplier<O> instance, @NotNull String name) {\n\t\treturn getTable(Table.class, type, instance, name);\n\t}\n\n\t@NotNull\n\tpublic <O> Table<O> getTable(@NotNull Class<O> type, @NotNull Supplier<O> instance) {\n\t\treturn getTable(type, instance, type.getSimpleName().toLowerCase());\n\t}\n\n\t@NotNull\n\tpublic DatabaseManager putData(@NotNull String name, @NotNull Object value) {\n\t\tdata.put(name, value);\n\t\treturn this;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@NotNull\n\tpublic <T> T getData(@NotNull String name) {\n\t\treturn (T) data.get(name);\n\t}\n}" } ]
import data.CustomTable; import data.TestClass; import de.mineking.javautils.database.DatabaseManager; import org.junit.jupiter.api.Test;
1,573
public class CustomTableTest { public final DatabaseManager manager; public final CustomTable table; public CustomTableTest() { manager = new DatabaseManager("jdbc:postgresql://localhost:5433/test", "postgres", "test123");
public class CustomTableTest { public final DatabaseManager manager; public final CustomTable table; public CustomTableTest() { manager = new DatabaseManager("jdbc:postgresql://localhost:5433/test", "postgres", "test123");
table = manager.getTable(CustomTable.class, TestClass.class, this::createInstance, "test").createTable();
1
2023-12-13 14:05:17+00:00
2k
serendipitk/LunarCore
src/main/java/emu/lunarcore/data/excel/RelicSubAffixExcel.java
[ { "identifier": "GameDepot", "path": "src/main/java/emu/lunarcore/data/GameDepot.java", "snippet": "public class GameDepot {\n // Exp\n @Getter private static List<AvatarExpItemExcel> avatarExpExcels = new ArrayList<>();\n @Getter private static List<EquipmentExpItemExcel> equipmentExpExcels = new ArrayList<>();\n @Getter private static List<RelicExpItemExcel> relicExpExcels = new ArrayList<>();\n \n // Relics\n private static Int2ObjectMap<List<RelicMainAffixExcel>> relicMainAffixDepot = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<List<RelicSubAffixExcel>> relicSubAffixDepot = new Int2ObjectOpenHashMap<>();\n\n // Rogue\n @Getter private static Int2ObjectMap<int[]> rogueMapGen = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueBuffExcel> rogueAeonBuffs = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<List<RogueBuffExcel>> rogueAeonEnhanceBuffs = new Int2ObjectOpenHashMap<>();\n @Getter private static List<RogueBuffExcel> rogueRandomBuffList = new ArrayList<>();\n @Getter private static List<RogueMiracleExcel> rogueRandomMiracleList = new ArrayList<>();\n @Getter private static List<RogueNPCExcel> rogueRandomNpcList = new ArrayList<>();\n private static Int2ObjectMap<List<RogueMapExcel>> rogueMapDepot = new Int2ObjectOpenHashMap<>();\n \n public static void addRelicMainAffix(RelicMainAffixExcel affix) {\n relicMainAffixDepot\n .computeIfAbsent(affix.getGroupID(), k -> new ArrayList<>())\n .add(affix);\n }\n\n public static void addRelicSubAffix(RelicSubAffixExcel affix) {\n relicSubAffixDepot\n .computeIfAbsent(affix.getGroupID(), k -> new ArrayList<>())\n .add(affix);\n }\n\n public static RelicMainAffixExcel getRandomRelicMainAffix(int groupId) {\n var list = relicMainAffixDepot.get(groupId);\n if (list == null) return null;\n\n return list.get(Utils.randomRange(0, list.size() - 1));\n }\n\n public static List<RelicSubAffixExcel> getRelicSubAffixList(int groupId) {\n return relicSubAffixDepot.get(groupId);\n }\n \n // TODO cache this so we don't have to run this function every time we get the schedule\n public static RogueManagerExcel getCurrentRogueSchedule() {\n long time = System.currentTimeMillis() - (GameConstants.CURRENT_ZONEOFFSET.getTotalSeconds() * 1000);\n \n for (var schedule : GameData.getRogueManagerExcelMap().values()) {\n if (time >= schedule.getBeginTime() && time < schedule.getEndTime()) {\n return schedule;\n }\n }\n \n return null;\n }\n \n public static List<RogueMapExcel> getRogueMapsById(int mapId) {\n return rogueMapDepot.computeIfAbsent(mapId, id -> new ArrayList<>());\n }\n \n}" }, { "identifier": "GameResource", "path": "src/main/java/emu/lunarcore/data/GameResource.java", "snippet": "public abstract class GameResource implements Comparable<GameResource> {\n\n public abstract int getId();\n\n public void onLoad() {\n\n }\n\n @Override\n public int compareTo(GameResource o) {\n return this.getId() - o.getId();\n }\n}" }, { "identifier": "AvatarPropertyType", "path": "src/main/java/emu/lunarcore/game/enums/AvatarPropertyType.java", "snippet": "public enum AvatarPropertyType {\n Unknown (0),\n MaxHP (1),\n Attack (2),\n Defence (3),\n Speed (4),\n CriticalChance (5),\n CriticalDamage (6),\n HealRatio (7),\n StanceBreakAddedRatio (8),\n SPRatio (9),\n StatusProbability (10),\n StatusResistance (11),\n PhysicalAddedRatio (12),\n PhysicalResistance (13),\n FireAddedRatio (14),\n FireResistance (15),\n IceAddedRatio (16),\n IceResistance (17),\n ThunderAddedRatio (18),\n ThunderResistance (19),\n WindAddedRatio (20),\n WindResistance (21),\n QuantumAddedRatio (22),\n QuantumResistance (23),\n ImaginaryAddedRatio (24),\n ImaginaryResistance (25),\n BaseHP (26),\n HPDelta (27),\n BaseAttack (28),\n AttackDelta (29),\n BaseDefence (30),\n DefenceDelta (31),\n HPAddedRatio (32),\n AttackAddedRatio (33),\n DefenceAddedRatio (34),\n BaseSpeed (35),\n HealTakenRatio (36),\n PhysicalResistanceDelta (37),\n FireResistanceDelta (38),\n IceResistanceDelta (39),\n ThunderResistanceDelta (40),\n WindResistanceDelta (41),\n QuantumResistanceDelta (42),\n ImaginaryResistanceDelta (43),\n AllDamageReduce (44),\n RelicValueExtraAdditionRatio (45),\n EquipValueExtraAdditionRatio (46),\n EquipExtraRank (47),\n AvatarExtraRank (48),\n AllDamageTypeAddedRatio (49),\n SpeedAddedRatio (50),\n SpeedDelta (51),\n CriticalChanceBase (52),\n CriticalDamageBase (53),\n SPRatioBase (54),\n HealRatioBase (55),\n StatusProbabilityBase (56),\n StatusResistanceBase (57),\n BreakDamageAddedRatio (58),\n BreakDamageAddedRatioBase (59),\n MaxSP (60);\n\n @Getter\n private int val;\n\n private AvatarPropertyType(int value) {\n this.val = value;\n }\n}" } ]
import emu.lunarcore.data.GameDepot; import emu.lunarcore.data.GameResource; import emu.lunarcore.data.ResourceType; import emu.lunarcore.data.ResourceType.LoadPriority; import emu.lunarcore.game.enums.AvatarPropertyType; import lombok.Getter;
1,508
package emu.lunarcore.data.excel; @Getter @ResourceType(name = {"RelicSubAffixConfig.json"}, loadPriority = LoadPriority.NORMAL) public class RelicSubAffixExcel extends GameResource { private int GroupID; private int AffixID;
package emu.lunarcore.data.excel; @Getter @ResourceType(name = {"RelicSubAffixConfig.json"}, loadPriority = LoadPriority.NORMAL) public class RelicSubAffixExcel extends GameResource { private int GroupID; private int AffixID;
private AvatarPropertyType Property;
2
2023-12-08 14:13:04+00:00
2k
adabox-aio/dextreme-sdk
src/main/java/io/adabox/dextreme/dex/api/SpectrumApi.java
[ { "identifier": "Api", "path": "src/main/java/io/adabox/dextreme/dex/api/base/Api.java", "snippet": "@Getter\npublic abstract class Api {\n\n private final HttpClient client = HttpClient.newHttpClient();\n private final ObjectMapper objectMapper = new ObjectMapper();\n private final DexType dexType;\n\n /**\n * Api Constructor\n * @param dexType DEX Type Enum\n */\n public Api(DexType dexType) {\n this.dexType = dexType;\n }\n\n /**\n * Fetch all liquidity pools\n */\n public List<LiquidityPool> liquidityPools() {\n return this.liquidityPools(null, null);\n }\n\n /**\n * Fetch all liquidity pools matching assetA &amp; assetB.\n */\n public abstract List<LiquidityPool> liquidityPools(Asset assetA, Asset assetB);\n}" }, { "identifier": "DexType", "path": "src/main/java/io/adabox/dextreme/dex/base/DexType.java", "snippet": "public enum DexType {\n Minswap,\n Muesliswap,\n Sundaeswap,\n VyFinance,\n Spectrum,\n WingRiders;\n\n public DexType resolveDexType(String dexTypeString) {\n return Arrays.stream(values()).filter(dexType -> dexType.name().equalsIgnoreCase(dexTypeString)).findFirst().orElse(null);\n }\n}" }, { "identifier": "Asset", "path": "src/main/java/io/adabox/dextreme/model/Asset.java", "snippet": "@Data\n@Slf4j\n@EqualsAndHashCode\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Asset {\n\n private String policyId;\n private String nameHex;\n private int decimals;\n\n public static Asset fromId(String id, int decimals) {\n id = id.replace(\".\", \"\");\n if (id.equals(LOVELACE)) {\n return AssetType.ADA.getAsset();\n } else {\n return new Asset(id.substring(0, 56), id.substring(56), decimals);\n }\n }\n\n public String getIdentifier(String delimiter) {\n return policyId + delimiter + nameHex;\n }\n\n public String getNameHex() {\n return isLovelace() ? \"\" : nameHex;\n }\n\n @JsonIgnore\n public boolean isLovelace() {\n return nameHex.equalsIgnoreCase(LOVELACE);\n }\n\n public String getAssetName() {\n return isLovelace() ? \"ADA\" : new String(HexUtil.decodeHexString(getNameHex()), StandardCharsets.UTF_8);\n }\n\n @Override\n public String toString() {\n return getAssetName();\n }\n}" }, { "identifier": "LiquidityPool", "path": "src/main/java/io/adabox/dextreme/model/LiquidityPool.java", "snippet": "@Setter\n@Getter\n@ToString\n@NoArgsConstructor\npublic class LiquidityPool {\n\n private String dex;\n private Asset assetA;\n private Asset assetB;\n private BigInteger reserveA;\n private BigInteger reserveB;\n private String address;\n private String marketOrderAddress;\n private String limitOrderAddress;\n\n @JsonIgnore\n private Asset lpToken;\n private String identifier = \"\";\n private double poolFeePercent = 0.0;\n\n @JsonIgnore\n private UTxO uTxO;\n\n public LiquidityPool(String dex, Asset assetA, Asset assetB, BigInteger reserveA, BigInteger reserveB,\n String address, String marketOrderAddress, String limitOrderAddress) {\n this.dex = dex;\n this.assetA = assetA;\n this.assetB = assetB;\n this.reserveA = reserveA;\n this.reserveB = reserveB;\n this.address = address;\n this.marketOrderAddress = marketOrderAddress;\n this.limitOrderAddress = limitOrderAddress;\n }\n\n @JsonProperty(\"uuid\")\n public String getUuid() {\n return dex + \".\" + getPair() + \".\" + identifier;\n }\n\n public String getPair() {\n return assetA.getAssetName() + \"/\" + assetB.getAssetName();\n }\n\n public double getPrice() {\n double adjustedReserveA = reserveA.doubleValue() / Math.pow(10, assetA.getDecimals());\n double adjustedReserveB = reserveB.doubleValue() / Math.pow(10, assetB.getDecimals());\n\n return adjustedReserveA / adjustedReserveB;\n }\n\n @JsonProperty(\"TVL\")\n public double getTotalValueLocked() {\n double assetADividedByDecimals = reserveA.doubleValue() / Math.pow(10, assetA.getDecimals());\n double assetBDividedByDecimals = reserveB.doubleValue() / Math.pow(10, assetB.getDecimals());\n if (assetA.isLovelace()) {\n return assetADividedByDecimals + assetBDividedByDecimals * getPrice();\n }\n return (assetADividedByDecimals) * getPrice() * assetBDividedByDecimals * (1.0 / getPrice());\n }\n}" } ]
import com.bloxbean.cardano.client.util.HexUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import io.adabox.dextreme.dex.api.base.Api; import io.adabox.dextreme.dex.base.DexType; import io.adabox.dextreme.model.Asset; import io.adabox.dextreme.model.LiquidityPool; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.math.BigInteger; import java.net.URI; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.bloxbean.cardano.client.common.CardanoConstants.LOVELACE;
1,414
package io.adabox.dextreme.dex.api; /** * Spectrum API Class */ @Slf4j @Getter public class SpectrumApi extends Api { private static final String BASE_URL = "https://analytics.spectrum.fi"; public SpectrumApi() {
package io.adabox.dextreme.dex.api; /** * Spectrum API Class */ @Slf4j @Getter public class SpectrumApi extends Api { private static final String BASE_URL = "https://analytics.spectrum.fi"; public SpectrumApi() {
super(DexType.Spectrum);
1
2023-12-10 12:14:48+00:00
2k
lucas0headshot/ODS-Agro-ADS2-BackEnd
agro/src/main/java/com/ods/agro/controller/VendaController.java
[ { "identifier": "Venda", "path": "agro/src/main/java/com/ods/agro/entities/Venda.java", "snippet": "@Entity(name = \"venda\")\n@Getter\n@Setter\npublic class Venda extends EntityID{\n\n @ManyToOne\n @JoinColumn(name = \"cliente_id\", referencedColumnName = \"id\", nullable = false)\n private Cliente cliente;\n\n @ManyToOne\n @JoinColumn(name = \"produto_id\", referencedColumnName = \"id\",nullable = false)\n private Produto produto;\n\n @Column(name = \"qtd_vendida\")\n private Double qtdVendida;\n\n @Column(name = \"dt_venda\")\n private LocalDate dataVenda;\n\n public Venda(){\n this.dataVenda = LocalDate.now();\n }\n}" }, { "identifier": "VendaService", "path": "agro/src/main/java/com/ods/agro/services/VendaService.java", "snippet": "@Service\npublic class VendaService {\n @Autowired\n private VendaRepository vendaRepository;\n\n @Autowired\n private ProdutoRepository produtoRepository;\n\n public Venda salvarVenda(Venda venda) {\n Optional<Produto> byId = produtoRepository.findById(venda.getProduto().getId());\n if (venda.getQtdVendida() > byId.get().getQtdEstoque()) {\n throw new ValidationException(\"Não há estoque suficiente\");\n }\n\n if (venda.getQtdVendida() == 0) {\n throw new ValidationException(\"Quantidade da venda deve ser maior que zero\");\n }\n\n byId.get().setQtdEstoque(byId.get().getQtdEstoque() - venda.getQtdVendida());\n return vendaRepository.save(venda);\n }\n\n public Venda buscaPorId(Long id){\n return vendaRepository.findById(id).orElse(null);\n }\n\n public List<Venda> buscaTodos(){\n return vendaRepository.findAll();\n }\n\n public Venda atualizarVenda(Long id, Venda modificado) {\n Optional<Venda> optional = vendaRepository.findById(id);\n\n if (optional.isPresent()) {\n var venda = optional.get();\n venda.setDataVenda(modificado.getDataVenda());\n venda.setProduto(modificado.getProduto());\n venda.setCliente(modificado.getCliente());\n venda.setQtdVendida(modificado.getQtdVendida());\n return vendaRepository.save(venda);\n }\n\n return null;\n }\n\n public void deletarPorId(Long id){\n vendaRepository.deleteById(id);\n }\n}" } ]
import com.ods.agro.entities.Venda; import com.ods.agro.services.VendaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.util.List;
693
package com.ods.agro.controller; @RestController @RequestMapping("/api/vendas") public class VendaController extends AbstractController{ @Autowired
package com.ods.agro.controller; @RestController @RequestMapping("/api/vendas") public class VendaController extends AbstractController{ @Autowired
VendaService service;
1
2023-12-05 22:16:35+00:00
2k
zhaw-iwi/promise
src/main/java/ch/zhaw/statefulconversation/controllers/AgentController.java
[ { "identifier": "Agent", "path": "src/main/java/ch/zhaw/statefulconversation/model/Agent.java", "snippet": "@Entity\npublic class Agent {\n\n // @TODO: maybe have an attribute or getter method is active?\n\n @Id\n @GeneratedValue\n private UUID id;\n\n public UUID getId() {\n return this.id;\n }\n\n protected Agent() {\n\n }\n\n private String name;\n private String description;\n\n @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private State initialState;\n @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private State currentState;\n @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private Storage storage;\n\n public Agent(String name, String description, State initialState) {\n this(name, description, initialState, null);\n }\n\n public Agent(String name, String description, State initialState, Storage storage) {\n this.name = name;\n this.description = description;\n this.initialState = initialState;\n this.storage = storage;\n this.currentState = this.initialState;\n }\n\n public String name() {\n return this.name;\n }\n\n public String description() {\n return this.description;\n }\n\n public Map<String, JsonElement> storage() {\n return this.storage.toMap();\n }\n\n public boolean isActive() {\n return this.currentState.isActive();\n }\n\n public List<Utterance> conversation() {\n if (this.isActive()) {\n return this.currentState.getUtterances().toList();\n }\n return this.initialState.getUtterances().toList();\n }\n\n public String summarise() {\n if (this.isActive()) {\n return this.currentState.summarise();\n }\n return this.initialState.summarise();\n }\n\n public String start() {\n return this.currentState.start();\n }\n\n public String respond(String userSays) {\n try {\n return this.currentState.respond(userSays);\n } catch (TransitionException e) {\n this.currentState = e.getSubsequentState();\n if (this.currentState.isStarting()) {\n return this.start();\n }\n return this.respond(userSays);\n }\n }\n\n public String reRespond() {\n\n if (!this.isActive()) {\n throw new RuntimeException(\"cannot rerespond if agent is inactive.\");\n }\n\n String lastUserSays = this.currentState.getUtterances().removeLastTwoUtterances();\n return this.respond(lastUserSays);\n }\n\n public void reset() {\n this.currentState = this.initialState;\n this.currentState.reset();\n }\n\n public void resetCurrentState() {\n this.currentState.reset();\n }\n\n @Override\n public String toString() {\n return \"Agent with current state \" + this.currentState;\n }\n}" }, { "identifier": "Utterance", "path": "src/main/java/ch/zhaw/statefulconversation/model/Utterance.java", "snippet": "@Entity\npublic class Utterance {\n\n @Id\n @GeneratedValue\n @GsonExclude\n private UUID id;\n\n protected Utterance() {\n\n }\n\n private String role;\n @Column(length = 1000)\n private String content;\n\n @CreationTimestamp\n @Column(name = \"createdDate\", nullable = false, updatable = false)\n private Instant createdDate;\n\n public Utterance(String role, String content) {\n this.role = role;\n this.content = content;\n }\n\n public String getRole() {\n return this.role;\n }\n\n public String getContent() {\n return this.content;\n }\n\n public Instant getCreatedDate() { return createdDate; }\n\n @Override\n public String toString() {\n return \"{role=\\\"\" + role + \"\\\", content=\\\"\" + content + \"\\\"}\";\n }\n}" }, { "identifier": "AgentRepository", "path": "src/main/java/ch/zhaw/statefulconversation/repositories/AgentRepository.java", "snippet": "public interface AgentRepository extends JpaRepository<Agent, UUID> {\n\n}" }, { "identifier": "AgentInfoView", "path": "src/main/java/ch/zhaw/statefulconversation/views/AgentInfoView.java", "snippet": "public class AgentInfoView {\n private UUID id;\n private String name;\n private String description;\n\n public AgentInfoView(UUID id, String name, String descripion) {\n this.id = id;\n this.name = name;\n this.description = descripion;\n }\n\n public UUID getID() {\n return this.id;\n }\n\n public String getName() {\n return this.name;\n }\n\n public String getDescription() {\n return this.description;\n }\n}" }, { "identifier": "ResponseView", "path": "src/main/java/ch/zhaw/statefulconversation/views/ResponseView.java", "snippet": "public class ResponseView {\n private List<String> assistantSays;\n private boolean isActive;\n\n public ResponseView(List<String> assistantSays, boolean isActive) {\n this.assistantSays = assistantSays;\n this.isActive = isActive;\n }\n\n public List<String> getAssistantSays() {\n return this.assistantSays;\n }\n\n public boolean isActive() {\n return this.isActive;\n }\n}" } ]
import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import ch.zhaw.statefulconversation.model.Agent; import ch.zhaw.statefulconversation.model.Utterance; import ch.zhaw.statefulconversation.repositories.AgentRepository; import ch.zhaw.statefulconversation.views.AgentInfoView; import ch.zhaw.statefulconversation.views.ResponseView;
1,403
package ch.zhaw.statefulconversation.controllers; @RestController public class AgentController { @Autowired
package ch.zhaw.statefulconversation.controllers; @RestController public class AgentController { @Autowired
private AgentRepository repository;
2
2023-12-06 09:36:58+00:00
2k
SkyDynamic/QuickBackupM-Fabric
src/main/java/dev/skydynamic/quickbackupmulti/mixin/MinecraftServer_ClientMixin.java
[ { "identifier": "Config", "path": "src/main/java/dev/skydynamic/quickbackupmulti/utils/config/Config.java", "snippet": "public class Config {\n public static QuickBackupMultiConfig INSTANCE = new QuickBackupMultiConfig();\n public static QbmTempConfig TEMP_CONFIG = new QbmTempConfig();\n}" }, { "identifier": "LOGGER", "path": "src/main/java/dev/skydynamic/quickbackupmulti/QuickBackupMulti.java", "snippet": "public static final Logger LOGGER = LoggerFactory.getLogger(\"QuickBackupMulti\");" }, { "identifier": "createBackupDir", "path": "src/main/java/dev/skydynamic/quickbackupmulti/utils/QbmManager.java", "snippet": "public static void createBackupDir(Path path) {\n if (!path.toFile().exists()) {\n LOGGER.info(tr(\"quickbackupmulti.init.start\"));\n path.toFile().mkdirs();\n LOGGER.info(tr(\"quickbackupmulti.init.finish\"));\n }\n for(int j = 1; j<= Config.INSTANCE.getNumOfSlot(); j++) {\n if (!path.resolve(\"Slot\" + j).toFile().exists()) path.resolve(\"Slot\" + j).toFile().mkdir();\n }\n}" }, { "identifier": "buildScheduler", "path": "src/main/java/dev/skydynamic/quickbackupmulti/utils/schedule/CronUtil.java", "snippet": "public static void buildScheduler() {\n try {\n JobDetail jb = JobBuilder.newJob(ScheduleBackup.class).withIdentity(\"ScheduleBackup\").build();\n Trigger t = buildTrigger();\n StdSchedulerFactory sf = new StdSchedulerFactory();\n Config.TEMP_CONFIG.setScheduler(sf.getScheduler());\n Config.TEMP_CONFIG.scheduler.scheduleJob(jb, t);\n } catch (SchedulerException e) {\n LOGGER.error(e.toString());\n }\n}" } ]
import dev.skydynamic.quickbackupmulti.utils.config.Config; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.server.MinecraftServer; import org.quartz.SchedulerException; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.nio.file.Path; import static dev.skydynamic.quickbackupmulti.QuickBackupMulti.LOGGER; import static dev.skydynamic.quickbackupmulti.utils.QbmManager.createBackupDir; import static dev.skydynamic.quickbackupmulti.utils.schedule.CronUtil.buildScheduler;
647
package dev.skydynamic.quickbackupmulti.mixin; @Environment(EnvType.CLIENT) @Mixin(MinecraftServer.class) public class MinecraftServer_ClientMixin { @Inject(method = "loadWorld", at = @At("RETURN")) private void initQuickBackupMultiClient(CallbackInfo ci) { MinecraftServer server = (MinecraftServer) (Object) this; Config.TEMP_CONFIG.setServerValue(server); String worldName = server.getSaveProperties().getLevelName(); Config.TEMP_CONFIG.setWorldName(worldName); Path backupDir = Path.of(System.getProperty("user.dir") + "/QuickBackupMulti/").resolve(worldName);
package dev.skydynamic.quickbackupmulti.mixin; @Environment(EnvType.CLIENT) @Mixin(MinecraftServer.class) public class MinecraftServer_ClientMixin { @Inject(method = "loadWorld", at = @At("RETURN")) private void initQuickBackupMultiClient(CallbackInfo ci) { MinecraftServer server = (MinecraftServer) (Object) this; Config.TEMP_CONFIG.setServerValue(server); String worldName = server.getSaveProperties().getLevelName(); Config.TEMP_CONFIG.setWorldName(worldName); Path backupDir = Path.of(System.getProperty("user.dir") + "/QuickBackupMulti/").resolve(worldName);
createBackupDir(backupDir);
2
2023-12-09 13:51:17+00:00
2k
quentin452/Garden-Stuff-Continuation
src/main/resources/com/jaquadro/minecraft/gardencore/item/ItemCompost.java
[ { "identifier": "GardenCore", "path": "src/main/java/com/jaquadro/minecraft/gardencore/GardenCore.java", "snippet": "@Mod(modid = \"GardenCore\", name = \"Garden Core\", version = \"1.7.10-1.7.0\")\npublic class GardenCore {\n\n public static final String MOD_ID = \"GardenCore\";\n public static final String MOD_NAME = \"Garden Core\";\n public static final String MOD_VERSION = \"1.7.10-1.7.0\";\n static final String SOURCE_PATH = \"com.jaquadro.minecraft.gardencore.\";\n public static final ModIntegration integration = new ModIntegration();\n public static final ModBlocks blocks = new ModBlocks();\n public static final ModItems items = new ModItems();\n public static final ModRecipes recipes = new ModRecipes();\n public static ConfigManager config;\n @Instance(\"GardenCore\")\n public static GardenCore instance;\n @SidedProxy(\n clientSide = \"com.jaquadro.minecraft.gardencore.core.ClientProxy\",\n serverSide = \"com.jaquadro.minecraft.gardencore.core.ServerProxy\")\n public static CommonProxy proxy;\n\n @EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n config = new ConfigManager(new File(event.getModConfigurationDirectory(), \"GardenStuff/GardenCore.cfg\"));\n blocks.init();\n items.init();\n }\n\n @EventHandler\n public void init(FMLInitializationEvent event) {\n proxy.registerRenderers();\n NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());\n MinecraftForge.EVENT_BUS.register(new ForgeEventHandler());\n integration.init();\n GardenCoreAPI.instance()\n .registerBonemealHandler(new VanillaBonemealHandler());\n }\n\n @EventHandler\n public void postInit(FMLPostInitializationEvent event) {\n proxy.postInit();\n integration.postInit();\n recipes.init();\n }\n}" }, { "identifier": "EnrichedSoilEvent", "path": "src/main/java/com/jaquadro/minecraft/gardencore/api/event/EnrichedSoilEvent.java", "snippet": "@Cancelable\n@HasResult\npublic class EnrichedSoilEvent extends PlayerEvent {\n\n public final World world;\n public final Block block;\n public final int x;\n public final int y;\n public final int z;\n\n public EnrichedSoilEvent(EntityPlayer player, World world, Block block, int x, int y, int z) {\n super(player);\n this.world = world;\n this.block = block;\n this.x = x;\n this.y = y;\n this.z = z;\n }\n}" }, { "identifier": "ConfigManager", "path": "src/main/java/com/jaquadro/minecraft/gardencore/config/ConfigManager.java", "snippet": "public class ConfigManager {\n\n private final Configuration config;\n public boolean enableCompostBonemeal;\n public double compostBonemealStrength;\n public boolean enableTilledSoilGrowthBonus;\n\n public ConfigManager(File file) {\n this.config = new Configuration(file);\n Property propEnableCompostBonemeal = this.config.get(\"general\", \"enableCompostBonemeal\", true);\n propEnableCompostBonemeal.comment = \"Allows compost trigger plant growth like bonemeal.\";\n this.enableCompostBonemeal = propEnableCompostBonemeal.getBoolean();\n Property propCompostBonemealStrength = this.config.get(\"general\", \"compostBonemealStrength\", 0.5D);\n propCompostBonemealStrength.comment = \"The probability that compost will succeed when used as bonemeal relative to bonemeal.\";\n this.compostBonemealStrength = propCompostBonemealStrength.getDouble();\n Property propEnableTilledSoilGrowthBonus = this.config.get(\"general\", \"enableTilledSoilGrowthBonus\", true)\n .setRequiresMcRestart(true);\n propEnableTilledSoilGrowthBonus.comment = \"Allows tilled garden soil to advance crop growth more quickly. Enables random ticks.\";\n this.enableTilledSoilGrowthBonus = propEnableTilledSoilGrowthBonus.getBoolean();\n this.config.save();\n }\n}" }, { "identifier": "ModCreativeTabs", "path": "src/main/java/com/jaquadro/minecraft/gardencore/core/ModCreativeTabs.java", "snippet": "public final class ModCreativeTabs {\n\n public static final CreativeTabs tabGardenCore = new CreativeTabs(\"gardenCore\") {\n\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return Item.getItemFromBlock(ModBlocks.gardenSoil);\n }\n };\n\n private ModCreativeTabs() {}\n}" } ]
import com.jaquadro.minecraft.gardencore.GardenCore; import com.jaquadro.minecraft.gardencore.api.event.EnrichedSoilEvent; import com.jaquadro.minecraft.gardencore.config.ConfigManager; import com.jaquadro.minecraft.gardencore.core.ModCreativeTabs; import cpw.mods.fml.common.eventhandler.Event.Result; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge;
1,403
package com.jaquadro.minecraft.gardencore.item; public class ItemCompost extends Item { public ItemCompost(String unlocalizedName) { this.setUnlocalizedName(unlocalizedName); this.setMaxStackSize(64); this.setTextureName("GardenCore:compost_pile"); this.setCreativeTab(ModCreativeTabs.tabGardenCore); } public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { return !player.canPlayerEdit(x, y, z, side, itemStack) ? false : this.applyEnrichment(itemStack, world, x, y, z, player); } public boolean applyEnrichment(ItemStack itemStack, World world, int x, int y, int z, EntityPlayer player) {
package com.jaquadro.minecraft.gardencore.item; public class ItemCompost extends Item { public ItemCompost(String unlocalizedName) { this.setUnlocalizedName(unlocalizedName); this.setMaxStackSize(64); this.setTextureName("GardenCore:compost_pile"); this.setCreativeTab(ModCreativeTabs.tabGardenCore); } public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { return !player.canPlayerEdit(x, y, z, side, itemStack) ? false : this.applyEnrichment(itemStack, world, x, y, z, player); } public boolean applyEnrichment(ItemStack itemStack, World world, int x, int y, int z, EntityPlayer player) {
ConfigManager config = GardenCore.config;
2
2023-12-12 08:13:16+00:00
2k
joyheros/realworld
app-article/src/main/java/io/zhifou/realworld/article/infra/ArticleFavoriteRepository.java
[ { "identifier": "ArticleFavorite", "path": "app-article/src/main/java/io/zhifou/realworld/article/domain/ArticleFavorite.java", "snippet": "public class ArticleFavorite {\n\tprivate Long articleId;\n\tprivate Long userId;\n\n\tpublic ArticleFavorite() {\n\t}\n\n\tpublic ArticleFavorite(Long articleId, Long userId) {\n\t\tthis.articleId = articleId;\n\t\tthis.userId = userId;\n\t}\n\n\t/**\n\t * @return the articleId\n\t */\n\tpublic Long getArticleId() {\n\t\treturn articleId;\n\t}\n\n\t/**\n\t * @return the userId\n\t */\n\tpublic Long getUserId() {\n\t\treturn userId;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\treturn obj instanceof ArticleFavorite other && Objects.equals(this.articleId, other.articleId)\n\t\t\t\t&& Objects.equals(this.userId, other.userId);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(this.articleId, this.userId);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Tag {\" + \"articleId=\" + articleId + \", userId=\" + userId + \"}\";\n\t}\n}" }, { "identifier": "ArticleFavoriteProvider", "path": "app-article/src/main/java/io/zhifou/realworld/article/domain/support/ArticleFavoriteProvider.java", "snippet": "public interface ArticleFavoriteProvider {\n\tOptional<ArticleFavorite> save(ArticleFavorite articleFavorite);\n\n\tOptional<ArticleFavorite> find(Long articleId, Long userId);\n\n\tvoid remove(ArticleFavorite favorite);\n\n\tlong favoriteCount(Long articleId);\n}" }, { "identifier": "ArticleFavoriteMapper", "path": "app-article/src/main/java/io/zhifou/realworld/article/infra/mapper/ArticleFavoriteMapper.java", "snippet": "@Mapper\npublic interface ArticleFavoriteMapper {\n\t@Results(id = \"articleFavorite\", value = {\n\t\t@Result(column=\"article_id\", property=\"articleId\"),\n\t\t@Result(column=\"user_id\", property=\"userId\")\n\t})\n\t@Select(\"select article_id, user_id from article_favorites where article_id = #{articleId} and user_id = #{userId}\")\n\tArticleFavorite find(@Param(\"articleId\") Long articleId, @Param(\"userId\") Long userId);\n\n\t@Insert(\"insert into article_favorites (article_id, user_id) values (#{articleFavorite.articleId}, #{articleFavorite.userId})\")\n\tvoid insert(@Param(\"articleFavorite\") ArticleFavorite articleFavorite);\n\n\t@Delete(\"delete from article_favorites where article_id = #{favorite.articleId} and user_id = #{favorite.userId}\")\n\tvoid delete(@Param(\"favorite\") ArticleFavorite favorite);\n\n\t@Select(\"select count(1) from article_favorites where article_id = #{articleId}\")\n\tlong favoriteCount(@Param(\"articleId\") Long articleId);\n}" } ]
import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import io.zhifou.realworld.article.domain.ArticleFavorite; import io.zhifou.realworld.article.domain.support.ArticleFavoriteProvider; import io.zhifou.realworld.article.infra.mapper.ArticleFavoriteMapper;
750
package io.zhifou.realworld.article.infra; @Repository public class ArticleFavoriteRepository implements ArticleFavoriteProvider {
package io.zhifou.realworld.article.infra; @Repository public class ArticleFavoriteRepository implements ArticleFavoriteProvider {
private ArticleFavoriteMapper mapper;
2
2023-12-14 07:28:49+00:00
2k
Zergatul/java-scripting-language
src/main/java/com/zergatul/scripting/compiler/variables/VariableEntry.java
[ { "identifier": "CompilerMethodVisitor", "path": "src/main/java/com/zergatul/scripting/compiler/CompilerMethodVisitor.java", "snippet": "public abstract class CompilerMethodVisitor {\r\n public abstract String getClassName();\r\n public abstract VariableContextStack getContextStack();\r\n public abstract LoopContextStack getLoops();\r\n public abstract SType getReturnType();\r\n public abstract void visitInsn(final int opcode);\r\n public abstract void visitIntInsn(final int opcode, final int operand);\r\n public abstract void visitFieldInsn(final int opcode, final String owner, final String name, final String descriptor);\r\n public abstract void visitJumpInsn(final int opcode, final Label label);\r\n public abstract void visitLabel(final Label label);\r\n public abstract void visitLdcInsn(final Object value);\r\n public abstract void visitMethodInsn(final int opcode, final String owner, final String name, final String descriptor, final boolean isInterface);\r\n public abstract void visitTypeInsn(final int opcode, final String descriptor);\r\n public abstract void visitVarInsn(final int opcode, final int index);\r\n public abstract void visitIincInsn(final int varIndex, final int increment);\r\n}" }, { "identifier": "SType", "path": "src/main/java/com/zergatul/scripting/compiler/types/SType.java", "snippet": "public abstract class SType {\r\n\r\n public abstract Class<?> getJavaClass();\r\n public abstract void storeDefaultValue(CompilerMethodVisitor visitor);\r\n public abstract int getLoadInst();\r\n public abstract int getStoreInst();\r\n public abstract int getArrayLoadInst();\r\n public abstract int getArrayStoreInst();\r\n public abstract boolean isReference();\r\n public abstract int getReturnInst();\r\n\r\n public String getDescriptor() {\r\n return Type.getDescriptor(getJavaClass());\r\n }\r\n\r\n public BinaryOperation add(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation subtract(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation multiply(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation divide(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation modulo(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation floorMod(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation floorDiv(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation lessThan(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation greaterThan(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation lessEquals(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation greaterEquals(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation equalsOp(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation notEqualsOp(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation and(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation or(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation binary(Node node, SType other) throws ScriptCompileException {\r\n if (node instanceof ASTPlus) {\r\n return add(other);\r\n } if (node instanceof ASTMinus) {\r\n return subtract(other);\r\n } if (node instanceof ASTMult) {\r\n return multiply(other);\r\n } if (node instanceof ASTDiv) {\r\n return divide(other);\r\n } if (node instanceof ASTMod) {\r\n return modulo(other);\r\n } if (node instanceof ASTFloorDiv) {\r\n return floorDiv(other);\r\n } if (node instanceof ASTFloorMod) {\r\n return floorMod(other);\r\n } if (node instanceof ASTLessThan) {\r\n return lessThan(other);\r\n } if (node instanceof ASTGreaterThan) {\r\n return greaterThan(other);\r\n } if (node instanceof ASTLessEquals) {\r\n return lessEquals(other);\r\n } if (node instanceof ASTGreaterEquals) {\r\n return greaterEquals(other);\r\n } if (node instanceof ASTEquality) {\r\n return equalsOp(other);\r\n } if (node instanceof ASTInequality) {\r\n return notEqualsOp(other);\r\n } if (node instanceof ASTAnd) {\r\n return and(other);\r\n } if (node instanceof ASTOr) {\r\n return or(other);\r\n } else {\r\n throw new ScriptCompileException(String.format(\"Unexpected operator %s.\", node.getClass().getSimpleName()));\r\n }\r\n }\r\n\r\n public UnaryOperation plus() {\r\n return null;\r\n }\r\n\r\n public UnaryOperation minus() {\r\n return null;\r\n }\r\n\r\n public UnaryOperation not() {\r\n return null;\r\n }\r\n\r\n public UnaryOperation unary(Node node) throws ScriptCompileException {\r\n if (node instanceof ASTPlus) {\r\n return plus();\r\n } else if (node instanceof ASTMinus) {\r\n return minus();\r\n } else if (node instanceof ASTNot) {\r\n return not();\r\n } else {\r\n throw new ScriptCompileException(String.format(\"Unexpected operator %s.\", node.getClass().getSimpleName()));\r\n }\r\n }\r\n\r\n public SType compileGetField(String field, CompilerMethodVisitor visitor) throws ScriptCompileException {\r\n return null;\r\n }\r\n\r\n public static SType fromJavaClass(Class<?> type) throws ScriptCompileException {\r\n if (type == void.class) {\r\n return SVoidType.instance;\r\n }\r\n if (type == boolean.class) {\r\n return SBoolean.instance;\r\n }\r\n if (type == int.class) {\r\n return SIntType.instance;\r\n }\r\n if (type == double.class) {\r\n return SFloatType.instance;\r\n }\r\n if (type == String.class) {\r\n return SStringType.instance;\r\n }\r\n if (type.isArray()) {\r\n return new SArrayType(fromJavaClass(type.getComponentType()));\r\n }\r\n throw new ScriptCompileException(\"Invalid java type.\");\r\n }\r\n}" } ]
import com.zergatul.scripting.compiler.CompilerMethodVisitor; import com.zergatul.scripting.compiler.types.SType;
1,460
package com.zergatul.scripting.compiler.variables; public abstract class VariableEntry { protected final SType type; protected VariableEntry(SType type) { this.type = type; } public SType getType() { return type; }
package com.zergatul.scripting.compiler.variables; public abstract class VariableEntry { protected final SType type; protected VariableEntry(SType type) { this.type = type; } public SType getType() { return type; }
public abstract void compileLoad(CompilerMethodVisitor visitor);
0
2023-12-10 00:37:27+00:00
2k
microsphere-projects/microsphere-multiactive
microsphere-multiactive-spring-cloud/src/main/java/io/microsphere/multiple/active/zone/aws/Ec2AvailabilityZoneEndpointZoneLocator.java
[ { "identifier": "AbstractZoneLocator", "path": "microsphere-multiactive-spring-cloud/src/main/java/io/microsphere/multiple/active/zone/AbstractZoneLocator.java", "snippet": "public abstract class AbstractZoneLocator implements ZoneLocator, BeanNameAware, Ordered {\n\n protected final Logger logger = LoggerFactory.getLogger(getClass());\n\n protected String beanName;\n\n protected int order;\n\n public AbstractZoneLocator(int order) {\n setOrder(order);\n }\n\n @Override\n public final void setBeanName(String beanName) {\n this.beanName = beanName;\n }\n\n @Override\n public final int getOrder() {\n return order;\n }\n\n public final void setOrder(int order) {\n this.order = order;\n }\n\n\n @Override\n public String toString() {\n return \"ZoneLocator{\" + \"beanName='\" + beanName + '\\'' + \", order=\" + order + '}';\n }\n\n}" }, { "identifier": "HttpUtils", "path": "microsphere-multiactive-spring-cloud/src/main/java/io/microsphere/multiple/active/zone/HttpUtils.java", "snippet": "public abstract class HttpUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);\n\n /**\n * Retrieve a representation by doing a GET on the specified URL. The response (if any) is returned.\n *\n * @param url the URL\n * @param timeout timeout – an int that specifies the connect timeout value in milliseconds\n * @return The response context\n * @throws IOException\n */\n public static String doGet(String url, int timeout) throws IOException {\n String content = null;\n if (StringUtils.hasText(url)) {\n URLConnection urlConnection = new URL(url).openConnection();\n if (urlConnection instanceof HttpURLConnection) {\n HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;\n urlConnection.setConnectTimeout(timeout);\n urlConnection.setReadTimeout(timeout);\n try (InputStream inputStream = httpURLConnection.getInputStream()) {\n content = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);\n logger.info(\"The response of Availability Zone Endpoint[URI : '{}'] : {}\", url, content);\n } finally {\n httpURLConnection.disconnect();\n }\n }\n }\n return content;\n }\n}" }, { "identifier": "ZoneLocator", "path": "microsphere-multiactive-spring-cloud/src/main/java/io/microsphere/multiple/active/zone/ZoneLocator.java", "snippet": "public interface ZoneLocator {\n\n /**\n * Current {@link ZoneLocator} supports or not ?\n * \n * @param environment {@link Environment}\n * @return if <code>true</code>, {@link #locate(Environment)} will be invoked, or invocation will be\n * ignored.\n */\n boolean supports(Environment environment);\n\n /**\n * Locate the zone\n * \n * @return zone info\n */\n String locate(Environment environment);\n\n\n}" } ]
import io.microsphere.multiple.active.zone.AbstractZoneLocator; import io.microsphere.multiple.active.zone.HttpUtils; import io.microsphere.multiple.active.zone.ZoneLocator; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; import static io.microsphere.multiple.active.zone.ZoneConstants.DEFAULT_TIMEOUT; import static io.microsphere.multiple.active.zone.ZoneConstants.LOCATOR_TIMEOUT_PROPERTY_NAME;
1,022
package io.microsphere.multiple.active.zone.aws; /** * Amazon EC2 Availability Zone Endpoint {@link ZoneLocator} * * * @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/> * @see ZoneLocator * @since 1.0.0 */ public class Ec2AvailabilityZoneEndpointZoneLocator extends AbstractZoneLocator implements EnvironmentAware { public static final String AVAILABILITY_ZONE_ENDPOINT_URI_PROPERTY_NAME = "EC2_AVAILABILITY_ZONE_ENDPOINT_URI"; public static final String DEFAULT_AVAILABILITY_ZONE_ENDPOINT_URI = "http://169.254.169.254/latest/meta-data/placement/availability-zone"; public static final int DEFAULT_ORDER = 15; private int timeout = DEFAULT_TIMEOUT; public Ec2AvailabilityZoneEndpointZoneLocator() { super(DEFAULT_ORDER); } @Override public boolean supports(Environment environment) { return true; } @Override public String locate(Environment environment) { String uri = getAvailabilityZoneEndpointURI(environment); String zone = null; if (StringUtils.hasText(uri)) { try {
package io.microsphere.multiple.active.zone.aws; /** * Amazon EC2 Availability Zone Endpoint {@link ZoneLocator} * * * @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/> * @see ZoneLocator * @since 1.0.0 */ public class Ec2AvailabilityZoneEndpointZoneLocator extends AbstractZoneLocator implements EnvironmentAware { public static final String AVAILABILITY_ZONE_ENDPOINT_URI_PROPERTY_NAME = "EC2_AVAILABILITY_ZONE_ENDPOINT_URI"; public static final String DEFAULT_AVAILABILITY_ZONE_ENDPOINT_URI = "http://169.254.169.254/latest/meta-data/placement/availability-zone"; public static final int DEFAULT_ORDER = 15; private int timeout = DEFAULT_TIMEOUT; public Ec2AvailabilityZoneEndpointZoneLocator() { super(DEFAULT_ORDER); } @Override public boolean supports(Environment environment) { return true; } @Override public String locate(Environment environment) { String uri = getAvailabilityZoneEndpointURI(environment); String zone = null; if (StringUtils.hasText(uri)) { try {
zone = HttpUtils.doGet(uri, timeout);
1
2023-12-11 09:23:26+00:00
2k
Serilum/Collective
Fabric/src/main/java/com/natamus/collective/fabric/mixin/MinecraftServerMixin.java
[ { "identifier": "CollectiveLifecycleEvents", "path": "Fabric/src/main/java/com/natamus/collective/fabric/callbacks/CollectiveLifecycleEvents.java", "snippet": "public class CollectiveLifecycleEvents {\n\tprivate CollectiveLifecycleEvents() { }\n\t \n public static final Event<Minecraft_Loaded> MINECRAFT_LOADED = EventFactory.createArrayBacked(Minecraft_Loaded.class, callbacks -> (isclient) -> {\n for (Minecraft_Loaded callback : callbacks) {\n \tcallback.onMinecraftLoad(isclient);\n }\n });\n\n\tpublic static final Event<Default_Language_Loaded> DEFAULT_LANGUAGE_LOADED = EventFactory.createArrayBacked(Default_Language_Loaded.class, callbacks -> () -> {\n\t\tfor (Default_Language_Loaded callback : callbacks) {\n\t\t\tcallback.onLanguageLoad();\n\t\t}\n\t});\n \n\t@FunctionalInterface\n\tpublic interface Minecraft_Loaded {\n\t\t void onMinecraftLoad(boolean isclient);\n\t}\n\n\tpublic interface Default_Language_Loaded {\n\t\tvoid onLanguageLoad();\n\t}\n}" }, { "identifier": "CollectiveMinecraftServerEvents", "path": "Fabric/src/main/java/com/natamus/collective/fabric/callbacks/CollectiveMinecraftServerEvents.java", "snippet": "public final class CollectiveMinecraftServerEvents {\n\tprivate CollectiveMinecraftServerEvents() { }\n\t\t \n public static final Event<Set_Spawn> WORLD_SET_SPAWN = EventFactory.createArrayBacked(Set_Spawn.class, callbacks -> (serverLevel, serverLevelData) -> {\n for (Set_Spawn callback : callbacks) {\n \tcallback.onSetSpawn(serverLevel, serverLevelData);\n }\n });\n \n\t@FunctionalInterface\n\tpublic interface Set_Spawn {\n\t\t void onSetSpawn(ServerLevel serverLevel, ServerLevelData serverLevelData);\n\t}\n}" }, { "identifier": "CollectiveWorldEvents", "path": "Fabric/src/main/java/com/natamus/collective/fabric/callbacks/CollectiveWorldEvents.java", "snippet": "public class CollectiveWorldEvents {\n\tprivate CollectiveWorldEvents() { }\n\t \n public static final Event<World_Unload> WORLD_UNLOAD = EventFactory.createArrayBacked(World_Unload.class, callbacks -> (serverLevel) -> {\n for (World_Unload callback : callbacks) {\n \tcallback.onWorldUnload(serverLevel);\n }\n });\n \n\t@FunctionalInterface\n\tpublic interface World_Unload {\n\t\t void onWorldUnload(ServerLevel serverLevel);\n\t}\n}" } ]
import com.mojang.datafixers.DataFixer; import com.natamus.collective.fabric.callbacks.CollectiveLifecycleEvents; import com.natamus.collective.fabric.callbacks.CollectiveMinecraftServerEvents; import com.natamus.collective.fabric.callbacks.CollectiveWorldEvents; import net.minecraft.server.MinecraftServer; import net.minecraft.server.Services; import net.minecraft.server.WorldStem; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.progress.ChunkProgressListenerFactory; import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.ServerLevelData; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.net.Proxy;
1,118
package com.natamus.collective.fabric.mixin; @Mixin(value = MinecraftServer.class, priority = 1001) public class MinecraftServerMixin { @Inject(method = "<init>(Ljava/lang/Thread;Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;Lnet/minecraft/server/packs/repository/PackRepository;Lnet/minecraft/server/WorldStem;Ljava/net/Proxy;Lcom/mojang/datafixers/DataFixer;Lnet/minecraft/server/Services;Lnet/minecraft/server/level/progress/ChunkProgressListenerFactory;)V", at = @At(value = "TAIL")) public void MinecraftServer_init(Thread thread, LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem worldStem, Proxy proxy, DataFixer dataFixer, Services services, ChunkProgressListenerFactory chunkProgressListenerFactory, CallbackInfo ci) { ((MinecraftServer)(Object)this).execute(() -> { CollectiveLifecycleEvents.MINECRAFT_LOADED.invoker().onMinecraftLoad(false); }); } @Inject(method = "setInitialSpawn", at = @At(value = "RETURN")) private static void MinecraftServer_setInitialSpawn(ServerLevel serverLevel, ServerLevelData serverLevelData, boolean bl, boolean bl2, CallbackInfo ci) { CollectiveMinecraftServerEvents.WORLD_SET_SPAWN.invoker().onSetSpawn(serverLevel, serverLevelData); } @ModifyVariable(method = "stopServer", at = @At(value= "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;close()V", ordinal = 0)) public ServerLevel MinecraftServer_stopServer(ServerLevel serverlevel1) {
package com.natamus.collective.fabric.mixin; @Mixin(value = MinecraftServer.class, priority = 1001) public class MinecraftServerMixin { @Inject(method = "<init>(Ljava/lang/Thread;Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;Lnet/minecraft/server/packs/repository/PackRepository;Lnet/minecraft/server/WorldStem;Ljava/net/Proxy;Lcom/mojang/datafixers/DataFixer;Lnet/minecraft/server/Services;Lnet/minecraft/server/level/progress/ChunkProgressListenerFactory;)V", at = @At(value = "TAIL")) public void MinecraftServer_init(Thread thread, LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem worldStem, Proxy proxy, DataFixer dataFixer, Services services, ChunkProgressListenerFactory chunkProgressListenerFactory, CallbackInfo ci) { ((MinecraftServer)(Object)this).execute(() -> { CollectiveLifecycleEvents.MINECRAFT_LOADED.invoker().onMinecraftLoad(false); }); } @Inject(method = "setInitialSpawn", at = @At(value = "RETURN")) private static void MinecraftServer_setInitialSpawn(ServerLevel serverLevel, ServerLevelData serverLevelData, boolean bl, boolean bl2, CallbackInfo ci) { CollectiveMinecraftServerEvents.WORLD_SET_SPAWN.invoker().onSetSpawn(serverLevel, serverLevelData); } @ModifyVariable(method = "stopServer", at = @At(value= "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;close()V", ordinal = 0)) public ServerLevel MinecraftServer_stopServer(ServerLevel serverlevel1) {
CollectiveWorldEvents.WORLD_UNLOAD.invoker().onWorldUnload(serverlevel1);
2
2023-12-11 22:37:15+00:00
2k
MrXiaoM/plugin-template
src/main/java/top/mrxiaom/example/func/DatabaseManager.java
[ { "identifier": "ExamplePlugin", "path": "src/main/java/top/mrxiaom/example/ExamplePlugin.java", "snippet": "@SuppressWarnings({\"unused\"})\npublic class ExamplePlugin extends JavaPlugin implements Listener, TabCompleter {\n private static ExamplePlugin instance;\n public static ExamplePlugin getInstance() {\n return instance;\n }\n private GuiManager guiManager = null;\n Placeholder papi = null;\n Economy economy;\n public GuiManager getGuiManager() {\n return guiManager;\n }\n @NotNull\n public Economy getEconomy() {\n return economy;\n }\n @NotNull\n public Placeholder getPapi() {\n return papi;\n }\n @Override\n public void onEnable() {\n instance = this;\n\n loadHooks();\n\n loadFunctions();\n reloadConfig();\n\n Bukkit.getPluginManager().registerEvents(this, this);\n\n getLogger().info(\"插件加载完毕\");\n }\n\n public void loadFunctions() {\n try {\n for (Class<?> clazz : Lists.newArrayList(\n CommandMain.class, DatabaseManager.class\n )) {\n clazz.getDeclaredConstructor(getClass()).newInstance(this);\n }\n } catch (Throwable t) {\n t.printStackTrace();\n }\n guiManager = new GuiManager(this);\n }\n\n public void loadHooks() {\n RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServicesManager().getRegistration(Economy.class);\n if (economyProvider != null) {\n economy = economyProvider.getProvider();\n }\n Util.registerPlaceholder(getLogger(), papi = new Placeholder(this));\n }\n\n @Override\n public void onDisable() {\n AbstractPluginHolder.disableAllModule();\n getLogger().info(\"插件已卸载\");\n }\n\n @Override\n public void reloadConfig() {\n this.saveDefaultConfig();\n super.reloadConfig();\n\n FileConfiguration config = getConfig();\n AbstractPluginHolder.reloadAllConfig(config);\n }\n}" }, { "identifier": "IDatabase", "path": "src/main/java/top/mrxiaom/example/db/IDatabase.java", "snippet": "public interface IDatabase {\n void reload(Connection conn);\n}" }, { "identifier": "ExampleDatabase", "path": "src/main/java/top/mrxiaom/example/db/ExampleDatabase.java", "snippet": "public class ExampleDatabase extends AbstractPluginHolder implements IDatabase {\n public static final String TABLE_NAME = \"EXAMPLE\";\n public final DatabaseManager manager;\n public ExampleDatabase(DatabaseManager manager) {\n super(manager.plugin);\n this.manager = manager;\n }\n\n @Override\n public void reload(Connection conn) {\n SQLang.createTable(conn, TABLE_NAME, true,\n TableColumn.create(SQLValueType.ValueString.of(255), \"name\"),\n TableColumn.create(SQLValueType.ValueString.of(255), \"example\")\n );\n }\n\n public List<String> getExamplesByName(String name) {\n List<String> record = new ArrayList<>();\n try (Connection conn = manager.getConnection()) {\n try (PreparedStatement ps = SQLang.select(TABLE_NAME)\n .column(\"name\", \"example\")\n .where(\n Condition.of(\"name\", EnumOperators.EQUALS, name)\n )\n .orderBy(EnumOrder.DESC, \" time\")\n .limit(600)\n .build(conn).orElse(null)) {\n if (ps == null) throw new SQLException(\"无法构建语句\");\n\n ResultSet result = ps.executeQuery();\n\n while (result.next()) {\n String example = result.getString(\"example\");\n\n record.add(example);\n }\n }\n } catch (Throwable e) {\n e.printStackTrace();\n }\n return record;\n }\n\n public void putNameExample(String name, String example) {\n try (Connection conn = manager.getConnection()) {\n try (PreparedStatement ps = SQLang.insertInto(TABLE_NAME)\n .addValues(\n Pair.of(\"name\", name),\n Pair.of(\"example\", example)\n ).build(conn).orElse(null)) {\n if (ps == null) return;\n ps.execute();\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n}" } ]
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.bukkit.configuration.MemoryConfiguration; import org.jetbrains.annotations.Nullable; import top.mrxiaom.example.ExamplePlugin; import top.mrxiaom.example.db.IDatabase; import top.mrxiaom.example.db.ExampleDatabase; import java.sql.Connection; import java.util.ArrayList; import java.util.List;
1,151
package top.mrxiaom.example.func; public class DatabaseManager extends AbstractPluginHolder { HikariDataSource dataSource = null; private final List<IDatabase> databases = new ArrayList<>(); @Nullable public Connection getConnection() { try { return dataSource.getConnection(); } catch (Throwable t) { t.printStackTrace(); return null; } } public final ExampleDatabase example;
package top.mrxiaom.example.func; public class DatabaseManager extends AbstractPluginHolder { HikariDataSource dataSource = null; private final List<IDatabase> databases = new ArrayList<>(); @Nullable public Connection getConnection() { try { return dataSource.getConnection(); } catch (Throwable t) { t.printStackTrace(); return null; } } public final ExampleDatabase example;
public DatabaseManager(ExamplePlugin plugin) {
0
2023-12-08 15:50:57+00:00
2k
SmartPuck111/mypuchpro
src/main/java/com/blog/service/CommentServiceImpl.java
[ { "identifier": "CommentException", "path": "src/main/java/com/blog/exception/CommentException.java", "snippet": "public class CommentException extends Exception {\n\n\tpublic CommentException() {\n\t\t// TODO Auto-generated constructor stub\n\t}\n\n\tpublic CommentException(String message) {\n\t\tsuper(message);\n\t}\n\n}" }, { "identifier": "LoginException", "path": "src/main/java/com/blog/exception/LoginException.java", "snippet": "public class LoginException extends Exception {\n\n\tpublic LoginException() {\n\t\t// TODO Auto-generated constructor stub\n\t}\n\n\tpublic LoginException(String message) {\n\t\tsuper(message);\n\t}\n\n}" }, { "identifier": "PostException", "path": "src/main/java/com/blog/exception/PostException.java", "snippet": "public class PostException extends Exception {\n\n\tpublic PostException() {\n\t\t// TODO Auto-generated constructor stub\n\t}\n\n\tpublic PostException(String message) {\n\t\tsuper(message);\n\t}\n\n}" }, { "identifier": "Comment", "path": "src/main/java/com/blog/model/Comment.java", "snippet": "@Data\n@Entity\npublic class Comment {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\tprivate Integer id;\n\tprivate Integer postId;\n\tprivate String text;\n\tprivate LocalDateTime date;\n\n}" }, { "identifier": "CommentDTO", "path": "src/main/java/com/blog/model/CommentDTO.java", "snippet": "@Data\npublic class CommentDTO {\n\n\tprivate String text;\n}" }, { "identifier": "CommentUpdateDTO", "path": "src/main/java/com/blog/model/CommentUpdateDTO.java", "snippet": "@Data\npublic class CommentUpdateDTO {\n\n\tprivate String text;\n}" }, { "identifier": "Login", "path": "src/main/java/com/blog/model/Login.java", "snippet": "@Data\n@Entity\npublic class Login {\n\n\t@Id\n\t@JsonIgnore\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\tprivate Integer id;\n\n\t@Email\n\t@NotNull(message = \"Email format is require\")\n\tprivate String email;\n\n\t@NotNull(message = \"Password is require\")\n\t@Size(min = 6, max = 16, message = \"Password should between 6 to 16\")\n\tprivate String password;\n\n\t@JsonIgnore\n\tprivate LocalDateTime date;\n\t\n\t@JsonIgnore\n\tprivate String loginKey;\n\n}" }, { "identifier": "Post", "path": "src/main/java/com/blog/model/Post.java", "snippet": "@Data\n@Entity\npublic class Post {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\tprivate Integer id;\n\n\tprivate String title;\n\tprivate String description;\n\tprivate LocalDateTime date;\n\tprivate Integer authorId;\n\n\t@OneToMany(cascade = CascadeType.ALL)\n\tList<Comment> commentList = new ArrayList<>();\n\n}" }, { "identifier": "CommentRepo", "path": "src/main/java/com/blog/repository/CommentRepo.java", "snippet": "public interface CommentRepo extends JpaRepository<Comment, Integer>{\n\n}" }, { "identifier": "LoginRepo", "path": "src/main/java/com/blog/repository/LoginRepo.java", "snippet": "@Repository\npublic interface LoginRepo extends JpaRepository<Login, Integer> {\n\n\tpublic Login findByEmail(String email);\n\n}" }, { "identifier": "PostRepo", "path": "src/main/java/com/blog/repository/PostRepo.java", "snippet": "@Repository\npublic interface PostRepo extends JpaRepository<Post, Integer> {\n\n}" } ]
import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.blog.exception.CommentException; import com.blog.exception.LoginException; import com.blog.exception.PostException; import com.blog.model.Comment; import com.blog.model.CommentDTO; import com.blog.model.CommentUpdateDTO; import com.blog.model.Login; import com.blog.model.Post; import com.blog.repository.CommentRepo; import com.blog.repository.LoginRepo; import com.blog.repository.PostRepo;
987
package com.blog.service; @Service public class CommentServiceImpl implements CommentService { @Autowired private LoginRepo loginRepo; @Autowired private PostRepo postRepo; @Autowired private CommentRepo commentRepo; // checking user login validation public void checkLoginStatus() throws LoginException { List<Login> loginList = loginRepo.findAll(); if (loginList.isEmpty()) throw new LoginException("User login required!"); } // checking valid postId public Post checkValidPostId(Integer postId) throws PostException { Optional<Post> postOpt = postRepo.findById(postId); if (postOpt.isEmpty()) throw new PostException("Invalid post id"); return postOpt.get(); } @Override
package com.blog.service; @Service public class CommentServiceImpl implements CommentService { @Autowired private LoginRepo loginRepo; @Autowired private PostRepo postRepo; @Autowired private CommentRepo commentRepo; // checking user login validation public void checkLoginStatus() throws LoginException { List<Login> loginList = loginRepo.findAll(); if (loginList.isEmpty()) throw new LoginException("User login required!"); } // checking valid postId public Post checkValidPostId(Integer postId) throws PostException { Optional<Post> postOpt = postRepo.findById(postId); if (postOpt.isEmpty()) throw new PostException("Invalid post id"); return postOpt.get(); } @Override
public List<Comment> getAllComment(Integer postId) throws PostException, CommentException, LoginException {
0
2023-12-10 09:21:53+00:00
2k
ferhatcamgoz/modular-desing
product/src/main/java/com/layer/product/ProductServiceImpl.java
[ { "identifier": "BasketProductService", "path": "product/src/main/java/com/layer/product/basket/BasketProductService.java", "snippet": "public interface BasketProductService {\n\n List<ProductDto> getBasketProductsInfo(List<Long> productIds);\n\n Product getById(long productId);\n\n\n int getStock(long productId);\n\n}" }, { "identifier": "ProductDto", "path": "product/src/main/java/com/layer/product/basket/ProductDto.java", "snippet": "public final class ProductDto {\n\n private String name;\n private String description;\n private Double price;\n private int stock;\n\n\n public ProductDto(Product product) {\n this.name = product.getName();\n this.description = product.getDescription();\n this.price = product.getPrice();\n this.stock = product.getStock();\n }\n\n public ProductDto() {\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Double getPrice() {\n return price;\n }\n\n public void setPrice(Double price) {\n this.price = price;\n }\n\n public int getStock() {\n return stock;\n }\n\n public void setStock(int stock) {\n this.stock = stock;\n }\n}" }, { "identifier": "Product", "path": "product/src/main/java/com/layer/product/model/Product.java", "snippet": "@Entity\npublic class Product extends BaseEntity {\n\n private String name;\n private String description;\n private Double price;\n private int stock;\n\n public Product(ProductDto product) {\n this.name = product.getName();\n this.description = product.getDescription();\n this.price = product.getPrice();\n this.stock = product.getStock();\n }\n\n public Product() {\n\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Double getPrice() {\n return price;\n }\n\n public void setPrice(Double price) {\n this.price = price;\n }\n\n public int getStock() {\n return stock;\n }\n\n public void setStock(int stock) {\n this.stock = stock;\n }\n}" } ]
import com.layer.product.basket.BasketProductService; import com.layer.product.basket.ProductDto; import com.layer.product.model.Product; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors;
762
package com.layer.product; @Service public class ProductServiceImpl implements ProductService, BasketProductService { private final ProductRepo productRepo; public ProductServiceImpl(ProductRepo productRepo) { this.productRepo = productRepo; } @Override public ProductDto getProductInfo(Long productId) { return productRepo.findById(productId).map(ProductDto::new).orElse(new ProductDto()); } @Override public ProductDto createProduct(ProductDto productDto) {
package com.layer.product; @Service public class ProductServiceImpl implements ProductService, BasketProductService { private final ProductRepo productRepo; public ProductServiceImpl(ProductRepo productRepo) { this.productRepo = productRepo; } @Override public ProductDto getProductInfo(Long productId) { return productRepo.findById(productId).map(ProductDto::new).orElse(new ProductDto()); } @Override public ProductDto createProduct(ProductDto productDto) {
return new ProductDto(productRepo.save(new Product(productDto)));
2
2023-12-14 16:40:40+00:00
2k
ExcaliburFRC/2024RobotTamplate
src/main/java/frc/robot/subsystems/LEDs.java
[ { "identifier": "Color", "path": "src/main/java/frc/lib/Color.java", "snippet": "public class Color extends edu.wpi.first.wpilibj.util.Color {\n public Color(double red, double green, double blue) {\n super(green, red, blue);\n }\n\n public Color(int red, int green, int blue) {\n super(green, red, blue);\n }\n\n public Color(){\n super(0, 0, 0);\n }\n\n public static Color balance(Color color) {\n double v = Math.max(Math.max(color.red, color.green), color.blue);\n Color newColor = new Color(color.red, color.green / 2, color.blue / 4);\n double newV = Math.max(Math.max(newColor.red, newColor.green), newColor.blue);\n double ratio = v / newV;\n return new Color(newColor.red * ratio, newColor.green * ratio, newColor.blue * ratio);\n }\n\n public enum Colors {\n OFF(new Color(0, 0, 0)),\n\n TEAM_GOLD(new Color(255, 170, 0)),\n TEAM_BLUE(new Color(1, 30, 202)),\n\n RED(new Color(255, 0, 0)),\n GREEN(new Color(0, 255, 0)),\n BLUE(new Color(0, 0, 255)),\n\n WHITE(new Color(255, 255, 255)),\n\n YELLOW(new Color(255, 255, 0)),\n CYAN(new Color(0, 255, 255)),\n PINK(new Color(255, 0, 255)),\n\n ORANGE(new Color(255, 165, 0)),\n PURPLE(new Color(75, 0, 130));\n\n // TODO: add more colors\n\n public final Color color;\n\n Colors(Color color) {\n this.color = color;\n }\n }\n}" }, { "identifier": "LEDS_PORT", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static final int LEDS_PORT = 0; // pwm" }, { "identifier": "LENGTH", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static final int LENGTH = 139;" } ]
import edu.wpi.first.math.MathUtil; import edu.wpi.first.wpilibj.AddressableLED; import edu.wpi.first.wpilibj.AddressableLEDBuffer; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj2.command.*; import frc.lib.Color; import java.util.Arrays; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static frc.lib.Color.Colors.OFF; import static frc.robot.Constants.LedsConstants.LEDS_PORT; import static frc.robot.Constants.LedsConstants.LENGTH;
816
package frc.robot.subsystems; public class LEDs extends SubsystemBase { private final AddressableLED LedStrip = new AddressableLED(LEDS_PORT); private final AddressableLEDBuffer buffer = new AddressableLEDBuffer(LENGTH); private static LEDs instance = null; private Random rnd = new Random(); private int tailIndex = 0; private double offset = 0; private LEDs() { LedStrip.setLength(LENGTH); LedStrip.start(); // setDefaultCommand(applyPatternCommand(LEDPattern.TRAIN_CIRCLE, BLUE.color, TEAM_GOLD.color)); } public static LEDs getInstance() { if (instance == null) { instance = new LEDs(); } return instance; }
package frc.robot.subsystems; public class LEDs extends SubsystemBase { private final AddressableLED LedStrip = new AddressableLED(LEDS_PORT); private final AddressableLEDBuffer buffer = new AddressableLEDBuffer(LENGTH); private static LEDs instance = null; private Random rnd = new Random(); private int tailIndex = 0; private double offset = 0; private LEDs() { LedStrip.setLength(LENGTH); LedStrip.start(); // setDefaultCommand(applyPatternCommand(LEDPattern.TRAIN_CIRCLE, BLUE.color, TEAM_GOLD.color)); } public static LEDs getInstance() { if (instance == null) { instance = new LEDs(); } return instance; }
public Command applyPatternCommand(LEDPattern pattern, Color mainColor, Color accentColor) {
0
2023-12-13 22:33:35+00:00
2k