auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Collection<Map.Entry<String, String>> enrich( final Collection<Map.Entry<String, String>> headers, final Response rsp ) { final List<String> list = rsp.headers().get( <START> this.scvh <END> ); final Map<String, String> map = new ConcurrentHashMap<>(headers.size() + 1); for (final Map.Entry<String, String> entry : headers) { map.put(entry.getKey(), entry.getValue()); } map.put( this.cmch, list.iterator().next() ); return map.entrySet(); }</code><technical_language>@gmandnepr indentation needs fixed</technical_language>

Target:
private Collection<Map.Entry<String, String>> enrich( final Collection<Map.Entry<String, String>> headers, final Response rsp ) { final Collection<String> list = rsp.headers().get( this.scvh ); final Map<String, String> map = new ConcurrentHashMap<>(headers.size() + 1); for (final Map.Entry<String, String> entry : headers) { map.put(entry.getKey(), entry.getValue()); } map.put( this.cmch, list.iterator().next() ); return map.entrySet(); }
Source:
<code>private String getOutgoingConnectorKind() { TaskRepository repository = getOutgoingRepository(); if (repository != null) { return repository.getConnectorKind(); } else { <START> return task.getConnectorKind(); <END> } }</code><technical_language>task null here</technical_language>

Target:
private String getOutgoingConnectorKind() { TaskRepository repository = getOutgoingRepository(); if (repository != null) { return repository.getConnectorKind(); } else if (task != null) { return task.getConnectorKind(); } return null; }
Source:
<code>public boolean contains(final String name) { try { <START> return !new JdkRequest(UriBuilder.fromUri(this.home).build()) <END> .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .method(Request.GET) .fetch() .as(RestResponse.class) .assertStatus(HttopURLConnection.HTTP_OK) .as(XmlResponse.class) .xml() .xpath(String.format("/page/stands/stand[name='%s']", name)) .isEmpty(); } catch (IOException ex) { throw new IllegalStateException(ex); } }</code><technical_language>need UriBuilder</technical_language>

Target:
public boolean contains(final String name) { try { return !new JdkRequest(this.home) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml() .xpath(String.format("/page/stands/stand[name='%s']", name)) .isEmpty(); } catch (IOException ex) { throw new IllegalStateException(ex); } }
Source:
<code>public void testLocationScriptDirConfigIsRespected() throws Exception { final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi"; Map<String, Object> locationConfig = ImmutableMap.<String, Object>builder() .put(SshMachineLocation.SCRIPT_DIR.getName(), "/var/tmp") .build(); <START> LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", true, locationConfig).orNull(); <END> SshMachineLocation sm = lhp.obtain(); int rc = sm.execScript("Test script directory execution", ImmutableList.of(command)); assertEquals(rc, 0); }</code><technical_language>default for managed param is true, miss out I think</technical_language>

Target:
public void testLocationScriptDirConfigIsRespected() throws Exception { final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi"; Map<String, Object> locationConfig = ImmutableMap.<String, Object>builder() .put(SshMachineLocation.SCRIPT_DIR.getName(), "/var/tmp") .build(); LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", locationConfig); SshMachineLocation sm = lhp.obtain(); int rc = sm.execScript("Test script directory execution", ImmutableList.of(command)); assertEquals(rc, 0); }
Source:
<code>private void updateDomainInProblem(final Guid vdsId, final String vdsName, final Set<Guid> domainsInProblems) { <START> if (domainsInProblems != null) { <END> ((EventQueue) EjbUtils.findBean(BeanType.EVENTQUEUE_MANAGER, BeanProxyType.LOCAL)).submitEventSync(new Event(_storagePoolId, null, EventType.DOMAINMONITORING), new Callable<EventResult>() { @Override public EventResult call() { EventResult result = new EventResult(true, EventType.DOMAINMONITORING); synchronized (_lockObject) { updateProblematicVdsData(vdsId, vdsName, domainsInProblems); } return result; } }); } }</code><technical_language>above, a bit hard read</technical_language>

Target:
private void updateDomainInProblem(final Guid vdsId, final String vdsName, final Set<Guid> domainsInProblems) { if (domainsInProblems != null) { ((EventQueue) EjbUtils.findBean(BeanType.EVENTQUEUE_MANAGER, BeanProxyType.LOCAL)).submitEventSync(new Event(_storagePoolId, null, vdsId, EventType.DOMAINMONITORING), new Callable<EventResult>() { @Override public EventResult call() { EventResult result = new EventResult(true, EventType.DOMAINMONITORING); updateProblematicVdsData(vdsId, vdsName, domainsInProblems); return result; } }); } }
Source:
<code>public void nakedS3Get() throws IOException, SignatureException, XmlProcessingException, URISyntaxException, InterruptedException { <START> final WritableByteChannel writeChannel = Channels.newChannel(new OutputStream() { <END> @Override public void write(final int b) throws IOException { } }); final GetObjectResponse getObjectResponse = client.getObject( new GetObjectRequest(BUCKET_NAME, "beowulf.txt", writeChannel)); assertThat(getObjectResponse.getStatusCode(), is(200)); }</code><technical_language>a NullChannel implementation want here. instead</technical_language>

Target:
public void nakedS3Get() throws IOException, SignatureException, XmlProcessingException, URISyntaxException, InterruptedException { final WritableByteChannel writeChannel = new NullChannel(); final GetObjectResponse getObjectResponse = client.getObject( new GetObjectRequest(BUCKET_NAME, "beowulf.txt", writeChannel)); assertThat(getObjectResponse.getStatusCode(), is(200)); }
Source:
<code>private void prepareAndCheckSender() { if (plainSender == null || plainSender.isClosed()) { Lock writeLock = senderLock.writeLock(); writeLock.lock(); try { if (plainSender == null || plainSender.isClosed()) { PlainStreamingSender newSender = new PlainStreamingSender(httpClientManager.getClientConfiguration(), plainSender); if (plainSender != null) { <START> log.info("Prepare new sende {}r, close old {}", newSender, plainSender); <END> plainSender.close(); } if (senderFuture != null) { senderFuture.cancel(true); } senderFuture = senderExecutor.submit(newSender); plainSender = newSender; } } finally { writeLock.unlock(); } } lastPingResult = check(); if (lastPingResult) { compareAndSendNewMarker(marker.get()); } }</code><technical_language>Please, fix</technical_language>

Target:
private void prepareAndCheckSender() { if (plainSender == null || plainSender.isClosed()) { Lock writeLock = senderLock.writeLock(); writeLock.lock(); try { if (plainSender == null || plainSender.isClosed()) { PlainStreamingSender newSender = new PlainStreamingSender(httpClientManager.getClientConfiguration(), plainSender); if (plainSender != null) { log.info("Prepare new sender {}, close old {}", newSender, plainSender); plainSender.close(); } if (senderFuture != null) { senderFuture.cancel(true); } senderFuture = senderExecutor.submit(newSender); plainSender = newSender; } } finally { writeLock.unlock(); } } lastPingResult = check(); if (lastPingResult) { compareAndSendNewMarker(marker.get()); } }
Source:
<code><START> public void enableTemperatureNotifications(Consumer<double[]> callback) { <END> Consumer<byte[]> callbackTemp = valueBytes -> callback.accept(calculateTemperature(valueBytes)); BluetoothLeGattCharacteristic tempValueChar; try { tempValueChar = this.gattServices.get(TEMPERATURE) .findCharacteristic(TiSensorTagGatt.UUID_TEMP_SENSOR_VALUE); tempValueChar.enableValueNotifications(callbackTemp); } catch (KuraException e) { logger.error("Temperature notification enable failed", e); } }</code><technical_language>I good return boolean signify success of this method invocation</technical_language>

Target:
public boolean enableTemperatureNotifications(Consumer<double[]> callback) { boolean result = false; Consumer<byte[]> callbackTemp = valueBytes -> callback.accept(calculateTemperature(valueBytes)); BluetoothLeGattCharacteristic tempValueChar; try { tempValueChar = this.gattServices.get(TEMPERATURE) .findCharacteristic(TiSensorTagGatt.UUID_TEMP_SENSOR_VALUE); tempValueChar.enableValueNotifications(callbackTemp); result = true; } catch (KuraException e) { logger.error("Temperature notification enable failed", e); } return result; }
Source:
<code><START> private String parseReturnSentence() throws ParseException { <END> int index = nextNonBlank(); if (index < 0 || !expression.startsWith(RETURN_SENTENCE, index)) { throw new ParseException(errorMessage(SENTENCE_EXPECTED_AT_POSITION_ERROR, RETURN_SENTENCE, parseIndex), parseIndex); } setParseIndex(index + RETURN_SENTENCE.length()); if (!isBlank(expression.charAt(parseIndex))) { throw new ParseException(errorMessage(BLANK_AFTER_RETURN_EXPECTED_ERROR, RETURN_SENTENCE), parseIndex); } return RETURN_SENTENCE; }</code><technical_language>Return of method is used</technical_language>

Target:
private void parseReturnSentence() throws ParseException { int index = nextNonBlank(); if (index < 0 || !expression.startsWith(RETURN_SENTENCE, index)) { throw new ParseException(errorMessage(SENTENCE_EXPECTED_AT_POSITION_ERROR, RETURN_SENTENCE, parseIndex), parseIndex); } setParseIndex(index + RETURN_SENTENCE.length()); if (isNoneBlank(expression.charAt(parseIndex))) { throw new ParseException(errorMessage(BLANK_AFTER_RETURN_EXPECTED_ERROR, RETURN_SENTENCE), parseIndex); } }
Source:
<code>public void scriptBindingClosureVariableCall() throws Exception { <START> assertEvaluate(new GenericWhitelist(), true, "def func = { 1 }; this.func2 = { 1 }; return func() == func2();\n"); <END> }</code><technical_language>A single variant is enough convince readers of ( "call", args) works correctly varargs. I expect closures zero, one, more parameters, implicit it</technical_language>

Target:
public void scriptBindingClosureVariableCall() throws Exception { assertEvaluate(new GenericWhitelist(), true, "def func = { 1 }; this.func2 = { 1 }; return func() == func2();\n"); assertEvaluate(new GenericWhitelist(), true, "def func = { x -> x }; this.func2 = { x -> x }; return func(5) == func2(5);\n"); assertEvaluate(new GenericWhitelist(), true, "def func = { x, y -> x * y }; this.func2 = { x, y -> x * y }; return func(4, 5) == func2(4, 5);\n"); assertEvaluate(new GenericWhitelist(), true, "def func = { it }; this.func2 = { it }; return func(12) == func2(12);\n"); }
Source:
<code>private KeyStore getSecretsStore() { final File secretStoreFile = createStoreIfNeeded(); try { final KeyStore keyStore = KeyStore.getInstance(SECRETS_STORE_KEYSTORE_TYPE); <START> try (InputStream inputStream = Files.newInputStream(secretStoreFile.toPath())) { <END> keyStore.load(inputStream, loadStorePassword()); } return keyStore; } catch (Exception e) { Logger.warn(this.getClass(), "unable to load secrets store " + SECRETS_STORE_FILE + ": " + e); throw new DotRuntimeException(e); } }</code><technical_language>Good is</technical_language>

Target:
private KeyStore getSecretsStore() { final File secretStoreFile = createStoreIfNeeded(); try { final KeyStore keyStore = KeyStore.getInstance(SECRETS_STORE_KEYSTORE_TYPE); try (InputStream inputStream = Files.newInputStream(secretStoreFile.toPath())) { keyStore.load(inputStream, loadStorePassword()); } return keyStore; } catch (Exception e) { Logger.error(this.getClass(), "unable to load secrets store " + SECRETS_STORE_FILE + ": " + e); throw new DotRuntimeException(e); } }
Source:
<code>protected void doStop() { <START> this.receivingTask.cancel(true); <END> }</code><technical_language>need cancel pingTask in receiver. Add Lifecycle ? closing folder</technical_language>

Target:
protected void doStop() { this.receivingTask.cancel(true); this.mailReceiver.cancelPing(); }
Source:
<code>public static Map<String, Path> scanIdentitiesFolder( Path dir, boolean strict, Collection<String> types, Transformer<String, String> idGenerator, LinkOption... options) throws IOException { if (GenericUtils.isEmpty(types)) { return Collections.emptyMap(); } if (!Files.exists(dir, options)) { return Collections.emptyMap(); } ValidateUtils.checkTrue(Files.isDirectory(dir, options), "Not a directory: %s", dir); Map<String, Path> paths = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (String t : types) { String fileName = idGenerator.transform(t); Path p = dir.resolve(fileName); if (!Files.exists(p, options)) { continue; } if (strict) { PosixFilePermission perm = KeyUtils.validateStrictKeyFilePermissions(p, options); if (perm != null) { continue; } String owner = KeyUtils.validateStrictKeyFileOwner(p, options); if (owner != null) { continue; } <START> } <END> Path prev = paths.put(t, p); ValidateUtils.checkTrue(prev == null, "Multiple mappings for type=%s", t); } return paths; }</code><technical_language>I prefer: java if (GenericUtils.length(owner) > 0) { continue; } I "empty" owner expected, if IMO "no user"</technical_language>

Target:
public static Map<String, Path> scanIdentitiesFolder( Path dir, boolean strict, Collection<String> types, Transformer<String, String> idGenerator, LinkOption... options) throws IOException { if (GenericUtils.isEmpty(types)) { return Collections.emptyMap(); } if (!Files.exists(dir, options)) { return Collections.emptyMap(); } ValidateUtils.checkTrue(Files.isDirectory(dir, options), "Not a directory: %s", dir); Map<String, Path> paths = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (String t : types) { String fileName = idGenerator.transform(t); Path p = dir.resolve(fileName); if (!Files.exists(p, options)) { continue; } if (strict) { if (KeyUtils.validateStrictKeyFilePermissions(p, options) != null) { continue; } } Path prev = paths.put(t, p); ValidateUtils.checkTrue(prev == null, "Multiple mappings for type=%s", t); } return paths; }
Source:
<code>protected void onBind() { Event<EventArgs> entityChangedEvent = getModel().getDiskViewType().getEntityChangedEvent(); entityChangedEvent.addListener(getView().getDiskTypeChangedEventListener()); Event<EventArgs> diskContentTypeEntityChangedEvent = getModel().getDiskContentType().getEntityChangedEvent(); diskContentTypeEntityChangedEvent.addListener(getView().getDiskContentTypeChangedEventListener()); <START> super.onBind(); <END> }</code><technical_language>call onBind (i.e. in line 83)? do conflict something</technical_language>

Target:
protected void onBind() { super.onBind(); Event<EventArgs> entityChangedEvent = getModel().getDiskViewType().getEntityChangedEvent(); entityChangedEvent.addListener(getView().getDiskTypeChangedEventListener()); Event<EventArgs> diskContentTypeEntityChangedEvent = getModel().getDiskContentType().getEntityChangedEvent(); diskContentTypeEntityChangedEvent.addListener(getView().getDiskContentTypeChangedEventListener()); }
Source:
<code>void GetFirstReminderBoarder() { HealthDescriptor healthDiscStub = GenerateHealthStub.generateHealthDescriptor(true, 1, 0); StaticAnalysisRun paramStub = mock(StaticAnalysisRun.class); when(paramStub.getTotalSize()).thenReturn(1); HealthSeriesBuilder b = new HealthSeriesBuilder(healthDiscStub); List<Integer> first = b.computeSeries(paramStub); assertThat(first).containsExactly(1, 0, 0); <START> assertThat(first.size()).isEqualTo(3); <END> }</code><technical_language>(first).hasSize(3);</technical_language>

Target:
void GetFirstReminderBoarder() { HealthDescriptor healthDiscStub = generateHealthDescriptor(true, 1, 0); StaticAnalysisRun paramStub = mock(StaticAnalysisRun.class); when(paramStub.getTotalSize()).thenReturn(1); HealthSeriesBuilder b = new HealthSeriesBuilder(healthDiscStub); List<Integer> first = b.computeSeries(paramStub); assertThat(first).containsExactly(1, 0, 0); assertThat(first).hasSize(3); }
Source:
<code><START> public void setSeltectedDevParams(List<VarDeclaration> selParams) { selectedDevParams = selParams; } <END></code><technical_language>initialized list is immutable list, this method save, provided list is immutable too, in order give a uniform behavior replacing original emptyList</technical_language>

Target:
public void setSeltectedDevParams(List<VarDeclaration> selParams) { selectedDevParams = Collections.unmodifiableList(new ArrayList<>(selParams)); }
Source:
<code>public ResultScanner adapt( final com.google.cloud.bigtable.grpc.scanner.ResultScanner<T> bigtableResultScanner, <START> final Span span) { <END> return new AbstractClientScanner() { int rowCount = 0; @Override public Result next() throws IOException { T row = bigtableResultScanner.next(); if (row == null) { span.end(); return null; } rowCount++; return rowAdapter.adaptResponse(row); } @Override public void close() { try { bigtableResultScanner.close(); } catch (IOException ioe) { throw Throwables.propagate(ioe); } finally { span.end(); } } public boolean renewLease() { throw new UnsupportedOperationException("renewLease"); } }; }</code><technical_language>more sense push this RetryingReadRowsOperation duplicate this for callback api</technical_language>

Target:
public ResultScanner adapt( final com.google.cloud.bigtable.grpc.scanner.ResultScanner<T> bigtableResultScanner, final Span span) { return new AbstractClientScanner() { int rowCount = 0; @Override public Result next() throws IOException { T row = bigtableResultScanner.next(); if (row == null) { closeSpan(); return null; } rowCount++; return rowAdapter.adaptResponse(row); } @Override public void close() { try { bigtableResultScanner.close(); } catch (IOException ioe) { throw Throwables.propagate(ioe); } finally { closeSpan(); } } protected void closeSpan() { try (AutoCloseable c = Tracing.getTracer().withSpan(span)) { span.end(); } catch (Exception e) { } } public boolean renewLease() { throw new UnsupportedOperationException("renewLease"); } }; }
Source:
<code>public static final boolean isAllowedAttributeValue(final Object value) { if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof String || value instanceof Character || value instanceof Float || value instanceof byte[] || value instanceof short[] || value instanceof int[] || value instanceof float[]) { return true; } if (value instanceof Long) { return isValidUnsignedInteger((Long) value) || ((Long) value >= Integer.MIN_VALUE && (Long) value <= Integer.MAX_VALUE); <START> } <END> return false; }</code><technical_language>a similar check implemented for Byte, Short, Integer, etc? This a special case, range check</technical_language>

Target:
protected static boolean isAllowedAttributeValue(final Object value) { if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof String || value instanceof Character || value instanceof Float || value instanceof byte[] || value instanceof short[] || value instanceof int[] || value instanceof float[]) { return true; } if (value instanceof Long) { return SAMUtils.isValidUnsignedIntegerAttribute((Long) value) || ((Long) value >= Integer.MIN_VALUE && (Long) value <= Integer.MAX_VALUE); } return false; }
Source:
<code>public int saveAnnouncement(final Announcement announcement) { LOG.debug("save new announcement"); final SqlSession session = factory.openSession(); int saveId = -1; try { final AnnouncementsMapper mapper = session.getMapper(AnnouncementsMapper.class); saveId = mapper.saveAnnouncement(announcement); session.commit(); } catch (Exception e) { throw new RuntimeException("Failed to save announcement", e); } finally { <START> session.close(); <END> } return saveId; }</code><technical_language>try-with-resources need manually close session</technical_language>

Target:
public int saveAnnouncement(final Announcement announcement) { int saveId = -1; try (final SqlSession session = factory.openSession()) { final AnnouncementsMapper mapper = session.getMapper(AnnouncementsMapper.class); saveId = mapper.saveAnnouncement(announcement); return saveId; } catch (Exception e) { throw new ServiceRuntimeException("Failed to save announcements", e); } }
Source:
<code>public static Archive readCollection(final ContentRepoService service, String archiveName, RepoCollectionMetadata collection, Function<? super RepoObjectMetadata, String> entryNameExtractor) { Preconditions.checkNotNull(service); ImmutableMap.Builder<String, RepoVersion> objects = ImmutableMap.builder(); for (RepoObjectMetadata objectMetadata : collection.getObjects()) { RepoVersion version = objectMetadata.getVersion(); String entryName = entryNameExtractor.apply(objectMetadata); if (entryName == null) { Optional<String> downloadName = objectMetadata.getDownloadName(); if (downloadName.isPresent()) { entryName = downloadName.get(); } else { String message = "Could not find archive entry name for object: " + version; throw new RuntimeException(message); } } objects.put(entryName, version); } return new Archive(archiveName, objects.build()) { @Override protected InputStream openFileFrom(Object repoVersion) { try { return service.getRepoObject((RepoVersion) repoVersion); } catch(NotFoundException nfe) { <START> throw new RestClientException(nfe.getMessage(), HttpStatus.NOT_FOUND); <END> } } }; }</code><technical_language>Pass nfe (third param) RestClientException</technical_language>

Target:
public static Archive readCollection(final ContentRepoService service, String archiveName, RepoCollectionMetadata collection, Function<? super RepoObjectMetadata, String> entryNameExtractor) { Preconditions.checkNotNull(service); ImmutableMap.Builder<String, RepoVersion> objects = ImmutableMap.builder(); for (RepoObjectMetadata objectMetadata : collection.getObjects()) { RepoVersion version = objectMetadata.getVersion(); String entryName = entryNameExtractor.apply(objectMetadata); if (entryName == null) { Optional<String> downloadName = objectMetadata.getDownloadName(); if (downloadName.isPresent()) { entryName = downloadName.get(); } else { String message = "Could not find archive entry name for object: " + version; throw new RuntimeException(message); } } objects.put(entryName, version); } return new Archive(archiveName, objects.build()) { @Override protected InputStream openFileFrom(Object repoVersion) { try { return service.getRepoObject((RepoVersion) repoVersion); } catch(NotFoundException nfe) { throw new RestClientException(String.format("The object with id: %s doesn't exist", repoVersion), HttpStatus.NOT_FOUND, nfe); } } }; }
Source:
<code>public void checkInterrupted() { Thread thread = Thread.currentThread(); String message; if (isInterruptable() && (message = mInterruptMessage.get(thread)) != null) { <START> thread.interrupt(); <END> throw new RunInterruptedException(message); } }</code><technical_language>do need interrupt current thread? throwing RunInterruptedException enough</technical_language>

Target:
public void checkInterrupted() { Thread thread = Thread.currentThread(); if (isInterruptable()) { String message = mInterruptMessage.remove(thread); if (message != null) { thread.interrupt(); throw new RunInterruptedException(message); } } }
Source:
<code>private static InputStream propertiesStream(final String clientPropertiesFileName) throws FileNotFoundException { if (clientPropertiesFileName.startsWith(CLASSPATH_PREFIX)) { <START> String resourcePath = clientPropertiesFileName.split(CLASSPATH_PREFIX)[1]; <END> log.info("Load properties from classpath: {}", resourcePath); return AtsdUtil.class.getResourceAsStream(resourcePath); } else { File file = new File(clientPropertiesFileName); log.info("Load properties from file: {}", file.getAbsolutePath()); return new FileInputStream(file); } }</code><technical_language>StringUtils.substringAfter</technical_language>

Target:
private static InputStream propertiesStream(final String clientPropertiesFileName) throws FileNotFoundException { if (clientPropertiesFileName.startsWith(CLASSPATH_PREFIX)) { String resourcePath = StringUtils.substringAfter(clientPropertiesFileName, CLASSPATH_PREFIX); log.info("Load properties from classpath: {}", resourcePath); return AtsdUtil.class.getResourceAsStream(resourcePath); } else { File file = new File(clientPropertiesFileName); log.info("Load properties from file: {}", file.getAbsolutePath()); return new FileInputStream(file); } }
Source:
<code>public void onNodeMainExecutorServiceConnected(final NodeMainExecutorService nodeMainExecutorService) { RosActivity.this.nodeMainExecutorService = nodeMainExecutorService; nodeMainExecutorService.addNodeMainExecutorServiceListener(new NodeMainExecutorServiceListener() { @Override public void onShutdown(NodeMainExecutorService nodeMainExecutorService) { if (!RosActivity.this.isFinishing()) { RosActivity.this.finish(); } } }); Intent notificationIntent = new Intent(nodeMainExecutorService, NodeMainExecutorService.class); notificationIntent.setAction(NodeMainExecutorService.ACTION_SHUTDOWN); PendingIntent pendingIntent = PendingIntent.getService(nodeMainExecutorService, 0, notificationIntent, 0); nodeMainExecutorService.updateNotification(rosActivityComponent.getNotificationTitle(), <START> "Tap to shutdown.",pendingIntent); <END> }</code><technical_language>formatting</technical_language>

Target:
public void onNodeMainExecutorServiceConnected(final NodeMainExecutorService nodeMainExecutorService) { RosActivity.this.nodeMainExecutorService = nodeMainExecutorService; nodeMainExecutorService.addNodeMainExecutorServiceListener(new NodeMainExecutorServiceListener() { @Override public void onShutdown(NodeMainExecutorService nodeMainExecutorService) { if (!RosActivity.this.isFinishing()) { RosActivity.this.finish(); } } }); nodeMainExecutorService.updateNotification(rosActivityComponent.getNotificationTitle(), "Tap to shutdown.", nodeMainExecutorService.getPendingIntentForShutdown()); }
Source:
<code>private String validateNamespaceArgument(ByteBuffer namespaceArg, TableOperation op, Validator<String> userValidator) throws ThriftTableOperationException { String namespace = namespaceArg == null ? null : ByteBufferUtil.toString(namespaceArg); if ((namespace != null) && (namespace.length() > MAX_NAMESPACE_LEN)) { log.warn("Namespaces greater than " + MAX_NAMESPACE_LEN <START> + " characters should be renamed to conform to a 1024 character limit. " <END> + "Longer namespaces are no longer supported and may result in unexpected behavior."); } return _validateArgument(namespace, op, Namespaces.VALID_NAME.and(userValidator)); }</code><technical_language>suggestion + " characters renamed conform a "+MAX_NAMESPACE_LEN+" character limit. "</technical_language>

Target:
private String validateNamespaceArgument(ByteBuffer namespaceArg, TableOperation op, Validator<String> userValidator) throws ThriftTableOperationException { String namespace = namespaceArg == null ? null : ByteBufferUtil.toString(namespaceArg); if ((namespace != null) && (namespace.length() > MAX_NAMESPACE_LEN)) { log.warn("Namespaces greater than " + MAX_NAMESPACE_LEN + " characters should be renamed to conform to a " + MAX_NAMESPACE_LEN + " character limit. " + "Longer namespaces are no longer supported and may result in unexpected behavior."); } return _validateArgument(namespace, op, Namespaces.VALID_NAME.and(userValidator)); }
Source:
<code>public ScaledNumberIndexFieldTypeContext<?, BigInteger> asBigInteger() { <START> return new StubScaledNumberIndexFieldTypeContext( BigInteger.class, defaultsProvider ); <END> }</code><technical_language>Missing <>, this is a raw type</technical_language>

Target:
public ScaledNumberIndexFieldTypeContext<?, BigInteger> asBigInteger() { return new StubScaledNumberIndexFieldTypeContext<>( BigInteger.class, defaultsProvider ); }
Source:
<code>private Vms getVmsFilteredAndSorted() { int max = ParametersHelper.getIntegerParameter(httpHeaders, uriInfo, "max", -1, -1); GetFilteredAndSortedParameters params = new GetFilteredAndSortedParameters(max); String searchConstraint = QueryHelper.getConstraint(httpHeaders, uriInfo, "", modelType); Integer pageNum = QueryHelper.parsePageNum(searchConstraint); <START> params.setPageNum(pageNum==null ? 1 : pageNum); <END> return mapCollection(getBackendCollection(QueryType.GetAllVmsFilteredAndSorted, params)); }</code><technical_language>specific constructor instead of invoking setter existing object? GetFilteredAndSortedParameters params = new GetFilteredAndSortedParameters(max, QueryHelper.parsePageNum( QueryHelper.getConstraint(httpHeaders, uriInfo, "", modelType);));</technical_language>

Target:
private Vms getVmsFilteredAndSorted() { int max = ParametersHelper.getIntegerParameter(httpHeaders, uriInfo, "max", -1, -1); String searchConstraint = QueryHelper.getConstraint(httpHeaders, uriInfo, "", modelType); Integer pageNum = QueryHelper.parsePageNum(searchConstraint); GetFilteredAndSortedParameters params = new GetFilteredAndSortedParameters(max, pageNum==null ? 1 : pageNum); return mapCollection(getBackendCollection(QueryType.GetAllVmsFilteredAndSorted, params)); }
Source:
<code>public FBNetworkContextMenuProvider(final DiagramEditorWithFlyoutPalette editor, final ActionRegistry registry, final ZoomManager zoomManager, Palette palette) { super(editor.getViewer(), zoomManager, registry); this.palette = palette; this.editor = editor; <START> editor.getViewer().getControl().addMenuDetectListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent e) { pt = getViewer().getControl().toControl(e.x, e.y); } }); <END> }</code><technical_language>remove lambda</technical_language>

Target:
public FBNetworkContextMenuProvider(final DiagramEditorWithFlyoutPalette editor, final ActionRegistry registry, final ZoomManager zoomManager, Palette palette) { super(editor.getViewer(), zoomManager, registry); this.palette = palette; this.editor = editor; editor.getViewer().getControl().addMenuDetectListener(e -> pt = getViewer().getControl().toControl(e.x, e.y)); }
Source:
<code>public boolean subscribe(FBOManagerSubscriber subscriber) { if (!fboManagerSubscribers.add(subscriber)) return false; <START> return true; <END> }</code><technical_language>a proper if/else statement please</technical_language>

Target:
public boolean subscribe(FBOManagerSubscriber subscriber) { for (FBOManagerSubscriber fboManagerSubscriber: fboManagerSubscribers) { if (fboManagerSubscriber == subscriber) { return false; } } return fboManagerSubscribers.add(subscriber); }
Source:
<code><START> public boolean getIsResponsePresent() { <END> for (StudentFeedbackSubmissionEditQuestionsWithResponses questionsResponses : questionsWithResponses) { for (FeedbackSubmissionEditResponse responses : questionsResponses.getResponses()) { if (responses.isExistingResponse()) { return true; } } } return false; }</code><technical_language>More code quality discussion: StudentFeedbackSubmissionEditQuestionsWithResponses/FeedbackSubmissionEditResponse related UI while method check data exist not. If u a FeedbackSubmissionEditPageData. find add fake FeedbackSubmissionEditResponse set isExisitingResponse false UI correctly displayed. suggestion is check bundle instead of questionsWithResponses questionsWithResponses is generated bundle (Single point of truth). do u think</technical_language>

Target:
public boolean getIsResponsePresent() { for (Map.Entry<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> entry : bundle.questionResponseBundle.entrySet()) { if (!entry.getValue().isEmpty()) { return true; } } return false; }
Source:
<code>public void internalReceiveCommand(String itemName, Command command) { if (password != null && !password.isEmpty()) { <START> logger.warn("Fritzbox password: "+password); <END> String type = null; for (FritzboxBindingProvider provider : providers) { type = provider.getType(itemName); if (type != null) { break; } } logger.info("Fritzbox type: {}", type); if (type == null) return; TelnetCommandThread thread = new TelnetCommandThread(type, command); thread.start(); } }</code><technical_language>passwords in log files - sense a warning. suggest remove reduce DEBUG level</technical_language>

Target:
public void internalReceiveCommand(String itemName, Command command) { if (password != null && !password.isEmpty()) { String type = null; for (FritzboxBindingProvider provider : providers) { type = provider.getType(itemName); if (type != null) { break; } } logger.info("Fritzbox type: {}", type); if (type == null) return; TelnetCommandThread thread = new TelnetCommandThread(type, command); thread.start(); } }
Source:
<code>public void testClusterSnapshotCreate() throws Exception { Ignite ignite = startGrids(2); ignite.cluster().state(ACTIVE); createCacheAndPreload(ignite, 10); CommandHandler h = new CommandHandler(); <START> assertEquals(EXIT_CODE_OK, execute(h, "--snapshot", "create", "snapshot_02052020")); <END> }</code><technical_language>check a snapshot created provided name</technical_language>

Target:
public void testClusterSnapshotCreate() throws Exception { int keysCnt = 100; String snpName = "snapshot_02052020"; IgniteEx ig = startGrid(0); ig.cluster().state(ACTIVE); createCacheAndPreload(ig, keysCnt); CommandHandler h = new CommandHandler(); assertEquals(EXIT_CODE_OK, execute(h, "--snapshot", "create", snpName)); assertTrue("Waiting for snapshot operation end failed.", waitForCondition(() -> ig.context().metric().registry(SNAPSHOT_METRICS) .<LongMetric>findMetric("LastSnapshotEndTime").value() > 0, getTestTimeout())); assertContains(log, (String)h.getLastOperationResult(), snpName); stopAllGrids(); IgniteConfiguration cfg = optimize(getConfiguration(getTestIgniteInstanceName(0))); cfg.setWorkDirectory(Paths.get(resolveSnapshotWorkDirectory(cfg).getAbsolutePath(), snpName).toString()); Ignite snpIg = startGrid(cfg); snpIg.cluster().state(ACTIVE); List<Integer> range = IntStream.range(0, keysCnt).boxed().collect(Collectors.toList()); snpIg.cache(DEFAULT_CACHE_NAME).forEach(e -> range.remove((Integer)e.getKey())); assertTrue("Snapshot must contains cache data [left=" + range + ']', range.isEmpty()); }
Source:
<code>private void run(String fileLocation) throws SQLException, AuthorizeException { Context context = new Context(); context.turnOffAuthorisationSystem(); List<RelationshipType> relationshipTypes = this.parseXMLToRelations(context, fileLocation); <START> this.saveRelations(context, relationshipTypes); <END> }</code><technical_language>context is closed correctly in this method (it is done in invoked saveRelations) commit/complete here. A proper exception handling is required avoid future connection leaks</technical_language>

Target:
private void run(String fileLocation) throws SQLException, AuthorizeException { Context context = new Context(); context.turnOffAuthorisationSystem(); this.parseXMLToRelations(context, fileLocation); context.complete(); }
Source:
<code>public void testListenableTimeout() throws Exception { SettableFuture<String> rootFuture = SettableFuture.create(); ListenableFuture<String> timeoutFuture = addTimeout(rootFuture, () -> "timeout", new Duration(0, MILLISECONDS), executorService); <START> assertEquals(tryGetFutureValue(timeoutFuture, 10, SECONDS).get(), "timeout"); <END> assertTrue(timeoutFuture.isDone()); assertFalse(timeoutFuture.isCancelled()); assertFailure(() -> rootFuture.get(10, SECONDS), e -> assertInstanceOf(e, CancellationException.class)); assertTrue(rootFuture.isDone()); assertTrue(rootFuture.isCancelled()); }</code><technical_language>orElse("failed")</technical_language>

Target:
public void testListenableTimeout() throws Exception { SettableFuture<String> rootFuture = SettableFuture.create(); ListenableFuture<String> timeoutFuture = addTimeout(rootFuture, () -> "timeout", new Duration(0, MILLISECONDS), executorService); assertEquals(tryGetFutureValue(timeoutFuture, 10, SECONDS).orElse("failed"), "timeout"); assertTrue(timeoutFuture.isDone()); assertFalse(timeoutFuture.isCancelled()); assertFailure(() -> rootFuture.get(10, SECONDS), e -> assertInstanceOf(e, CancellationException.class)); assertTrue(rootFuture.isDone()); assertTrue(rootFuture.isCancelled()); }
Source:
<code>private static void unpackFace(File outputDirectory) throws IOException { <START> ClassLoader loader = Thread.currentThread().getContextClassLoader(); <END> for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) { Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName()); if (matcher.find()) { String resourcePath = matcher.group(1); File dest = new File(outputDirectory, resourcePath); Files.createParentDirs(dest); try (FileOutputStream output = new FileOutputStream(dest); InputStream input = info.url().openStream()) { IOUtils.copy(input, output); LOGGER.debug("{} successfully copied.", resourcePath); } } } }</code><technical_language>In case need AllureMain.class.getClassLoader(). resource I need unpack is located in allure-bundle.jar, ClassLoader loaded AllureMain</technical_language>

Target:
private static void unpackFace(File outputDirectory) throws IOException { ClassLoader loader = AllureMain.class.getClassLoader(); for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) { Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName()); if (matcher.find()) { String resourcePath = matcher.group(1); File dest = new File(outputDirectory, resourcePath); Files.createParentDirs(dest); try (FileOutputStream output = new FileOutputStream(dest); InputStream input = info.url().openStream()) { IOUtils.copy(input, output); LOGGER.debug("{} successfully copied.", resourcePath); } } } }
Source:
<code>public List<ASTAnnotation> getDeclaredAnnotations() { List<ASTAnnotation> result = new ArrayList<>(); ASTClassOrInterfaceBodyDeclaration decl = ((ASTClassOrInterfaceBodyDeclaration) jjtGetParent()); for (int i = 0; i < decl.jjtGetNumChildren() - 1; i++) { if (!(decl.jjtGetChild(i) instanceof ASTAnnotation)) { <START> break; <END> } result.add((ASTAnnotation) decl.jjtGetChild(i)); } return result; }</code><technical_language>this assumes annotations children modifiers, false. public @Override static @PostConstruct void foo() { } is completely valid Java code</technical_language>

Target:
public List<ASTAnnotation> getDeclaredAnnotations() { return this.jjtGetParent().findChildrenOfType(ASTAnnotation.class); }
Source:
<code>public static void apply(Editable editable, int oldCursorPosition, int newCursorPosition) { if (!isValidCursorIncrement(oldCursorPosition, newCursorPosition)) { return; } String noteContent = editable.toString(); String prevChar = noteContent.substring(newCursorPosition - 1, newCursorPosition); if (prevChar.equals(STR_LINE_BREAK)) { int prevParagraphEnd = newCursorPosition - 1; int prevParagraphStart = noteContent.lastIndexOf(STR_LINE_BREAK, prevParagraphEnd - 1); prevParagraphStart++; String prevParagraph = noteContent.substring(prevParagraphStart, prevParagraphEnd); BulletMetadata metadata = extractBulletMetadata(prevParagraph); CheckableSpan[] checkableSpans = editable.getSpans(prevParagraphStart, prevParagraphStart + 1, CheckableSpan.class); if (checkableSpans.length > 0) { if (prevParagraph.equals(STR_SPACE + STR_SPACE)) { <START> editable.replace(prevParagraphStart, newCursorPosition, STR_LINE_BREAK); <END> } else { editable.insert(newCursorPosition, ChecklistUtils.UNCHECKED_MARKDOWN + STR_SPACE); } return; } if (metadata.isBullet) { String bullet; if (!metadata.isEmptyBullet) { bullet = buildBullet(metadata); editable.insert(newCursorPosition, bullet); } else { if (metadata.numSpacesPrefixed > 0) { metadata.numSpacesPrefixed -= 1; bullet = buildBullet(metadata); } else { bullet = STR_LINE_BREAK; } editable.replace(prevParagraphStart, newCursorPosition, bullet); } } } }</code><technical_language>Tapping enter empty checkbox line removes checkbox expected moves cursor next line, I expecting first. I thought cursor remain line, I noticed cursor moves next line tapping enter empty bullet list well. move next line stay line? I noticed some awesome apps (e.g. WordPress for Android/iOS) some stock apps (e.g. Notes for iOS) stay line</technical_language>

Target:
public static void apply(Editable editable, int oldCursorPosition, int newCursorPosition) { if (!isValidCursorIncrement(oldCursorPosition, newCursorPosition)) { return; } String noteContent = editable.toString(); String prevChar = noteContent.substring(newCursorPosition - 1, newCursorPosition); if (prevChar.equals(STR_LINE_BREAK)) { int prevParagraphEnd = newCursorPosition - 1; int prevParagraphStart = noteContent.lastIndexOf(STR_LINE_BREAK, prevParagraphEnd - 1); prevParagraphStart++; String prevParagraph = noteContent.substring(prevParagraphStart, prevParagraphEnd); BulletMetadata metadata = extractBulletMetadata(prevParagraph); CheckableSpan[] checkableSpans = editable.getSpans(prevParagraphStart, prevParagraphStart + 1, CheckableSpan.class); if (checkableSpans.length > 0) { if (prevParagraph.equals(STR_SPACE + STR_SPACE)) { editable.replace(prevParagraphStart, newCursorPosition, ""); } else { editable.insert(newCursorPosition, ChecklistUtils.UNCHECKED_MARKDOWN + STR_SPACE); } return; } if (metadata.isBullet) { String bullet; if (!metadata.isEmptyBullet) { bullet = buildBullet(metadata); editable.insert(newCursorPosition, bullet); } else { if (metadata.numSpacesPrefixed > 0) { metadata.numSpacesPrefixed -= 1; bullet = buildBullet(metadata); } else { bullet = ""; } editable.replace(prevParagraphStart, newCursorPosition, bullet); } } } }
Source:
<code>public ActivityLogEntry(AppLogLine appLog){ time = appLog.getTimeUsec() / 1000; String[] tokens = appLog.getLogMessage().split("\\|\\|\\|", -1); try{ servletName = tokens[1]; action = tokens[2]; toShow = (tokens[3].equals("true") ? true : false); role = tokens[4]; name = tokens[5]; googleId = tokens[6]; email = tokens[7]; message = tokens[8]; url = tokens[9]; if (tokens.length >= 11) { boolean isLogId = tokens[10].contains(googleId) || tokens[10].contains("%"); if (isLogId) { id = tokens[10]; timeTaken = tokens.length == 12 ? Long.parseLong(tokens[11].trim()) : null; } else { timeTaken = Long.parseLong(tokens[10].trim()); <START> } <END> } keyStringsToHighlight = null; } catch (ArrayIndexOutOfBoundsException e){ servletName = "Unknown"; action = "Unknown"; role = "Unknown"; name = "Unknown"; googleId = "Unknown"; email = "Unknown"; toShow = true; message = "<span class=\"text-danger\">Error. Problem parsing log message from the server.</span><br>" + "System Error: " + e.getMessage() + "<br>" + appLog.getLogMessage(); url = "Unknown"; id = "Unknown" + formatTimeForId(new Date(time)); timeTaken = null; keyStringsToHighlight = null; } logInfoAsHtml = getLogInfoForTableRowAsHtml(); }</code><technical_language>Extract try catch blocks separate methods? a rule of thumb, try constructors simple. Similarly, if this if statement extracted out</technical_language>

Target:
public ActivityLogEntry(AppLogLine appLog){ time = appLog.getTimeUsec() / 1000; try { String[] tokens = appLog.getLogMessage().split("\\|\\|\\|", -1); initUsingAppLogMessage(tokens); } catch (ArrayIndexOutOfBoundsException e) { initAsFailure(appLog, e); } keyStringsToHighlight = null; logInfoAsHtml = getLogInfoForTableRowAsHtml(); }
Source:
<code><START> public Class<MongoCodeListEntry> getEntryType() { <END> return MongoCodeListEntry.class; }</code><technical_language>s.a</technical_language>

Target:
protected Class<MongoCodeListEntry> getEntryType() { return MongoCodeListEntry.class; }
Source:
<code>public static Pair<String, Map<String, String>> formatWithAttributes(String messageTemplate, Object... args) { if (messageTemplate == null) { return formatWithAttributes("", args); } if (args == null) { return formatWithAttributes(messageTemplate, new Object[0]); } StringBuilder outputStringBuilder = new StringBuilder(messageTemplate.length() + args.length * 20); ImmutableMap.Builder<String, String> attributesMap = ImmutableMap.builder(); String pattern = "\\{(\\w+)\\}"; Pattern regexPattern = Pattern.compile(pattern); Matcher matcher = regexPattern.matcher(messageTemplate); int groupIndex = 0; int lastAddedStringEndIndex = 0; int matchesCount = 0; while (matcher.find()) { matchesCount++; } if (matchesCount > args.length) { throw new IllegalArgumentException( Messages.format("You have included placeholders, however only provided arguments.", matchesCount, args.length)); } matcher.reset(); <START> while (matcher.find()) { <END> String attributeName = matcher.group(1); int startIndex = matcher.start(); int endIndex = matcher.end(); String replacement = args[groupIndex].toString(); attributesMap.put(attributeName, replacement); String unmodifiedText = messageTemplate.substring(lastAddedStringEndIndex, startIndex); outputStringBuilder .append(unmodifiedText) .append(replacement); lastAddedStringEndIndex = endIndex; groupIndex++; } if(lastAddedStringEndIndex < messageTemplate.length()) { outputStringBuilder.append(messageTemplate.substring(lastAddedStringEndIndex, messageTemplate.length())); } return Pair.of(outputStringBuilder.toString(), attributesMap.build()); }</code><technical_language>Matcher.appendReplacement() simplify this? <LINK_0></technical_language>

Target:
public static Pair<String, Map<String, String>> formatWithAttributes(String messageTemplate, Object... args) { if (messageTemplate == null) { return formatWithAttributes("", args); } if (args == null) { return formatWithAttributes(messageTemplate); } Map<String, String> attributes = new HashMap<>(); Matcher matcher = REGEX_PATTERN.matcher(messageTemplate); int argIndex = 0; StringBuffer outputMessageBuffer = new StringBuffer(); while (matcher.find()) { if (argIndex >= args.length) { continue; } String attributeName = matcher.group(1); String replacement = args[argIndex].toString().replace("$", "\\$"); matcher.appendReplacement(outputMessageBuffer, replacement); if (!attributeName.isEmpty()) { attributes.put(attributeName, replacement); } argIndex++; } matcher.appendTail(outputMessageBuffer); return Pair.of(outputMessageBuffer.toString(), ImmutableMap.copyOf(attributes)); }
Source:
<code>public PortPairsOperation(OperationLogger logger, String portPairs) { this(logger, new ArrayList<Pair<String, String>>()); <START> for (String pair : portPairs.split("[\n\r]+")) { <END> String[] pairLine = pair.split("[\\s,]+"); this.portPairs.add(new Pair<String, String>(pairLine[0], pairLine[1])); } }</code><technical_language>\n \r supposed doubly escaped \\s below? splitting based java platform line delimiter instead of assuming DOS/Windows</technical_language>

Target:
public PortPairsOperation(OperationLogger logger, String portPairs) throws OseeArgumentException { this(logger, new ArrayList<Pair<String, String>>()); for (String pair : portPairs.split("[\n\r]+")) { String[] pairLine = pair.split("[\\s,]+"); if (pairLine.length != 2) { throw new OseeArgumentException("Invalid porting pairs"); } this.portPairs.add(new Pair<String, String>(pairLine[0], pairLine[1])); } }
Source:
<code>public void getRelatedNoResult() throws Exception { PushOneCommit push = pushFactory.create(db, admin.getIdent()); PatchSet.Id ps = push.to(git, "refs/for/master").getPatchSetId(); List<ChangeAndCommit> related = getRelated(ps); <START> assertThat(related.size()).isEqualTo(0); <END> }</code><technical_language>assertThat(related).isEmpty();</technical_language>

Target:
public void getRelatedNoResult() throws Exception { PushOneCommit push = pushFactory.create(db, admin.getIdent()); PatchSet.Id ps = push.to(git, "refs/for/master").getPatchSetId(); List<ChangeAndCommit> related = getRelated(ps); assertThat(related).isEmpty(); }
Source:
<code>ApplicationPresenter( <START> EventBus eventBus, <END> MyView view, MyProxy proxy, PlaceManager placeManager) { super(eventBus, view, proxy, RevealType.Root); this.placeManager = placeManager; }</code><technical_language>line 61 line 60 align parentheses in ArcBees's projects</technical_language>

Target:
ApplicationPresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager) { super(eventBus, view, proxy, RevealType.Root); this.placeManager = placeManager; getView().setUiHandlers(this); }