auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testConsistentIdConfiguredInJvmProp() throws Exception { String specificConsistentId = "JvmProp consistent id"; System.setProperty(IgniteSystemProperties.IGNITE_CONSISTENT_ID, specificConsistentId); Ignite ignite = startGrid(0); assertEquals(specificConsistentId, ignite.configuration().getConsistentId()); assertEquals(specificConsistentId, ignite.cluster().localNode().consistentId()); <START> info("Consistent id in that case: " + ignite.cluster().localNode().consistentId()); <END> }</code><technical_language>suggestion info("Consistent ID: " + ignite.cluster().localNode().consistentId());</technical_language>

Target:
public void testConsistentIdConfiguredInJvmProp() throws Exception { String specificConsistentId = "JvmProp consistent id"; System.setProperty(IgniteSystemProperties.IGNITE_OVERRIDE_CONSISTENT_ID, specificConsistentId); Ignite ignite = startGrid(0); assertEquals(specificConsistentId, ignite.configuration().getConsistentId()); assertEquals(specificConsistentId, ignite.cluster().localNode().consistentId()); info("Consistent ID: " + ignite.cluster().localNode().consistentId()); }
Source:
<code><START> public Result runMain(JUnitSystem system, String... args) { <END> system.out().println("JUnit version " + Version.id()); List<Class<?>> classes = new ArrayList<Class<?>>(); List<Failure> failures = new ArrayList<Failure>(); FilterFactoryFactory filterFactoryFactory = new FilterFactoryFactory(); for (String each : args) { try { if (each.startsWith("--")) { if (each.startsWith("--filter")) { String filterSpec = each.substring(each.indexOf('=') + 1); Filter filter = filterFactoryFactory.apply(filterSpec); addFilter(filter); } else { system.out().println("JUnit knows nothing about the " + each + " option"); return new Result() { @Override public boolean wasSuccessful() { return false; } }; } } else { classes.add(Class.forName(each)); } } catch (FilterFactory.FilterNotFoundException e) { system.out().println("Could not find filter: " + e.getMessage()); Description description = Description.createSuiteDescription(each); Failure failure = new Failure(description, e); failures.add(failure); } catch (FilterFactoryFactory.FilterFactoryNotFoundException e) { system.out().println("Could not find filter factory: " + e.getMessage()); Description description = Description.createSuiteDescription(each); Failure failure = new Failure(description, e); failures.add(failure); } catch (ClassNotFoundException e) { system.out().println("Could not find class: " + each); Description description = Description.createSuiteDescription(each); Failure failure = new Failure(description, e); failures.add(failure); } } RunListener listener = new TextListener(system); addListener(listener); Result result = run(classes.toArray(new Class<?>[0])); for (Failure each : failures) { result.getFailures().add(each); } return result; }</code><technical_language>making this public</technical_language>

Target:
Result runMain(JUnitSystem system, String... args) { system.out().println("JUnit version " + Version.id()); JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args); RunListener listener = new TextListener(system); addListener(listener); return run(jUnitCommandLineParseResult.createRequest(defaultComputer())); }
Source:
<code>public SymbolResolver getSymbolResolver() { <START> return symbolResolver; <END> }</code><technical_language>nulls please, Optional.ofNullable rescue :-)</technical_language>

Target:
public Optional<SymbolResolver> getSymbolResolver() { return Optional.ofNullable(symbolResolver); }
Source:
<code>public static PurgeConfiguration newDefaultPurgeConfiguration(Configuration config, IdUuidPair idUuidPair, Collection<String> disabledComponentUuids) { <START> Collection<String> qualifiersWithoutHistoricalData = asList(Qualifiers.FILE, Qualifiers.UNIT_TEST_FILE); <END> if (config.getBoolean(PurgeConstants.PROPERTY_CLEAN_DIRECTORY).orElse(false)) { qualifiersWithoutHistoricalData = asList(Qualifiers.DIRECTORY, Qualifiers.FILE, Qualifiers.UNIT_TEST_FILE); } return new PurgeConfiguration(idUuidPair, qualifiersWithoutHistoricalData, config.getInt(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES).get(), config.getInt(PurgeConstants.DAYS_BEFORE_DELETING_INACTIVE_SHORT_LIVING_BRANCHES), System2.INSTANCE, disabledComponentUuids); }</code><technical_language>changes this method rollbacked define scopes scopes qualifiers in default PurgeConfiguration</technical_language>

Target:
public static PurgeConfiguration newDefaultPurgeConfiguration(Configuration config, IdUuidPair idUuidPair, Collection<String> disabledComponentUuids) { Collection<String> scopesWithoutHistoricalData = singletonList(Scopes.FILE); if (config.getBoolean(PurgeConstants.PROPERTY_CLEAN_DIRECTORY).orElse(false)) { scopesWithoutHistoricalData = asList(Scopes.FILE, Scopes.DIRECTORY); } return new PurgeConfiguration(idUuidPair, scopesWithoutHistoricalData, config.getInt(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES).get(), config.getInt(PurgeConstants.DAYS_BEFORE_DELETING_INACTIVE_SHORT_LIVING_BRANCHES), System2.INSTANCE, disabledComponentUuids); }
Source:
<code>public void list(FluoConfiguration config) { try (CuratorFramework curator = CuratorUtil.newFluoCurator(config)) { curator.start(); try { List<String> children = curator.getChildren().forPath("/"); if (children.isEmpty()) { System.out.println("Fluo instance (" + config.getInstanceZookeepers() + ") does not " + " contain any applications"); } else { System.out.println("Fluo instance (" + config.getInstanceZookeepers() + ") contains " + children.size() + " applications\n"); System.out.println("Application Status"); System.out.println("----------- ------"); for (String path : children) { System.out.format("%-20s", path); FluoConfiguration appConfig = new FluoConfiguration(config); appConfig.setApplicationName(path); if (!twillIdExists(appConfig)) { <START> System.out.println("STOPPED"); <END> } else { String twillId = getTwillId(appConfig); TwillController controller = getTwillRunner(appConfig).lookup( getYarnApplicationName(appConfig.getApplicationName()), RunIds.fromString(twillId)); if (controller == null) { System.out.println("STOPPED"); } else { System.out.println(controller.state()); } } } } } catch (Exception e) { throw new FluoException(e); } } }</code><technical_language>places STOPPED is printed, of UNKNOWN</technical_language>

Target:
public void list(FluoConfiguration config) { try (CuratorFramework curator = CuratorUtil.newFluoCurator(config)) { curator.start(); try { if (curator.checkExists().forPath("/") == null) { System.out.println("Fluo instance (" + config.getInstanceZookeepers() + ") has not been " + "created yet in Zookeeper. It will be created when the first Fluo application is " + "initialized for this instance."); return; } List<String> children = curator.getChildren().forPath("/"); if (children.isEmpty()) { System.out.println("Fluo instance (" + config.getInstanceZookeepers() + ") does not " + "contain any Fluo applications."); return; } Collections.sort(children); System.out.println("Fluo instance (" + config.getInstanceZookeepers() + ") contains " + children.size() + " application(s)\n"); System.out.println("Application Status YarnAppName YarnAppId"); System.out.println("----------- ------ ----------- ---------"); for (String path : children) { FluoConfiguration appConfig = new FluoConfiguration(config); appConfig.setApplicationName(path); String state = "INITIALIZED"; String yarnId = "not started yet"; String yarnAppName = getYarnApplicationName(path); if (twillIdExists(appConfig)) { String twillId = getTwillId(appConfig); yarnId = getAppId(appConfig); TwillController controller = getTwillRunner(appConfig).lookup( getYarnApplicationName(appConfig.getApplicationName()), RunIds.fromString(twillId)); if (controller == null) { state = "STOPPED"; } else { state = controller.state().toString(); } } System.out.format("%-15s %-11s %-20s %s\n", path, state, yarnAppName, yarnId); } } catch (Exception e) { throw new FluoException(e); } } }
Source:
<code>public void handle(Willie bot, Channel channel, User sender, String[] args) { if (args.length == 0) { channel.sendMessage(Colors.RED + "Please specify a subreddit!"); } else { <START> if (!args[0].matches("^[a-zA-Z0-9]*$")) { <END> channel.sendMessage(Colors.RED + "Only subreddits with letters and numbers are valid!"); } else { channel.sendMessage(Colors.BOLD + "<LINK_1>" + args[0]); } } }</code><technical_language>This regex is incorrect. [correct regex](<LINK_0> ^[A-Za-z0-9][A-Za-z0-9_]{2,20}$</technical_language>

Target:
public void handle(Willie bot, Channel channel, User sender, String[] args) { if (args.length == 0) { channel.sendMessage(Colors.RED + "Please specify a subreddit!"); } else { if (!args[0].matches("^[A-Za-z0-9][A-Za-z0-9_]{2,20}$")) { channel.sendMessage(Colors.RED + "Only subreddits with letters and numbers are valid!"); } else { channel.sendMessage(Colors.BOLD + "<LINK_1>" + args[0]); } } }
Source:
<code>public void sendMessage(String message) { <START> buffer.append(message); <END> }</code><technical_language>I suitable if some kind of padding is applied messages, a newline</technical_language>

Target:
public void sendMessage(String message) { buffer.append(message).append("\n"); }
Source:
<code>public List<Double> execute() throws XMLStreamException, IOException, MSDKException { List<Double> mzValuesResult = new ArrayList<Double>(); createTempFeatureXMLFile(); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileReader(FEATURE_XML_FILE)); while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startElement = xmlEvent.asStartElement(); if (startElement.getName().getLocalPart().equals("position")) { xmlEvent = xmlEventReader.nextEvent(); Attribute idAttr = startElement.getAttributeByName(new QName("dim")); if (idAttr.getValue().equals("1")) { Characters characters = xmlEvent.asCharacters(); <START> mzValuesResult.add(Double.valueOf(characters.getData())); <END> } } } } return mzValuesResult; }</code><technical_language>This part needs some exception handling - if text contains parsed a Double</technical_language>

Target:
public List<Double> execute() throws XMLStreamException, IOException, MSDKException { List<Double> mzValuesResult = new ArrayList<Double>(); createTempFeatureXMLFile(); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileReader(FEATURE_XML_FILE)); while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startElement = xmlEvent.asStartElement(); if (startElement.getName().getLocalPart().equals("position") && xmlEventReader.hasNext()) { xmlEvent = xmlEventReader.nextEvent(); Attribute idAttr = startElement.getAttributeByName(new QName("dim")); if (idAttr.getValue().equals("1")) { Characters characters = xmlEvent.asCharacters(); try { mzValuesResult.add(Double.valueOf(characters.getData())); } catch (NumberFormatException e) { throw new MSDKException("The featureXML contains an invalid m/z value.\n" + e.getMessage()); } } } } } return mzValuesResult; }
Source:
<code>private void assignUniquePrefix(final Waypoint waypoint) { final Set<String> assignedPrefixes = new HashSet<>(); for (final Waypoint wp : waypoints) { assignedPrefixes.add(wp.getPrefix()); } int a = 0; int b = 6; <START> while (a < WP_PREFIX_CHARS.length()) { <END> a++; while (b < WP_PREFIX_CHARS.length()) { b++; final String prefixCandidate = "" + WP_PREFIX_CHARS.charAt(a) + WP_PREFIX_CHARS.charAt(b); if (!assignedPrefixes.contains(prefixCandidate)) { waypoint.setPrefix(prefixCandidate); return; } } b = 0; } throw new IllegalStateException("too many waypoints, unable to assign unique prefix"); }</code><technical_language>I prefer style of original loop. Rough idea: final int length = WP_PREFIX_CHARS.length(); for (int i = OWN_WP_PREFIX_OFFSET; i < length * length; i++) { final int a = i / length; final int b = i % length; ..</technical_language>

Target:
private void assignUniquePrefix(final Waypoint waypoint) { final Set<String> assignedPrefixes = new HashSet<>(); for (final Waypoint wp : waypoints) { assignedPrefixes.add(wp.getPrefix()); } final int length = WP_PREFIX_CHARS.length(); for (int i = 0; i < length * length; i++) { final String prefixCandidate = "" + WP_PREFIX_CHARS.charAt(i / length) + WP_PREFIX_CHARS.charAt(i % length); if (!assignedPrefixes.contains(prefixCandidate)) { waypoint.setPrefix(prefixCandidate); return; } } throw new IllegalStateException("too many waypoints, unable to assign unique prefix"); }
Source:
<code>public Object getValue(ELContext ctx, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (ctx == null) { throw new NullPointerException(); } Integer numOfKids; Path path; if (base == null) { numOfKids = (Integer) ctx.getContext(AstIdentifier.class); path = new Path(); } else { numOfKids = (!_numOfKids.isEmpty()) ? _numOfKids.removeFirst() : null; <START> path = (!_paths.isEmpty()) ? _paths.removeFirst() : new Path(); <END> } if (numOfKids != null) { int nums = numOfKids.intValue() - 1; numOfKids = new Integer(nums); ctx.putContext(Integer.class, numOfKids); path.add(toNodeString(ctx), Objects.toString(property)); ctx.putContext(Path.class, path); if (nums > 0) { _numOfKids.addFirst(numOfKids); _paths.addFirst(path); } } return null; }</code><technical_language>Unnecessary parenthesis, !XXX ? A : B</technical_language>

Target:
public Object getValue(ELContext ctx, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (ctx == null) { throw new NullPointerException(); } Integer numOfKids; Path path; if (base == null) { numOfKids = (Integer) ctx.getContext(AstIdentifier.class); path = new Path(); } else { numOfKids = !_numOfKids.isEmpty() ? _numOfKids.removeFirst() : null; path = !_paths.isEmpty() ? _paths.removeFirst() : new Path(); } if (numOfKids != null) { int nums = numOfKids.intValue() - 1; numOfKids = new Integer(nums); ctx.putContext(Integer.class, numOfKids); path.add(toNodeString(ctx), Objects.toString(property)); ctx.putContext(Path.class, path); if (nums > 0) { _numOfKids.addFirst(numOfKids); _paths.addFirst(path); } } return null; }
Source:
<code>public void clientCallback(ClientResponse clientResponse) throws Exception { if (clientResponse.getStatus() == ClientResponse.SUCCESS) { try { synchronized (Distributer.this) { VoltTable results[] = clientResponse.getResults(); if (results != null && results.length > 0) { updatePartitioning(results[0]); } } } catch (Exception e) { <START> e.printStackTrace(); <END> } } if (m_latch != null) { m_latch.countDown(); } }</code><technical_language>want handle errors printing stacks stderr. want update internal state, return errors people try run partition procs. want retry, I happen</technical_language>

Target:
public void clientCallback(ClientResponse clientResponse) throws Exception { if (clientResponse.getStatus() == ClientResponse.SUCCESS) { VoltTable results[] = clientResponse.getResults(); if (results != null && results.length > 0) { updatePartitioning(results[0]); } } m_partitionUpdateStatus.set(clientResponse); if (m_latch != null) { m_latch.countDown(); } }
Source:
<code>public final boolean isReadOnly() { <START> return this.isReadOnly; <END> }</code><technical_language>isReadOnly field is removed, change this method return this.cache.isReadOnly();</technical_language>

Target:
public final boolean isReadOnly() { return cache().isReadOnly(); }
Source:
<code>public void removeSelectionListener(SelectionListener listener) { if <START> (this.dropdownTableViewer != <END> null && !this.dropdownTable.isDisposed()) this.dropdownTable.removeSelectionListener(listener); }</code><technical_language>a check for viewer here? this dropdownTable? table</technical_language>

Target:
public void removeSelectionListener(SelectionListener listener) { if (this.dropdownTable != null && !this.dropdownTable.isDisposed()) this.dropdownTable.removeSelectionListener(listener); }
Source:
<code>public void removeMessagesFromGroup(Object groupId, Collection<Message<?>> messages) { Assert.notNull(groupId, "'groupId' must not be null"); Assert.notNull(messages, "'messages' must not be null"); Object mgm = this.doRetrieve(MESSAGE_GROUP_KEY_PREFIX + groupId); if (mgm != null) { Assert.isInstanceOf(MessageGroupMetadata.class, mgm); MessageGroupMetadata messageGroupMetadata = (MessageGroupMetadata) mgm; messageGroupMetadata.setLastModified(System.currentTimeMillis()); for (Message<?> messageToRemove : messages) { this.removeMessage(messageToRemove.getHeaders().getId()); } MessageGroup messageGroup = this.getSimpleMessageGroup(this.getMessageGroup(groupId)); <START> this.doStore(MESSAGE_GROUP_KEY_PREFIX + groupId, new MessageGroupMetadata(messageGroup)); <END> } }</code><technical_language>This lines do proper. other side update MessageGroupMetadata in persistence store. For like: java Assert.isInstanceOf(MessageGroupMetadata.class, mgm); MessageGroupMetadata messageGroupMetadata = (MessageGroupMetadata) mgm; ... UUID messageId = messageToRemove.getHeaders().getId(); ... messageGroupMetadata.remove(messageId); .... doStore(MESSAGE_GROUP_KEY_PREFIX + groupId, messageGroupMetadata);</technical_language>

Target:
public void removeMessagesFromGroup(Object groupId, Collection<Message<?>> messages) { Assert.notNull(groupId, "'groupId' must not be null"); Assert.notNull(messages, "'messages' must not be null"); Object mgm = doRetrieve(MESSAGE_GROUP_KEY_PREFIX + groupId); if (mgm != null) { Assert.isInstanceOf(MessageGroupMetadata.class, mgm); MessageGroupMetadata messageGroupMetadata = (MessageGroupMetadata) mgm; for (Message<?> messageToRemove : messages) { UUID messageId = messageToRemove.getHeaders().getId(); messageGroupMetadata.remove(messageId); doRemove(MESSAGE_KEY_PREFIX + messageId); } messageGroupMetadata.setLastModified(System.currentTimeMillis()); doStore(MESSAGE_GROUP_KEY_PREFIX + groupId, messageGroupMetadata); } }
Source:
<code>Mono<Response<Key>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { <START> Objects.requireNonNull(keyProperties, "The key input parameter cannot be null."); <END> KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyOps(Arrays.asList(keyOperations)) .setKeyAttributes(new KeyRequestAttributes(keyProperties)); return service.updateKey(endpoint, keyProperties.getName(), keyProperties.getVersion(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); }</code><technical_language>key properties parameter null</technical_language>

Target:
Mono<Response<Key>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null."); KeyRequestParameters parameters = new KeyRequestParameters() .setTags(keyProperties.getTags()) .setKeyAttributes(new KeyRequestAttributes(keyProperties)); if (keyOperations.length > 0) { parameters.setKeyOps(Arrays.asList(keyOperations)); } return service.updateKey(endpoint, keyProperties.getName(), keyProperties.getVersion(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context) .doOnRequest(ignored -> logger.info("Updating key - {}", keyProperties.getName())) .doOnSuccess(response -> logger.info("Updated key - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error)); }
Source:
<code>public boolean doSupportKerberizedKafka() { return false; <START> } <END></code><technical_language>need override this, Spark 2.x distributions support kafka kerberos of returned this method</technical_language>

Target:
public boolean doSupportKerberizedKafka() { return true; }
Source:
<code>private CommandResult<RuleViolation> checkBounds(final GraphCommandExecutionContext context) { final Element<? extends View<?>> element = getNodeNotNull(context); final Graph<DefinitionSet, Node> graph = (Graph<DefinitionSet, Node>) getGraph(context); final BoundsImpl newBounds = getTargetBounds(element); final GraphCommandResultBuilder result = new GraphCommandResultBuilder(); <START> if (parentConstrained) { <END> if (!GraphUtils.isRootNode(element, graph)) { final Bounds parentBounds = getParentBounds(element, graph); if (GraphUtils.checkBoundsExceeded(parentBounds, newBounds)) { ((View) element.getContent()).setBounds(newBounds); } else { result.addViolation(new BoundsExceededViolation(parentBounds) .setUUID(element.getUUID())); } } } else { if (GraphUtils.checkBoundsExceeded(graph, newBounds)) { ((View) element.getContent()).setBounds(newBounds); } else { final Bounds graphBounds = graph.getContent().getBounds(); result.addViolation(new BoundsExceededViolation(graphBounds) .setUUID(element.getUUID())); } } return result.build(); }</code><technical_language>in general if sentences a bit confusing look, I duplicated code in if/else clauses... this improved more clear easy maintain. if removing parentConstrained flag (as consider true always), simplify this..</technical_language>

Target:
private CommandResult<RuleViolation> checkBounds(final GraphCommandExecutionContext context) { final Element<? extends View<?>> element = getNodeNotNull(context); final Graph<DefinitionSet, Node> graph = (Graph<DefinitionSet, Node>) getGraph(context); final BoundsImpl newBounds = getTargetBounds(element); final GraphCommandResultBuilder result = new GraphCommandResultBuilder(); final Bounds parentBounds = getParentBounds(element, graph); if (GraphUtils.checkBoundsExceeded(parentBounds, newBounds)) { ((View) element.getContent()).setBounds(newBounds); } else { result.addViolation(new BoundsExceededViolation(parentBounds) .setUUID(element.getUUID())); } return result.build(); }
Source:
<code>private String resolveGroupDN(String searchFilter, String role, LDAPRoleContext context) throws UserStoreException { String roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(role)); <START> String membershipAttribute = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); <END> String[] returningAttributes = new String[]{membershipAttribute}; String searchBase = context.getSearchBase(); DirContext mainDirContext = this.connectionSource.getContext(); try { NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup; String groupDN = null; if (groupResults.hasMore()) { resultedGroup = groupResults.next(); groupDN = resultedGroup.getName(); } return groupDN; } catch (NamingException e) { String errorMessage = "Error while resolving the GroupDN."; throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeContext(mainDirContext); } }</code><technical_language>returning MEMBERSHIP_ATTRIBUTE attribute? If not, do request it</technical_language>

Target:
private String resolveGroupDN(String searchFilter, String role, LDAPRoleContext context) throws UserStoreException { String roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(role)); String[] returningAttributes = new String[]{}; String searchBase = context.getSearchBase(); DirContext mainDirContext = this.connectionSource.getContext(); try { NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup; String groupDN = null; if (groupResults.hasMore()) { resultedGroup = groupResults.next(); groupDN = resultedGroup.getName(); } return groupDN; } catch (NamingException e) { String errorMessage = "Error while resolving the GroupDN."; throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeContext(mainDirContext); } }
Source:
<code>private String createTempFile() throws IOException, IllegalStateException { <START> String tempFile = System.getProperty("java.io.tmpdir") + "/test_file.txt"; <END> FileWriter writer = new FileWriter(tempFile); writer.write("Lorem ipsum dolor sit amet ..."); writer.flush(); writer.close(); tempFiles.add(tempFile); return tempFile; }</code><technical_language>is API create temp file - File.createTempFile(...);</technical_language>

Target:
private File createTempFile() throws IOException, IllegalStateException { File tempFile = File.createTempFile("test", null); FileWriter writer = new FileWriter(tempFile); writer.write("Lorem ipsum dolor sit amet ..."); writer.flush(); writer.close(); tempFiles.add(tempFile); return tempFile; }
Source:
<code>private void assertGetResult(StorageDomain result) { assertNotNull(result); assertEquals(existingDomain, result); assertEquals("Wrong committed disk size", 8, result.getCommittedDiskSize()); assertEquals("Wrong actual disk size", 4, result.getActualImagesSize()); assertEquals("Wrong first metadata device", FixturesTool.LUN_ID_OF_DOMAIN_METADATA, result.getFirstMetadataDevice()); assertEquals("Wrong vg metadata device", FixturesTool.LUN_ID_OF_DOMAIN_VG_METADATA, result.getVgMetadataDevice()); assertEquals("Wrong shared status", StorageDomainSharedStatus.Active, result.getStorageDomainSharedStatus()); <START> assertEquals("Wrong backup flag status", true, result.isBackup()); <END> }</code><technical_language>backup flag of result false for 72e3a666-89e1-4005-a7ca-f7548004a9ab</technical_language>

Target:
private void assertGetResult(StorageDomain result) { assertNotNull(result); assertEquals(existingDomain, result); assertEquals("Wrong committed disk size", 8, result.getCommittedDiskSize()); assertEquals("Wrong actual disk size", 4, result.getActualImagesSize()); assertEquals("Wrong first metadata device", FixturesTool.LUN_ID_OF_DOMAIN_METADATA, result.getFirstMetadataDevice()); assertEquals("Wrong vg metadata device", FixturesTool.LUN_ID_OF_DOMAIN_VG_METADATA, result.getVgMetadataDevice()); assertEquals("Wrong shared status", StorageDomainSharedStatus.Active, result.getStorageDomainSharedStatus()); assertEquals("Wrong backup flag status", false, result.isBackup()); }
Source:
<code>public boolean validateOptions(Map<String,String> options) { if (options.containsKey(ALL_OPTION)) { try { combineAllColumns = Boolean.parseBoolean(options.get(ALL_OPTION)); } catch (Exception e) { throw new IllegalArgumentException("bad boolean " + ALL_OPTION + ":" + options.get(ALL_OPTION)); } if (combineAllColumns) return true; } if (!options.containsKey(COLUMNS_OPTION)) throw new IllegalArgumentException("options must include " + ALL_OPTION + " or " + COLUMNS_OPTION); String encodedColumns = options.get(COLUMNS_OPTION); if (encodedColumns.length() == 0) throw new IllegalArgumentException("empty columns specified in option " + COLUMNS_OPTION); for (String columns : Splitter.on(",").split(encodedColumns)) { if (!ColumnSet.isValidEncoding(columns)) throw new IllegalArgumentException("invalid column encoding " + encodedColumns); } if (options.containsKey(DELETE_HANDLING_ACTION_OPTION)) { <START> DeleteHandlingAction.valueOf(options.get(DELETE_HANDLING_ACTION_OPTION)); <END> } return true; }</code><technical_language>suggestion a meaningful error message here</technical_language>

Target:
public boolean validateOptions(Map<String,String> options) { if (options.containsKey(ALL_OPTION)) { try { combineAllColumns = Boolean.parseBoolean(options.get(ALL_OPTION)); } catch (Exception e) { throw new IllegalArgumentException("bad boolean " + ALL_OPTION + ":" + options.get(ALL_OPTION)); } if (combineAllColumns) return true; } if (!options.containsKey(COLUMNS_OPTION)) throw new IllegalArgumentException("options must include " + ALL_OPTION + " or " + COLUMNS_OPTION); String encodedColumns = options.get(COLUMNS_OPTION); if (encodedColumns.length() == 0) throw new IllegalArgumentException("empty columns specified in option " + COLUMNS_OPTION); for (String columns : Splitter.on(",").split(encodedColumns)) { if (!ColumnSet.isValidEncoding(columns)) throw new IllegalArgumentException("invalid column encoding " + encodedColumns); } return true; }
Source:
<code>protected void writeProperty(JsonGenerator jg, Property prop) throws IOException { if (prop.isScalar()) { writeScalarProperty(jg, prop); } else if (prop.isList()) { <START> writeListProperty(jg, prop); <END> } else if (prop.isComplex()) { writeComplexProperty(jg, prop); } else if (prop instanceof BlobProperty) { writeBlobProperty(jg, prop); } else if (prop.isPhantom()) { jg.writeNull(); } }</code><technical_language>a BlobProperty is a complex property, this check prop.isComplex(). In local tests I a NuxeoException access a member of a null object: mime-type write a blob property, treated a complex</technical_language>

Target:
protected void writeProperty(JsonGenerator jg, Property prop) throws IOException { if (prop.isScalar()) { writeScalarProperty(jg, prop); } else if (prop.isList()) { writeListProperty(jg, prop); } else if (prop instanceof BlobProperty) { writeBlobProperty(jg, prop); } else if (prop.isComplex()) { writeComplexProperty(jg, prop); } else if (prop.isPhantom()) { jg.writeNull(); } }
Source:
<code>public void endVisit(CastExpression x, BlockScope scope) { try { SourceInfo info = makeSourceInfo(x); JExpression expression = pop(x.expression); JMultiCastOperation multiCastOp = null; if (x.resolvedType instanceof IntersectionTypeBinding18) { multiCastOp = new JMultiCastOperation(info, expression, getTypeMap().getBounds((IntersectionTypeBinding18) x.resolvedType)); } else { <START> multiCastOp = new JMultiCastOperation(info, expression, getTypeMap().get(x.resolvedType)); <END> } push(multiCastOp); } catch (JTypeLookupException e) { throw translateException(x, e); } catch (RuntimeException e) { throw translateException(x, e); } }</code><technical_language>single cast here</technical_language>

Target:
public void endVisit(CastExpression x, BlockScope scope) { try { SourceInfo info = makeSourceInfo(x); JExpression expression = pop(x.expression); JDynamicCastOperation castOp = null; if (x.resolvedType instanceof IntersectionTypeBinding18) { castOp = new JDynamicCastOperation(info, expression, getTypeMap().getBounds((IntersectionTypeBinding18) x.resolvedType)); } else { castOp = new JDynamicCastOperation(info, expression, getTypeMap().get(x.resolvedType)); } push(castOp); } catch (JTypeLookupException e) { throw translateException(x, e); } catch (RuntimeException e) { throw translateException(x, e); } }
Source:
<code>public void populate() { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { Resource[] bootstrap3Themes = resolver.getResources(LOCAL_CSS_BOOTSTRAP_3_THEME_LOCATION); Resource[] bootstrap4Themes = resolver.getResources(LOCAL_CSS_BOOTSTRAP_4_THEME_LOCATION); List<Resource> newThemes = Arrays.stream(bootstrap3Themes) .filter( theme -> dataService.getRepository(STYLE_SHEET).findOneById(theme.getFilename()) == null) .collect(Collectors.toList()); <START> newThemes.forEach(nt -> addNewTheme(nt, bootstrap4Themes)); <END> } catch (IOException e) { LOG.error("error populating bootstrap themes", e); } }</code><technical_language>I if populating theme X fails IOException, this throw runtime error stop. catch StyleException, log continue other styles. Is this intentional</technical_language>

Target:
public void populate() { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { Resource[] bootstrap3Themes = resolver.getResources(LOCAL_CSS_BOOTSTRAP_3_THEME_LOCATION); Resource[] bootstrap4Themes = resolver.getResources(LOCAL_CSS_BOOTSTRAP_4_THEME_LOCATION); List<Resource> newThemes = Arrays.stream(bootstrap3Themes) .filter( theme -> dataService.getRepository(STYLE_SHEET).findOneById(theme.getFilename()) == null) .collect(Collectors.toList()); newThemes.forEach(nt -> addNewTheme(nt, bootstrap4Themes)); } catch (Exception e) { LOG.error("error populating bootstrap themes", e); } }
Source:
<code>public synchronized void start() throws Exception { super.start(); addShutdownHook(new Thread(new Runnable() { @Override public void run() { try { final ProcessBuilder processBuilder = new ProcessBuilder(configuration.generateStopCommand()); processBuilder.inheritIO(); final Process p = processBuilder.start(); p.waitFor(); } catch (Exception e) { <START> throw new IllegalStateException("Fuse container was not stopped", e); <END> } } })); }</code><technical_language>Fuse container</technical_language>

Target:
public synchronized void start() throws Exception { super.start(); addShutdownHook(new Thread(new Runnable() { @Override public void run() { try { final ProcessBuilder processBuilder = new ProcessBuilder(configuration.generateStopCommand()); processBuilder.inheritIO(); final Process p = processBuilder.start(); p.waitFor(); } catch (Exception e) { throw new IllegalStateException("Tomcat container was not stopped", e); } } })); }
Source:
<code>private Guid createTemplate() { VmTemplate blankTemplate = DbFacade.getInstance().getVmTemplateDao().get(VmTemplateHandler.BLANK_VM_TEMPLATE_ID); <START> VmStatic masterVm = new VmStatic(blankTemplate); <END> DiskImage templateDiskImage = getEnclosingCommand().getParameters().getDiskImage(); String vmTemplateName = "GlanceTemplate-" + Guid.newGuid().toString().substring(0, 7); AddVmTemplateParameters parameters = new AddVmTemplateParameters(masterVm, vmTemplateName, templateDiskImage.getDiskDescription()); if (getEnclosingCommand().getParameters().getClusterId() != null) { masterVm.setVdsGroupId(getEnclosingCommand().getParameters().getClusterId()); } VdcReturnValueBase addVmTemplateReturnValue = Backend.getInstance().runInternalAction(VdcActionType.AddVmTemplate, parameters, ExecutionHandler.createDefaultContexForTasks(getEnclosingCommand().getExecutionContext())); return addVmTemplateReturnValue.getActionReturnValue() != null ? (Guid) addVmTemplateReturnValue.getActionReturnValue() : null; }</code><technical_language>Creating VMs templates in architecture-aware code requires OS display protocol set automatically selected command creates them. a "add(VM vm)" method in BackendVmsResource class example of this</technical_language>

Target:
private Guid createTemplate() { VmTemplate blankTemplate = DbFacade.getInstance().getVmTemplateDao().get(VmTemplateHandler.BLANK_VM_TEMPLATE_ID); VmStatic masterVm = new VmStatic(blankTemplate); OsRepository osRepository = SimpleDependecyInjector.getInstance().get(OsRepository.class); DiskImage templateDiskImage = getEnclosingCommand().getParameters().getDiskImage(); String vmTemplateName = "GlanceTemplate-" + Guid.newGuid().toString().substring(0, 7); AddVmTemplateParameters parameters = new AddVmTemplateParameters(masterVm, vmTemplateName, templateDiskImage.getDiskDescription()); if (getEnclosingCommand().getParameters().getClusterId() != null) { masterVm.setVdsGroupId(getEnclosingCommand().getParameters().getClusterId()); VDSGroup vdsGroup = getVdsGroup(masterVm.getVdsGroupId()); masterVm.setOsId(osRepository.getDefaultOSes().get(vdsGroup.getArchitecture())); DisplayType defaultDisplayType = osRepository.getDisplayTypes(masterVm.getOsId(), vdsGroup.getcompatibility_version()).get(0); masterVm.setDefaultDisplayType(defaultDisplayType); } VdcReturnValueBase addVmTemplateReturnValue = Backend.getInstance().runInternalAction(VdcActionType.AddVmTemplate, parameters, ExecutionHandler.createDefaultContexForTasks(getEnclosingCommand().getExecutionContext())); return addVmTemplateReturnValue.getActionReturnValue() != null ? (Guid) addVmTemplateReturnValue.getActionReturnValue() : null; }
Source:
<code>public CompletableFuture<Void> deleteSnapshot(String snapshotName) { return CompletableFuture.supplyAsync(() -> { String btSnapshotName = null; try { btSnapshotName = getClusterName().toSnapshotName(snapshotName); } catch (IOException e) { <START> FutureUtils.failedFuture(e); <END> } DeleteSnapshotRequest request = DeleteSnapshotRequest.newBuilder() .setName(btSnapshotName) .build(); return request; }).thenCompose( d -> FutureUtils.toCompletableFuture( bigtableTableAdminClient.deleteSnapshotAsync(d)).thenApply(r -> null)); }</code><technical_language>I if return FutureUtils.failedFuture(e) do supplyAsync</technical_language>

Target:
public CompletableFuture<Void> deleteSnapshot(String snapshotName) { return CompletableFuture.supplyAsync(() -> { try { return DeleteSnapshotRequest.newBuilder() .setName(getClusterName().toSnapshotName(snapshotName)) .build(); } catch (IOException e) { throw new CompletionException(e); } }).thenCompose( d -> bigtableTableAdminClient.deleteSnapshotAsync(d).thenApply(r -> null)); }
Source:
<code>public EndpointRegistry getEndpointRegistryByUUID(String regsitryId) throws APIManagementException { String query = SQLConstants.GET_ENDPOINT_REGISTRY_BY_UUID; <START> EndpointRegistry endpointRegistry = new EndpointRegistry(); <END> try (Connection connection = APIMgtDBUtil.getConnection(); PreparedStatement ps = connection.prepareStatement(query)) { ps.setString(1, regsitryId); ps.executeQuery(); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { endpointRegistry.setUuid(rs.getString("UUID")); endpointRegistry.setName(rs.getString("REG_NAME")); endpointRegistry.setType(rs.getString("REG_TYPE")); endpointRegistry.setMode(rs.getString("MODE")); endpointRegistry.setOwner(rs.getString("REG_OWNER")); } } } catch (SQLException e) { handleException("Error while retrieving details of endpoint registry with Id: " + regsitryId, e); } return endpointRegistry; }</code><technical_language>instantiation of EndpointRegistry **if (rs.next()) {** block ? return null</technical_language>

Target:
public EndpointRegistryInfo getEndpointRegistryByUUID(String regsitryId) throws APIManagementException { String query = SQLConstants.GET_ENDPOINT_REGISTRY_BY_UUID; try (Connection connection = APIMgtDBUtil.getConnection(); PreparedStatement ps = connection.prepareStatement(query)) { ps.setString(1, regsitryId); ps.executeQuery(); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { EndpointRegistryInfo endpointRegistry = new EndpointRegistryInfo(); endpointRegistry.setUuid(rs.getString("UUID")); endpointRegistry.setName(rs.getString("REG_NAME")); endpointRegistry.setType(rs.getString("REG_TYPE")); endpointRegistry.setMode(rs.getString("MODE")); endpointRegistry.setOwner(rs.getString("REG_OWNER")); return endpointRegistry; } } } catch (SQLException e) { handleException("Error while retrieving details of endpoint registry with Id: " + regsitryId, e); } return null; }
Source:
<code>public static List<? extends SqlFunction> extractFunctions(Class<?> clazz) { if (WindowFunction.class.isAssignableFrom(clazz)) { @SuppressWarnings("unchecked") Class<? extends WindowFunction> windowClazz = (Class<? extends WindowFunction>) clazz; return WindowAnnotationsParser.parseFunctionDefinition(windowClazz); } if (clazz.isAnnotationPresent(AggregationFunction.class)) { return SqlAggregationFunction.createFunctionsByAnnotations(clazz); } if (clazz.isAnnotationPresent(ScalarFunction.class) || clazz.isAnnotationPresent(ScalarOperator.class)) { return ScalarFromAnnotationsParser.parseFunctionDefinition(clazz); } <START> if (clazz.isAnnotationPresent(SqlInvokedScalarFunctions.class)) { <END> return SqlInvokedScalarFromAnnotationsParser.parseFunctionDefinitions(clazz); } if (clazz.isAnnotationPresent(SqlInvokedScalarFunction.class)) { return SqlInvokedScalarFromAnnotationsParser.parseFunctionDefinition(clazz); } return ScalarFromAnnotationsParser.parseFunctionDefinitions(clazz); }</code><technical_language>combine two? I point a annotation for multiple functions single function. @ScalarFunction annotate class method. confusing user hard notice difference of (so easily wrong one)</technical_language>

Target:
public static List<? extends SqlFunction> extractFunctions(Class<?> clazz) { if (WindowFunction.class.isAssignableFrom(clazz)) { @SuppressWarnings("unchecked") Class<? extends WindowFunction> windowClazz = (Class<? extends WindowFunction>) clazz; return WindowAnnotationsParser.parseFunctionDefinition(windowClazz); } if (clazz.isAnnotationPresent(AggregationFunction.class)) { return SqlAggregationFunction.createFunctionsByAnnotations(clazz); } if (clazz.isAnnotationPresent(ScalarFunction.class) || clazz.isAnnotationPresent(ScalarOperator.class)) { return ScalarFromAnnotationsParser.parseFunctionDefinition(clazz); } if (clazz.isAnnotationPresent(SqlInvokedScalarFunction.class)) { return SqlInvokedScalarFromAnnotationsParser.parseFunctionDefinition(clazz); } List<SqlFunction> scalarFunctions = ImmutableList.<SqlFunction>builder() .addAll(ScalarFromAnnotationsParser.parseFunctionDefinitions(clazz)) .addAll(SqlInvokedScalarFromAnnotationsParser.parseFunctionDefinitions(clazz)) .build(); checkArgument(!scalarFunctions.isEmpty(), "Class [%s] does not define any scalar functions", clazz.getName()); return scalarFunctions; }
Source:
<code>public void updateTopic(TopicName topicName, PatchData patch) { Topic beforeUpdate = endpoints.topic().get(topicName.qualifiedName()); Topic reference = Patch.apply(beforeUpdate, patch); ofNullable(reference.getMessageSchema()).ifPresent(s -> assertThat(endpoints.schema().save(reference.getQualifiedName(), false, s).getStatus()).isEqualTo(CREATED.getStatusCode())); Response r = endpoints.topic().update(topicName.qualifiedName(), patch); <START> System.out.println("---------------------"); <END> System.out.println(r.readEntity(String.class)); System.out.println("---------------------"); assertThat(r.getStatus()).isEqualTo(OK.getStatusCode()); wait.untilTopicUpdated(reference); }</code><technical_language>I need this :-) empty lines either</technical_language>

Target:
public void updateTopic(TopicName topicName, PatchData patch) { Topic beforeUpdate = endpoints.topic().get(topicName.qualifiedName()); Topic reference = Patch.apply(beforeUpdate, patch); ofNullable(reference.getMessageSchema()).ifPresent(s -> assertThat(endpoints.schema().save(reference.getQualifiedName(), false, s).getStatus()).isEqualTo(CREATED.getStatusCode())); assertThat(endpoints.topic().update(topicName.qualifiedName(), patch).getStatus()).isEqualTo(OK.getStatusCode()); wait.untilTopicUpdated(reference); }
Source:
<code>public void returnsCorrectInputWithStream() throws Exception { final byte[] bytes = new Utf8String("Stream returnsCorrectInput!").asBytes(); MatcherAssert.assertThat( <START> "Stream doesn't provide correct bytes", <END> new BytesOf( new Body.TempFile(new Body.ByteArray(bytes)) ).asBytes(), new IsEqual<>(bytes) ); }</code><technical_language>@Serranya here. above</technical_language>

Target:
public void returnsCorrectInputWithStream() throws Exception { final byte[] bytes = new Utf8String("Stream returnsCorrectInput!").asBytes(); MatcherAssert.assertThat( "Body content of Body.TempFile doesn't provide the correct bytes", new BytesOf( new Body.TempFile(new Body.ByteArray(bytes)) ).asBytes(), new IsEqual<>(bytes) ); }
Source:
<code>public SearchMandateConnectorResponseBuilder withMandates(List<MandateConnectorResponse> mandates) { <START> this.mandates = mandates; <END> return this; }</code><technical_language>Another defensive copy opportunity</technical_language>

Target:
public SearchMandateConnectorResponseBuilder withMandates(List<MandateConnectorResponse> mandates) { this.mandates = List.copyOf(mandates); return this; }
Source:
<code>public String getModelName(CloseableHttpResponse response) throws MLHttpClientException { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); JSONObject responseJson = new JSONObject(bufferedReader.readLine()); bufferedReader.close(); response.close(); return responseJson.getString("name"); } catch (IOException e) { throw new MLHttpClientException("Failed to get the name of model" , e); } catch (JSONException e) { throw new MLHttpClientException("Failed to get the name of model" , e); <START> } <END> }</code><technical_language>returning exception message right? Hence, catch Exception catching exceptions? a typo in message. /s/Faile/Failed</technical_language>

Target:
public String getModelName(CloseableHttpResponse response) throws MLHttpClientException { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); JSONObject responseJson = new JSONObject(bufferedReader.readLine()); bufferedReader.close(); response.close(); return responseJson.getString("name"); } catch (Exception e) { throw new MLHttpClientException("Failed to get the name of model" , e); } }
Source:
<code>public static CloudBigtableTableConfiguration BuildImportConfig(ImportOptions opts) { CloudBigtableTableConfiguration.Builder builder = new CloudBigtableTableConfiguration.Builder() .withProjectId(opts.getBigtableProject()) .withInstanceId(opts.getBigtableInstanceId()) .withTableId(opts.getBigtableTableId()); if (opts.getBigtableAppProfileId() != null) { builder.withAppProfileId(opts.getBigtableAppProfileId()); } <START> if (opts.getBigtableWriteThrottleMs() != null) { <END> builder.withConfiguration("google.bigtable.buffered.mutator.throttling.enable" , "true"); builder.withConfiguration( "google.bigtable.buffered.mutator.throttling.threshold.ms", opts.getBigtableWriteThrottleMs()); } return builder.build(); }</code><technical_language>getBigtableWriteThrottleMs() returns a ValueProvider non-null. I more correct a NestedValueProvider transforms opts.getBigtableWriteThrottleMs() ValueProvider a "true" "false" for google.bigtable.buffered.mutator.throttling.enable</technical_language>

Target:
public static CloudBigtableTableConfiguration BuildImportConfig(ImportOptions opts) { CloudBigtableTableConfiguration.Builder builder = new CloudBigtableTableConfiguration.Builder() .withProjectId(opts.getBigtableProject()) .withInstanceId(opts.getBigtableInstanceId()) .withTableId(opts.getBigtableTableId()); if (opts.getBigtableAppProfileId() != null) { builder.withAppProfileId(opts.getBigtableAppProfileId()); } ValueProvider enableThrottling = ValueProvider.NestedValueProvider.of( opts.getMutationThrottleLatencyMs(), (Integer throttleMs) -> String.valueOf(throttleMs > 0)); builder.withConfiguration(BigtableOptionsFactory.BIGTABLE_BUFFERED_MUTATOR_ENABLE_THROTTLING, enableThrottling); builder.withConfiguration(BigtableOptionsFactory.BIGTABLE_BUFFERED_MUTATOR_THROTTLING_THRESHOLD_MILLIS, ValueProvider.NestedValueProvider.of(opts.getMutationThrottleLatencyMs(), String::valueOf)); return builder.build(); }