jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
    public void translate(ServerPlayerHealthPacket packet, GeyserSession session) {
        SessionPlayerEntity entity = session.getPlayerEntity();

        int health = (int) Math.ceil(packet.getHealth());
        SetHealthPacket setHealthPacket = new SetHealthPacket();
        setHealthPacket.setHealth(health);
        session.sendUpstreamPacket(setHealthPacket);

        entity.setHealth(packet.getHealth());

        UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
        List<AttributeData> attributes = attributesPacket.getAttributes();

        AttributeData healthAttribute = entity.createHealthAttribute();
        entity.getAttributes().put(GeyserAttributeType.HEALTH, healthAttribute);
        attributes.add(healthAttribute);

        AttributeData hungerAttribute = GeyserAttributeType.HUNGER.getAttribute(packet.getFood());
        entity.getAttributes().put(GeyserAttributeType.HUNGER, hungerAttribute);
        attributes.add(hungerAttribute);

        AttributeData saturationAttribute = GeyserAttributeType.SATURATION.getAttribute(packet.getSaturation());
        entity.getAttributes().put(GeyserAttributeType.SATURATION, saturationAttribute);
        attributes.add(saturationAttribute);

        attributesPacket.setRuntimeEntityId(entity.getGeyserId());
        session.sendUpstreamPacket(attributesPacket);
    }
//  [java]
    public void translate(GeyserSession session, ServerEntityPropertiesPacket packet) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (!(entity instanceof LivingEntity)) return;

        ((LivingEntity) entity).updateBedrockAttributes(session, packet.getAttributes());
    }
//  [java]
    public void translate(ServerEntityPropertiesPacket packet, GeyserSession session) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (!(entity instanceof LivingEntity)) return;

        ((LivingEntity) entity).updateBedrockAttributes(session, packet.getAttributes());
    }
//  [java]
		public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
	    throws IOException {
			String filename = file.getFileName().toString();

	        if(filename.endsWith(WikiManager.WIKI_PROPERTIES_SUFFIX)) {
	        	String f = convertAlternativeFilename(file.toString());
	        	final Path destFile = Paths.get(wikiDir.toString(), f);
	        	checkDestinationFile(destFile);
	        	resetAndCopyProperties(file, destFile);
	        } else if (filename.endsWith(WIKI_FILE_SUFFIX)) {
	        	String f = convertAlternativeFilename(file.toString());
	        	final Path destFile = Paths.get(wikiDir.toString(), f);
	        	checkDestinationFile(destFile);
	        	Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
			} else if (!filename.contains(WIKI_FILE_SUFFIX + "-")
					&& !filename.contains(WIKI_PROPERTIES_SUFFIX + "-")) {
				final Path destFile = Paths.get(mediaDir.toString(), file.toString());
				checkDestinationFile(destFile);
				Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
			}
	        return FileVisitResult.CONTINUE;
		}
//  [java]
	public boolean importWiki(File file, String filename, File targetDirectory) {
		try {
			Path path = FileResource.getResource(file, filename);
			if(path == null) {
				return false;
			}
			
			Path destDir = targetDirectory.toPath();
			Files.walkFileTree(path, EnumSet.noneOf(FileVisitOption.class), 16, new ImportVisitor(destDir));
			PathUtils.closeSubsequentFS(path);
			return true;
		} catch (IOException e) {
			log.error("", e);
			return false;
		}
	}
//  [java]
	public boolean importWiki(File file, String filename, File targetDirectory) {
		try {
			Path path = FileResource.getResource(file, filename);
			if(path == null) {
				return false;
			}
			
			Path destDir = targetDirectory.toPath();
			Files.walkFileTree(path, new ImportVisitor(destDir));
			PathUtils.closeSubsequentFS(path);
			return true;
		} catch (IOException e) {
			log.error("", e);
			return false;
		}
	}
//  [java]
    private Runnable getDiscoveryRequestSetup(final String url) {
        return new Runnable() {
            public void run() {
                expect(request.getHeader("Origin")).andStubReturn(null);
                expect(request.getHeader("Referer")).andStubReturn(null);
                expect(request.getRemoteHost()).andReturn("localhost");
                expect(request.getRemoteAddr()).andReturn("127.0.0.1");
                expect(request.getRequestURI()).andReturn("/jolokia/");
                expect(request.getParameterMap()).andReturn(null);
                expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null);

                expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
                expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain").anyTimes();
                StringBuffer buf = new StringBuffer();
                buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
                expect(request.getRequestURL()).andReturn(buf);
                expect(request.getRequestURI()).andReturn("/jolokia" + HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
                expect(request.getContextPath()).andReturn("/jolokia");
                expect(request.getAuthType()).andReturn("BASIC");
                expect(request.getAttribute("subject")).andReturn(null);
                expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null);

            }
        };
    }
//  [java]
    private Runnable getDiscoveryRequestSetup(final String url) {
        return new Runnable() {
            public void run() {
                expect(request.getHeader("Origin")).andStubReturn(null);
                expect(request.getHeader("Referer")).andStubReturn(null);
                expect(request.getRemoteHost()).andReturn("localhost");
                expect(request.getRemoteAddr()).andReturn("127.0.0.1");
                expect(request.getRequestURI()).andReturn("/jolokia/");
                expect(request.getParameterMap()).andReturn(null);
                expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null);

                expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
                expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
                StringBuffer buf = new StringBuffer();
                buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
                expect(request.getRequestURL()).andReturn(buf);
                expect(request.getRequestURI()).andReturn("/jolokia" + HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
                expect(request.getContextPath()).andReturn("/jolokia");
                expect(request.getAuthType()).andReturn("BASIC");
                expect(request.getAttribute("subject")).andReturn(null);
                expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null);

            }
        };
    }
//  [java]
	 public void doFilter(ServletRequest srequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

	 		HttpServletRequest request = (HttpServletRequest) srequest;
	 		filterChain.doFilter(new XssHttpServletRequestWrapper(request) {}, response);

	 }
//  [java]
	 public void doFilter(ServletRequest srequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

/*	 		HttpServletRequest request = (HttpServletRequest) srequest;
	 		//final String realIp = request.getHeader(X_FORWARDED_FOR);

	 		//if (realIp != null) {
	 			filterChain.doFilter(new XssHttpServletRequestWrapper(request) {
	 				*//**
	 				public String getRemoteAddr() {
	 					return realIp;
	 				}

	 				public String getRemoteHost() {
	 					return realIp;
	 				}
	 				**//*
	 			}, response);

	 			return;
	 		//}

*/

	 }
//  [java]
    private ByteArrayOutputStream initRequestResponseMocks(String callback,Runnable requestSetup,Runnable responseSetup) throws IOException {
        request = createMock(HttpServletRequest.class);
        response = createMock(HttpServletResponse.class);
        setNoCacheHeaders(response);

        expect(request.getParameter(ConfigKey.CALLBACK.getKeyValue())).andReturn(callback).anyTimes();
        requestSetup.run();
        responseSetup.run();

        class MyServletOutputStream extends ServletOutputStream {
            ByteArrayOutputStream baos;
            public void write(int b) throws IOException {
                baos.write(b);
            }

            public void setBaos(ByteArrayOutputStream baos){
                this.baos = baos;
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MyServletOutputStream sos = new MyServletOutputStream();
        sos.setBaos(baos);
        expect(response.getOutputStream()).andReturn(sos);

        return baos;
    }
//  [java]
    private ByteArrayOutputStream initRequestResponseMocks(String callback,Runnable requestSetup,Runnable responseSetup) throws IOException {
        request = createMock(HttpServletRequest.class);
        response = createMock(HttpServletResponse.class);
        setNoCacheHeaders(response);

        expect(request.getParameter(ConfigKey.CALLBACK.getKeyValue())).andReturn(callback);
        requestSetup.run();
        responseSetup.run();

        class MyServletOutputStream extends ServletOutputStream {
            ByteArrayOutputStream baos;
            public void write(int b) throws IOException {
                baos.write(b);
            }

            public void setBaos(ByteArrayOutputStream baos){
                this.baos = baos;
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MyServletOutputStream sos = new MyServletOutputStream();
        sos.setBaos(baos);
        expect(response.getOutputStream()).andReturn(sos);

        return baos;
    }
//  [java]
    public void translate(GeyserSession session, ServerPingPacket packet) {
        session.sendDownstreamPacket(new ClientPongPacket(packet.getId()));
    }
//  [java]
    public void translate(ServerPingPacket packet, GeyserSession session) {
        session.sendDownstreamPacket(new ClientPongPacket(packet.getId()));
    }
//  [java]
    public void translate(GeyserSession session, MoveEntityAbsolutePacket packet) {
        session.setLastVehicleMoveTimestamp(System.currentTimeMillis());

        float y = packet.getPosition().getY();
        if (session.getRidingVehicleEntity() instanceof BoatEntity) {
            // Remove the offset to prevents boats from looking like they're floating in water
            y -= EntityType.BOAT.getOffset();
        }
        ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket(
                packet.getPosition().getX(), y, packet.getPosition().getZ(),
                packet.getRotation().getY() - 90, packet.getRotation().getX()
        );
        session.sendDownstreamPacket(clientVehicleMovePacket);
    }
//  [java]
    public void translate(MoveEntityAbsolutePacket packet, GeyserSession session) {
        session.setLastVehicleMoveTimestamp(System.currentTimeMillis());

        float y = packet.getPosition().getY();
        if (session.getRidingVehicleEntity() instanceof BoatEntity) {
            // Remove the offset to prevents boats from looking like they're floating in water
            y -= EntityType.BOAT.getOffset();
        }
        ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket(
                packet.getPosition().getX(), y, packet.getPosition().getZ(),
                packet.getRotation().getY() - 90, packet.getRotation().getX()
        );
        session.sendDownstreamPacket(clientVehicleMovePacket);
    }
//  [java]
    public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file)
    {
        SysUser currentUser = getSysUser();
        try
        {
            if (!file.isEmpty())
            {
                String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
                currentUser.setAvatar(avatar);
                if (userService.updateUserInfo(currentUser) > 0)
                {
                    setSysUser(userService.selectUserById(currentUser.getUserId()));
                    return success();
                }
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("修改头像失败！", e);
            return error(e.getMessage());
        }
    }
//  [java]
    public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file)
    {
        SysUser currentUser = getSysUser();
        try
        {
            if (!file.isEmpty())
            {
                String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
                currentUser.setAvatar(avatar);
                if (userService.updateUserInfo(currentUser) > 0)
                {
                    setSysUser(userService.selectUserById(currentUser.getUserId()));
                    return success();
                }
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("修改头像失败！", e);
            return error(e.getMessage());
        }
    }
//  [java]
    protected TestPolicy(Policy.ParseContext parseContext) {
        super(parseContext);
    }
//  [java]
    protected TestPolicy(Policy.ParseContext parseContext) throws PolicyException {
        super(parseContext);
    }
//  [java]
	public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) {
		setTranslator(trans);
		currentContainer = folderComponent.getCurrentContainer();
		if (currentContainer.canWrite() != VFSConstants.YES) {
			throw new AssertException("Cannot write to current folder.");
		}
		
		status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
		if(status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
	
		selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());
		status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);
		if(status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
		
		if(selection.getFiles().isEmpty()) {
			status = FolderCommandStatus.STATUS_FAILED;
			wControl.setWarning(trans.translate("warning.file.selection.empty"));
			return null;
		}
		
		initForm(ureq);
		return this;
	}
//  [java]
	public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) {
		setTranslator(trans);
		currentContainer = folderComponent.getCurrentContainer();
		if (currentContainer.canWrite() != VFSConstants.YES) {
			throw new AssertException("Cannot write to current folder.");
		}
		
		status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
		if(status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
	
		selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
		status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);
		if(status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
		
		if(selection.getFiles().isEmpty()) {
			status = FolderCommandStatus.STATUS_FAILED;
			wControl.setWarning(trans.translate("warning.file.selection.empty"));
			return null;
		}
		
		initForm(ureq);
		return this;
	}
//  [java]
  public CsrfTokenHandler(final Form< ? > form)
  {
    csrfToken = getCsrfSessionToken();
    form.add(new HiddenField<String>("csrfToken", new PropertyModel<String>(this, "csrfToken")));
  }
//  [java]
  public CsrfTokenHandler(final Form< ? > form)
  {
    form.add(csrfTokenField = new HiddenField<String>("csrfToken", Model.of(getCsrfSessionToken())));
  }
//  [java]
	public Map<String, FileEntry> generatorCode(TableDetails tableDetails, String tablePrefix,
			Map<String, String> customProperties, List<TemplateFile> templateFiles) {

		Map<String, FileEntry> map = new HashMap<>(templateFiles.size());

		// 模板渲染
		Map<String, Object> context = GenUtils.getContext(tableDetails, tablePrefix, customProperties);

		for (TemplateFile templateFile : templateFiles) {
			FileEntry fileEntry = new FileEntry();
			fileEntry.setType(templateFile.getType());

			// 替换路径中的占位符
			String templateFilename = templateFile.getFilename();
			String filename = StrUtil.format(templateFilename, context);
			fileEntry.setFilename(filename);

			String parentFilePath = GenUtils.evaluateRealPath(templateFile.getParentFilePath(), context);
			fileEntry.setParentFilePath(parentFilePath);

			// 如果是文件
			if (TemplateEntryTypeEnum.FILE.getType().equals(fileEntry.getType())) {
				String filePath = GenUtils.concatFilePath(parentFilePath, filename);
				fileEntry.setFilePath(filePath);
				// 文件内容渲染
				TemplateEngineTypeEnum engineTypeEnum = TemplateEngineTypeEnum.of(templateFile.getEngineType());

				try {
					String content = templateEngineDelegator.render(engineTypeEnum, templateFile.getContent(), context);
					fileEntry.setContent(content);
				}
				catch (TemplateRenderException ex) {
					String errorMessage = StrUtil.format("模板渲染异常，模板文件名：【{}】，错误详情：{}", templateFilename,
							ex.getMessage());
					throw new BusinessException(SystemResultCode.SERVER_ERROR.getCode(), errorMessage);
				}
			}
			else {
				String currentPath = GenUtils.evaluateRealPath(templateFilename, context);
				fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, currentPath));
			}

			map.put(fileEntry.getFilePath(), fileEntry);
		}

		return map;
	}
//  [java]
	public Map<String, FileEntry> generatorCode(TableDetails tableDetails, String tablePrefix,
			Map<String, String> customProperties, List<TemplateFile> templateFiles) {

		Map<String, FileEntry> map = new HashMap<>(templateFiles.size());

		// 模板渲染
		Map<String, Object> context = GenUtils.getContext(tableDetails, tablePrefix, customProperties);

		for (TemplateFile templateFile : templateFiles) {
			FileEntry fileEntry = new FileEntry();
			fileEntry.setType(templateFile.getType());

			// 替换路径中的占位符
			String filename = StrUtil.format(templateFile.getFilename(), context);
			fileEntry.setFilename(filename);

			String parentFilePath = GenUtils.evaluateRealPath(templateFile.getParentFilePath(), context);
			fileEntry.setParentFilePath(parentFilePath);

			// 如果是文件
			if (TemplateEntryTypeEnum.FILE.getType().equals(fileEntry.getType())) {
				fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, filename));
				// 文件内容渲染
				TemplateEngineTypeEnum engineTypeEnum = TemplateEngineTypeEnum.of(templateFile.getEngineType());
				String content = templateEngineDelegator.render(engineTypeEnum, templateFile.getContent(), context);
				fileEntry.setContent(content);
			}
			else {
				String currentPath = GenUtils.evaluateRealPath(templateFile.getFilename(), context);
				fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, currentPath));
			}

			map.put(fileEntry.getFilePath(), fileEntry);
		}

		return map;
	}
//  [java]
    public void translate(GeyserSession session, NetworkStackLatencyPacket packet) {
        long pingId;
        // so apparently, as of 1.16.200
        // PS4 divides the network stack latency timestamp FOR US!!!
        // WTF
        if (session.getClientData().getDeviceOs().equals(DeviceOs.PS4)) {
            pingId = packet.getTimestamp();
        } else {
            pingId = packet.getTimestamp() / 1000;
        }

        // negative timestamps are used as hack to fix the url image loading bug
        if (packet.getTimestamp() > 0) {
            if (session.getConnector().getConfig().isForwardPlayerPing()) {
                ClientKeepAlivePacket keepAlivePacket = new ClientKeepAlivePacket(pingId);
                session.sendDownstreamPacket(keepAlivePacket);
            }
            return;
        }

        // Hack to fix the url image loading bug
        UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
        attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());

        AttributeData attribute = session.getPlayerEntity().getAttributes().get(GeyserAttributeType.EXPERIENCE_LEVEL);
        if (attribute != null) {
            attributesPacket.setAttributes(Collections.singletonList(attribute));
        } else {
            attributesPacket.setAttributes(Collections.singletonList(GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(0)));
        }

        session.getConnector().getGeneralThreadPool().schedule(
                () -> session.sendUpstreamPacket(attributesPacket),
                500, TimeUnit.MILLISECONDS);
    }
//  [java]
    public void translate(NetworkStackLatencyPacket packet, GeyserSession session) {
        long pingId;
        // so apparently, as of 1.16.200
        // PS4 divides the network stack latency timestamp FOR US!!!
        // WTF
        if (session.getClientData().getDeviceOs().equals(DeviceOs.PS4)) {
            pingId = packet.getTimestamp();
        } else {
            pingId = packet.getTimestamp() / 1000;
        }

        // negative timestamps are used as hack to fix the url image loading bug
        if (packet.getTimestamp() > 0) {
            if (session.getConnector().getConfig().isForwardPlayerPing()) {
                ClientKeepAlivePacket keepAlivePacket = new ClientKeepAlivePacket(pingId);
                session.sendDownstreamPacket(keepAlivePacket);
            }
            return;
        }

        // Hack to fix the url image loading bug
        UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
        attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());

        AttributeData attribute = session.getPlayerEntity().getAttributes().get(GeyserAttributeType.EXPERIENCE_LEVEL);
        if (attribute != null) {
            attributesPacket.setAttributes(Collections.singletonList(attribute));
        } else {
            attributesPacket.setAttributes(Collections.singletonList(GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(0)));
        }

        session.getConnector().getGeneralThreadPool().schedule(
                () -> session.sendUpstreamPacket(attributesPacket),
                500, TimeUnit.MILLISECONDS);
    }
//  [java]
  public void onSubmit()
  {
    final String sessionCsrfToken = getCsrfSessionToken();
    if (StringUtils.equals(sessionCsrfToken, csrfToken) == false) {
      log.error("Cross site request forgery alert. csrf token doesn't match! session csrf token="
          + sessionCsrfToken
          + ", posted csrf token="
          + csrfToken);
      throw new InternalErrorException("errorpage.csrfError");
    }
  }
//  [java]
  public void onSubmit()
  {
    final String sessionCsrfToken = getCsrfSessionToken();
    final String postedCsrfToken = this.csrfTokenField.getInput();
    if (StringUtils.equals(sessionCsrfToken, postedCsrfToken) == false) {
      log.error("Cross site request forgery alert. csrf token doesn't match! session csrf token="
          + sessionCsrfToken
          + ", posted csrf token="
          + postedCsrfToken);
      throw new InternalErrorException("errorpage.csrfError");
    }
  }
//  [java]
    public void translate(GeyserSession session, MapInfoRequestPacket packet) {
        long mapId = packet.getUniqueMapId();

        ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId);
        if (mapPacket != null) {
            // Delay the packet 100ms to prevent the client from ignoring the packet
            GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket),
                    100, TimeUnit.MILLISECONDS);
        }
    }
//  [java]
    public void translate(MapInfoRequestPacket packet, GeyserSession session) {
        long mapId = packet.getUniqueMapId();

        ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId);
        if (mapPacket != null) {
            // Delay the packet 100ms to prevent the client from ignoring the packet
            GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket),
                    100, TimeUnit.MILLISECONDS);
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerBossBarPacket packet) {
        BossBar bossBar = session.getEntityCache().getBossBar(packet.getUuid());
        switch (packet.getAction()) {
            case ADD:
                long entityId = session.getEntityCache().getNextEntityId().incrementAndGet();
                bossBar = new BossBar(session, entityId, packet.getTitle(), packet.getHealth(), 0, 1, 0);
                session.getEntityCache().addBossBar(packet.getUuid(), bossBar);
                break;
            case UPDATE_TITLE:
                if (bossBar != null) bossBar.updateTitle(packet.getTitle());
                break;
            case UPDATE_HEALTH:
                if (bossBar != null) bossBar.updateHealth(packet.getHealth());
                break;
            case REMOVE:
                session.getEntityCache().removeBossBar(packet.getUuid());
                break;
            case UPDATE_STYLE:
            case UPDATE_FLAGS:
                //todo
        }
    }
//  [java]
    public void translate(ServerBossBarPacket packet, GeyserSession session) {
        BossBar bossBar = session.getEntityCache().getBossBar(packet.getUuid());
        switch (packet.getAction()) {
            case ADD:
                long entityId = session.getEntityCache().getNextEntityId().incrementAndGet();
                bossBar = new BossBar(session, entityId, packet.getTitle(), packet.getHealth(), 0, 1, 0);
                session.getEntityCache().addBossBar(packet.getUuid(), bossBar);
                break;
            case UPDATE_TITLE:
                if (bossBar != null) bossBar.updateTitle(packet.getTitle());
                break;
            case UPDATE_HEALTH:
                if (bossBar != null) bossBar.updateHealth(packet.getHealth());
                break;
            case REMOVE:
                session.getEntityCache().removeBossBar(packet.getUuid());
                break;
            case UPDATE_STYLE:
            case UPDATE_FLAGS:
                //todo
        }
    }
//  [java]
    public void translate(GeyserSession session, ServerSpawnPlayerPacket packet) {
        Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
        Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getYaw());

        PlayerEntity entity;
        if (packet.getUuid().equals(session.getPlayerEntity().getUuid())) {
            // Server is sending a fake version of the current player
            entity = new PlayerEntity(session.getPlayerEntity().getProfile(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), position, Vector3f.ZERO, rotation);
        } else {
            entity = session.getEntityCache().getPlayerEntity(packet.getUuid());
            if (entity == null) {
                GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.entity.player.failed_list", packet.getUuid()));
                return;
            }

            entity.setEntityId(packet.getEntityId());
            entity.setPosition(position);
            entity.setRotation(rotation);
        }
        session.getEntityCache().cacheEntity(entity);

        entity.sendPlayer(session);
        SkinManager.requestAndHandleSkinAndCape(entity, session, null);
    }
//  [java]
    public void translate(ServerSpawnPlayerPacket packet, GeyserSession session) {
        Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
        Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getYaw());

        PlayerEntity entity;
        if (packet.getUuid().equals(session.getPlayerEntity().getUuid())) {
            // Server is sending a fake version of the current player
            entity = new PlayerEntity(session.getPlayerEntity().getProfile(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), position, Vector3f.ZERO, rotation);
        } else {
            entity = session.getEntityCache().getPlayerEntity(packet.getUuid());
            if (entity == null) {
                GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.entity.player.failed_list", packet.getUuid()));
                return;
            }

            entity.setEntityId(packet.getEntityId());
            entity.setPosition(position);
            entity.setRotation(rotation);
        }
        session.getEntityCache().cacheEntity(entity);

        entity.sendPlayer(session);
        SkinManager.requestAndHandleSkinAndCape(entity, session, null);
    }
//  [python]
def _load_yamlconfig(self, configfile):
    yamlconfig = None
    try:
        if self._recent_pyyaml():
            # https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation
            # only for 5.1+
            yamlconfig = yaml.load(open(configfile), Loader=yaml.SafeLoader)
        else:
            yamlconfig = yaml.safe_load(open(configfile))
    except yaml.YAMLError as exc:
        logger.error("Error in configuration file {0}:".format(configfile))
        if hasattr(exc, 'problem_mark'):
            mark = exc.problem_mark
            raise PystemonConfigException("error position: (%s:%s)" % (mark.line + 1, mark.column + 1))
    for includes in yamlconfig.get("includes", []):
        try:
            logger.debug("loading include '{0}'".format(includes))
            yamlconfig.update(yaml.safe_load(open(includes)))
        except Exception as e:
            raise PystemonConfigException("failed to load '{0}': {1}".format(includes, e))
    return yamlconfig
//  [python]
def _load_yamlconfig(self, configfile):
    yamlconfig = None
    try:
        if self._recent_pyyaml():
            # https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation
            # only for 5.1+
            yamlconfig = yaml.load(open(configfile), Loader=yaml.FullLoader)
        else:
            yamlconfig = yaml.load(open(configfile))
    except yaml.YAMLError as exc:
        logger.error("Error in configuration file {0}:".format(configfile))
        if hasattr(exc, 'problem_mark'):
            mark = exc.problem_mark
            raise PystemonConfigException("error position: (%s:%s)" % (mark.line + 1, mark.column + 1))
    for includes in yamlconfig.get("includes", []):
        try:
            logger.debug("loading include '{0}'".format(includes))
            yamlconfig.update(yaml.load(open(includes)))
        except Exception as e:
            raise PystemonConfigException("failed to load '{0}': {1}".format(includes, e))
    return yamlconfig
//  [python]
def __init__(self, sourceName: str, *, chroot: bool, chrootPath: Optional[str] = None):
    self.sourceName = sourceName
    self.chrootPath = chrootPath
    self.type = "file"
    self.content = None

    if chroot and self.chrootPath is None:
        self.chrootPath = self.directory()
    if self.chrootPath is not None:
        self.sourceName = config.chrootPath(self.chrootPath, self.sourceName)
//  [python]
def __init__(self, sourceName: str):
    self.sourceName = sourceName
    self.type = "file"
    self.content = None
//  [python]
def auth_ldap_server(self) -> str:
    return self.appbuilder.get_app.config["AUTH_LDAP_SERVER"]
//  [python]
def auth_ldap_server(self):
    return self.appbuilder.get_app.config["AUTH_LDAP_SERVER"]
//  [python]
def auth_role_admin(self) -> str:
    return self.appbuilder.get_app.config["AUTH_ROLE_ADMIN"]
//  [python]
def auth_role_admin(self):
    return self.appbuilder.get_app.config["AUTH_ROLE_ADMIN"]
//  [python]
def auth_ldap_use_tls(self) -> bool:
    return self.appbuilder.get_app.config["AUTH_LDAP_USE_TLS"]
//  [python]
def auth_ldap_use_tls(self):
    return self.appbuilder.get_app.config["AUTH_LDAP_USE_TLS"]
//  [python]
def relative(self, relativePath) -> FileInputSource:
    return FileInputSource(os.path.join(self.directory(), relativePath), chroot=False, chrootPath=self.chrootPath)
//  [python]
def relative(self, relativePath) -> FileInputSource:
    return FileInputSource(os.path.join(self.directory(), relativePath))
//  [python]
def auth_type(self) -> int:
    return self.appbuilder.get_app.config["AUTH_TYPE"]
//  [python]
def auth_type(self):
    return self.appbuilder.get_app.config["AUTH_TYPE"]
//  [python]
def __new__(cls, sourceName: str, **kwargs):
    """Dispatches to the right subclass."""
    if cls != InputSource:
        # Only take control of calls to InputSource(...) itself.
        return super().__new__(cls)

    if sourceName == "-":
        return StdinInputSource(sourceName, **kwargs)
    if sourceName.startswith("https:"):
        return UrlInputSource(sourceName, **kwargs)
    return FileInputSource(sourceName, **kwargs)
//  [python]
def __new__(cls, sourceName: str):
    """Dispatches to the right subclass."""
    if cls != InputSource:
        # Only take control of calls to InputSource(...) itself.
        return super().__new__(cls)

    if sourceName == "-":
        return StdinInputSource(sourceName)
    if sourceName.startswith("https:"):
        return UrlInputSource(sourceName)
    return FileInputSource(sourceName)
//  [python]
def auth_user_registration(self) -> bool:
    return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION"]
//  [python]
def auth_user_registration(self):
    return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION"]
//  [python]
def auth_role_public(self) -> str:
    return self.appbuilder.get_app.config["AUTH_ROLE_PUBLIC"]
//  [python]
def auth_role_public(self):
    return self.appbuilder.get_app.config["AUTH_ROLE_PUBLIC"]
//  [python]
def auth_username_ci(self) -> str:
    return self.appbuilder.get_app.config.get("AUTH_USERNAME_CI", True)
//  [python]
def auth_username_ci(self):
    return self.appbuilder.get_app.config.get("AUTH_USERNAME_CI", True)
//  [python]
def auth_user_registration_role(self) -> str:
    return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION_ROLE"]
//  [python]
def auth_user_registration_role(self):
    return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION_ROLE"]
//  [python]
def builtin_roles(self) -> Dict[str, Any]:
    return self._builtin_roles
//  [python]
def builtin_roles(self):
    return self._builtin_roles
//  [python]
async def apiui_command_help(request, user):
    template = env.get_template('apiui_command_help.html')
    if len(request.query_args) != 0:
        data = urllib.parse.unquote(request.query_args[0][1])
        query = await db_model.payloadtype_query()
        try:
            payloadtype = await db_objects.get(query, ptype=data)
        except Exception as e:
            data = ""
    else:
        data = ""
    if use_ssl:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="https",
                                  ws="wss", config=user['ui_config'], view_utc_time=user['view_utc_time'], agent=data)
    else:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="http",
                                  ws="ws", config=user['ui_config'], view_utc_time=user['view_utc_time'], agent=data)
    return response.html(content)
//  [python]
async def apiui_command_help(request, user):
    template = env.get_template('apiui_command_help.html')
    if len(request.query_args) != 0:
        data = urllib.parse.unquote(request.query_args[0][1])
        print(data)
    else:
        data = ""
    if use_ssl:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="https",
                                  ws="wss", config=user['ui_config'], view_utc_time=user['view_utc_time'], agent=data)
    else:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="http",
                                  ws="ws", config=user['ui_config'], view_utc_time=user['view_utc_time'], agent=data)
    return response.html(content)
//  [python]
def calc(self, irc, msg, args, text):
    """<math expression>

    Returns the value of the evaluated <math expression>.  The syntax is
    Python syntax; the type of arithmetic is floating point.  Floating
    point arithmetic is used in order to prevent a user from being able to
    crash to the bot with something like '10**10**10**10'.  One consequence
    is that large values such as '10**24' might not be exact.
    """
    try:
        self.log.info('evaluating %q from %s', text, msg.prefix)
        x = complex(safe_eval(text, allow_ints=False))
        irc.reply(self._complexToString(x))
    except OverflowError:
        maxFloat = math.ldexp(0.9999999999999999, 1024)
        irc.error(_('The answer exceeded %s or so.') % maxFloat)
    except InvalidNode as e:
        irc.error(_('Invalid syntax: %s') % e.args[0])
    except NameError as e:
        irc.error(_('%s is not a defined function.') % e.args[0])
    except Exception as e:
        irc.error(str(e))
//  [python]
def calc(self, irc, msg, args, text):
    """<math expression>

    Returns the value of the evaluated <math expression>.  The syntax is
    Python syntax; the type of arithmetic is floating point.  Floating
    point arithmetic is used in order to prevent a user from being able to
    crash to the bot with something like '10**10**10**10'.  One consequence
    is that large values such as '10**24' might not be exact.
    """
    try:
        text = str(text)
    except UnicodeEncodeError:
        irc.error(_("There's no reason you should have fancy non-ASCII "
                        "characters in your mathematical expression. "
                        "Please remove them."))
        return
    if self._calc_match_forbidden_chars.match(text):
        # Note: this is important to keep this to forbid usage of
        # __builtins__
        irc.error(_('There\'s really no reason why you should have '
                       'underscores or brackets in your mathematical '
                       'expression.  Please remove them.'))
        return
    text = self._calc_remover(text)
    if 'lambda' in text:
        irc.error(_('You can\'t use lambda in this command.'))
        return
    text = text.lower()
    def handleMatch(m):
        s = m.group(1)
        if s.startswith('0x'):
            i = int(s, 16)
        elif s.startswith('0') and '.' not in s:
            try:
                i = int(s, 8)
            except ValueError:
                i = int(s)
        else:
            i = float(s)
        x = complex(i)
        if x.imag == 0:
            x = x.real
            # Need to use string-formatting here instead of str() because
            # use of str() on large numbers loses information:
            # str(float(33333333333333)) => '3.33333333333e+13'
            # float('3.33333333333e+13') => 33333333333300.0
            return '%.16f' % x
        return str(x)
    text = self._mathRe.sub(handleMatch, text)
    try:
        self.log.info('evaluating %q from %s', text, msg.prefix)
        x = complex(eval(text, self._mathSafeEnv, self._mathSafeEnv))
        irc.reply(self._complexToString(x))
    except OverflowError:
        maxFloat = math.ldexp(0.9999999999999999, 1024)
        irc.error(_('The answer exceeded %s or so.') % maxFloat)
    except TypeError:
        irc.error(_('Something in there wasn\'t a valid number.'))
    except NameError as e:
        irc.error(_('%s is not a defined function.') % str(e).split()[1])
    except Exception as e:
        irc.error(str(e))
//  [python]
def decompile(self):
	self.writeln("** Decompiling APK...", clr.OKBLUE)
	with ZipFile(self.file) as zipped:
		try:
			dex = self.tempdir + "/" + self.apk.package + ".dex"
			with open(dex, "wb") as classes:
				classes.write(zipped.read("classes.dex"))
		except Exception as e:
			sys.exit(self.writeln(str(e), clr.WARNING))
	args = [self.jadx, dex, "-d", self.tempdir, "--deobf"]
	comm = "%s" % (" ".join(quote(arg) for arg in args))
	os.system(comm)
	return self.tempdir
//  [python]
def decompile(self):
	self.writeln("** Decompiling APK...", clr.OKBLUE)
	with ZipFile(self.file) as zipped:
		try:
			dex = self.tempdir + "/" + self.apk.package + ".dex"
			with open(dex, "wb") as classes:
				classes.write(zipped.read("classes.dex"))
		except Exception as e:
			sys.exit(self.writeln(str(e), clr.WARNING))
	dec = "%s %s -d %s --deobf" % (self.jadx, dex, self.tempdir)
	os.system(dec)
	return self.tempdir
//  [python]
def traverse(cls, base, request, path_items):
    """See ``zope.app.pagetemplate.engine``."""

    validate = getSecurityManager().validate
    path_items = list(path_items)
    path_items.reverse()

    while path_items:
        name = path_items.pop()

        if ITraversable.providedBy(base):
            base = getattr(base, cls.traverse_method)(name)
        else:
            found = traversePathElement(base, name, path_items,
                                        request=request)

            # If traverse_method is something other than
            # ``restrictedTraverse`` then traversal is assumed to be
            # unrestricted. This emulates ``unrestrictedTraverse``
            if cls.traverse_method != 'restrictedTraverse':
                base = found
                continue

            # Special backwards compatibility exception for the name ``_``,
            # which was often used for translation message factories.
            # Allow and continue traversal.
            if name == '_':
                warnings.warn('Traversing to the name `_` is deprecated '
                              'and will be removed in Zope 6.',
                              DeprecationWarning)
                base = found
                continue

            # All other names starting with ``_`` are disallowed.
            # This emulates what restrictedTraverse does.
            if name.startswith('_'):
                raise NotFound(name)

            # traversePathElement doesn't apply any Zope security policy,
            # so we validate access explicitly here.
            try:
                validate(base, base, name, found)
                base = found
            except Unauthorized:
                # Convert Unauthorized to prevent information disclosures
                raise NotFound(name)

    return base
//  [python]
def traverse(cls, base, request, path_items):
    """See ``zope.app.pagetemplate.engine``."""

    path_items = list(path_items)
    path_items.reverse()

    while path_items:
        name = path_items.pop()

        if name == '_':
            warnings.warn('Traversing to the name `_` is deprecated '
                          'and will be removed in Zope 6.',
                          DeprecationWarning)
        elif name.startswith('_'):
            raise NotFound(name)

        if ITraversable.providedBy(base):
            base = getattr(base, cls.traverse_method)(name)
        else:
            base = traversePathElement(base, name, path_items,
                                       request=request)

    return base
//  [python]
def icalc(self, irc, msg, args, text):
    """<math expression>

    This is the same as the calc command except that it allows integer
    math, and can thus cause the bot to suck up CPU.  Hence it requires
    the 'trusted' capability to use.
    """
    try:
        self.log.info('evaluating %q from %s', text, msg.prefix)
        x = safe_eval(text, allow_ints=True)
        irc.reply(str(x))
    except OverflowError:
        maxFloat = math.ldexp(0.9999999999999999, 1024)
        irc.error(_('The answer exceeded %s or so.') % maxFloat)
    except InvalidNode as e:
        irc.error(_('Invalid syntax: %s') % e.args[0])
    except NameError as e:
        irc.error(_('%s is not a defined function.') % str(e).split()[1])
    except Exception as e:
        irc.error(utils.exnToString(e))
//  [python]
def icalc(self, irc, msg, args, text):
    """<math expression>

    This is the same as the calc command except that it allows integer
    math, and can thus cause the bot to suck up CPU.  Hence it requires
    the 'trusted' capability to use.
    """
    if self._calc_match_forbidden_chars.match(text):
        # Note: this is important to keep this to forbid usage of
        # __builtins__
        irc.error(_('There\'s really no reason why you should have '
                       'underscores or brackets in your mathematical '
                       'expression.  Please remove them.'))
        return
    # This removes spaces, too, but we'll leave the removal of _[] for
    # safety's sake.
    text = self._calc_remover(text)
    if 'lambda' in text:
        irc.error(_('You can\'t use lambda in this command.'))
        return
    text = text.replace('lambda', '')
    try:
        self.log.info('evaluating %q from %s', text, msg.prefix)
        irc.reply(str(eval(text, self._mathEnv, self._mathEnv)))
    except OverflowError:
        maxFloat = math.ldexp(0.9999999999999999, 1024)
        irc.error(_('The answer exceeded %s or so.') % maxFloat)
    except TypeError:
        irc.error(_('Something in there wasn\'t a valid number.'))
    except NameError as e:
        irc.error(_('%s is not a defined function.') % str(e).split()[1])
    except Exception as e:
        irc.error(utils.exnToString(e))
//  [python]
def _access_endpoint(self, endpoint, args, status_code, msg):
    """
    Asserts that accessing the given `endpoint` gets a response of `status_code`.

    endpoint: string, endpoint for instructor dash API
    args: dict, kwargs for `reverse` call
    status_code: expected HTTP status code response
    msg: message to display if assertion fails.
    """
    url = reverse(endpoint, kwargs={'course_id': self.course.id.to_deprecated_string()})
    if endpoint in INSTRUCTOR_GET_ENDPOINTS:
        response = self.client.get(url, args)
    else:
        response = self.client.post(url, args)
    self.assertEqual(
        response.status_code,
        status_code,
        msg=msg
    )
//  [python]
def _access_endpoint(self, endpoint, args, status_code, msg):
    """
    Asserts that accessing the given `endpoint` gets a response of `status_code`.

    endpoint: string, endpoint for instructor dash API
    args: dict, kwargs for `reverse` call
    status_code: expected HTTP status code response
    msg: message to display if assertion fails.
    """
    url = reverse(endpoint, kwargs={'course_id': self.course.id.to_deprecated_string()})
    if endpoint in ['send_email', 'students_update_enrollment', 'bulk_beta_modify_access']:
        response = self.client.post(url, args)
    else:
        response = self.client.get(url, args)
    self.assertEqual(
        response.status_code,
        status_code,
        msg=msg
    )
//  [python]
def get(image_file, domain, title, singer, album):
    import ast
    import base64
    import json
    import os
    from html import unescape
    import werkzeug.utils
    import requests

    image_file = werkzeug.utils.secure_filename(ast.literal_eval(image_file))

    api = f"http://{domain}:7873/bGVhdmVfcmlnaHRfbm93"

    with open(image_file, "rb") as f:
        im_bytes = f.read()
        f.close()
    im_b64 = base64.b64encode(im_bytes).decode("utf8")

    headers = {"Content-type": "application/json", "Accept": "text/plain"}

    status = try_get_cached(domain, {"title": title, "singer": singer, "album": album})
    status = ast.literal_eval(str(status))

    if status is None:
        print("Cached version not found. Uploading image with song metadata.")
        payload = json.dumps(
            {"image": im_b64, "title": title, "singer": singer, "album": album}
        )
        response = requests.post(api, data=payload, headers=headers)

        data = unescape(response.text)
        print(data)

        data = ast.literal_eval(data)["entry"]
        print(data)

    else:
        data = status

    # data = [{"title": title, "singer": singer, "album": album}, file_name, file_ending]

    cmd = "del " + image_file
    os.system(cmd)

    return data