auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void handle(LoginRequest loginRequest) throws Exception { Preconditions.checkState( thisState == State.USERNAME, "Not expecting USERNAME" ); this.loginRequest = loginRequest; if ( !Protocol.supportedVersions.contains( handshake.getProtocolVersion() ) ) { disconnect( bungee.getTranslation( "outdated_server" ) ); return; } if ( getName().contains( "." ) ) { disconnect( bungee.getTranslation( "name_invalid" ) ); return; } if ( getName().length() > 16 ) { disconnect( bungee.getTranslation( "name_too_long" ) ); return; } int limit = BungeeCord.getInstance().config.getPlayerLimit(); if ( limit > 0 && bungee.getOnlineCount() > limit ) { disconnect( bungee.getTranslation( "proxy_full" ) ); return; } if ( !isOnlineMode() && bungee.getPlayer( getName() ) != null ) { disconnect( bungee.getTranslation( "already_connected" ) ); return; } if ( !isOnlineMode() && bungee.getPlayer( getName() ).getUniqueId() != null ) { disconnect( bungee.getTranslation( "already_connected" ) ); return; } Callback<PreLoginEvent> callback = new Callback<PreLoginEvent>() { @Override public void done(PreLoginEvent result, Throwable error) { if ( result.isCancelled() ) { disconnect( result.getCancelReason() ); return; } if ( ch.isClosed() ) { return; } if ( onlineMode ) { unsafe().sendPacket( request = EncryptionUtil.encryptRequest() ); } else { finish(); } thisState = State.ENCRYPT; } }; bungee.getPluginManager().callEvent( new PreLoginEvent( InitialHandler.this, callback ) ); }

Target:
public void handle(LoginRequest loginRequest) throws Exception { Preconditions.checkState( thisState == State.USERNAME, "Not expecting USERNAME" ); this.loginRequest = loginRequest; if ( !Protocol.supportedVersions.contains( handshake.getProtocolVersion() ) ) { disconnect( bungee.getTranslation( "outdated_server" ) ); return; } if ( getName().contains( "." ) ) { disconnect( bungee.getTranslation( "name_invalid" ) ); return; } if ( getName().length() > 16 ) { disconnect( bungee.getTranslation( "name_too_long" ) ); return; } int limit = BungeeCord.getInstance().config.getPlayerLimit(); if ( limit > 0 && bungee.getOnlineCount() > limit ) { disconnect( bungee.getTranslation( "proxy_full" ) ); return; } if ( !isOnlineMode() && bungee.getPlayer( getName() ) != null ) { disconnect( bungee.getTranslation( "already_connected" ) ); return; } if ( !isOnlineMode() && bungee.getPlayer( getUUID() ) != null ) { disconnect( bungee.getTranslation( "already_connected" ) ); return; } Callback<PreLoginEvent> callback = new Callback<PreLoginEvent>() { @Override public void done(PreLoginEvent result, Throwable error) { if ( result.isCancelled() ) { disconnect( result.getCancelReason() ); return; } if ( ch.isClosed() ) { return; } if ( onlineMode ) { unsafe().sendPacket( request = EncryptionUtil.encryptRequest() ); } else { finish(); } thisState = State.ENCRYPT; } }; bungee.getPluginManager().callEvent( new PreLoginEvent( InitialHandler.this, callback ) ); }
Source:
public List<String> getExtendedLabelsForVSM() { List<String> labels = Lists.newArrayList(); for (IConfigurationElement configurationElement : extensions) { labels.add(configurationElement.getAttribute(LABEL_ATTRIBUTE) + " - " + configurationElement.getNamespaceIdentifier()); } return labels; }

Target:
public List<String> getExtendedLabelsForVSM() { List<String> labels = Lists.newArrayList(); for (IConfigurationElement configurationElement : extensions) { labels.add(getExtendedLabelForVSM(configurationElement)); } return labels; }
Source:
public void init() { Properties properties = new Properties(); try { properties.load(new FileInputStream("config.properties")); PopulatorContext context = new PopulatorContext(); context.setURI(properties.getProperty("xcri.oxcap.populator.uri")); context.setUser(properties.getProperty("xcri.oxcap.populator.username")); context.setPassword(properties.getProperty("xcri.oxcap.populator.password")); context.setName(properties.getProperty("xcri.oxcap.populator.name")); populator.update(context); } catch (IOException e) { e.printStackTrace(); } }

Target:
public void init() { Properties properties = new Properties(); try { properties.load(new FileInputStream("config.properties")); PopulatorContext context = new PopulatorContext("xcri.oxcap.populator", properties); populator.update(context); } catch (IOException e) { log.error("IOException [config.properties]", e); } }
Source:
public static ReplicationCache createCache(long expiration, TimeUnit unit) { ReplicationCache cache = new ReplicationCache(expiration, unit); if (!cache.initialize()) { cache = new ReplicationCache(); cache.initialize(); } return cache; }

Target:
public static ReplicationCache createCache(long expiration, TimeUnit unit) { ReplicationCache cache = new ReplicationCache(expiration, unit); if (!cache.initialize()) { logger.info("Initialized replication cache with default settings."); cache = new ReplicationCache(); cache.initialize(); } return cache; }
Source:
public void onResponse(Call<List<Resource>> call, Response<List<Resource>> response) { HashMap<String, String> hashMap = new HashMap<String, String>(); if (!response.isSuccessful()) { Log.d("Error", response.errorBody().toString()); } else { List<Resource> resources = response.body(); String decoded = rebuildFromChunks(resources.get(0).getData()); try { JSONObject structure = (new JSONObject(decoded)).getJSONObject("inventoryStructure"); JSONObject data = structure.getJSONObject("data"); String type1 = data.getString("type"); metric1.getConfiguration().setType(type1); Log.d("Type", metric1.getConfiguration().getType()); Intent intent = Intents.Builder.of(getApplicationContext()).buildMetricIntent(metric1); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }

Target:
public void onResponse(Call<List<Resource>> call, Response<List<Resource>> response) { if (!response.isSuccessful()) { Log.d("Error", response.errorBody().toString()); } else { List<Resource> resources = response.body(); String decoded = rebuildFromChunks(resources.get(0).getData()); try { JSONObject structure = (new JSONObject(decoded)).getJSONObject("inventoryStructure"); JSONObject data = structure.getJSONObject("data"); String type1 = data.getString("type"); metric1.getConfiguration().setType(type1); Intent intent = Intents.Builder.of(getApplicationContext()).buildMetricIntent(metric1); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }
Source:
public void validateBadUUIDSFiltered() { Map<String, Object> innerMap = new HashMap<>(); innerMap.put(IMAGES_LIST, new Object[]{"28e983b9-c2f6-4a50-a5d5-7a38089797c7", "c3d75234-b360-4aed-8d78-413d7488bd9b", "_remove_me_2f17489c-285e-496d-bd86-0d63d1be2efe"}); ImagesListReturn imagesListReturn = new ImagesListReturn(innerMap); assertEquals(2, imagesListReturn.getImageList().length); }

Target:
public void validateBadUUIDSFiltered() { Map<String, Object> innerMap = new HashMap<>(); innerMap.put(IMAGES_LIST, new Object[]{"28e983b9-c2f6-4a50-a5d5-7a38089797c7", "c3d75234-b360-4aed-8d78-413d7488bd9b", "_remove_me_2f17489c-285e-496d-bd86-0d63d1be2efe"}); ImagesListReturn imagesListReturn = new ImagesListReturn(innerMap); String[] expectedUUIDList = new String[]{"28e983b9-c2f6-4a50-a5d5-7a38089797c7", "c3d75234-b360-4aed-8d78-413d7488bd9b"}; assertArrayEquals(expectedUUIDList, imagesListReturn.getImageList()); }
Source:
public void resetContentAndSettings() { if (instrumentsVersion.getMajor() < 6) { if (hasContentAndSettingsFolder()) { boolean ok = deleteRecursive(getContentAndSettingsFolder()); if (!ok) { System.err.println("cannot delete content and settings folder " + contentAndSettingsFolder); } } boolean ok = contentAndSettingsFolder.mkdirs(); if (!ok) { System.err.println("couldn't re-create: " + contentAndSettingsFolder); } } else { DeviceUUIDsMap uuidsMap = new DeviceUUIDsMap(); uuidsMap.loadData(); String uuid = uuidsMap.getUUID(exactSdkVersion, deviceName); if (uuid == null) { System.err.println("Unable to get UUID for device " + deviceName + " with SDK " + exactSdkVersion); } List<String> simctlArgs = new ArrayList<>(); simctlArgs.add("xcrun"); simctlArgs.add("simctl"); simctlArgs.add("erase"); simctlArgs.add(uuid); Command simctlCmd = new Command(simctlArgs, true); int exitCode = simctlCmd.executeAndWait(true); if (exitCode == 146) { log.log(Level.WARNING, "Reset content and settings exit code = " + exitCode + ", possibly device is in booted state, shutdown device = " + uuid); simctlArgs = Arrays.asList("xcrun", "simctl", "shutdown", uuid); simctlCmd = new Command(simctlArgs, true); exitCode = simctlCmd.executeAndWait(false); ClassicCommands.killall("iOS Simulator"); simctlArgs = Arrays.asList("xcrun", "simctl", "erase", uuid); simctlCmd = new Command(simctlArgs, true); exitCode = simctlCmd.executeAndWait(false); } else if (exitCode != 0) { throw new WebDriverException("execution failed. Exit code =" + exitCode + " , command was: " + simctlCmd.commandString()); } } }

Target:
public void resetContentAndSettings() { if (instrumentsVersion.getMajor() < 6) { if (hasContentAndSettingsFolder()) { boolean ok = deleteRecursive(getContentAndSettingsFolder()); if (!ok) { System.err.println("cannot delete content and settings folder " + contentAndSettingsFolder); } } boolean ok = contentAndSettingsFolder.mkdirs(); if (!ok) { System.err.println("couldn't re-create: " + contentAndSettingsFolder); } } else { DeviceUUIDsMap uuidsMap = new DeviceUUIDsMap(); uuidsMap.loadData(); String uuid = uuidsMap.getUUID(exactSdkVersion, deviceName); if (uuid == null) { System.err.println("Unable to get UUID for device " + deviceName + " with SDK " + exactSdkVersion); } List<String> simctlArgs = new ArrayList<>(); simctlArgs.add("xcrun"); simctlArgs.add("simctl"); simctlArgs.add("erase"); simctlArgs.add(uuid); Command simctlCmd = new Command(simctlArgs, true); int exitCode = simctlCmd.executeAndWait(true); if (exitCode == 146) { log.log(Level.WARNING, "Reset content and settings exit code = " + exitCode + ", possibly device is in booted state, shutdown device = " + uuid); simctlArgs = Arrays.asList("xcrun", "simctl", "shutdown", uuid); simctlCmd = new Command(simctlArgs, true); simctlCmd.executeAndWait(false); simctlArgs = Arrays.asList("xcrun", "simctl", "erase", uuid); simctlCmd = new Command(simctlArgs, true); simctlCmd.executeAndWait(false); } else if (exitCode != 0) { throw new WebDriverException("execution failed. Exit code =" + exitCode + " , command was: " + simctlCmd.commandString()); } } }
Source:
public void setStatus(final StateStatus status) { this.status = status; }

Target:
protected void setStatus(final StateStatus status) { this.status = status; }
Source:
public void onError(ObjectServerError error) { if (error.getErrorCode() == ErrorCode.TOKEN_EXPIRED) { session.getUser().removeAccessToken(session.getServerUrl()); session.stopNativeSession(); session.createNativeSession(); gotoNextState(SessionState.BINDING); } else { switch (error.getCategory()) { case FATAL: gotoNextState(SessionState.STOPPED); break; case RECOVERABLE: gotoNextState(SessionState.UNBOUND); break; } } }

Target:
public void onError(ObjectServerError error) { if (error.getErrorCode() == ErrorCode.TOKEN_EXPIRED) { session.stopNativeSession(); session.removeAccessToken(); session.createNativeSession(); gotoNextState(SessionState.BINDING); } else { switch (error.getCategory()) { case FATAL: gotoNextState(SessionState.STOPPED); break; case RECOVERABLE: gotoNextState(SessionState.UNBOUND); break; } } }
Source:
public boolean checkDistinguishedName(String userName) { Name name = null; try { name = new LdapName(userName); } catch (InvalidNameException ex) { LOG.error("Invalid distinguished name {}", userName); LOG.debug("Invalid distinguished name {}", userName, ex); } return name != null; }

Target:
public boolean checkDistinguishedName(String userName) { Name name = null; try { name = new LdapName(userName); } catch (InvalidNameException ex) { LOG.error("Invalid distinguished name {}", userName, ex); } return name != null; }
Source:
protected void executeQueryCommand() { VM vm = vmDao.get(getParameters().getId()); if (vm == null || vm.getVmFQDN() == null) { getQueryReturnValue().setReturnValue(Collections.<Erratum> emptyList()); return; } Provider<?> provider = providerDao.get(vm.getProviderId()); if (provider != null) { HostProviderProxy proxy = (HostProviderProxy) ProviderProxyFactory.getInstance().create(provider); getQueryReturnValue().setReturnValue(proxy.getErrataForHost(vm.getVmFQDN())); } else { getQueryReturnValue().setReturnValue(Collections.<Erratum> emptyList()); } }

Target:
protected void executeQueryCommand() { VM vm = vmDao.get(getParameters().getId()); if (vm == null || vm.getVmHost() == null) { getQueryReturnValue().setReturnValue(Collections.<Erratum> emptyList()); return; } Provider<?> provider = providerDao.get(vm.getProviderId()); if (provider != null) { HostProviderProxy proxy = (HostProviderProxy) ProviderProxyFactory.getInstance().create(provider); getQueryReturnValue().setReturnValue(proxy.getErrataForHost(vm.getVmHost())); } else { getQueryReturnValue().setReturnValue(Collections.<Erratum> emptyList()); } }
Source:
private static Result documentEntity(ImmutableMap<String, String> extIdentifiers) { Result result = minimalEntityBuilder(ID, InfoSpaceConstants.SEMANTIC_CLASS_INSTANCE_TYPE_ARTICLE, InfoSpaceConstants.SEMANTIC_CLASS_INSTANCE_TYPE_DATASET); addTitle(result, TITLE, null); addTitle(result, OTHER_TITLE, null); addDescription(result, ABSTRACT); if (result.getPid() == null) { result.setPid(new ArrayList<>()); } for (Entry<String, String> entry : extIdentifiers.entrySet()) { StructuredProperty structPid = new StructuredProperty(); structPid.setValue(entry.getValue()); Qualifier pidQualifier = new Qualifier(); pidQualifier.setClassid(entry.getKey()); structPid.setQualifier(pidQualifier); result.getPid().add(structPid); result.getPid().add(structPid); } Field<String> dateOfAcc = new Field<>(); dateOfAcc.setValue(String.format("%s-02-29", YEAR)); result.setDateofacceptance(dateOfAcc); Field<String> publisher = new Field<>(); publisher.setValue(PUBLISHER); result.setPublisher(publisher); Field<String> format = new Field<>(); format.setValue(FORMAT); if (result.getFormat() == null) { result.setFormat(new ArrayList<>()); } result.getFormat().add(format); result.setResulttype(buildQualifierWithClassId(RESULT_TYPE_CLASSID)); result.setResourcetype(buildQualifierWithClassId(RESOURCE_TYPE_CLASSID)); Author author = new Author(); author.setFullname(FULL_NAME); author.setRank(0); if (result.getAuthor() == null) { result.setAuthor(new ArrayList<>()); } result.getAuthor().add(author); return result; }

Target:
private static Result documentEntity(ImmutableMap<String, String> extIdentifiers) { Result result = minimalEntityBuilder(ID, InfoSpaceConstants.SEMANTIC_CLASS_INSTANCE_TYPE_ARTICLE, InfoSpaceConstants.SEMANTIC_CLASS_INSTANCE_TYPE_DATASET); addTitle(result, TITLE, null); addTitle(result, OTHER_TITLE, null); addDescription(result, ABSTRACT); if (result.getPid() == null) { result.setPid(new ArrayList<>()); } extIdentifiers.entrySet().stream().map(entry -> { StructuredProperty structPid = new StructuredProperty(); structPid.setValue(entry.getValue()); Qualifier pidQualifier = new Qualifier(); pidQualifier.setClassid(entry.getKey()); structPid.setQualifier(pidQualifier); return structPid; }).forEach(pid -> { result.getPid().add(pid); result.getPid().add(pid); }); Field<String> dateOfAcc = new Field<>(); dateOfAcc.setValue(String.format("%s-02-29", YEAR)); result.setDateofacceptance(dateOfAcc); Field<String> publisher = new Field<>(); publisher.setValue(PUBLISHER); result.setPublisher(publisher); Field<String> format = new Field<>(); format.setValue(FORMAT); if (result.getFormat() == null) { result.setFormat(new ArrayList<>()); } result.getFormat().add(format); result.setResulttype(buildQualifierWithClassId(RESULT_TYPE_CLASSID)); result.setResourcetype(buildQualifierWithClassId(RESOURCE_TYPE_CLASSID)); Author author = new Author(); author.setFullname(FULL_NAME); author.setRank(0); if (result.getAuthor() == null) { result.setAuthor(new ArrayList<>()); } result.getAuthor().add(author); return result; }
Source:
public void testWithInvalidForcedQualifier() throws Exception { File basedir = getBasedir("projects/buildqualifier"); File pom = new File(basedir, "p001/pom.xml"); MavenExecutionRequest request = newMavenExecutionRequest(pom); request.getProjectBuildingRequest().setProcessPlugins(false); MavenProject project = getProject(request); ArrayList<MavenProject> projects = new ArrayList<MavenProject>(); projects.add(project); MavenSession session = newMavenSession(projects.get(0), projects); BuildQualifierMojo mojo = getMojo(project, session); setVariableValueToObject(mojo, "forceContextQualifier", "invalid:Qualifier"); try { mojo.execute(); fail(); } catch (MojoFailureException e) { assertEquals( "Invalid build qualifier, it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')", e.getMessage()); } }

Target:
public void testWithInvalidForcedQualifier() throws Exception { MavenProject project = getProject("projects/buildqualifier", "p001/pom.xml"); BuildQualifierMojo mojo = createMojoWithProject(project); setVariableValueToObject(mojo, "forceContextQualifier", "invalid:Qualifier"); try { mojo.execute(); fail(); } catch (MojoFailureException e) { assertEquals( "Invalid build qualifier, it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')", e.getMessage()); } }
Source:
List<? extends Message> reactOn(RejectionEnvelope rejection) { final CommandClass commandClass = CommandClass.of(rejection.getCommandMessage() .getClass()); final RejectionReactorMethod method = thisClass().getReactor(rejection.getMessageClass(), commandClass); final List<? extends Message> messages = method.invoke(this, rejection.getMessage(), rejection.getRejectionContext()); return from(messages).filter(nonEmpty()).toList(); }

Target:
List<? extends Message> reactOn(RejectionEnvelope rejection) { final CommandClass commandClass = CommandClass.of(rejection.getCommandMessage()); final RejectionReactorMethod method = thisClass().getReactor(rejection.getMessageClass(), commandClass); final List<? extends Message> messages = method.invoke(this, rejection.getMessage(), rejection.getRejectionContext()); return from(messages).filter(nonEmpty()).toList(); }
Source:
public Object perform(InvocationContext ctx) throws Throwable { if (valueMatcher == ValueMatcher.MATCH_NEVER) { successful = false; return null; } MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); Object prevValue = e.getValue(hasFlag(Flag.COMMAND_RETRY)); if (prevValue == null) { nonExistent = true; if (valueMatcher.matches(prevValue, value, null, valueEquivalence)) { e.setChanged(true); e.setRemoved(true); e.setCreated(false); if (this instanceof EvictCommand) { e.setEvicted(true); } e.setValue(null); return isConditional() ? true : null; } else { log.trace("Nothing to remove since the entry doesn't exist in the context or it is null"); successful = false; return false; } } if (!valueMatcher.matches(prevValue, value, null, valueEquivalence)) { successful = false; return false; } if (this instanceof EvictCommand) { e.setEvicted(true); } return performRemove(e, prevValue, ctx); }

Target:
public Object perform(InvocationContext ctx) throws Throwable { if (valueMatcher == ValueMatcher.MATCH_NEVER) { successful = false; return null; } MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); Object prevValue = e.getValue(); if (prevValue == null) { nonExistent = true; if (valueMatcher.matches(null, value, null, valueEquivalence)) { e.setChanged(true); e.setRemoved(true); e.setCreated(false); if (this instanceof EvictCommand) { e.setEvicted(true); } e.setValue(null); return isConditional() ? true : null; } else { log.trace("Nothing to remove since the entry doesn't exist in the context or it is null"); successful = false; return false; } } if (!valueMatcher.matches(prevValue, value, null, valueEquivalence)) { successful = false; return false; } if (this instanceof EvictCommand) { e.setEvicted(true); } return performRemove(e, prevValue, ctx); }
Source:
public BSONObject getReplicaSetConfig() { try { return client.getDB("local").getCollection("system.replset").findOne(); } catch (MongoException e) { LOG.warn("Failed to get replica set config on {}: {}", client, e); return null; } }

Target:
public BSONObject getReplicaSetConfig() { try { return client.getDB("local").getCollection("system.replset").findOne(); } catch (MongoException e) { LOG.error("Failed to get replica set config on "+client, e); return null; } }
Source:
public TaskRepositoryManager() { INSTANCE = this; this.migrators = Collections.emptyList(); Category catTasks = new Category(TaskRepository.CATEGORY_TASKS, "Tasks", 0); repositoryCategories.put(catTasks.getId(), catTasks); Category catBugs = new Category(TaskRepository.CATEGORY_BUGS, "Bugs", 100); repositoryCategories.put(catBugs.getId(), catBugs); Category catBuild = new Category(TaskRepository.CATEGORY_BUILD, "Builds", 200); repositoryCategories.put(catBuild.getId(), catBuild); Category catReview = new Category(TaskRepository.CATEGORY_REVIEW, "Reviews", 300); repositoryCategories.put(catReview.getId(), catReview); Category catOther = new Category(IRepositoryConstants.CATEGORY_OTHER, "Other", 400); repositoryCategories.put(catOther.getId(), catOther); }

Target:
public TaskRepositoryManager() { this.migrators = Collections.emptyList(); Category catTasks = new Category(TaskRepository.CATEGORY_TASKS, "Tasks", 0); repositoryCategories.put(catTasks.getId(), catTasks); Category catBugs = new Category(TaskRepository.CATEGORY_BUGS, "Bugs", 100); repositoryCategories.put(catBugs.getId(), catBugs); Category catBuild = new Category(TaskRepository.CATEGORY_BUILD, "Builds", 200); repositoryCategories.put(catBuild.getId(), catBuild); Category catReview = new Category(TaskRepository.CATEGORY_REVIEW, "Reviews", 300); repositoryCategories.put(catReview.getId(), catReview); Category catOther = new Category(IRepositoryConstants.CATEGORY_OTHER, "Other", 400); repositoryCategories.put(catOther.getId(), catOther); }
Source:
private void runParallelDataLoad(HttpServletRequest req, HttpServletResponse resp, final Properties props, final String namespace, int masTmpStatementsSize, int fileReadersCount, int mergersCount, int tmpQueueLimit) { try { submitApiTask( new ParallelDataLoaderTask(req, resp, namespace, ITx.UNISOLATED, props, masTmpStatementsSize, fileReadersCount, mergersCount, tmpQueueLimit)) .get(); } catch (Throwable t) { BigdataRDFServlet.launderThrowable( t, resp, "DATALOADER-SERVLET: " + namespace); } }

Target:
private void runParallelDataLoad(HttpServletRequest req, HttpServletResponse resp, final Properties props, final String namespace, int masTmpStatementsSize, int fileReadersCount, int mergersCount, int tmpQueueLimit) { try { submitApiTask( new ParallelDataLoaderTask(req, resp, namespace, ITx.UNISOLATED, props, masTmpStatementsSize, fileReadersCount, mergersCount, tmpQueueLimit)) .get(); } catch (RuntimeException | DatasetNotFoundException | ExecutionException | InterruptedException | IOException | TimeoutException t) { BigdataRDFServlet.launderThrowable( t, resp, "DATALOADER-SERVLET: " + namespace); } }
Source:
public List<List<String>> getSummaryTableAsList() { summaryTableAsList = new ArrayList<List<String>>(); sessionNames = new ArrayList<String>(); sortedSessionsSet.clear(); sortedSessionsSet.addAll(chosenSessions); for (SessionDataDto sdDto : sortedSessionsSet) { sessionNames.add(sdDto.getName()); } List<String> sessions = new ArrayList<String>(sessionNames); sessions.add(0, ""); summaryTableAsList.add(sessions); for (TreeItem rootItem : treeStore.getRootItems()) { collectInfoFromTree(rootItem); } return summaryTableAsList; }

Target:
public SummaryTableDto getSummaryTableAsList() { summaryTableDto = new SummaryTableDto(); sessionNames = new ArrayList<String>(); for (SessionDataDto sdDto : sortedSessionsSet) { sessionNames.add(sdDto.getName()); } List<String> sessions = new ArrayList<String>(sessionNames); sessions.add(0, ""); summaryTableDto.insertRow(sessions); for (TreeItem rootItem : treeStore.getRootItems()) { collectInfoFromTree(rootItem); } return summaryTableDto; }
Source:
public void initialise() { ownedVillagesList = find(Constants.OWNED_VILLAGES_LIST_ID, UIList.class); managedVillagesList = find(Constants.MANAGED_VILLAGES_LIST_ID, UIList.class); selectedVillageNameLabel = find(Constants.SELECTED_VILLAGE_NAME_LABEL_ID, UILabel.class); selectedVillageInfoLabel = find(Constants.SELECTED_VILLAGE_INFO_LABEL_ID, UILabel.class); List<String> cityNames = new ArrayList<String>(); cityNames.add("Lordaeron"); cityNames.add("Prague"); cityNames.add("Kategad"); cityNames.add("London"); cityNames.add("Berlin"); cityNames.add("Helsinki"); cityNames.add("Viena"); cityNames.add("NewYork"); cityNames.add("Brno"); cityNames.add("Katowice"); debugOwnedVillages = new ArrayList<VillageEntity>(); for (int i = 0; i < 6; i++) { VillageEntity city = new VillageEntity(cityNames.get(i),"nightmaredev"); debugOwnedVillages.add(city); } debugManagedVillages = new ArrayList<VillageEntity>(); for (int i = 6; i < 10; i++) { VillageEntity city = new VillageEntity(cityNames.get(i),"xXxSlayer1337"); debugManagedVillages.add(city); } ownedVillagesList.subscribeSelection((widget, item) -> { DisplayVillageInfo((VillageEntity)item); }); managedVillagesList.subscribeSelection((widget, item) -> { DisplayVillageInfo((VillageEntity)item); }); populateLists(); }

Target:
public void initialise() { ownedVillagesList = find(Constants.OWNED_VILLAGES_LIST_ID, UIList.class); managedVillagesList = find(Constants.MANAGED_VILLAGES_LIST_ID, UIList.class); selectedVillageNameLabel = find(Constants.SELECTED_VILLAGE_NAME_LABEL_ID, UILabel.class); selectedVillageInfoLabel = find(Constants.SELECTED_VILLAGE_INFO_LABEL_ID, UILabel.class); selectedVillageNameLabel.setText(""); selectedVillageInfoLabel.setText(""); CreateDebugData(); ownedVillagesList.subscribeSelection((widget, item) -> { DisplayVillageInfo((UIList)widget, (VillageEntity)item); }); managedVillagesList.subscribeSelection((widget, item) -> { DisplayVillageInfo((UIList)widget, (VillageEntity)item); }); populateLists(); }
Source:
public void setup(final Optional<HasName> hasName) { this.metaData = new NameAndDataTypeHeaderMetaData(hasExpression, hasName, clearDisplayNameConsumer, setDisplayNameConsumer, setTypeRefConsumer, cellEditorControls, headerEditor, EDITOR_TITLE) { @Override public String getColumnGroup() { return NAME_DATA_TYPE_COLUMN_GROUP; } @Override public Optional<String> getPlaceHolder() { return Optional.of("placeholder"); } }; }

Target:
public void setup(final Optional<HasName> hasName) { this.metaData = new NameAndDataTypeHeaderMetaData(hasExpression, hasName, clearDisplayNameConsumer, setDisplayNameConsumer, setTypeRefConsumer, cellEditorControls, headerEditor, EDITOR_TITLE) { @Override public String getColumnGroup() { return NAME_DATA_TYPE_COLUMN_GROUP; } @Override public Optional<String> getPlaceHolder() { return Optional.of(PLACEHOLDER); } }; }
Source:
Map<StoreKey, StoreKey> createConversionKeyMap(File[] replicas, Map<File, DumpIndexTool.IndexProcessingResults> results) throws Exception { Set<StoreKey> storeKeys = new HashSet<>(); for (File replica : replicas) { DumpIndexTool.IndexProcessingResults result = results.get(replica); for (Map.Entry<StoreKey, DumpIndexTool.Info> entry : result.getKeyToState().entrySet()) { storeKeys.add(entry.getKey()); } } logger.info("Converting store keys...", storeKeys.size()); Map<StoreKey, StoreKey> ans = storeKeyConverter.convert(storeKeys); logger.info("Store keys converted!"); return ans; }

Target:
public Map<StoreKey, StoreKey> createConversionKeyMap(File[] replicas, Map<File, DumpIndexTool.IndexProcessingResults> results) throws Exception { Set<StoreKey> storeKeys = new HashSet<>(); for (File replica : replicas) { DumpIndexTool.IndexProcessingResults result = results.get(replica); for (Map.Entry<StoreKey, DumpIndexTool.Info> entry : result.getKeyToState().entrySet()) { storeKeys.add(entry.getKey()); } } logger.info("Converting store keys...", storeKeys.size()); Map<StoreKey, StoreKey> ans = storeKeyConverter.convert(storeKeys); logger.info("Store keys converted!"); return ans; }
Source:
public static int getInternalInboundPort() { File synapseProperties = Paths.get(CarbonUtils.getCarbonConfigDirPath(), "synapse.properties").toFile(); Properties properties = new Properties(); InputStream inputStream; try { inputStream = new FileInputStream(synapseProperties); properties.load(inputStream); inputStream.close(); } catch (FileNotFoundException e) { handleException("synapse.properties file not found", e); } catch (IOException e) { handleException("Error while reading synapse.properties file", e); } int internalInboundPort = Constants.DEFAULT_INTERNAL_HTTP_API_PORT; String internalInboundEnabledProperty = properties.getProperty(Constants.INTERNAL_HTTP_API_ENABLED); if (internalInboundEnabledProperty == null) { return -1; } boolean internalInboundEnabled = Boolean.parseBoolean(internalInboundEnabledProperty); if (!internalInboundEnabled) { return -1; } String internalInboundPortProperty = properties.getProperty(Constants.INTERNAL_HTTP_API_PORT); if (internalInboundPortProperty != null) { try { internalInboundPort = Integer.parseInt(internalInboundPortProperty); } catch (Exception ex) { handleException(Constants.INTERNAL_HTTP_API_PORT + " is not in proper format", ex); } } return internalInboundPort; }

Target:
public static int getInternalInboundPort() { File synapseProperties = Paths.get(CarbonUtils.getCarbonConfigDirPath(), "synapse.properties").toFile(); Properties properties = new Properties(); InputStream inputStream = null; try { inputStream = new FileInputStream(synapseProperties); properties.load(inputStream); } catch (FileNotFoundException e) { handleException("synapse.properties file not found", e); } catch (IOException e) { handleException("Error while reading synapse.properties file", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ignored) { } } } int internalInboundPort = Constants.DEFAULT_INTERNAL_HTTP_API_PORT; String internalInboundEnabledProperty = properties.getProperty(Constants.INTERNAL_HTTP_API_ENABLED); if (internalInboundEnabledProperty == null) { return -1; } boolean internalInboundEnabled = Boolean.parseBoolean(internalInboundEnabledProperty); if (!internalInboundEnabled) { return -1; } String internalInboundPortProperty = properties.getProperty(Constants.INTERNAL_HTTP_API_PORT); if (internalInboundPortProperty != null) { try { internalInboundPort = Integer.parseInt(internalInboundPortProperty); } catch (Exception ex) { handleException(Constants.INTERNAL_HTTP_API_PORT + " is not in proper format", ex); } } return internalInboundPort; }
Source:
public EventHubClientManager getEventHubClientManager(String systemName, String streamName, EventHubConfig config) { String eventHubNamespace = config.getStreamNamespace(systemName, streamName); String entityPath = config.getStreamEntityPath(systemName, streamName); String sasKeyName = config.getStreamSasKeyName(systemName, streamName); String sasToken = config.getStreamSasToken(systemName, streamName); return new SamzaEventHubClientManager(eventHubNamespace, entityPath, sasKeyName, sasToken, config.getNumClientThreads(systemName)); }

Target:
public EventHubClientManager getEventHubClientManager(String systemName, String streamName, EventHubConfig config) { String eventHubNamespace = config.getStreamNamespace(systemName, streamName); String entityPath = config.getStreamEntityPath(systemName, streamName); String sasKeyName = config.getStreamSasKeyName(systemName, streamName); String sasToken = config.getStreamSasToken(systemName, streamName); int numClientThreads = config.getNumClientThreads(systemName); return new SamzaEventHubClientManager(eventHubNamespace, entityPath, sasKeyName, sasToken, numClientThreads); }
Source:
public WriteInfo getPartitionWriteInfo(LocationHandle locationHandle, Optional<Partition> partition, String partitionName) { if (partition.isPresent()) { WriteMode writeMode = locationHandle.getWriteMode(); Path targetPath = new Path(partition.get().getStorage().getLocation()); Path writePath; if (writeMode.isWritePathSameAsTargetPath()) { writePath = targetPath; } else { writePath = new Path(locationHandle.getWritePath(), partitionName); } return new WriteInfo(targetPath, writePath, writeMode); } else { return new WriteInfo( new Path(locationHandle.getTargetPath(), partitionName), new Path(locationHandle.getWritePath(), partitionName), locationHandle.getWriteMode()); } }

Target:
public WriteInfo getPartitionWriteInfo(LocationHandle locationHandle, Optional<Partition> partition, String partitionName) { if (partition.isPresent()) { WriteMode writeMode = locationHandle.getWriteMode(); Path targetPath = new Path(partition.get().getStorage().getLocation()); Path writePath; switch (writeMode) { case STAGE_AND_MOVE_TO_TARGET_DIRECTORY: writePath = new Path(locationHandle.getWritePath(), partitionName); break; case DIRECT_TO_TARGET_EXISTING_DIRECTORY: writePath = targetPath; break; case DIRECT_TO_TARGET_NEW_DIRECTORY: default: throw new UnsupportedOperationException(format("inserting into existing partition is not supported for %s", writeMode)); } return new WriteInfo(targetPath, writePath, writeMode); } else { return new WriteInfo( new Path(locationHandle.getTargetPath(), partitionName), new Path(locationHandle.getWritePath(), partitionName), locationHandle.getWriteMode()); } }
Source:
public StatisticsResource getStatisticsResource() { EntityIdResolver<Guid> resolver = new EntityIdResolver<Guid>() { @Override public org.ovirt.engine.core.common.businessentities.Disk lookupEntity( Guid id) throws BackendFailureException { return collection.lookupEntity(guid); } }; DiskStatisticalQuery query = new DiskStatisticalQuery(resolver, newModel(id)); return inject(new BackendStatisticsResource<Disk, org.ovirt.engine.core.common.businessentities.Disk>(entityType, guid, query)); }

Target:
public StatisticsResource getStatisticsResource() { EntityIdResolver<Guid> resolver = new EntityIdResolver<Guid>() { @Override public org.ovirt.engine.core.common.businessentities.Disk lookupEntity( Guid guid) throws BackendFailureException { return collection.lookupEntity(guid); } }; DiskStatisticalQuery query = new DiskStatisticalQuery(resolver, newModel(id)); return inject(new BackendStatisticsResource<Disk, org.ovirt.engine.core.common.businessentities.Disk>(entityType, guid, query)); }
Source:
public void addConnector(String connectorType, Connector connector, AssignmentStrategy strategy, boolean customCheckpointing) { _log.info("Add new connector of type " + connectorType + " to coordinator"); if (_connectors.containsKey(connectorType)) { String err = "A connector of type " + connectorType + " already exists."; _log.error(err); _dynamicMetricsManager.createOrUpdateCounter(this.getClass(), "addConnector", NUM_ERRORS, 1); throw new IllegalArgumentException(err); } Optional<Map<String, Metric>> connectorMetrics = Optional.ofNullable(connector.getMetrics()); connectorMetrics.ifPresent(m -> _metrics.putAll(m)); ConnectorWrapper connectorWrapper = new ConnectorWrapper(connectorType, connector); _connectors.put(connectorType, connectorWrapper); _strategies.put(connectorWrapper, strategy); if (customCheckpointing) { _customCheckpointingConnectorTypes.add(connectorType); } }

Target:
public void addConnector(String connectorType, Connector connector, AssignmentStrategy strategy, boolean customCheckpointing) { _log.info("Add new connector of type " + connectorType + " to coordinator"); if (_connectors.containsKey(connectorType)) { String err = "A connector of type " + connectorType + " already exists."; _log.error(err); throw new IllegalArgumentException(err); } Optional<Map<String, Metric>> connectorMetrics = Optional.ofNullable(connector.getMetrics()); connectorMetrics.ifPresent(m -> _metrics.putAll(m)); ConnectorWrapper connectorWrapper = new ConnectorWrapper(connectorType, connector); _connectors.put(connectorType, connectorWrapper); _strategies.put(connectorWrapper, strategy); if (customCheckpointing) { _customCheckpointingConnectorTypes.add(connectorType); } }
Source:
public void equalsTest() { SequenceDeclaration a = new SequenceDeclaration("Hi", IntegerDeclaration.INT_32B_DECL); SequenceDeclaration b = new SequenceDeclaration("Hello", IntegerDeclaration.INT_32B_DECL); SequenceDeclaration c = new SequenceDeclaration("Hi", new StringDeclaration()); SequenceDeclaration d = new SequenceDeclaration("Hi", IntegerDeclaration.INT_32B_DECL); assertNotEquals(a, null); assertNotEquals(a, new Object()); assertNotEquals(a, b); assertNotEquals(a, c); assertEquals(a, d); assertEquals(a, a); assertFalse(a.isBinaryEquivalent(b)); assertFalse(a.isBinaryEquivalent(c)); assertTrue(a.isBinaryEquivalent(d)); assertTrue(a.isBinaryEquivalent(a)); }

Target:
public void equalsTest() { SequenceDeclaration a = new SequenceDeclaration("Hi", IntegerDeclaration.INT_32B_DECL); SequenceDeclaration b = new SequenceDeclaration("Hello", IntegerDeclaration.INT_32B_DECL); SequenceDeclaration c = new SequenceDeclaration("Hi", new StringDeclaration()); SequenceDeclaration d = new SequenceDeclaration("Hi", IntegerDeclaration.INT_32B_DECL); assertNotEquals(a, null); assertNotEquals(a, new Object()); assertNotEquals(a, b); assertNotEquals(a, c); assertEquals(a, d); assertNotEquals(b, a); assertNotEquals(c, a); assertEquals(d, a); assertEquals(a, a); assertFalse(a.isBinaryEquivalent(b)); assertFalse(a.isBinaryEquivalent(c)); assertTrue(a.isBinaryEquivalent(d)); assertTrue(a.isBinaryEquivalent(a)); }
Source:
private void startActionMode(@ActionModeType int type) { if (adapter.getItems().isEmpty()) { ToastUtil.showError(getActivity(), getString(R.string.am_empty_list)); resetActionModeParameters(); } else { actionModeType = type; actionMode = getActivity().startActionMode(this); BottomBar.hideBottomBar(getActivity()); } }

Target:
private void startActionMode(@ActionModeType int type) { if (adapter.getItems().isEmpty()) { ToastUtil.showError(getActivity(), R.string.am_empty_list); resetActionModeParameters(); } else { actionModeType = type; actionMode = getActivity().startActionMode(this); BottomBar.hideBottomBar(getActivity()); } }
Source:
public static void showZeroBanner(@NonNull Activity activity, @NonNull String text, @ColorInt int foreColor, @ColorInt int backColor) { Snackbar snackbar = Snackbar.make(activity.findViewById(R.id.page_contents_container), text, Snackbar.LENGTH_LONG); ViewGroup rootView = (ViewGroup) snackbar.getView(); TextView textView = (TextView) rootView.findViewById(R.id.snackbar_text); rootView.setBackgroundColor(backColor); textView.setTextColor(foreColor); textView.setTextSize(BANNER_TEXT_SIZE); textView.setGravity(Gravity.CENTER_HORIZONTAL); rootView.setMinimumHeight((int) (BANNER_HEIGHT * WikipediaApp.getInstance().getScreenDensity())); snackbar.show(); }

Target:
public static void showZeroBanner(@NonNull Activity activity, @NonNull String text, @ColorInt int foreColor, @ColorInt int backColor) { Snackbar snackbar = Snackbar.make(activity.findViewById(R.id.page_contents_container), text, Snackbar.LENGTH_LONG); ViewGroup rootView = (ViewGroup) snackbar.getView(); TextView textView = (TextView) rootView.findViewById(R.id.snackbar_text); rootView.setBackgroundColor(backColor); textView.setTextColor(foreColor); textView.setTextSize(BANNER_TEXT_SIZE); textView.setGravity(Gravity.CENTER_HORIZONTAL); rootView.setMinimumHeight(BANNER_HEIGHT); snackbar.show(); }
Source:
static Bindable getBindable(ClassDeclaration expr, String s, int fieldCount) throws CompileException, IOException, ExecutionException { ICompilerFactory compilerFactory; try { compilerFactory = CompilerFactoryFactory.getDefaultCompilerFactory(); } catch (Exception e) { throw new IllegalStateException( "Unable to instantiate java compiler", e); } final IClassBodyEvaluator cbe = compilerFactory.newClassBodyEvaluator(); cbe.setClassName(expr.name); cbe.setExtendedClass(Utilities.class); cbe.setImplementedInterfaces( fieldCount == 1 ? new Class[] {Bindable.class, Typed.class} : new Class[] {ArrayBindable.class}); cbe.setParentClassLoader(EnumerableInterpretable.class.getClassLoader()); if (CalcitePrepareImpl.DEBUG) { cbe.setDebuggingInformation(true, true, true); } if (BINDABLE_CACHE_MAX_SIZE != 0) { StaticFieldDetector detector = new StaticFieldDetector(); expr.accept(detector); if (!detector.containsStaticField) { return BINDABLE_CACHE.get(s, () -> (Bindable) cbe.createInstance(new StringReader(s))); } } return (Bindable) cbe.createInstance(new StringReader(s)); }

Target:
static Bindable getBindable(ClassDeclaration expr, String s, int fieldCount) throws CompileException, IOException, ExecutionException { ICompilerFactory compilerFactory; try { compilerFactory = CompilerFactoryFactory.getDefaultCompilerFactory(); } catch (Exception e) { throw new IllegalStateException( "Unable to instantiate java compiler", e); } final IClassBodyEvaluator cbe = compilerFactory.newClassBodyEvaluator(); cbe.setClassName(expr.name); cbe.setExtendedClass(Utilities.class); cbe.setImplementedInterfaces( fieldCount == 1 ? new Class[] {Bindable.class, Typed.class} : new Class[] {ArrayBindable.class}); cbe.setParentClassLoader(EnumerableInterpretable.class.getClassLoader()); if (CalciteSystemProperty.DEBUG.value()) { cbe.setDebuggingInformation(true, true, true); } if (CalciteSystemProperty.BINDABLE_CACHE_MAX_SIZE.value() != 0) { StaticFieldDetector detector = new StaticFieldDetector(); expr.accept(detector); if (!detector.containsStaticField) { return BINDABLE_CACHE.get(s, () -> (Bindable) cbe.createInstance(new StringReader(s))); } } return (Bindable) cbe.createInstance(new StringReader(s)); }
Source:
public void endTurn(UserBean user, String gameIdString) throws PlayException, GameException { log.debug("User tries to end his turn of game id {}", user == null ? "<EMPTY>" : user.getUsername(), gameIdString); GameBean game = gameUtil.getGameById(gameIdString, ERROR_CODE_ERROR); validateGameStatusIsPlaying(game); validateUserNotEmpty(user); validateCurrentTurnOfUser(game, user); validateActionIsAllowed(user, game, GameUserActions.END_TURN); playUtil.updateNextMoveOrder(game); playUtil.updateCurrentCycleBuildingNumber(game); playUtil.updateAvailableUserActions(game); gameDao.updateGame(game); }

Target:
public void endTurn(UserBean user, String gameIdString) throws PlayException, GameException { log.debug("{} tries to end his turn of game id {}", user, gameIdString); GameBean game = gameUtil.getGameById(gameIdString, ERROR_CODE_ERROR); validateUserNotEmpty(user); validateGameStatusIsPlaying(game); validateActionIsAllowed(user, game, GameUserActionCode.END_TURN); boolean shouldUpdateNextMove = true; if (game.getStage().equals(GameStage.PREPARATION)) { Integer currentPreparationCycle = game.getPreparationCycle(); preparationStageUtil.updateGameStageToMain(game); preparationStageUtil.updateCurrentCycleBuildingNumber(game); preparationStageUtil.updatePreparationCycle(game); shouldUpdateNextMove = currentPreparationCycle.equals(game.getPreparationCycle()); } if (shouldUpdateNextMove) { playUtil.updateNextMove(game); } playUtil.updateAvailableUserActions(game); gameDao.updateGame(game); log.debug("User successfully ended his turn", user.getUsername(), gameIdString); }
Source:
public void test() { TimeZoneKey.getTimeZoneKey("GMT-13:00"); TreeSet<String> jodaZones = new TreeSet<>(DateTimeZone.getAvailableIDs()); TreeSet<String> jdkZones = new TreeSet<>(Arrays.asList(TimeZone.getAvailableIDs())); for (String zoneId : new TreeSet<>(Sets.intersection(jodaZones, jdkZones))) { if (zoneId.toLowerCase(ENGLISH).startsWith("etc/") || zoneId.toLowerCase(ENGLISH).startsWith("gmt")) { continue; } DateTimeZone dateTimeZone = DateTimeZone.forID(zoneId); DateTimeZone indexedZone = getDateTimeZone(TimeZoneKey.getTimeZoneKey(zoneId)); if (!java.util.TimeZone.getTimeZone(zoneId).hasSameRules(dateTimeZone.toTimeZone())) { continue; } assertDateTimeZoneEquals(zoneId, indexedZone); assertTimeZone(zoneId, dateTimeZone); } for (int offsetHours = -13; offsetHours < 14; offsetHours++) { for (int offsetMinutes = 0; offsetMinutes < 60; offsetMinutes++) { DateTimeZone dateTimeZone = DateTimeZone.forOffsetHoursMinutes(offsetHours, offsetMinutes); assertTimeZone(dateTimeZone.getID(), dateTimeZone); } } }

Target:
public void test() { TimeZoneKey.getTimeZoneKey("GMT-13:00"); TreeSet<String> jodaZones = new TreeSet<>(DateTimeZone.getAvailableIDs()); TreeSet<String> jdkZones = new TreeSet<>(Arrays.asList(TimeZone.getAvailableIDs())); for (String zoneId : new TreeSet<>(Sets.intersection(jodaZones, jdkZones))) { if (zoneId.toLowerCase(ENGLISH).startsWith("etc/") || zoneId.toLowerCase(ENGLISH).startsWith("gmt")) { continue; } if (JavaVersion.current().getMajor() == 8 && JavaVersion.current().getUpdate().orElse(0) < 121 && zoneId.equals("Asia/Rangoon")) { continue; } DateTimeZone dateTimeZone = DateTimeZone.forID(zoneId); DateTimeZone indexedZone = getDateTimeZone(TimeZoneKey.getTimeZoneKey(zoneId)); assertDateTimeZoneEquals(zoneId, indexedZone); assertTimeZone(zoneId, dateTimeZone); } for (int offsetHours = -13; offsetHours < 14; offsetHours++) { for (int offsetMinutes = 0; offsetMinutes < 60; offsetMinutes++) { DateTimeZone dateTimeZone = DateTimeZone.forOffsetHoursMinutes(offsetHours, offsetMinutes); assertTimeZone(dateTimeZone.getID(), dateTimeZone); } } }
Source:
public void onEnchant(EnchantItemEvent e) { Random random = ThreadLocalRandom.current(); if (Talisman.checkFor(e, (SlimefunItemStack) SlimefunItems.TALISMAN_MAGICIAN)) { List<String> enchantments = new LinkedList<>(); for (Enchantment en : Enchantment.values()) { for (int i = 1; i <= en.getMaxLevel(); i++) { if ((en.canEnchantItem(e.getItem()) || e.getItem().getType() == Material.BOOK) && (boolean) Slimefun.getItemValue("MAGICIAN_TALISMAN", "allow-enchantments." + en.getKey().getKey() + ".level." + i)) { enchantments.add(en.getKey().getKey() + '-' + i); } } } String enchant = enchantments.get(random.nextInt(enchantments.size())); String[] enchantSplit = PatternUtils.SLASH_SEPARATOR.split(enchant); e.getEnchantsToAdd().put(Enchantment.getByKey(NamespacedKey.minecraft(enchantSplit[0])), Integer.parseInt(enchantSplit[1])); } if (!e.getEnchantsToAdd().containsKey(Enchantment.SILK_TOUCH) && Enchantment.LOOT_BONUS_BLOCKS.canEnchantItem(e.getItem()) && Talisman.checkFor(e, (SlimefunItemStack) SlimefunItems.TALISMAN_WIZARD)) { Set<Enchantment> enchantments = e.getEnchantsToAdd().keySet(); for (Enchantment en : enchantments) { if (random.nextInt(100) < 40) { e.getEnchantsToAdd().put(en, random.nextInt(3) + 1); } } e.getEnchantsToAdd().put(Enchantment.LOOT_BONUS_BLOCKS, random.nextInt(3) + 3); } }

Target:
public void onEnchant(EnchantItemEvent e) { Random random = ThreadLocalRandom.current(); if (Talisman.checkFor(e, (SlimefunItemStack) SlimefunItems.TALISMAN_MAGICIAN)) { List<String> enchantments = new LinkedList<>(); for (Enchantment en : Enchantment.values()) { for (int i = 1; i <= en.getMaxLevel(); i++) { if ((en.canEnchantItem(e.getItem()) || e.getItem().getType() == Material.BOOK) && (boolean) Slimefun.getItemValue("MAGICIAN_TALISMAN", "allow-enchantments." + en.getKey().getKey() + ".level." + i)) { enchantments.add(en.getKey().getKey() + '-' + i); } } } String enchant = enchantments.get(random.nextInt(enchantments.size())); String[] enchantSplit = PatternUtils.DASH.split(enchant); e.getEnchantsToAdd().put(Enchantment.getByKey(NamespacedKey.minecraft(enchantSplit[0])), Integer.parseInt(enchantSplit[1])); } if (!e.getEnchantsToAdd().containsKey(Enchantment.SILK_TOUCH) && Enchantment.LOOT_BONUS_BLOCKS.canEnchantItem(e.getItem()) && Talisman.checkFor(e, (SlimefunItemStack) SlimefunItems.TALISMAN_WIZARD)) { Set<Enchantment> enchantments = e.getEnchantsToAdd().keySet(); for (Enchantment en : enchantments) { if (random.nextInt(100) < 40) { e.getEnchantsToAdd().put(en, random.nextInt(3) + 1); } } e.getEnchantsToAdd().put(Enchantment.LOOT_BONUS_BLOCKS, random.nextInt(3) + 3); } }