auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void registerJava8TimeConversions() { if ( !isJava8TimeAvailable() ) { return; } register( JavaTimeConstants.ZONED_DATE_TIME_FQN, String.class, new JavaZonedDateTimeToStringConversion() ); register( JavaTimeConstants.LOCAL_DATE_FQN, String.class, new JavaLocalDateToStringConversion() ); register( JavaTimeConstants.LOCAL_DATE_TIME_FQN, String.class, new JavaLocalDateTimeToStringConversion() ); register( JavaTimeConstants.LOCAL_TIME_FQN, String.class, new JavaLocalTimeToStringConversion() ); register( JavaTimeConstants.ZONED_DATE_TIME_FQN, Date.class, new JavaZonedDateTimeToDateConversion() ); register( JavaTimeConstants.LOCAL_DATE_TIME_FQN, Date.class, new JavaLocalDateTimeToDateConversion() ); register( JavaTimeConstants.LOCAL_DATE_FQN, Date.class, new JavaLocalDateToDateConversion() ); register( java.sql.Date.class, JavaTimeConstants.LOCAL_DATE_FQN, new JavaSqlDateToLocalDateConversion() ); register( JavaTimeConstants.INSTANT, Date.class, new JavaInstantToDateConversion() ); }

Target:
private void registerJava8TimeConversions() { if ( !isJava8TimeAvailable() ) { return; } register( JavaTimeConstants.ZONED_DATE_TIME_FQN, String.class, new JavaZonedDateTimeToStringConversion() ); register( JavaTimeConstants.LOCAL_DATE_FQN, String.class, new JavaLocalDateToStringConversion() ); register( JavaTimeConstants.LOCAL_DATE_TIME_FQN, String.class, new JavaLocalDateTimeToStringConversion() ); register( JavaTimeConstants.LOCAL_TIME_FQN, String.class, new JavaLocalTimeToStringConversion() ); register( JavaTimeConstants.ZONED_DATE_TIME_FQN, Date.class, new JavaZonedDateTimeToDateConversion() ); register( JavaTimeConstants.LOCAL_DATE_TIME_FQN, Date.class, new JavaLocalDateTimeToDateConversion() ); register( JavaTimeConstants.LOCAL_DATE_FQN, Date.class, new JavaLocalDateToDateConversion() ); register( JavaTimeConstants.LOCAL_DATE_FQN, java.sql.Date.class, new JavaLocalDateToSqlDateConversion() ); register( JavaTimeConstants.INSTANT, Date.class, new JavaInstantToDateConversion() ); }
Source:
public boolean regenerate(Region region, EditSession editSession) { try { Server server = Sponge.getServer(); WorldProperties tempWorldProperties; try { tempWorldProperties = server.createWorldProperties("worldedittemp", this.regenerationArchetype); } catch (IOException e) { e.printStackTrace(); return false; } Optional<World> tempWorldOpt = server.loadWorld(tempWorldProperties); if (!tempWorldOpt.isPresent()) { return false; } World freshWorld = tempWorldOpt.get(); CuboidRegion expandedPreGen = new CuboidRegion(region.getMinimumPoint().subtract(16, 0, 16), region.getMaximumPoint().add(16, 0, 16)); for (Vector2D chunk : expandedPreGen.getChunks()) { freshWorld.getChunk(chunk.getBlockX(), 0, chunk.getBlockZ()); } SpongeWorld from = SpongeWorldEdit.inst().getWorld(freshWorld); for (BlockVector vec : region) { editSession.setBlock(vec, from.getBlock(vec)); } server.unloadWorld(freshWorld); server.deleteWorld(tempWorldProperties); } catch (MaxChangedBlocksException e) { throw new RuntimeException(e); } return false; }

Target:
public boolean regenerate(Region region, EditSession editSession) { Server server = Sponge.getServer(); final String id = "regenArchetype" + getWorld().getName(); final WorldArchetype regenerationArchetype = Sponge.getRegistry().getType(WorldArchetype.class, id) .orElseGet(() -> WorldArchetype.builder() .from(getWorld().getProperties()) .serializationBehavior(SerializationBehaviors.NONE) .build(id, id)); WorldProperties tempWorldProperties; try { tempWorldProperties = server.createWorldProperties("worldedittemp", regenerationArchetype); tempWorldProperties.setGenerateSpawnOnLoad(false); } catch (IOException e) { log.error("Error creating world properties", e); return false; } Optional<World> tempWorldOpt = server.loadWorld(tempWorldProperties); if (!tempWorldOpt.isPresent()) { log.error("Failed to load temp world"); return false; } World freshWorld = tempWorldOpt.get(); try { CuboidRegion expandedPreGen = new CuboidRegion(region.getMinimumPoint().subtract(16, 0, 16), region.getMaximumPoint().add(16, 0, 16)); for (Vector2D chunk : expandedPreGen.getChunks()) { freshWorld.getChunk(chunk.getBlockX(), 0, chunk.getBlockZ()); } SpongeWorld from = SpongeWorldEdit.inst().getWorld(freshWorld); for (BlockVector vec : region) { editSession.setBlock(vec, from.getBlock(vec)); } } catch (MaxChangedBlocksException e) { throw new RuntimeException(e); } finally { server.unloadWorld(freshWorld); server.deleteWorld(tempWorldProperties); } return false; }
Source:
public void testWindowsMachines(String osFamily) throws Exception { brooklynProperties.put("brooklyn.location.byon.user", "myuser"); brooklynProperties.put("brooklyn.location.byon.password", "mypassword"); String spec = "byon"; Map<String, ?> flags = ImmutableMap.of( "hosts", ImmutableList.of("1.1.1.1", "2.2.2.2"), "osFamily", "windows" ); MachineProvisioningLocation<MachineLocation> provisioner = resolve(spec, flags); WinRmMachineLocation location = (WinRmMachineLocation) provisioner.obtain(ImmutableMap.of()); assertEquals(location.config().get(WinRmMachineLocation.USER), "myuser"); assertEquals(location.config().get(WinRmMachineLocation.PASSWORD), "mypassword"); assertEquals(location.config().get(WinRmMachineLocation.ADDRESS).getHostAddress(), "1.1.1.1"); }

Target:
public void testWindowsMachines(String osFamily) throws Exception { brooklynProperties.put("brooklyn.location.byon.user", "myuser"); brooklynProperties.put("brooklyn.location.byon.password", "mypassword"); String spec = "byon"; Map<String, ?> flags = ImmutableMap.of( "hosts", ImmutableList.of("1.1.1.1", "2.2.2.2"), "osFamily", osFamily ); MachineProvisioningLocation<MachineLocation> provisioner = resolve(spec, flags); WinRmMachineLocation location = (WinRmMachineLocation) provisioner.obtain(ImmutableMap.of()); assertEquals(location.config().get(WinRmMachineLocation.USER), "myuser"); assertEquals(location.config().get(WinRmMachineLocation.PASSWORD), "mypassword"); assertEquals(location.config().get(WinRmMachineLocation.ADDRESS).getHostAddress(), "1.1.1.1"); }
Source:
protected Method getGetterMethod(SystemResource sr) { try { return operatingSystemMXBean.getClass().getMethod("get" + sr.name(), null); } catch (Exception e) { throw new RuntimeException("Invalid SystemResource: " + sr); } }

Target:
private Method getGetterMethod(SystemResource sr) { try { return operatingSystemMXBean.getClass().getMethod("get" + sr.name(), null); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
private <T> List<T> nullToEmpty(List<T> list) { if (list == null) { return Collections.emptyList(); } else { return new ArrayList<>(list); } }

Target:
private <T> List<T> nullToEmpty(List<T> list) { if (list == null) { return Collections.emptyList(); } return new ArrayList<>(list); }
Source:
public AbstractRepositoryRestController(PagedResourcesAssembler<Object> assembler, PersistentEntityResourceAssembler<Object> entityResourceAssembler) { System.out.println("Registering " + this.getClass() + " controller..."); this.assembler = assembler; this.perAssembler = entityResourceAssembler; }

Target:
public AbstractRepositoryRestController(PagedResourcesAssembler<Object> assembler, PersistentEntityResourceAssembler<Object> entityResourceAssembler) { this.assembler = assembler; this.perAssembler = entityResourceAssembler; }
Source:
public Optional<MethodSpec> generate() { TypeVariableName settableT = TypeVariableName.get("SettableT"); settableT = settableT.withBounds( ParameterizedTypeName.get(ClassName.get(SettableByName.class), settableT)); TypeName nullSavingStrategyT = TypeVariableName.get(NullSavingStrategy.class); MethodSpec.Builder injectBuilder = MethodSpec.methodBuilder("set") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addTypeVariable(settableT) .addParameter(ParameterSpec.builder(entityDefinition.getClassName(), "entity").build()) .addParameter(ParameterSpec.builder(settableT, "target").build()) .addParameter(ParameterSpec.builder(nullSavingStrategyT, "nullSavingStrategy").build()) .returns(settableT); for (PropertyDefinition property : entityDefinition.getAllColumns()) { GeneratedCodePatterns.setValue( property.getCqlName(), property.getType(), CodeBlock.of("entity.$L()", property.getGetterName()), "target", injectBuilder, enclosingClass, CodeBlock.of("nullSavingStrategy")); } injectBuilder.addCode("\n").addStatement("return target"); return Optional.of(injectBuilder.build()); }

Target:
public Optional<MethodSpec> generate() { TypeVariableName settableT = TypeVariableName.get("SettableT"); settableT = settableT.withBounds( ParameterizedTypeName.get(ClassName.get(SettableByName.class), settableT)); MethodSpec.Builder injectBuilder = MethodSpec.methodBuilder("set") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addTypeVariable(settableT) .addParameter(ParameterSpec.builder(entityDefinition.getClassName(), "entity").build()) .addParameter(ParameterSpec.builder(settableT, "target").build()) .addParameter( ParameterSpec.builder(NullSavingStrategy.class, "nullSavingStrategy").build()) .returns(settableT); for (PropertyDefinition property : entityDefinition.getAllColumns()) { GeneratedCodePatterns.setValue( property.getCqlName(), property.getType(), CodeBlock.of("entity.$L()", property.getGetterName()), "target", injectBuilder, enclosingClass, true); } injectBuilder.addCode("\n").addStatement("return target"); return Optional.of(injectBuilder.build()); }
Source:
protected HeaderParams writeHeader( Transport transport, HeaderParams params, byte version) { transport.writeByte(HotRodConstants.REQUEST_MAGIC); transport.writeVLong(params.messageId(MSG_ID.incrementAndGet()).messageId); transport.writeByte(version); transport.writeByte(params.opCode); transport.writeArray(params.cacheName); int flagInt = 0; if (params.flags != null) { for (Flag flag : params.flags) { flagInt = flag.getFlagInt() | flagInt; } } transport.writeVInt(flagInt); transport.writeByte(params.clientIntel); transport.writeVInt(params.topologyId.get()); getLog().tracef("Wrote header for message %d. Operation code: %#04x. Flags: %#x", params.messageId, params.opCode, flagInt); return params; }

Target:
protected HeaderParams writeHeader( Transport transport, HeaderParams params, byte version) { transport.writeByte(HotRodConstants.REQUEST_MAGIC); transport.writeVLong(params.messageId(MSG_ID.incrementAndGet()).messageId); transport.writeByte(version); transport.writeByte(params.opCode); transport.writeArray(params.cacheName); int joinedFlags = HeaderParams.joinFlags(params.flags); transport.writeVInt(joinedFlags); transport.writeByte(params.clientIntel); transport.writeVInt(params.topologyId.get()); if (trace) getLog().tracef("Wrote header for message %d. Operation code: %#04x. Flags: %#x", params.messageId, params.opCode, joinedFlags); return params; }
Source:
@Override public void clearFeatures() { map.getOverlays().clear(); map.getOverlays().add(new AttributionOverlay(getContext())); map.getOverlays().add(new MapEventsOverlay(this)); map.getOverlays().add(myLocationOverlay); map.invalidate(); features.clear(); }

Target:
@Override public void clearFeatures() { map.getOverlays().clear(); addAttributionAndMapEventsOverlays(); map.getOverlays().add(myLocationOverlay); map.invalidate(); features.clear(); }
Source:
public void onEventMainThread(DownloadEvent event) { Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]"); DownloaderUpdate update = event.update; if (isUpdatingFeeds != update.feedIds.length > 0) { getActivity().invalidateOptionsMenu(); } }

Target:
public void onEventMainThread(DownloadEvent event) { Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]"); if (event.hasChangedFeedUpdateStatus(isUpdatingFeeds)) { getActivity().invalidateOptionsMenu(); } }
Source:
public Map<IPath, RepositoryMapping> getRepositoryMappings() { return mappings; }

Target:
public final Map<IPath, RepositoryMapping> getRepositoryMappings() { return mappings; }
Source:
public void testReadingAllEntries() { writeBulkSets(); List<Integer> matches = storage.getIDsForValues(new String[]{}, new String[]{}); Set<Integer> expectedMatches = getIdsFromModels(tenSizesOfMensNikes); expectedMatches.addAll(getIdsFromModels(eightSizesOfWomensNikes)); expectedMatches.addAll(getIdsFromModels(fiveSizesOfMensVans)); Assert.assertEquals("Failed index match [brand,style][nike,mens]", expectedMatches, new HashSet<>(matches)); }

Target:
public void testReadingAllEntries() { writeBulkSets(); List<Integer> matches = storage.getIDsForValues(new String[0], new String[0]); Set<Integer> expectedMatches = getIdsFromModels(tenSizesOfMensNikes); expectedMatches.addAll(getIdsFromModels(eightSizesOfWomensNikes)); expectedMatches.addAll(getIdsFromModels(fiveSizesOfMensVans)); Assert.assertEquals("Failed index match for all entries", expectedMatches, new HashSet<>(matches)); }
Source:
public void deleteAllDLCMessages() { String deletingMessageID = null; try { deletingMessageID = driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.first.message.id"))).getText(); if(StringUtils.isNotBlank(deletingMessageID)) { log.info("delete all dlc messages"); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.table.choose.all.box.xpath"))) .click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.table.delete.button"))).click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.function.confirm"))).click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.function.success"))).click(); } }catch (Exception e) { log.error("unable to find any valid messages in dead letter channel."); } }

Target:
public void deleteAllDLCMessages() { WebElement dlcTable = driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.content.table"))); List<WebElement> allDlcRows = dlcTable.findElements(By.tagName("tr")); if(allDlcRows.size() > 0) { log.info("delete all dlc messages"); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.table.choose.all.box.xpath"))) .click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.table.delete.button"))) .click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.function.confirm"))).click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.function.success"))).click(); } }
Source:
public static void teardown() { if (threadPoolSize != null) { System.setProperty("org.codice.ddf.system.threadPoolSize", threadPoolSize); } if (cipherSuites != null) { System.setProperty("https.cipherSuites", cipherSuites); } else { System.clearProperty("https.cipherSuites"); } if (protocols != null) { System.setProperty("https.protocols", protocols); } else { System.clearProperty("https.protocols"); } }

Target:
public static void teardown() { if (threadPoolSize != null) { System.setProperty("org.codice.ddf.system.threadPoolSize", threadPoolSize); } else { System.clearProperty("org.codice.ddf.system.threadPoolSize"); } if (cipherSuites != null) { System.setProperty("https.cipherSuites", cipherSuites); } else { System.clearProperty("https.cipherSuites"); } if (protocols != null) { System.setProperty("https.protocols", protocols); } else { System.clearProperty("https.protocols"); } }
Source:
protected void simulateError(int hostNumber, Result result, Config config) { PrimingRequestBuilder builder = PrimingRequest.queryBuilder() .withQuery("mock query") .withThen(then().withResult(result)); if (config != null) builder = builder.withThen(then().withConfig(config)); scassandras.node(hostNumber).primingClient().prime(builder.build()); }

Target:
protected void simulateError(int hostNumber, Result result, Config config) { PrimingRequest.Then.ThenBuilder then = then().withResult(result); PrimingRequestBuilder builder = PrimingRequest.queryBuilder().withQuery("mock query"); if (config != null) then = then.withConfig(config); builder = builder.withThen(then); scassandras.node(hostNumber).primingClient().prime(builder.build()); }
Source:
private static final ModelContext getModelContext() { return Utils.getComponent(ModelContext.class); }

Target:
private final ModelContext getModelContext() { return Utils.getComponent(ModelContext.class); }
Source:
public void shouldDecreaseIdleWhenClosedInsidePool() throws Throwable { Channel channel = newChannel(); tracker.channelCreated( channel, null ); assertEquals( 1, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); tracker.channelReleased( channel ); assertEquals( 0, tracker.inUseChannelCount( address ) ); assertEquals( 1, tracker.idleChannelCount( address ) ); channel.close(); assertEquals( 0, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); }

Target:
public void shouldDecreaseIdleWhenClosedInsidePool() throws Throwable { Channel channel = newChannel(); tracker.channelCreated( channel, null ); assertEquals( 1, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); tracker.channelReleased( channel ); assertEquals( 0, tracker.inUseChannelCount( address ) ); assertEquals( 1, tracker.idleChannelCount( address ) ); channel.close().sync(); assertEquals( 0, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); }
Source:
public String getEntityType() { return ET_UNSUPPORTED; }

Target:
public String getEntityType() { if (value.entityType == null) { return ET_UNSUPPORTED; } String[] parts = value.entityType.split("-"); for(int i = 0; i < parts.length; i++) { parts[i] = StringUtils.capitalize(parts[i]); } return "<LINK_0>" + StringUtils.join(parts); }
Source:
public FormulaDto save(final FormulaDto formulaDto) { Formula formula = FormulaUtils.convertToFormula(formulaDto); formula = this.daoFactory.getFormulaDAO().save(formula); final FormulaDto result = FormulaUtils.convertToFormulaDto(formula); return result; }

Target:
public FormulaDto save(final FormulaDto formulaDto) { final Formula formula = FormulaUtils.convertToFormula(formulaDto); this.daoFactory.getFormulaDAO().save(formula); final FormulaDto result = FormulaUtils.convertToFormulaDto(formula); return result; }
Source:
protected static GenotypesContext fixGenotypes(final GenotypesContext originals, final List<Allele> originalAlleles, final List<Allele> newAlleles) { if (originalAlleles.equals(newAlleles)) { return originals; } if (originalAlleles.size() != newAlleles.size()) { throw new IllegalStateException("Error in allele lists: the original and new allele lists are not the same length: " + originalAlleles.toString() + " / " + newAlleles.toString()); } final Map<Allele, Allele> alleleMap = new HashMap<>(); for (int idx = 0; idx < originalAlleles.size(); idx++) { alleleMap.put(originalAlleles.get(idx), newAlleles.get(idx)); } final GenotypesContext fixedGenotypes = GenotypesContext.create(originals.size()); for (final Genotype genotype : originals) { final List<Allele> fixedAlleles = new ArrayList<>(); for (final Allele allele : genotype.getAlleles()) { if (allele.isSymbolic() || allele.isNoCall()) { fixedAlleles.add(allele); } else { Allele newAllele = alleleMap.get(allele); if (newAllele == null) { throw new IllegalStateException("Allele not found: " + allele.toString() + ", " + originalAlleles + "/ " + newAlleles); } fixedAlleles.add(newAllele); } } fixedGenotypes.add(new GenotypeBuilder(genotype).alleles(fixedAlleles).make()); } return fixedGenotypes; }

Target:
protected static GenotypesContext fixGenotypes(final GenotypesContext originals, final List<Allele> originalAlleles, final List<Allele> newAlleles) { if (originalAlleles.equals(newAlleles)) { return originals; } if (originalAlleles.size() != newAlleles.size()) { throw new IllegalStateException("Error in allele lists: the original and new allele lists are not the same length: " + originalAlleles.toString() + " / " + newAlleles.toString()); } final Map<Allele, Allele> alleleMap = new HashMap<>(); for (int idx = 0; idx < originalAlleles.size(); idx++) { alleleMap.put(originalAlleles.get(idx), newAlleles.get(idx)); } final GenotypesContext fixedGenotypes = GenotypesContext.create(originals.size()); for (final Genotype genotype : originals) { final List<Allele> fixedAlleles = new ArrayList<>(); for (final Allele allele : genotype.getAlleles()) { if (allele.isNoCall()) { fixedAlleles.add(allele); } else { Allele newAllele = alleleMap.get(allele); if (newAllele == null) { throw new IllegalStateException("Allele not found: " + allele.toString() + ", " + originalAlleles + "/ " + newAlleles); } fixedAlleles.add(newAllele); } } fixedGenotypes.add(new GenotypeBuilder(genotype).alleles(fixedAlleles).make()); } return fixedGenotypes; }
Source:
public ActionMetadataProviderGenerator( TypeOracle typeOracle, Logger logger, Provider<VelocityContext> velocityContextProvider, VelocityEngine velocityEngine, GeneratorUtil generatorUtil, EventBus eventBus) { super(typeOracle, logger, velocityContextProvider, velocityEngine, generatorUtil); eventBus.register(this); }

Target:
ActionMetadataProviderGenerator(TypeOracle typeOracle, Logger logger, Provider<VelocityContext> velocityContextProvider, VelocityEngine velocityEngine, GeneratorUtil generatorUtil, EventBus eventBus) { super(typeOracle, logger, velocityContextProvider, velocityEngine, generatorUtil); eventBus.register(this); }
Source:
List<File> parseGroovyScripts( final String value ) throws ManipulationException { if ( isEmpty( value ) ) { return Collections.emptyList(); } else { final List<File> result = new ArrayList<>(); logger.debug( "Processing groovy scripts ", value ); try { final String[] scripts = value.split( "," ); for ( final String script : scripts ) { File found; logger.info( "Processing groovy script {}", script ); if ( script.startsWith( "http:" ) || script.startsWith( "file:" ) ) { URL url = new URL( script ); logger.info( "Attempting to read URL {}", url ); found = fileIO.resolveURL( url ); } else { final ArtifactRef ar = SimpleArtifactRef.parse( script ); logger.info( "Attempting to read GAV with classifier and type ", ar.asProjectVersionRef(), ar.getClassifier(), ar.getType() ); found = modelBuilder.resolveRawFile( ar ); } result.add( found ); } } catch ( IOException e ) { throw new ManipulationException( "Unable to parse groovyScripts", e ); } return result; } }

Target:
List<File> parseGroovyScripts( final String value ) throws ManipulationException { if ( isEmpty( value ) ) { return Collections.emptyList(); } else { final List<File> result = new ArrayList<>(); logger.debug( "Processing groovy scripts ", value ); try { final String[] scripts = value.split( "," ); for ( final String script : scripts ) { File found; if ( script.startsWith( "http:" ) || script.startsWith( "https:" ) || script.startsWith( "file:" )) { logger.info( "Attempting to read URL ", script ); found = fileIO.resolveURL( new URL( fixFileURL( script ) ) ); } else { final ArtifactRef ar = SimpleArtifactRef.parse( script ); logger.info( "Attempting to read GAV with classifier and type ", ar.asProjectVersionRef(), ar.getClassifier(), ar.getType() ); found = modelBuilder.resolveRawFile( ar ); } result.add( found ); } } catch ( IOException e ) { throw new ManipulationException( "Unable to parse groovyScripts", e ); } return result; } }
Source:
public void getAllChannelsShouldReturnSingleElementListWhenThereIsOneChannel() { List<ChannelEntity> channels = Arrays.asList(facebookEntity); Collection<ChannelDTO> expected = Arrays.asList(facebookDto); given(channelRepository.findAll()).willReturn(channels); given(modelMapper.map(channels, CHANNEL_DTO_LIST_TYPE)).willReturn(expected); Collection<ChannelDTO> result = channelService.getAllChannels(); assertEquals(result, expected); then(channelRepository).should(times(1)).findAll(); }

Target:
public void getAllChannelsShouldReturnSingleElementListWhenThereIsOneChannel() { List<ChannelEntity> channels = Arrays.asList(facebookEntity); Collection<ChannelDTO> expected = Arrays.asList(facebookDto); given(channelRepository.findAll()).willReturn(channels); given(modelMapper.map(channels, CHANNEL_DTO_LIST_TYPE)).willReturn(expected); Collection<ChannelDTO> result = channelService.getAllChannels(); assertEquals(result, expected); then(channelRepository).should().findAll(); then(modelMapper).should().map(channels, CHANNEL_DTO_LIST_TYPE); }
Source:
public ColorStateList getTextColor() { return super.getTextColors(); }

Target:
public int getTextColor() { return super.getCurrentTextColor(); }
Source:
public static Configuration grabConfig(File content) { try { final ArrayList<String> strings = new ArrayList<>( Arrays.asList("java", "-jar", getNextFlowTargetFile().getAbsolutePath(), "config", "-properties")); final String join = Joiner.on(" ").join(strings); LOG.info("running: " + join); final ImmutablePair<String, String> execute = Utilities.executeCommand(join, content.getParentFile()); String stdout = execute.getLeft(); Properties properties = new Properties(); properties.load(new StringReader(stdout)); return ConfigurationConverter.getConfiguration(properties); } catch (RuntimeException | IOException e) { LOG.error("Problem running NextFlow: ", e); throw new NextflowParsingException("Could not run NextFlow", e); } }

Target:
public static Configuration grabConfig(File content) { try { final List<String> strings = Arrays.asList("java", "-jar", getNextFlowTargetFile().getAbsolutePath(), "config", "-properties"); final String join = Joiner.on(" ").join(strings); LOG.info("running: " + join); final ImmutablePair<String, String> execute = Utilities.executeCommand(join, content.getParentFile()); String stdout = execute.getLeft(); Properties properties = new Properties(); properties.load(new StringReader(stdout)); return ConfigurationConverter.getConfiguration(properties); } catch (RuntimeException | IOException e) { LOG.error("Problem running NextFlow: ", e); throw new NextflowParsingException("Could not run NextFlow", e); } }
Source:
protected Short getNetworkAccessPointTypeCode(String hostAddress) { if (InetAddressValidator.getInstance().isValid(hostAddress)) { return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_IP; } else { return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_NAME; } }

Target:
protected Short getNetworkAccessPointTypeCode(String hostAddress) { if (InetAddressValidator.getInstance().isValid(hostAddress)) { return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_IP; } return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_NAME; }
Source:
public void testListTableNamesWithEmptyElement() throws IOException { try (Admin admin = getConnection().getAdmin()) { sharedTestEnv.createTable(sharedTestEnv.newTestTableName()); Exception actualError = null; try { TableName[] tableNames = admin.listTableNames((Pattern) null); assertTrue(tableNames.length > 0); } catch (Exception e) { actualError = e; } assertNull(actualError); try { admin.listTableNames((String) null); } catch (Exception e) { actualError = e; } assertNotNull(actualError); assertTrue(actualError instanceof NullPointerException); actualError = null; try { assertEquals(0, admin.listTableNames("").length); } catch (Exception e) { actualError = e; } assertNull(actualError); } }

Target:
public void testListTableNamesWithEmptyElement() throws IOException { try (Admin admin = getConnection().getAdmin()) { sharedTestEnv.createTable(sharedTestEnv.newTestTableName()); TableName[] tableNames = admin.listTableNames((Pattern) null); assertTrue(tableNames.length > 0); Exception actualError = null; try { admin.listTableNames((String) null); } catch (Exception e) { actualError = e; } assertNotNull(actualError); assertTrue(actualError instanceof NullPointerException); assertEquals(0, admin.listTableNames("").length); } }
Source:
private void fillDefaults(Map<String, Object> argMap) { for(ParserArgument arg : arguments.values()) { if (!argMap.containsKey(arg.getName())) { if (arg.getDefaultValue() != null) { argMap.put( arg.getName(), Util.getObjectValueByString(arg.getConvert(), arg.getDefaultValue()) ); } if (arg.getType() == ArgumentType.no_argument) { argMap.put(arg.getName(), arg.isValue()); } } } }

Target:
private void fillDefaults(Map<String, Object> argMap) { for(ParserArgument arg : arguments.values()) { if (!argMap.containsKey(arg.getName())) { if (arg.getDefaultValue() != null) { argMap.put( arg.getName(), Util.getObjectValueByString(arg.getConvert(), arg.getDefaultValue()) ); } } } }
Source:
public void toJson() throws Exception { Person person = new Person("Emil", 27); String got = gson.toJson(person); String want = "{\"name\":\"Emil\",\"age\":27}"; assertThat(got, deepEquals(want)); }

Target:
public void toJson() throws Exception { Person person = new Person("Emil", 27); String got = json.toJson(person); String want = "{\"name\":\"Emil\",\"age\":27}"; assertThat(got, is(want)); }
Source:
public Embedding deserialize(JsonNode rootNode, Configuration configuration) { String data = rootNode.get("data").asText(); JsonNode media = rootNode.get("media"); String mimeType; if (media != null) { mimeType = media.get("type").asText(); } else { mimeType = rootNode.get("mime_type").asText(); } Embedding embedding = new Embedding(mimeType, data); storeEmbedding(embedding, configuration.getEmbeddingDirectory()); return embedding; }

Target:
public Embedding deserialize(JsonNode rootNode, Configuration configuration) { String data = rootNode.get("data").asText(); String mimeType = findMimeType(rootNode); Embedding embedding = new Embedding(mimeType, data); storeEmbedding(embedding, configuration.getEmbeddingDirectory()); return embedding; }
Source:
public static DataHandler reassembledStringMessage2(final int streamId) throws Exception { return (buffer, offset, length, header) -> { final byte[] data = new byte[length]; buffer.getBytes(offset, data); System.out.format( "message to stream %d from session %x term id %x term offset %d (%d@%d)%n", streamId, header.sessionId(), header.termId(), header.termOffset(), length, offset); if (length != 9000) { try { throw new Exception( "Received message is not assembled properly, received lenth " + length + " Expecting " + "9000"); } catch (final Exception e) { e.printStackTrace(); } } }; }

Target:
public static DataHandler reassembledStringMessage2(final int streamId) throws Exception { return (buffer, offset, length, header) -> { final byte[] data = new byte[length]; buffer.getBytes(offset, data); System.out.format( "message to stream %d from session %x term id %x term offset %d (%d@%d)%n", streamId, header.sessionId(), header.termId(), header.termOffset(), length, offset); if (length != 9000) { System.out.format("Received message was not assembled properly; received length was %d," + " but was expecting 9000%n", length); } }; }
Source:
public void close() throws IOException { workbook.write(new FileOutputStream(target)); workbook.close(); }

Target:
public void close() throws IOException { try { workbook.write(Files.newOutputStream(target)); } catch (IOException e) { throw e; } finally { workbook.close(); } }
Source:
private void populateTagsInFilterPanel(Target target) { Set<String> tags = new LinkedHashSet<>(); SiteNode siteNode = target.getStartNode(); if (siteNode != null) { this.addTagsInFilterPanel(siteNode, tags); } else if (target.getContext() != null || target.isInScopeOnly()) { List<SiteNode> nodes = Collections.emptyList(); if (target.isInScopeOnly()) { nodes = Model.getSingleton().getSession().getTopNodesInScopeFromSiteTree(); } else if (target.getContext() != null) { nodes = target.getContext().getTopNodesInContextFromSiteTree(); } for (SiteNode node : nodes) { this.addTagsInFilterPanel(node, tags); } } this.setAllTags(new ArrayList<String>(tags)); }

Target:
private void populateTagsInFilterPanel(Target target) { Set<String> tags = new LinkedHashSet<>(); if (target != null) { SiteNode siteNode = target.getStartNode(); if (siteNode != null) { this.addTagsInFilterPanel(siteNode, tags); } else if (target.getContext() != null || target.isInScopeOnly()) { List<SiteNode> nodes = Collections.emptyList(); if (target.isInScopeOnly()) { nodes = Model.getSingleton().getSession().getTopNodesInScopeFromSiteTree(); } else if (target.getContext() != null) { nodes = target.getContext().getTopNodesInContextFromSiteTree(); } for (SiteNode node : nodes) { this.addTagsInFilterPanel(node, tags); } } } this.setAllTags(new ArrayList<String>(tags)); }
Source:
public Collection<? extends Action> getProjectActions() { return Collections.singleton(new CucumberReportProjectAction(run.getParent(), title, directoryQualifier)); }

Target:
public Collection<? extends Action> getProjectActions() { return Collections.singleton(new CucumberReportProjectAction(run.getParent(), getDisplayName(), directorySuffix)); }
Source:
private <T> void setValueInternal(IPreferenceStore store, String name, T value, Function<String, T> prefGetter, BiConsumer<String, T> prefSetter) { Map<String, Object> knownValues = savedPreferences.get(store); if (knownValues == null) { knownValues = new HashMap<>(); savedPreferences.put(store, knownValues); } if (!knownValues.containsKey(name)) { knownValues.put(name, prefGetter.apply(name)); } prefSetter.accept(name, value); }

Target:
private <T> void setValueInternal(IPreferenceStore store, String name, T value, Function<String, T> prefGetter, BiConsumer<String, T> prefSetter) { Map<String, Object> knownValues = savedPreferences.computeIfAbsent(store, key -> new HashMap<>()); if (!knownValues.containsKey(name)) { knownValues.put(name, prefGetter.apply(name)); } prefSetter.accept(name, value); }
Source:
private <T> Publisher<? extends T> readResponseBody(Request request, ClientResponse response, Class<T> responseType) { if (RawActionResponse.class.equals(responseType)) { return Mono.just((T) new RawActionResponse(response)); } if (response.statusCode().is5xxServerError()) { throw new HttpClientErrorException(response.statusCode(), String.format("%s request to %s returned error code %s.", request.getMethod(), request.getEndpoint(), response.statusCode().value())); } return response.body(BodyExtractors.toDataBuffers()).flatMap(it -> { try { String content = StreamUtils.copyToString(it.asInputStream(true), StandardCharsets.UTF_8); try { XContentParser contentParser = XContentType .fromMediaTypeOrFormat( response.headers().contentType().map(MediaType::toString).orElse(XContentType.JSON.mediaType())) .xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, content); Method fromXContent = ReflectionUtils.findMethod(responseType, "fromXContent", XContentParser.class); return Mono.just((T) ReflectionUtils.invokeMethod(fromXContent, responseType, contentParser)); } catch (Exception parseFailure) { try { XContentParser errorParser = XContentType .fromMediaTypeOrFormat( response.headers().contentType().map(MediaType::toString).orElse(XContentType.JSON.mediaType())) .xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, content); return Mono.error(BytesRestResponse.errorFromXContent(errorParser)); } catch (Exception errorParseFailure) { return Mono.error(new ElasticsearchStatusException("Unable to parse response body", RestStatus.fromCode(response.statusCode().value()))); } } } catch (IOException e) { throw new DataAccessResourceFailureException("Error parsing XContent.", e); } }); }

Target:
private <T> Publisher<? extends T> readResponseBody(Request request, ClientResponse response, Class<T> responseType) { if (RawActionResponse.class.equals(responseType)) { return Mono.just(responseType.cast(RawActionResponse.create(response))); } if (response.statusCode().is5xxServerError()) { return handleServerError(request, response); } return response.body(BodyExtractors.toMono(byte[].class)) .map(it -> new String(it, StandardCharsets.UTF_8)) .flatMap(content -> doDecode(response, responseType, content)); }
Source:
public void testSendAndReceive() throws Exception { ChannelRegistry registry = getRegistry(); DirectChannel moduleOutputChannel = new DirectChannel(); QueueChannel moduleInputChannel = new QueueChannel(); QueueChannel tapChannel = new QueueChannel(); registry.createOutbound("foo.0", moduleOutputChannel, false); registry.createInbound("foo.0", moduleInputChannel, ALL, false); registry.tap("tapper", "foo.0", tapChannel); Message<?> message = MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar").build(); boolean tapSuccess = false; boolean retried = false; while (!tapSuccess) { moduleOutputChannel.send(message); Message<?> inbound = moduleInputChannel.receive(5000); assertNotNull(inbound); assertEquals("foo", new String((byte[]) inbound.getPayload())); assertNull(inbound.getHeaders().get(ChannelRegistrySupport.ORIGINAL_CONTENT_TYPE_HEADER)); assertEquals("foo/bar", inbound.getHeaders().get(MessageHeaders.CONTENT_TYPE)); Message<?> tapped = tapChannel.receive(5000); if (tapped == null) { assertFalse("Failed to receive tap after retry", retried); retried = true; continue; } tapSuccess = true; assertEquals("foo", new String((byte[]) tapped.getPayload())); assertNull(tapped.getHeaders().get(ChannelRegistrySupport.ORIGINAL_CONTENT_TYPE_HEADER)); assertEquals("foo/bar", tapped.getHeaders().get(MessageHeaders.CONTENT_TYPE)); } registry.deleteInbound("foo.0"); registry.deleteOutbound("foo.0"); }

Target:
public void testSendAndReceive() throws Exception { ChannelRegistry registry = getRegistry(); DirectChannel moduleOutputChannel = new DirectChannel(); QueueChannel moduleInputChannel = new QueueChannel(); QueueChannel tapChannel = new QueueChannel(); registry.createOutbound("foo.0", moduleOutputChannel, false); registry.createInbound("foo.0", moduleInputChannel, ALL, false); registry.tap("tapper", "foo.0", tapChannel); Message<?> message = MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar").build(); boolean tapSuccess = false; boolean retried = false; while (!tapSuccess) { moduleOutputChannel.send(message); Message<?> inbound = moduleInputChannel.receive(5000); assertNotNull(inbound); assertEquals("foo", inbound.getPayload()); assertNull(inbound.getHeaders().get(ChannelRegistrySupport.ORIGINAL_CONTENT_TYPE_HEADER)); assertEquals("foo/bar", inbound.getHeaders().get(MessageHeaders.CONTENT_TYPE)); Message<?> tapped = tapChannel.receive(5000); if (tapped == null) { assertFalse("Failed to receive tap after retry", retried); retried = true; continue; } tapSuccess = true; assertEquals("foo", tapped.getPayload()); assertNull(tapped.getHeaders().get(ChannelRegistrySupport.ORIGINAL_CONTENT_TYPE_HEADER)); assertEquals("foo/bar", tapped.getHeaders().get(MessageHeaders.CONTENT_TYPE)); } registry.deleteInbound("foo.0"); registry.deleteOutbound("foo.0"); registry.deleteInbound("tapper"); }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == CHOOSE_ACCOUNT_SSO) { importedAccount = null; try { AccountImporter.requestAuthToken(LoginDialogFragment.this, data); } catch (NextcloudFilesAppNotSupportedException e) { UiExceptionManager.showDialogForException(getActivity(), e); } } else if(requestCode == REQUEST_AUTH_TOKEN__SSO) { SingleSignOnAccount singleSignOnAccount = AccountImporter.extractSingleSignOnAccountFromResponse(data, getActivity()); accountAccessGranted(singleSignOnAccount); } } else if (resultCode == RESULT_CANCELED) { if (requestCode == CHOOSE_ACCOUNT_SSO) { Toast.makeText(getActivity(), "Unknown error.. please report!", Toast.LENGTH_LONG).show(); } else if (requestCode == REQUEST_AUTH_TOKEN__SSO) { try { AccountImporter.handleFailedAuthRequest(data); } catch (SSOException e) { UiExceptionManager.showDialogForException(getActivity(), e); } catch (Exception e) { Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } } } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); AccountImporter.onActivityResult(requestCode, resultCode, data, LoginDialogFragment.this, new AccountImporter.IAccountAccessGranted() { @Override public void accountAccessGranted(SingleSignOnAccount account) { mUsernameView.setText(account.username); mPasswordView.setText(""); mOc_root_path_View.setText(account.url); mPasswordContainerView.setVisibility(View.GONE); mImageViewShowPwd.setVisibility(View.GONE); mCbDisableHostnameVerificationView.setVisibility(View.GONE); LoginDialogFragment.getInstance().importedAccount = account; attemptLogin(); } }); }
Source:
public List<SimpleObject> searchNonCoded(UiSessionContext context, UiUtils ui, @SpringBean("emrApiProperties") EmrApiProperties emrApiProperties, @SpringBean("emrConceptService") EmrConceptService emrConceptService, @SpringBean("conceptService") ConceptService conceptService, @RequestParam("term") String query, @RequestParam(value = "start", defaultValue = "0") Integer start, @RequestParam(value = "size", defaultValue = "50") Integer size) throws Exception { List<SimpleObject> ret = search(context, ui, emrApiProperties, emrConceptService, conceptService, query, null, null, start, size); return ret; }

Target:
public List<SimpleObject> searchNonCoded(UiSessionContext context, UiUtils ui, @SpringBean("emrApiProperties") EmrApiProperties emrApiProperties, @SpringBean("emrConceptService") EmrConceptService emrConceptService, @SpringBean("conceptService") ConceptService conceptService, @RequestParam("term") String query, @RequestParam(value = "start", defaultValue = "0") Integer start, @RequestParam(value = "size", defaultValue = "50") Integer size) throws Exception { return search(context, ui, emrApiProperties, emrConceptService, conceptService, query, null, null, start, size); }
Source:
public void testParseFail() { List<JSONPathParser.FieldSpec> fields = new ArrayList<>(); try { final Parser<String, Object> jsonParser = new JSONPathParser(fields, true, null); final Map<String, Object> jsonMap = jsonParser.parse(notJson); } catch (Exception e) { Assert.assertEquals(ParseException.class, e.getClass()); return; } Assert.fail("Invalid JSON did not trigger ParseException."); }

Target:
public void testParseFail() { List<JSONPathParser.FieldSpec> fields = new ArrayList<>(); thrown.expect(ParseException.class); thrown.expectMessage("Unable to parse row [" + notJson + "]"); final Parser<String, Object> jsonParser = new JSONPathParser(fields, true, null); final Map<String, Object> jsonMap = jsonParser.parse(notJson); }
Source:
public Map<String, String> getAllMappingUnderPath(String namespace, String path) { if (!_routingDataMap.containsKey(namespace)) { throw new IllegalArgumentException( "Failed to get all mapping under path: Namespace " + namespace + " is not found!"); } return _routingDataMap.get(namespace).getAllMappingUnderPath(path); }

Target:
public Map<String, String> getAllMappingUnderPath(String namespace, String path) { if (!_routingDataMap.containsKey(namespace)) { throw new NoSuchElementException( "Failed to get all mapping under path: Namespace " + namespace + " is not found!"); } return _routingDataMap.get(namespace).getAllMappingUnderPath(path); }
Source:
private ListenableFuture<Transport> bind0() { InetAddress listenAddress; if (config.getListenAddress() != null && config.getListenInterface() != null) { throw new IllegalArgumentException("Not allowed to set both listenAddress and listenInterface, choose one"); } else if (config.getListenAddress() != null) { try { listenAddress = InetAddress.getByName(config.getListenAddress()); } catch (UnknownHostException e) { throw new IllegalArgumentException("Unknown listenAddress: " + config.getListenAddress()); } if (listenAddress.isAnyLocalAddress()) { throw new IllegalArgumentException( "listenAddress: " + config.getListenAddress() + " cannot be a wildcard address"); } } else if (config.getListenInterface() != null) { listenAddress = getNetworkInterfaceAddress(config.getListenInterface(), config.isPreferIPv6()); } else { listenAddress = Address.getLocalIpAddress(); } incomingMessagesSubject.subscribeOn(Schedulers.from(bootstrapFactory.getWorkerGroup())); int bindPort = config.isPortAutoIncrement() ? AvailablePortFinder.getNextAvailable(config.getPort(), config.getPortCount()) : config.getPort(); address = Address.createLocal(bindPort); ServerBootstrap server = bootstrapFactory.serverBootstrap().childHandler(incomingChannelInitializer); ChannelFuture bindFuture = server.bind(listenAddress, address.port()); final SettableFuture<Transport> result = SettableFuture.create(); final InetAddress finalListenAddress = listenAddress; bindFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { serverChannel = (ServerChannel) channelFuture.channel(); LOGGER.info("Bound to: {}", finalListenAddress); result.set(Transport.this); } else { LOGGER.error("Failed to bind to: {}, cause: {}", finalListenAddress, channelFuture.cause()); result.setException(channelFuture.cause()); } } }); return result; }

Target:
private ListenableFuture<Transport> bind0() { incomingMessagesSubject.subscribeOn(Schedulers.from(bootstrapFactory.getWorkerGroup())); final InetAddress listenAddress = Addressing.getLocalIpAddress(config.getListenAddress(), config.getListenInterface(), config.isPreferIPv6()); int bindPort = config.isPortAutoIncrement() ? Addressing.getNextAvailablePort(listenAddress, config.getPort(), config.getPortCount()) : config.getPort(); address = Address.create(listenAddress.getHostAddress(), bindPort); ServerBootstrap server = bootstrapFactory.serverBootstrap().childHandler(incomingChannelInitializer); ChannelFuture bindFuture = server.bind(listenAddress, address.port()); final SettableFuture<Transport> result = SettableFuture.create(); bindFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { serverChannel = (ServerChannel) channelFuture.channel(); LOGGER.info("Bound to: {}", listenAddress); result.set(Transport.this); } else { LOGGER.error("Failed to bind to: {}, cause: {}", listenAddress, channelFuture.cause()); result.setException(channelFuture.cause()); } } }); return result; }
Source:
public static Tip loadTip(int pId) { assert pId >= 1 && pId <= NUM_TIPS; String tipFileName = String.format(TIP_FILE_PATH_FORMAT, pId); InputStream tipsInputStream = TipLoader.class.getResourceAsStream(tipFileName); InputStreamReader tipsReader = new InputStreamReader(tipsInputStream); JSONTokener jsonTokener = new JSONTokener(tipsReader); JSONObject jsonObject = new JSONObject(jsonTokener); Tip tip = new Tip(pId, jsonObject); return tip; }

Target:
public static Tip loadTip(int pId) { assert pId >= 1 && pId <= NUM_TIPS; String tipFileName = String.format(TIP_FILE_PATH_FORMAT, pId); InputStream tipsInputStream = TipLoader.class.getResourceAsStream(tipFileName); InputStreamReader tipsReader = new InputStreamReader(tipsInputStream, StandardCharsets.UTF_8); JSONTokener jsonTokener = new JSONTokener(tipsReader); JSONObject jsonObject = new JSONObject(jsonTokener); Tip tip = new Tip(pId, jsonObject); return tip; }