auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void main(String[] args) throws Exception { final Options options = getOptions(); final CommandLineParser parser = new PosixParser(); final CommandLine commandLine; try { commandLine = parser.parse(options, args); } catch (ParseException e) { System.err.println(e.getMessage()); printHelp(options); return; } final ApplicationContext applicationContext = PortalApplicationContextLocator.getApplicationContext(); try { final Binding binding = new SpringBinding(applicationContext); binding.setVariable("logger", LOGGER); if (commandLine.hasOption("script")) { final String scriptName = commandLine.getOptionValue("script"); final File scriptFile = getAbsoluteFile(scriptName); final CompilerConfiguration conf = new CompilerConfiguration(System.getProperties()); final GroovyShell shell = new GroovyShell(binding, conf); shell.run(scriptFile, args); <START> } <END> } finally { if (applicationContext instanceof DisposableBean) { ((DisposableBean) applicationContext).destroy(); } } }</code><technical_language>Is necessary remove this part? positive, connected Ant task launches open-ended groovy shell uPortal in classpath. (I'm pretty a task exists, did.)</technical_language>

Target:
public static void main(String[] args) throws Exception { final Options options = getOptions(); final CommandLineParser parser = new PosixParser(); final CommandLine commandLine; try { commandLine = parser.parse(options, args); } catch (ParseException e) { System.err.println(e.getMessage()); printHelp(options); return; } final ApplicationContext applicationContext = PortalApplicationContextLocator.getApplicationContext(); try { final Binding binding = new SpringBinding(applicationContext); binding.setVariable("logger", LOGGER); final CompilerConfiguration conf = new CompilerConfiguration(System.getProperties()); final GroovyShell shell = new GroovyShell(binding, conf); if (commandLine.hasOption("script")) { final String scriptName = commandLine.getOptionValue("script"); final File scriptFile = getAbsoluteFile(scriptName); shell.run(scriptFile, args); } } finally { if (applicationContext instanceof DisposableBean) { ((DisposableBean) applicationContext).destroy(); } } }
Source:
<code>public SplitStreamlet(StreamletImpl<R> parent, Map<String, SerializablePredicate<R>> splitFns) { StreamletUtils.require(splitFns.size() > 0, "At least one entry is required"); <START> for (String stream: splitFns.keySet()) { <END> StreamletUtils.checkNotBlank(stream, "Stream id can not be empty"); } this.parent = parent; this.splitFns = splitFns; setNumPartitions(parent.getNumPartitions()); }</code><technical_language>this validation moved StreamletImpl splitFns is set place? StreamletUtils.require(!splitFns.isEmpty(), "splitFns empty"); StreamletUtils.require(splitFns.keySet().stream().allMatch(stream -> StringUtils.isNotBlank(stream)), "Stream Id blank");</technical_language>

Target:
public SplitStreamlet(StreamletImpl<R> parent, Map<String, SerializablePredicate<R>> splitFns) { this.parent = parent; this.splitFns = splitFns; setNumPartitions(parent.getNumPartitions()); }
Source:
<code>public void testFullTextExtractionFilterValidMimeType() throws Exception { getMockEndpoint("mock:direct:fulltext.extraction").expectedMessageCount(1); createContext(extractionRoute); <START> template.sendBodyAndHeaders("", createEvent(fileID, eventTypes)); <END> assertMockEndpointsSatisfied(); }</code><technical_language>turn real mimetype filter want give a real valid mimetype</technical_language>

Target:
public void testFullTextExtractionFilterValidMimeType() throws Exception { getMockEndpoint("mock:direct:fulltext.extraction").expectedMessageCount(1); createContext(EXTRACTION_ROUTE); template.sendBodyAndHeaders("", createEvent(FILE_ID)); assertMockEndpointsSatisfied(); }
Source:
<code>private void updatePartitionPools(SequencerPartitionContainer<SequencerPoolPartition> source, SequencerPartitionContainer<SequencerPoolPartition> managed) throws IOException { for (SequencerPoolPartition sourcePartition : source.getPartitions()) { for (SequencerPoolPartition managedPartition : source.getPartitions()) { if (sourcePartition.getId() == managedPartition.getId()) { Pool sourcePool = sourcePartition.getPool(); Pool managedPool = managedPartition.getPool(); if (sourcePool == null && managedPool == null) continue; if (sourcePool == null && managedPool != null) { managedPartition.setPool(null); } else if (sourcePool != null && managedPool == null) { managedPartition.setPool(getPoolById(sourcePool.getId())); <START> } else if (sourcePool.getId() == managedPool.getId()) { <END> managedPartition.setPool(getPoolById(sourcePool.getId())); } } } } }</code><technical_language>!=</technical_language>

Target:
private void updatePartitionPools(SequencerPartitionContainer<SequencerPoolPartition> source, SequencerPartitionContainer<SequencerPoolPartition> managed) throws IOException { for (SequencerPoolPartition sourcePartition : source.getPartitions()) { for (SequencerPoolPartition managedPartition : source.getPartitions()) { if (sourcePartition.getId() == managedPartition.getId()) { Pool sourcePool = sourcePartition.getPool(); Pool managedPool = managedPartition.getPool(); if (sourcePool == null && managedPool == null) continue; if (sourcePool == null && managedPool != null) { managedPartition.setPool(null); } else if (sourcePool != null && managedPool == null) { managedPartition.setPool(getPoolById(sourcePool.getId())); } else if (sourcePool.getId() != managedPool.getId()) { managedPartition.setPool(getPoolById(sourcePool.getId())); } } } } }
Source:
<code>public static EndpointContext extractContext(Identity identity, boolean preventConnectionInitiation) { Principal peerIdentity = null; if (identity != null) { if (identity.isPSK()) { peerIdentity = new PreSharedKeyIdentity(identity.getPskIdentity()); } else if (identity.isRPK()) { peerIdentity = new RawPublicKeyIdentity(identity.getRawPublicKey()); } else if (identity.isX509()) { peerIdentity = new X500Principal("CN=" + identity.getX509CommonName()); } } if (peerIdentity != null) { <START> if (preventConnectionInitiation) { <END> return new MapBasedEndpointContext(identity.getPeerAddress(), peerIdentity, DtlsEndpointContext.KEY_HANDSHAKE_MODE, DtlsEndpointContext.HANDSHAKE_MODE_NONE); } } return new AddressEndpointContext(identity.getPeerAddress(), peerIdentity); }</code><technical_language>single line "ifs"</technical_language>

Target:
public static EndpointContext extractContext(Identity identity, boolean preventConnectionInitiation) { Principal peerIdentity = null; if (identity != null) { if (identity.isPSK()) { peerIdentity = new PreSharedKeyIdentity(identity.getPskIdentity()); } else if (identity.isRPK()) { peerIdentity = new RawPublicKeyIdentity(identity.getRawPublicKey()); } else if (identity.isX509()) { peerIdentity = new X500Principal("CN=" + identity.getX509CommonName()); } } if (peerIdentity != null && preventConnectionInitiation) { return new MapBasedEndpointContext(identity.getPeerAddress(), peerIdentity, DtlsEndpointContext.KEY_HANDSHAKE_MODE, DtlsEndpointContext.HANDSHAKE_MODE_NONE); } return new AddressEndpointContext(identity.getPeerAddress(), peerIdentity); }
Source:
<code>public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { final Resource original = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS); delegate.execute(context, operation); assert context.isBooting() == false; if (context.isBooting()) { return; } final Resource domain = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS); if (context.getRunningMode() == RunningMode.ADMIN_ONLY) { return; <START> } <END> if (syncWithMaster(domain, hostElement)) { final MasterDomainControllerClient masterDomainControllerClient = (MasterDomainControllerClient) context.getServiceRegistry(false).getRequiredService(MasterDomainControllerClient.SERVICE_NAME).getValue(); masterDomainControllerClient.fetchAndSyncMissingConfiguration(context, original); } }</code><technical_language>If HC is in admin-only domain.sh, connect master if is running: <LINK_0> disable this syncing; fail in admin-only if MasterDomainControllerClient available</technical_language>

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { final Resource original = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS); delegate.execute(context, operation); assert context.isBooting() == false; if (context.isBooting()) { return; } final Resource domain = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS); if (syncWithMaster(domain, hostElement)) { MasterDomainControllerClient masterDomainControllerClient = null; try { masterDomainControllerClient = (MasterDomainControllerClient) context.getServiceRegistry(false).getRequiredService(MasterDomainControllerClient.SERVICE_NAME).getValue(); } catch (ServiceNotFoundException e) { if (context.getRunningMode() == RunningMode.ADMIN_ONLY) { return; } throw e; } masterDomainControllerClient.fetchAndSyncMissingConfiguration(context, original); } }
Source:
<code>public static boolean isIanaResource(final RpslObject resource) { final RpslAttribute netname = resource.findAttribute(AttributeType.NETNAME); final boolean status = (netname != null && IANA_NETNAME.equals(netname.getValue().trim())); <START> LOGGER.debug("Is inetnum with netname iana? {}", resource.getKey(), netname != null ? netname.getValue() : null, status); <END> return status; }</code><technical_language>this appears a useless check - null is</technical_language>

Target:
public static boolean isIanaResource(final RpslObject resource) { final RpslAttribute netname = resource.findAttribute(AttributeType.NETNAME); return (netname != null && IANA_NETNAME.equals(netname.getValue().trim())); }
Source:
<code>public CdnDTO clone() { CdnDTO copy = super.clone(); CertificateDTO cdnCert = this.getCertificate(); <START> copy.cert = cdnCert != null ? cdnCert.clone() : null; <END> return copy; }</code><technical_language>setCertificate method assigning directly</technical_language>

Target:
public CdnDTO clone() { CdnDTO copy = super.clone(); CertificateDTO cdnCert = this.getCertificate(); copy.setCertificate(cdnCert != null ? cdnCert.clone() : null); return copy; }
Source:
<code>void configureUriWithUsernameAndPasswordWhenUsernameAndPasswordPropertiesSet() { this.contextRunner.withUserConfiguration(CredentialsProviderConfiguration.class) .withPropertyValues("spring.elasticsearch.rest.uris=http://user:password@localhost:9200,localhost:9201", "spring.elasticsearch.rest.username=admin", "spring.elasticsearch.rest.password=admin") .run((context) -> { RestClient client = context.getBean(RestClient.class); assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) .containsExactly("http://localhost:9200", "http://localhost:9201"); CredentialsProvider credentialsProvider = context.getBean(CredentialsProvider.class); Credentials uriCredentials = credentialsProvider.getCredentials(new AuthScope("localhost", 9200)); assertThat(uriCredentials.getUserPrincipal().getName()).isEqualTo("user"); assertThat(uriCredentials.getPassword()).isEqualTo("password"); Credentials defaultCredentials = credentialsProvider .getCredentials(new AuthScope("localhost", 9201)); <START> assertThat(defaultCredentials.getUserPrincipal().getName()).isEqualTo("admin"); <END> assertThat(defaultCredentials.getPassword()).isEqualTo("admin"); }); }</code><technical_language>I username in URI win name of principal user</technical_language>

Target:
void configureUriWithUsernameAndPasswordWhenUsernameAndPasswordPropertiesSet() { this.contextRunner .withPropertyValues("spring.elasticsearch.rest.uris=http://user:password@localhost:9200,localhost:9201", "spring.elasticsearch.rest.username=admin", "spring.elasticsearch.rest.password=admin") .run((context) -> { RestClient client = context.getBean(RestClient.class); assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) .containsExactly("http://localhost:9200", "http://localhost:9201"); assertThat(client).extracting("client") .extracting("credentialsProvider", InstanceOfAssertFactories.type(CredentialsProvider.class)) .satisfies((credentialsProvider) -> { Credentials uriCredentials = credentialsProvider .getCredentials(new AuthScope("localhost", 9200)); assertThat(uriCredentials.getUserPrincipal().getName()).isEqualTo("user"); assertThat(uriCredentials.getPassword()).isEqualTo("password"); Credentials defaultCredentials = credentialsProvider .getCredentials(new AuthScope("localhost", 9201)); assertThat(defaultCredentials.getUserPrincipal().getName()).isEqualTo("admin"); assertThat(defaultCredentials.getPassword()).isEqualTo("admin"); }); }); }
Source:
<code>public static void computePermissions() throws IOException { <START> final File tempDir = com.google.common.io.Files.createTempDir(); <END> final File newFile = new File(tempDir, "blah"); assertThat(newFile.createNewFile(), is(true)); if (!isPosixSupported(newFile)) { return; } DEFAULT_GIVEN_PERMISSIONS = Files.getPosixFilePermissions(newFile.toPath()); }</code><technical_language>introducing this - TemporaryFolder [create directories](<LINK_0></technical_language>

Target:
public static void computePermissions() throws IOException { final File tempDir = tmp.newFolder(); final File newFile = new File(tempDir, "blah"); assertThat(newFile.createNewFile(), is(true)); if (!isPosixSupported(newFile)) { return; } DEFAULT_GIVEN_PERMISSIONS = Files.getPosixFilePermissions(newFile.toPath()); }
Source:
<code><START> public void handleQueueItemsUntilEmpty() <END> { if (cancelled.get()) { return; } if (handler == null) { logger.warning("No handler set, the reading will not start."); return; } synchronized (syncRoot) { if ((readerFuture == null || readerFuture.isDone()) && (delayedFuture == null || delayedFuture.isDone())) { readerFuture = executor.submit(reader); } } }</code><technical_language>this a misnomer considering empty queue if hit maxSequentiallyHandledItems, right</technical_language>

Target:
public void handleQueueItemsUntilEmpty() { synchronized (syncRoot) { if (readerFuture == null || readerFuture.isDone()) { rescheduleReader(); } } }
Source:
<code>public void updateErrorRate(long val, String message, Exception e) { <START> if (!StringUtils.isEmpty(message)) { <END> LOG.error("updateErrorRate with message: " + message, e); } _errorRate.mark(val); _aggregatedErrorRate.mark(val); }</code><technical_language>i common connector metrics do logging. left connector do. this metrics class deal creating/registering/updating metrics</technical_language>

Target:
public void updateErrorRate(long val, String message, Exception e) { if (!StringUtils.isEmpty(message)) { _errorLogger.error("updateErrorRate with message: " + message, e); } _errorRate.mark(val); _aggregatedErrorRate.mark(val); }
Source:
<code>public void onMessageFrame(int channelId, WebSocketMessage message, Initiator initiator) { WebSocketProxy proxy = extension.getWebSocketProxy(channelId); if (proxy.isAllowAPI()) { return; } if (message.isFinished) { Map<String, String> map = new HashMap<String, String>(); map.put(FIELD_CHANNEL_ID, Integer.toString(channelId)); map.put(FIELD_TIME_IN_MS, Long.toString(message.getTimestamp().getTime())); map.put(FIELD_OP_CODE, Integer.toString(message.getOpcode())); map.put(FIELD_OP_CODE_STRING, message.getOpcodeString()); map.put(FIELD_DIRECTION, message.getDirection().name()); map.put(FIELD_MSG_ID, Integer.toString(message.getMessageId())); map.put(FIELD_LENGTH, Integer.toString(message.getPayloadLength())); if (message.isText()) { String txt = message.getReadablePayload(); if (txt.length() > 1024) { txt = txt.substring(0, 1024); } map.put(FIELD_MSG_SUMMARY, txt); } else { StringBuilder sb = new StringBuilder(); for (byte b : message.getPayload()) { sb.append(String.format("%02X ", b)); if (sb.length() > 1024) { break; } } map.put(FIELD_MSG_SUMMARY, sb.toString()); } <START> Runnable runnableTask = () -> { <END> ZAP.getEventBus().publishSyncEvent( this, new Event(this, EVENT_MESSAGE, null, map)); }; this.executor.execute(runnableTask); } }</code><technical_language>passed argument instead of a variable</technical_language>

Target:
public void onMessageFrame(int channelId, WebSocketMessage message, Initiator initiator) { WebSocketProxy proxy = extension.getWebSocketProxy(channelId); if (proxy.isAllowAPI()) { return; } if (message.isFinished) { this.executor.execute(() -> { Map<String, String> map = new HashMap<String, String>(); map.put(FIELD_CHANNEL_ID, Integer.toString(channelId)); map.put(FIELD_TIME_IN_MS, Long.toString(message.getTimestamp().getTime())); map.put(FIELD_OP_CODE, Integer.toString(message.getOpcode())); map.put(FIELD_OP_CODE_STRING, message.getOpcodeString()); map.put(FIELD_DIRECTION, message.getDirection().name()); map.put(FIELD_MSG_ID, Integer.toString(message.getMessageId())); map.put(FIELD_LENGTH, Integer.toString(message.getPayloadLength())); if (message.isText()) { String txt = message.getReadablePayload(); if (txt.length() > 1024) { txt = txt.substring(0, 1024); } map.put(FIELD_MSG_SUMMARY, txt); } else { StringBuilder sb = new StringBuilder(); for (byte b : message.getPayload()) { sb.append(String.format("%02X ", b)); if (sb.length() > 1024) { break; } } map.put(FIELD_MSG_SUMMARY, sb.toString()); } ZAP.getEventBus().publishSyncEvent( this, new Event(this, EVENT_MESSAGE, null, map)); }); } }
Source:
<code>public EvalTypeId(IType type, IBinding templateDefinition, ICPPEvaluation... arguments) { super(templateDefinition); <START> Assert.isNotNull(arguments); <END> fInputType= type; fArguments= arguments; }</code><technical_language>Better: if (arguments == null) throw new NullPointerException();</technical_language>

Target:
public EvalTypeId(IType type, IBinding templateDefinition, ICPPEvaluation... arguments) { super(templateDefinition); if (arguments==null) throw new NullPointerException("arguments"); fInputType= type; fArguments= arguments; }
Source:
<code>public static CtfTmfEvent createEvent(EventDefinition eventDef, String fileName, CtfTmfTrace originTrace) { long ts = eventDef.getTimestamp(); <START> CtfTmfTimestamp timestamp = (CtfTmfTimestamp)originTrace.createTimestamp(originTrace.getCTFTrace().timestampCyclesToNanos(ts)); <END> int sourceCPU = eventDef.getCPU(); ITmfEventField content = new TmfEventField( ITmfEventField.ROOT_FIELD_ID, null, parseFields(eventDef)); String reference = fileName == null ? CtfTmfEvent.NO_STREAM : fileName; CtfTmfEvent event = new CtfTmfEvent( originTrace, ITmfContext.UNKNOWN_RANK, timestamp, content, reference, sourceCPU, eventDef.getDeclaration() ); return event; }</code><technical_language>space cast. In fact CtfTmfTrace.createTimestamp return a CtfTmfTimestamp (covariant return type), need cast here</technical_language>

Target:
public static CtfTmfEvent createEvent(EventDefinition eventDef, String fileName, CtfTmfTrace originTrace) { long ts = eventDef.getTimestamp(); CtfTmfTimestamp timestamp = originTrace.createTimestamp(originTrace.getCTFTrace().timestampCyclesToNanos(ts)); int sourceCPU = eventDef.getCPU(); ITmfEventField content = new TmfEventField( ITmfEventField.ROOT_FIELD_ID, null, parseFields(eventDef)); String reference = fileName == null ? CtfTmfEvent.NO_STREAM : fileName; CtfTmfEvent event = new CtfTmfEvent( originTrace, ITmfContext.UNKNOWN_RANK, timestamp, content, reference, sourceCPU, eventDef.getDeclaration() ); return event; }
Source:
<code>private static void verifyInputFile(Map<String, List<String>> allTests, boolean skipFileNaming, String path, String fileName) { List<String> classes; int slash = path.lastIndexOf(File.separatorChar); String packge = path.substring(0, slash); boolean found = false; for (int depth = 0; depth < 4; depth++) { final String folderPath = packge; slash = packge.lastIndexOf(File.separatorChar); if (slash != -1) { <START> packge = path.substring(0, slash); <END> } classes = allTests.get(packge); if (classes != null && checkInputMatchCorrectFileStructure(classes, folderPath, skipFileNaming, fileName)) { found = true; break; } } if (!skipFileNaming) { assertTrue(found, "Resource must be named after a Test like 'InputMyCustomCase.java' " + "and be in the sub-package of the test like 'mycustom' " + "for test 'MyCustomCheckTest': " + path); } }</code><technical_language>1. slash -> slashIdx 2. packge typo, packageName this is</technical_language>

Target:
private static void verifyInputFile(Map<String, List<String>> allTests, boolean skipFileNaming, String path, String fileName) { List<String> classes; int slash = path.lastIndexOf(File.separatorChar); String packge = path.substring(0, slash); boolean found = false; for (int depth = 0; depth < 4; depth++) { final String folderPath = packge; slash = packge.lastIndexOf(File.separatorChar); packge = path.substring(0, slash); classes = allTests.get(packge); if (classes != null && checkInputMatchCorrectFileStructure(classes, folderPath, skipFileNaming, fileName)) { found = true; break; } } assertTrue(found, "Resource must be named after a Test like 'InputMyCustomCase.java' " + "and be in the sub-package of the test like 'mycustom' " + "for test 'MyCustomCheckTest': " + path); }
Source:
<code>private void setupFab() { fab = (FloatingActionButton) findViewById(R.id.fab); chatBox = (SwipeRemoveLinearLayout) findViewById(R.id.messageBoxContainer); chatBox.registerToSwipeEvents(this); fabHidder = new CountDownTimer(HIDE_FAB_AFTER_SEC * 1000, HIDE_FAB_AFTER_SEC * 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { if (!isTextFieldFocused) { displayFAB(true); displayChatBox(false); } else { start(); } } }; fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { currentList.stopRecyclerViewScroll(); displayChatBox(true); displayFAB(false); fabHidder.start(); showSoftKeyboard(); <START> if (streamActv.getText().toString().isEmpty() || streamActv.getText().toString().equals("")) { <END> streamActv.requestFocus(); } else if (topicActv.getText().toString().isEmpty() || topicActv.getText().toString().equals("")) { topicActv.requestFocus(); } else { messageEt.requestFocus(); } } }); }</code><technical_language>a check if string is null empty is [TextUtils.isEmpty()](<LINK_0></technical_language>

Target:
private void setupFab() { fab = (FloatingActionButton) findViewById(R.id.fab); chatBox = (SwipeRemoveLinearLayout) findViewById(R.id.messageBoxContainer); chatBox.registerToSwipeEvents(this); fabHidder = new CountDownTimer(HIDE_FAB_AFTER_SEC * 1000, HIDE_FAB_AFTER_SEC * 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { if (!isTextFieldFocused) { displayFAB(true); displayChatBox(false); } else { start(); } } }; fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { currentList.stopRecyclerViewScroll(); displayChatBox(true); displayFAB(false); fabHidder.start(); showSoftKeyboard(); checkForChatBoxFocusRequest(); } }); }
Source:
<code>private Object[] getRoots() { if (roots == null) { List<Object> rootList = new ArrayList<Object>(); rootFolders = getRootFolders(); <START> for (StagingFolderEntry rootFolder : rootFolders) { <END> rootList.add(rootFolder); } if (rootFiles != null) { for (StagingEntry rootFile : rootFiles) { rootList.add(rootFile); } } roots = new Object[rootList.size()]; rootList.toArray(roots); } return roots; }</code><technical_language>style nit: braces</technical_language>

Target:
private Object[] getRoots() { if (roots == null) { List<Object> rootList = new ArrayList<Object>(); rootFolders = getRootFolders(); for (StagingFolderEntry rootFolder : rootFolders) rootList.add(rootFolder); if (rootFiles != null) { for (StagingEntry rootFile : rootFiles) rootList.add(rootFile); } roots = new Object[rootList.size()]; rootList.toArray(roots); } return roots; }
Source:
<code>private static void askInteractively(Console console, UserInfo userInfo, Action action) { System.out.println(action); System.out.print("login: "); <START> if (Strings.isNullOrEmpty(userInfo.getLogin())) { <END> userInfo.setLogin(console.readLine()); } else { System.out.println(userInfo.getLogin()); } System.out.print("password: "); if ((action.isCreate() && Strings.isNullOrEmpty(userInfo.getPassword())) || (action.isUpdate() && Strings.isNullOrEmpty(userInfo.getPassword()) && userInfo.getGroups().isEmpty())) { userInfo.setPassword(new String(console.readPassword())); } else { System.out.println("*******"); } if (action.isCreate() && userInfo.getGroups().isEmpty()) { System.out.print("groups for user " + userInfo.getLogin() + ":"); String groupString = console.readLine(); userInfo.setGroups(Arrays.asList(groupString.split(","))); } }</code><technical_language>Creating a method named for example isLoginSet() perform tests prevent duplicated composition _Strings.isNullOrEmpty_. allow updating condition in future code. apply password</technical_language>

Target:
private static void askInteractively(Console console, UserInfo userInfo, Action action) { System.out.println(action); System.out.print("login: "); if (!userInfo.isLoginSet()) { userInfo.setLogin(console.readLine()); } else { System.out.println(userInfo.getLogin()); } System.out.print("password: "); if ((action.isCreate() && !userInfo.isPasswordSet()) || (action.isUpdate() && !userInfo.isPasswordSet()) && !userInfo.isGroupSet()) { userInfo.setPassword(new String(console.readPassword())); } else { System.out.println("*******"); } if (action.isCreate() && !userInfo.isGroupSet()) { System.out.print("groups for user " + userInfo.getLogin() + ":"); String groupString = console.readLine(); userInfo.setGroups(Arrays.asList(groupString.split(","))); } }
Source:
<code>public void append(String tempFile, String committedFile) throws ConnectException { try { acquireLease(); WALEntry key = new WALEntry(tempFile); WALEntry value = new WALEntry(committedFile); writer.append(key, value); writer.hsync(); } catch (IOException e) { <START> close(); <END> throw new ConnectException(e); } }</code><technical_language>Hmm, for sake of debuggability, if work in exception handler throw exceptions, I want log wrong. current code, if close() throws exception, info original exception is lost. This is true for a couple of other similar changes below. alternative I of is allowing close() extra parameter original of calling close (or null if one) attaching if fails, lose info other exception. I logging this proactively is fine exceptional conditions</technical_language>

Target:
public void append(String tempFile, String committedFile) throws ConnectException { try { acquireLease(); WALEntry key = new WALEntry(tempFile); WALEntry value = new WALEntry(committedFile); writer.append(key, value); writer.hsync(); } catch (IOException e) { log.error("Error appending WAL file: {}, {}", logFile, e); close(); throw new DataException(e); } }
Source:
<code>public void testSTIsClosed() throws Exception { <START> assertQuery("select st_is_closed(st_geometry_from_text('linestring(1 1, 2 2, 1 3, 1 1)'))", "select true"); <END> }</code><technical_language>nit: consider testing linestring is closed</technical_language>

Target:
public void testSTIsClosed() throws Exception { assertFunction("ST_IsClosed(ST_GeometryFromText('LINESTRING (1 1, 2 2, 1 3, 1 1)'))", BOOLEAN, true); assertFunction("ST_IsClosed(ST_GeometryFromText('LINESTRING (1 1, 2 2, 1 3)'))", BOOLEAN, false); assertInvalidFunction("ST_IsClosed(ST_GeometryFromText('POLYGON ((1 1, 1 4, 4 4, 4 1))'))", "ST_IsClosed only applies to LINE_STRING or MULTI_LINE_STRING. Input type is: POLYGON"); }
Source:
<code>private View createCheckableAction(CarMenuItem item) { Context context = getContext(); <START> Switch switchWidget = new Switch(context); <END> switchWidget.setEnabled(item.isEnabled()); switchWidget.setChecked(item.isChecked()); switchWidget.setScaleX(mSwitchScale); switchWidget.setScaleY(mSwitchScale); switchWidget.setPadding(mActionButtonPadding, 0, mActionButtonPadding, 0); CharSequence title = item.getTitle(); if (title == null || TextUtils.isEmpty(title)) { switchWidget.setOnCheckedChangeListener((b, isChecked) -> { item.setChecked(isChecked); CarMenuItem.OnClickListener itemOnClickListener = item.getOnClickListener(); if (itemOnClickListener != null) { itemOnClickListener.onClick(item); } }); return switchWidget; } else { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setGravity(Gravity.CENTER_VERTICAL); linearLayout.setOnClickListener((v -> { if (!item.isEnabled()) { return; } switchWidget.toggle(); item.setChecked(switchWidget.isChecked()); CarMenuItem.OnClickListener itemOnClickListener = item.getOnClickListener(); if (itemOnClickListener != null) { itemOnClickListener.onClick(item); } })); switchWidget.setClickable(false); Button button = new Button( new ContextThemeWrapper(context, item.getStyleResId()), null, 0); button.setText(title); button.setBackgroundResource(0); linearLayout.addView(switchWidget); linearLayout.addView(button); return linearLayout; } }</code><technical_language>a LinearLayout for this anyway, inflate XML. View checkableAction = LayoutInflater.fromContext(getContext()).inflate(R.layout.your_layout,...); // set need checkableAction (use ids get views)</technical_language>

Target:
private View createCheckableAction(CarMenuItem item) { ViewGroup checkableAction = (ViewGroup) LayoutInflater.from(getContext()) .inflate(R.layout.checkable_action_item, this, false); Switch switchWidget = checkableAction.findViewById(R.id.switch_widget); switchWidget.setEnabled(item.isEnabled()); switchWidget.setChecked(item.isChecked()); switchWidget.setScaleX(mSwitchScale); switchWidget.setScaleY(mSwitchScale); checkableAction.setOnClickListener(b -> { if (!item.isEnabled()) { return; } switchWidget.toggle(); item.setChecked(switchWidget.isChecked()); CarMenuItem.OnClickListener itemOnClickListener = item.getOnClickListener(); if (itemOnClickListener != null) { itemOnClickListener.onClick(item); } }); CharSequence title = item.getTitle(); if (!(title == null || TextUtils.isEmpty(title))) { Button button = new Button(new ContextThemeWrapper(getContext(), item.getStyleResId()), null, 0); button.setText(title); button.setBackgroundResource(0); checkableAction.addView(button); } return checkableAction; }
Source:
<code>public String getName() { <START> return "STATIC"; <END> }</code><technical_language>Copy paste error? this SQL</technical_language>

Target:
public String getName() { return "SQL"; }
Source:
<code>public StreamsAddressRequest(ByteBuf buf) { this.reqType = ICorfuPayload.fromBuffer(buf, Byte.class); this.beforeCompactionMark = ICorfuPayload.fromBuffer(buf, Boolean.class); if (reqType == STREAMS) { this.streamsRanges = ICorfuPayload.listFromBuffer(buf, StreamAddressRange.class); } else { <START> this.streamsRanges = Collections.EMPTY_LIST; <END> } }</code><technical_language>Collections.emptyList() prevent generating warnings</technical_language>

Target:
public StreamsAddressRequest(ByteBuf buf) { this.reqType = ICorfuPayload.fromBuffer(buf, Byte.class); this.forSequencerTrim = ICorfuPayload.fromBuffer(buf, Boolean.class); if (reqType == STREAMS) { this.streamsRanges = ICorfuPayload.listFromBuffer(buf, StreamAddressRange.class); } else { this.streamsRanges = Collections.emptyList(); } }
Source:
<code>public synchronized void flush() throws IOException { checkFlushException(); for (int i = 1; i <= executionOptions.getMaxRetries(); i++) { try { attemptFlush(); batchCount = 0; break; } catch (SQLException e) { LOG.error("JDBC executeBatch error, retry times = {}", i, e); if (i >= executionOptions.getMaxRetries()) { throw new IOException(e); } try { if (!connection.isValid(JdbcLookupFunction.CONNECTION_CHECK_TIMEOUT)) { connection = connectionProvider.reestablishConnection(); jdbcStatementExecutor.reopen(connection); } } catch (Exception excpetion) { LOG.error("JDBC connection is not valid, and reestablish connection failed.", excpetion); <START> throw new RuntimeException("Reestablish JDBC connection failed", excpetion); <END> } try { Thread.sleep(1000 * i); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IOException("unable to flush; interrupted while doing another attempt", e); } } } }</code><technical_language>IOException instead</technical_language>

Target:
public synchronized void flush() throws IOException { checkFlushException(); for (int i = 1; i <= executionOptions.getMaxRetries(); i++) { try { attemptFlush(); batchCount = 0; break; } catch (SQLException e) { LOG.error("JDBC executeBatch error, retry times = {}", i, e); if (i >= executionOptions.getMaxRetries()) { throw new IOException(e); } try { if (!connection.isValid(CONNECTION_CHECK_TIMEOUT_SECONDS)) { connection = connectionProvider.reestablishConnection(); jdbcStatementExecutor.closeStatements(); jdbcStatementExecutor.prepareStatements(connection); } } catch (Exception excpetion) { LOG.error("JDBC connection is not valid, and reestablish connection failed.", excpetion); throw new IOException("Reestablish JDBC connection failed", excpetion); } try { Thread.sleep(1000 * i); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IOException("unable to flush; interrupted while doing another attempt", e); } } } }
Source:
<code>public void testTaskWithEnableAutoClaimTaskWithGroupOnly() throws Exception { TestWorkItemManager manager = new TestWorkItemManager(); <START> env.set("Autoclaim", new String("true")); <END> ksession.setEnvironment(env); ksession.setWorkItemManager(manager); WorkItemImpl workItem = new WorkItemImpl(); workItem.setName("Human Task"); workItem.setParameter("NodeName", "TaskName"); workItem.setParameter("Comment", "Comment"); workItem.setParameter("Priority", "10"); workItem.setParameter("GroupId", "Crusaders"); workItem.setParameter("SwimlaneActorId", "Darth Vader"); workItem.setProcessInstanceId(10); handler.executeWorkItem(workItem, manager); List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK"); assertEquals(1, tasks.size()); TaskSummary task = tasks.get(0); assertEquals("TaskName", task.getName()); assertEquals(10, task.getPriority().intValue()); assertEquals("Comment", task.getDescription()); assertEquals(Status.Reserved, task.getStatus()); assertEquals("Darth Vader", task.getActualOwner().getId()); assertEquals(10, task.getProcessInstanceId().intValue()); taskService.start(task.getId(), "Darth Vader"); taskService.complete(task.getId(), "Darth Vader", null); assertTrue(manager.waitTillCompleted(MANAGER_COMPLETION_WAIT_TIME)); }</code><technical_language>I plain "true" here. is sufficient</technical_language>

Target:
public void testTaskWithEnableAutoClaimTaskWithGroupOnly() throws Exception { TestWorkItemManager manager = new TestWorkItemManager(); env.set("Autoclaim", "true"); ksession.setEnvironment(env); ksession.setWorkItemManager(manager); WorkItemImpl workItem = new WorkItemImpl(); workItem.setName("Human Task"); workItem.setParameter("NodeName", "TaskName"); workItem.setParameter("Comment", "Comment"); workItem.setParameter("Priority", "10"); workItem.setParameter("GroupId", "Crusaders"); workItem.setParameter("SwimlaneActorId", "Darth Vader"); workItem.setProcessInstanceId(10); handler.executeWorkItem(workItem, manager); List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK"); assertEquals(1, tasks.size()); TaskSummary task = tasks.get(0); assertEquals("TaskName", task.getName()); assertEquals(10, task.getPriority().intValue()); assertEquals("Comment", task.getDescription()); assertEquals(Status.Reserved, task.getStatus()); assertEquals("Darth Vader", task.getActualOwner().getId()); assertEquals(10, task.getProcessInstanceId().intValue()); taskService.start(task.getId(), "Darth Vader"); taskService.complete(task.getId(), "Darth Vader", null); assertTrue(manager.waitTillCompleted(MANAGER_COMPLETION_WAIT_TIME)); }
Source:
<code>void localize() { nameEditor.setLabel(constants.makeTemplatePopupNameLabel()); descriptionEditor.setLabel(constants.makeTemplatePopupDescriptionLabel()); commentEditor.setLabel(constants.commentLabel()); clusterEditor.setLabel(constants.makeTemplateClusterLabel()); quotaEditor.setLabel(constants.makeTemplateQuotaLabel()); isTemplatePublicEditor.setLabel(constants.makeTemplateIsTemplatePublicEditorLabel()); copyVmPermissions.setLabel(constants.copyVmPermissions()); <START> sealTemplateEditor.setLabel(constants.sealTemplate()); <END> disksAllocationLabel.setText(constants.disksAllocation()); isSubTemplateEditor.setLabel(constants.createAsSubTemplate()); baseTemplateEditor.setLabel(constants.rootTemplate()); templateVersionNameEditor.setLabel(constants.templateVersionName()); cpuProfilesEditor.setLabel(constants.cpuProfileLabel()); }</code><technical_language>please set label declaratively in ui.xml file instead. In general (and related this patch of course) manual setters (that logic depend global constants) refactored (moved) xml file</technical_language>

Target:
void localize() { nameEditor.setLabel(constants.makeTemplatePopupNameLabel()); descriptionEditor.setLabel(constants.makeTemplatePopupDescriptionLabel()); commentEditor.setLabel(constants.commentLabel()); clusterEditor.setLabel(constants.makeTemplateClusterLabel()); quotaEditor.setLabel(constants.makeTemplateQuotaLabel()); isTemplatePublicEditor.setLabel(constants.makeTemplateIsTemplatePublicEditorLabel()); copyVmPermissions.setLabel(constants.copyVmPermissions()); disksAllocationLabel.setText(constants.disksAllocation()); isSubTemplateEditor.setLabel(constants.createAsSubTemplate()); baseTemplateEditor.setLabel(constants.rootTemplate()); templateVersionNameEditor.setLabel(constants.templateVersionName()); cpuProfilesEditor.setLabel(constants.cpuProfileLabel()); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InterfacesTag that = (InterfacesTag) o; <START> return !(interfaces != null ? !interfaces.equals(that.interfaces) : that.interfaces != null); <END> }</code><technical_language>negation is a bit of a confusing phrase about: return interfaces == null ? that.interfaces == null : interfaces.equals(that.interfaces);</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InterfacesTag that = (InterfacesTag) o; return interfaces == null ? that.interfaces == null : interfaces.equals(that.interfaces); }
Source:
<code>public HostMaintenanceConfirmationPopupView(EventBus eventBus) { super(eventBus); latch = new EntityModelCheckBoxEditor(Align.RIGHT); latch.setLabel(constants.approveOperation()); force = new EntityModelCheckBoxEditor(Align.RIGHT); force.setLabel(constants.forceRemove()); force.getContentWidgetContainer().getElement().getStyle().setWidth(90, Unit.PCT); stopGlusterServices = new EntityModelCheckBoxEditor(Align.RIGHT); stopGlusterServices.getContentWidgetContainer().getElement().getStyle().setWidth(90, Unit.PCT); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); ViewIdHandler.idHandler.generateAndSetIds(this); localize(); driver.initialize(this); <START> reasonPanel.setVisible(true); <END> pinnedVMsInfoPanel.setVisible(false); pinnedVMsInfoMessage.setAlertType(AlertType.INFO); }</code><technical_language>I true default, probaly need set</technical_language>

Target:
public HostMaintenanceConfirmationPopupView(EventBus eventBus) { super(eventBus); latch = new EntityModelCheckBoxEditor(Align.RIGHT); latch.setLabel(constants.approveOperation()); force = new EntityModelCheckBoxEditor(Align.RIGHT); force.setLabel(constants.forceRemove()); force.getContentWidgetContainer().getElement().getStyle().setWidth(90, Unit.PCT); stopGlusterServices = new EntityModelCheckBoxEditor(Align.RIGHT); stopGlusterServices.getContentWidgetContainer().getElement().getStyle().setWidth(90, Unit.PCT); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); ViewIdHandler.idHandler.generateAndSetIds(this); localize(); driver.initialize(this); pinnedVMsInfoPanel.setVisible(false); pinnedVMsInfoMessage.setAlertType(AlertType.INFO); }
Source:
<code><START> public AbstractTableViewer <END> getTableViewer() { return actionContext.getViewer(); }</code><technical_language>this protected well</technical_language>

Target:
protected AbstractTableViewer getTableViewer() { return actionContext.getViewer(); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LookupExtractorFactoryContainer that = (LookupExtractorFactoryContainer) o; <START> if (version != null ? !version.equals(that.version) : that.version != null) { <END> return false; } return lookupExtractorFactory.equals(that.lookupExtractorFactory); }</code><technical_language>here, <LINK_0>, choose instead of "IntelliJ default" "Objects.equals() hashCode(), Java 7+" in dropdown. more concise, harder a mistake, easier review</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LookupExtractorFactoryContainer that = (LookupExtractorFactoryContainer) o; return Objects.equals(version, that.version) && Objects.equals(lookupExtractorFactory, that.lookupExtractorFactory); }
Source:
<code>public OpenMRSPatient getPatientByUuid(String uuid) { Validate.notEmpty(uuid, "Patient Id cannot be empty"); Patient patient; try { patient = patientResource.getPatientById(uuid); } catch (HttpException e) { LOGGER.error("Failed to get patient by id: " + uuid); return null; } String motechIdentifierUuid; try { motechIdentifierUuid = patientResource.getMotechPatientIdentifierUuid(); } catch (HttpException e) { LOGGER.error("There was an exception retrieving the MoTeCH Identifier Type UUID"); return null; } String motechId = null; OpenMRSFacility facility = null; Identifier motechIdentifier = patient.getIdentifierByIdentifierType(motechIdentifierUuid); if (motechIdentifier == null) { LOGGER.warn("No MoTeCH Id found on Patient with id: " + patient.getUuid()); } else { if (motechIdentifier.getLocation() != null) { facility = facilityAdapter.getFacilityByUuid(motechIdentifier.getLocation().getUuid()); } motechId = motechIdentifier.getIdentifier(); } <START> List<Identifier> supportedIdentifierList = new ArrayList<>(); <END> for (Identifier identifier : patient.getIdentifiers()) { IdentifierType identifierType = identifier.getIdentifierType(); if (identifierType.getUuid().equals(motechIdentifierUuid)) { continue; } else { try { String identifierName = patientResource.getPatientIdentifierName(identifierType.getUuid()); if (identifierName == null) { LOGGER.warn("The identifier with UUID is not supported", identifierType.getUuid()); } else { identifier.getIdentifierType().setName(identifierName); supportedIdentifierList.add(identifier); } } catch (HttpException e) { LOGGER.error("There was an exception retrieving the identifier with UUID {}", identifierType.getUuid()); return null; } } } return ConverterUtils.toOpenMRSPatient(patient, facility, motechId, supportedIdentifierList); }</code><technical_language>process for discovering supported identifiers moved separate, private method</technical_language>

Target:
public OpenMRSPatient getPatientByUuid(String uuid) { Validate.notEmpty(uuid, "Patient Id cannot be empty"); Patient patient; try { patient = patientResource.getPatientById(uuid); } catch (HttpException e) { LOGGER.error("Failed to get patient by id: " + uuid); return null; } String motechIdentifierUuid; try { motechIdentifierUuid = patientResource.getMotechPatientIdentifierUuid(); } catch (HttpException e) { LOGGER.error("There was an exception retrieving the MoTeCH Identifier Type UUID"); return null; } String motechId = null; OpenMRSFacility facility = null; Identifier motechIdentifier = patient.getIdentifierByIdentifierType(motechIdentifierUuid); if (motechIdentifier == null) { LOGGER.warn("No MoTeCH Id found on Patient with id: " + patient.getUuid()); } else { if (motechIdentifier.getLocation() != null) { facility = facilityAdapter.getFacilityByUuid(motechIdentifier.getLocation().getUuid()); } motechId = motechIdentifier.getIdentifier(); } List<Identifier> supportedIdentifierTypeList = getSupportedIdentifierTypeList(patient.getIdentifiers(), motechIdentifierUuid); return ConverterUtils.toOpenMRSPatient(patient, facility, motechId, supportedIdentifierTypeList); }
Source:
<code>private ByteArrayOutputStream setUpLoggerStream() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final WriterAppender writerAppender = new WriterAppender( new SimpleLayout(), baos ); <START> writerAppender.setThreshold( <END> Level.ERROR ); writerAppender.activateOptions(); Logger.getRootLogger().addAppender( writerAppender ); return baos; }</code><technical_language>@piddubnyi this fit in a single line writerAppender.setThreshold(Level.ERROR);</technical_language>

Target:
private ByteArrayOutputStream setUpLoggerStream() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final WriterAppender appender = new WriterAppender( new SimpleLayout(), baos ); appender.setThreshold(Level.ERROR); appender.activateOptions(); Logger.getRootLogger().addAppender(appender); return baos; }
Source:
<code>public InputStream getContent(TaskRepository repository, ITask task, TaskAttribute attachmentAttribute, IProgressMonitor monitor) throws CoreException { BugzillaClient client; try { monitor.beginTask(Messages.BugzillaTaskAttachmentHandler_Getting_attachment, IProgressMonitor.UNKNOWN); TaskAttachmentMapper attachment = TaskAttachmentMapper.createFrom(attachmentAttribute); client = connector.getClientManager().getClient(repository, <START> new SubProgressMonitor(monitor, IProgressMonitor.UNKNOWN)); <END> return client.getAttachmentData(attachment.getAttachmentId(), monitor); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, "Unable to retrieve attachment", e)); } finally { monitor.done(); } }</code><technical_language>clear a SubProgressMonitor a difference passing monitor directly</technical_language>

Target:
public InputStream getContent(TaskRepository repository, ITask task, TaskAttribute attachmentAttribute, IProgressMonitor monitor) throws CoreException { BugzillaClient client; try { monitor.beginTask(Messages.BugzillaTaskAttachmentHandler_Getting_attachment, IProgressMonitor.UNKNOWN); TaskAttachmentMapper attachment = TaskAttachmentMapper.createFrom(attachmentAttribute); client = connector.getClientManager().getClient(repository, monitor); return client.getAttachmentData(attachment.getAttachmentId(), monitor); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, "Unable to retrieve attachment", e)); } finally { monitor.done(); } }
Source:
<code>public Region<Object, Object> getRegion() throws IOException { <START> if (clientCache == null && clientCache.isClosed()) { <END> initClient(); } if (region == null) { region = clientCache.getRegion(regionName); if (region == null) { region = clientCache.<Object, Object> createClientRegionFactory(ClientRegionShortcut.PROXY).create(regionName); } } return region; }</code><technical_language>null pointer exception</technical_language>

Target:
public Region<Object, Object> getRegion() throws IOException { if (clientCache == null || clientCache.isClosed()) { initClient(); } if (region == null) { region = clientCache.getRegion(regionName); if (region == null) { region = clientCache.<Object, Object> createClientRegionFactory(ClientRegionShortcut.PROXY).create(regionName); } } return region; }
Source:
<code><START> public String toString() { <END> return "TransferStepImpl{" + "srcId='" + srcId + '\'' + ", dstId='" + dstId + '\'' + ", dataInfo=" + dataInfo + '}'; }</code><technical_language>StringBuilder</technical_language>

Target:
public String toString() { final StringBuilder sb = new StringBuilder("TransferStepImpl{"); sb.append("srcId='").append(srcId).append('\''); sb.append(", dstId='").append(dstId).append('\''); sb.append(", dataInfo=").append(dataInfo); sb.append('}'); return sb.toString(); }