auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<UserDto> getAllUsersSortedByLastName() { try { final Criteria criteria = this.getSession().createCriteria(WorkbenchUser.class); criteria.createAlias("person", "person", CriteriaSpecification.LEFT_JOIN); criteria.createAlias("person.crops", "crops", CriteriaSpecification.LEFT_JOIN); criteria.addOrder(Order.asc("person.lastName")); criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); final List<WorkbenchUser> workbenchUsers = criteria.list(); final List<UserDto> users = new ArrayList<>(); if (workbenchUsers != null) { for (final WorkbenchUser workbenchUser : workbenchUsers) { final UserDto user = new UserDto(); if (workbenchUser.getRoles() != null && !workbenchUser.getRoles().isEmpty()) { user.setUserRoles(UserRoleMapper.map(workbenchUser.getRoles())); } user.setUserId(workbenchUser.getUserid()); if (workbenchUser.getPerson() != null) { user.setEmail(workbenchUser.getPerson().getEmail()); user.setFirstName(workbenchUser.getPerson().getFirstName()); user.setLastName(workbenchUser.getPerson().getLastName()); if (workbenchUser.getPerson().getCrops() != null) { final Set<CropDto> crops = new HashSet<>(); <START> for (final CropType cropType : workbenchUser.getPerson().getCrops()) { <END> final CropDto crop = new CropDto(); crop.setCropName(cropType.getCropName()); crops.add(crop); } user.setCrops(crops); } } user.setStatus(workbenchUser.getStatus()); user.setUsername(workbenchUser.getName()); users.add(user); } } return users; } catch (final HibernateException e) { final String message = "Error with getAllUserDtosSorted() query from User: " + e.getMessage(); WorkbenchUserDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } }</code><technical_language>create CropMapper class this code follow pattern of UserRoleMapper RoleMapper classes</technical_language>

Target:
public List<UserDto> getAllUsersSortedByLastName() { try { final Criteria criteria = this.getSession().createCriteria(WorkbenchUser.class); criteria.createAlias("person", "person", CriteriaSpecification.LEFT_JOIN); criteria.createAlias("person.crops", "crops", CriteriaSpecification.LEFT_JOIN); criteria.addOrder(Order.asc("person.lastName")); criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); final List<WorkbenchUser> workbenchUsers = criteria.list(); final List<UserDto> users = new ArrayList<>(); if (workbenchUsers != null) { for (final WorkbenchUser workbenchUser : workbenchUsers) { users.add(new UserDto(workbenchUser)); } } return users; } catch (final HibernateException e) { final String message = "Error with getAllUserDtosSorted() query from User: " + e.getMessage(); WorkbenchUserDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } }
Source:
<code>public Set<String> getWriteScopes() { <START> return writeScopes; <END> }</code><technical_language>I a step immutability wrapped Collections.unmodifiableSet(...) for getReadScopes</technical_language>

Target:
public Set<String> getWriteScopes() { return Collections.unmodifiableSet(writeScopes); }
Source:
<code>protected void persist(final StepContribution contribution, final Chunk<O> chunk) throws Exception { RetryCallback<Object> retryCallback = new RetryCallback<Object>() { @Override @SuppressWarnings("unchecked") public Object doWithRetry(RetryContext context) throws Exception { chunkMonitor.setChunkSize(chunk.size()); try { doPersist(contribution, chunk); } catch (Exception e) { if (shouldSkip(skipPolicy, e, contribution.getStepSkipCount())) { for (O item : chunk.getItems()) { getListener().onSkipInWrite(item, e); <START> } <END> } else { getListener().onRetryWriteException((List<Object>) chunk.getItems(), e); if (rollbackClassifier.classify(e)) { throw e; } } throw new ForceRollbackForWriteSkipException( "Force rollback on skippable exception so that skipped item can be located.", e); } contribution.incrementWriteCount(chunk.size()); return null; } }; RecoveryCallback<Object> recoveryCallback = new RecoveryCallback<Object>() { @Override public O recover(RetryContext context) throws Exception { Throwable e = context.getLastThrowable(); if (shouldSkip(skipPolicy, e, contribution.getStepSkipCount())) { contribution.incrementWriteSkipCount(); logger.debug("Skipping after failed write", e); return null; } else { if (rollbackClassifier.classify(e)) { throw new RetryException("Non-skippable exception in recoverer while write", e); } return null; } } }; batchRetryTemplate.execute(retryCallback, recoveryCallback); }</code><technical_language>section 9.2.7 of JSR-352, SkipListener receive item receives items chunk. previous code correct</technical_language>

Target:
protected void persist(final StepContribution contribution, final Chunk<O> chunk) throws Exception { RetryCallback<Object> retryCallback = new RetryCallback<Object>() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Object doWithRetry(RetryContext context) throws Exception { chunkMonitor.setChunkSize(chunk.size()); try { doPersist(contribution, chunk); } catch (Exception e) { if (shouldSkip(skipPolicy, e, contribution.getStepSkipCount())) { ((MulticasterBatchListener) getListener()).onSkipInWrite(chunk.getItems(), e); } else { getListener().onRetryWriteException((List<Object>) chunk.getItems(), e); if (rollbackClassifier.classify(e)) { throw e; } } throw new ForceRollbackForWriteSkipException( "Force rollback on skippable exception so that skipped item can be located.", e); } contribution.incrementWriteCount(chunk.size()); return null; } }; RecoveryCallback<Object> recoveryCallback = new RecoveryCallback<Object>() { @Override public O recover(RetryContext context) throws Exception { Throwable e = context.getLastThrowable(); if (shouldSkip(skipPolicy, e, contribution.getStepSkipCount())) { contribution.incrementWriteSkipCount(); logger.debug("Skipping after failed write", e); return null; } else { if (rollbackClassifier.classify(e)) { throw new RetryException("Non-skippable exception in recoverer while write", e); } return null; } } }; batchRetryTemplate.execute(retryCallback, recoveryCallback); }
Source:
<code>public boolean isCompiletimeEvaluable() { <START> return true; <END> }</code><technical_language>I defer value's isCompiletimeEvaluable method -- for example, types literals "runtime evaluable"</technical_language>

Target:
public boolean isCompiletimeEvaluable() { return value.isCompiletimeEvaluable(); }
Source:
<code>public Image apply(@Nullable VirtualMachine from) { if (from == null || from.getConfig() == null) { OperatingSystem os = OperatingSystem.builder().description("null").family(OsFamily.UNRECOGNIZED) .version("null").is64Bit(true).arch("null").build(); return new ImageBuilder() .id("null") .name("null") .description("null") .operatingSystem(os).status(toPortableImageStatus.get(from.getRuntime().getPowerState())) <START> .build(); <END> } String guestFamily = from.getConfig().getGuestId(); String annotation = from.getConfig().getAnnotation(); OsFamily family = parseOsFamilyOrUnrecognized(annotation); String version = parseVersionOrReturnEmptyString(family, annotation, osVersionMap); OperatingSystem os = OperatingSystem.builder().description(annotation).family(family) .version(version).is64Bit(true).arch("x86_64").build(); return new ImageBuilder() .id(from.getName()) .name(from.getName()) .description(from.getName()) .operatingSystem(os).status(toPortableImageStatus.get(from.getRuntime().getPowerState())) .build(); }</code><technical_language>Is this "fake null image" used</technical_language>

Target:
public Image apply(@Nullable VirtualMachine from) { if (from == null || from.getConfig() == null) { OperatingSystem os = OperatingSystem.builder().description("null").family(OsFamily.UNRECOGNIZED) .version("null").is64Bit(true).arch("null").build(); return new ImageBuilder() .id("null") .name("null") .description("null") .operatingSystem(os).status(toPortableImageStatus.get(from.getRuntime().getPowerState())) .build(); } String guestFamily = from.getConfig().getGuestId(); String annotation = from.getConfig().getAnnotation(); OsFamily family = annotation == null ? OsFamily.UNRECOGNIZED : parseOsFamilyOrUnrecognized(annotation); String description = annotation == null ? guestFamily : annotation; String version = parseVersionOrReturnEmptyString(family, annotation, osVersionMap); OperatingSystem os = OperatingSystem.builder().description(description).family(family) .version(version).is64Bit(true).arch("x86_64").build(); return new ImageBuilder() .id(from.getName()) .name(from.getName()) .description(from.getName()) .operatingSystem(os).status(toPortableImageStatus.get(from.getRuntime().getPowerState())) .build(); }
Source:
<code><START> public Double getPriority() { <END> return getValueAsDouble("priority", Double.MAX_VALUE); }</code><technical_language>This effectively mirrors TabOptions#getPriority convention. However, places (like in PluginUiFunctions), code options.getPriority().intValue() fail if UI plugins decimal values 1.23 etc. code fixed, effectively limiting TabOptions#getPriority integer precision</technical_language>

Target:
public Integer getPriority() { return getValueAsInteger("priority", Integer.MAX_VALUE); }
Source:
<code>private QueryRequest getQueryRequest() throws IOException { QueryRequest queryRequest = null; if (request.method() == HttpMethod.GET) { <START> String queryString = getParameterValue(QUERY_STRING); <END> String strOffset = getParameterValue(OFFSET); String queryMode = getParameterValue(QUERY_MODE); Integer offset = strOffset != null ? Integer.valueOf(strOffset) : null; String strMaxResults = getParameterValue(MAX_RESULTS); Integer maxResults = strMaxResults != null ? Integer.valueOf(strMaxResults) : null; IndexedQueryMode qm = queryMode == null ? IndexedQueryMode.FETCH : IndexedQueryMode.valueOf(queryMode); queryRequest = new QueryRequest(queryString, offset, maxResults, qm); } else if (request.method() == HttpMethod.POST || request.method() == HttpMethod.PUT) { queryRequest = getQueryFromJSON(); } return queryRequest; }</code><technical_language>body of this ifstatement if extracted a separate getQueryFromString method in spirit of getQueryFromJSON</technical_language>

Target:
private QueryRequest getQueryRequest() throws IOException { QueryRequest queryRequest = null; if (request.method() == HttpMethod.GET) { queryRequest = getQueryFromString(); } else if (request.method() == HttpMethod.POST || request.method() == HttpMethod.PUT) { queryRequest = getQueryFromJSON(); } return queryRequest; }
Source:
<code>public final Object doResolveAfter(final VirtualFrame frame, final SResolver resolver, final long timeout) { <START> Timer t = new Timer(); <END> t.schedule(new TimerTask() { @Override public void run() { resolvePromise(frame, resolver, true, false); } }, timeout); return true; }</code><technical_language>this one. I think, I change merging a field of node. a static field. want a separate timer thread for time out :)</technical_language>

Target:
public final Object doResolveAfter(final VirtualFrame frame, final SResolver resolver, final long timeout) { if (timerThread == null) { timerThread = new Timer(); } timerThread.schedule(new TimerTask() { @Override public void run() { ResolvePromiseNode.resolve(wrapper, resolver.getPromise(), true, resolver.getPromise().getOwner(), false); } }, timeout); return true; }
Source:
<code>public String publish(ArtifactId templateArtId, ArtifactId headArtId) { ArtifactReadable artifact = getArtifactHead(headArtId); String template = setUpTemplateWithOptions(templateArtId); <START> <END> if (!artifact.equals(ArtifactReadable.SENTINEL)) { if (!template.equals("") && elementType.equals(ARTIFACT)) { StringBuilder wordMlOutput = applyContentToTemplate(artifact, template); return wordMlOutput.toString(); } else { return null; } } else { return null; } }</code><technical_language>artifact.isInValid() instead of ! equals</technical_language>

Target:
public String publish(ArtifactId templateArtId, ArtifactId headArtId) { ArtifactReadable artifact = getArtifactHead(headArtId); String template = setUpTemplateWithOptions(templateArtId); if (artifact.isValid()) { if (Strings.isValid(template) && elementType.equals(ARTIFACT)) { StringBuilder wordMlOutput = applyContentToTemplate(artifact, template); return wordMlOutput.toString(); } else { return null; } } else { return null; } }
Source:
<code>SymbolMapper getCorrelatedSymbolMapper() { return new SymbolMapper(correlatedSymbolsMapping.asMap().entrySet().stream() <START> .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, symbols -> Iterables.getLast(symbols.getValue())))); <END> }</code><technical_language>static import</technical_language>

Target:
SymbolMapper getCorrelatedSymbolMapper() { return new SymbolMapper(correlatedSymbolsMapping.asMap().entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, symbols -> Iterables.getLast(symbols.getValue())))); }
Source:
<code>Location getLocation() { <START> return new TypeInInputLibraryLocation(inputJackLibrary.getLocation(), <END> Jack.getUserFriendlyFormatter().getName(enclosingPackage, simpleName)); }</code><technical_language>Cache in field</technical_language>

Target:
Location getLocation() { return location; }
Source:
<code>private void writeTimeGrainHoursHeaders() { for (TimeGrain timeGrain : solution.getTimeGrainList()) { LocalTime startTime = LocalTime.ofSecondOfDay(timeGrain.getStartingMinuteOfDay() * 60); <START> LocalTime endTime = LocalTime.ofSecondOfDay( <END> (timeGrain.getStartingMinuteOfDay() + timeGrain.GRAIN_LENGTH_IN_MINUTES) * 60); nextHeaderCell(TIME_FORMATTER.format(startTime)); } }</code><technical_language>This variable is unused. a bug useless code</technical_language>

Target:
private void writeTimeGrainHoursHeaders() { for (TimeGrain timeGrain : solution.getTimeGrainList()) { LocalTime startTime = LocalTime.ofSecondOfDay(timeGrain.getStartingMinuteOfDay() * 60); nextHeaderCell(TIME_FORMATTER.format(startTime)); } }
Source:
<code>public void testGridSetLoading() throws Exception { GWC gwc = GWC.get(); int waited = 0; <START> while(waited <= 30000 && GWC.get().getGridSetBroker().get(INSPIRE_GRID_SET_NAME) == null) { <END> Thread.sleep(100); waited += 100; } assertThat(gwc.getGridSetBroker().get(INSPIRE_GRID_SET_NAME), notNullValue()); assertThat(gwc.isInternalGridSet(INSPIRE_GRID_SET_NAME), is(true)); }</code><technical_language>Confused, do wait, context loaded notifications happening in a background thread? time method is run full initialization happened not</technical_language>

Target:
public void testGridSetLoading() throws Exception { GWC gwc = GWC.get(); assertThat(gwc.getGridSetBroker().get(INSPIRE_GRID_SET_NAME), notNullValue()); assertThat(gwc.isInternalGridSet(INSPIRE_GRID_SET_NAME), is(true)); }
Source:
<code>public Function<String, String> from1_1to1_2() { <START> return rawXml -> rawXml.replaceAll("</simulationDescriptor>", "<dmoSession></dmoSession>\n<type>RULE</type>\n</simulationDescriptor>").replaceAll("<ScenarioSimulationModel version=\"1.1\">", "<ScenarioSimulationModel version=\"1.2\">"); <END> }</code><technical_language>I implement migration strategy idempotent, moment if (for reason) called multiple times add missing nodes time, implement if skip if available. WDYT</technical_language>

Target:
public Function<String, String> from1_1to1_2() { return rawXml -> { if ((rawXml.contains("<dmoSession>") || (rawXml.contains("<dmnFilePath>")) && (rawXml.contains("<type>")))) { return rawXml.replaceAll("<ScenarioSimulationModel version=\"1.1\">", "<ScenarioSimulationModel version=\"1.2\">"); } else { return rawXml.replaceAll("</simulationDescriptor>", "<dmoSession></dmoSession>\n<type>RULE</type>\n</simulationDescriptor>").replaceAll("<ScenarioSimulationModel version=\"1.1\">", "<ScenarioSimulationModel version=\"1.2\">"); } }; }
Source:
<code>static boolean looselyMatches(URI notifyUri, String repository) { boolean result = false; try { URI repositoryUri = new URI(repository); <START> result = Objects.equal(getScheme(notifyUri), getScheme(repositoryUri)) <END> && Objects.equal(notifyUri.getHost(), repositoryUri.getHost()) && getPort(notifyUri) == getPort(repositoryUri) && Objects.equal(notifyUri.getPath(), repositoryUri.getPath()) && Objects.equal(notifyUri.getQuery(), repositoryUri.getQuery()); } catch ( URISyntaxException ex ) { LOGGER.log(Level.SEVERE, "could not parse repository uri " + repository, ex); } return result; }</code><technical_language>need Objects.equal more: .equals(</technical_language>

Target:
static boolean looselyMatches(URI notifyUri, String repository) { boolean result = false; try { URI repositoryUri = new URI(repository); result = getScheme(notifyUri).equals(getScheme(repositoryUri)) && Objects.equal(notifyUri.getHost(), repositoryUri.getHost()) && getPort(notifyUri) == getPort(repositoryUri) && Objects.equal(notifyUri.getPath(), repositoryUri.getPath()) && Objects.equal(notifyUri.getQuery(), repositoryUri.getQuery()); } catch ( URISyntaxException ex ) { LOGGER.log(Level.SEVERE, "could not parse repository uri " + repository, ex); } return result; }
Source:
<code>protected void onPostExecute(List<SetupConfiguration> setupConfigurations){ if(setupConfigurations == null){ <START> Toast.makeText(getContext(), "Setup configurations could not be loaded", Toast.LENGTH_SHORT).show(); <END> return; } allSetupConfigurations = setupConfigurations; SetupConfigurationAdapter.this.clear(); addAll(setupConfigurations); notifyDataSetChanged(); if (backgroundListQueryTaskListener != null) { backgroundListQueryTaskListener.onQueryTaskFinish(); } }</code><technical_language>Need extract this for localisation</technical_language>

Target:
protected void onPostExecute(List<SetupConfiguration> setupConfigurations){ if(setupConfigurations == null){ Toast.makeText(getContext(), R.string.error_setup_configuration_download, Toast.LENGTH_SHORT).show(); return; } allSetupConfigurations = setupConfigurations; SetupConfigurationAdapter.this.clear(); addAll(setupConfigurations); notifyDataSetChanged(); if (backgroundListQueryTaskListener != null) { backgroundListQueryTaskListener.onQueryTaskFinish(); } }
Source:
<code>public Chain get(long key) { EhcacheEntityResponse response; try { response = entity.invoke(messageFactory.getOperation(key), false); } catch (Exception e) { throw new ServerStoreProxyException(e); } if (response != null && response.getType() == EhcacheEntityResponse.Type.GET_RESPONSE) { return ((EhcacheEntityResponse.GetResponse)response).getChain(); } else { throw new ServerStoreProxyException("Response for get operation was invalid : " + <START> response != null ? response.getType().toString() : "null message"); <END> } }</code><technical_language>wrong - fixed in master in ServerStoreProxy fix needs applied here</technical_language>

Target:
public Chain get(long key) { EhcacheEntityResponse response; try { response = entity.invoke(messageFactory.getOperation(key), false); } catch (Exception e) { throw new ServerStoreProxyException(e); } if (response != null && response.getType() == EhcacheEntityResponse.Type.GET_RESPONSE) { return ((EhcacheEntityResponse.GetResponse)response).getChain(); } else { throw new ServerStoreProxyException("Response for get operation was invalid : " + (response != null ? response.getType().toString() : "null message")); } }
Source:
<code><START> public void testUpdateNoNetworkWithPortMirroringNetwork() throws Exception { <END> setUriInfo(setUpBasicUriExpectations()); control.replay(); NIC nic = getNic(false); nic.setNetwork(new Network()); nic = resource.update(nic); assertNotNull(nic); }</code><technical_language>this test is about? fail? validate content of WebApplicationException</technical_language>

Target:
public void testUpdateNoNetworkWithPortMirroringNetwork() throws Exception { try { setUriInfo(setUpBasicUriExpectations()); control.replay(); NIC nic = getNic(false); nic.setNetwork(new Network()); nic = resource.update(nic); fail("expected WebApplicationException"); } catch (WebApplicationException wae) { assertEquals(400, wae.getResponse().getStatus()); assertEquals("Cannot set port mirroring if there is no network on the NIC", ((Fault) wae.getResponse().getEntity()).getReason()); } }
Source:
<code><START> public void <END> invoke(String... parameters) { CmdLineParser parser = new CmdLineParser(this); try { try { parser.parseArgument(parameters); if (inputFiles.isEmpty()) { throw new CmdLineException(parser, "asciidoctor: FAILED: input file missing"); } } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); return; } Options options = parse(); ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile)); for (String inputFile : inputFiles) { String output = renderInput(options, inputFile); zip.putNextEntry(new ZipEntry(mapInFileToOutFile(inputFile))); zip.write(output.getBytes()); zip.closeEntry(); } zip.close(); } catch (java.io.IOException e) { System.err.println(e.getMessage()); } }</code><technical_language>private, main calls</technical_language>

Target:
private void invoke(String... parameters) { CmdLineParser parser = new CmdLineParser(this); try { try { parser.parseArgument(parameters); if (inputFiles.isEmpty()) { throw new CmdLineException(parser, "asciidoctor: FAILED: input file missing"); } } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.exit(1); return; } ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile)); byte[] buf = new byte[BUFSIZ]; for (String inputFile : inputFiles) { Options options = createOptions(inputFile); renderInput(options, inputFile); FileInputStream f = new FileInputStream(new File(mapInFileToOutFileWithDir(inputFile))); int len; zip.putNextEntry(new ZipEntry(mapInFileToOutFile(inputFile))); while ((len = f.read(buf)) > 0) { zip.write(buf, 0, len); } f.close(); zip.closeEntry(); } zip.close(); } catch (java.io.IOException e) { System.err.println(e.getMessage()); System.exit(1); } }
Source:
<code>public void initialize() { GatewayConfig configuration = getConfigAs(GatewayConfig.class); if (isConfigurationValid(configuration)) { <START> scheduler.schedule(new Runnable() { <END> @Override public void run() { try { setupGateway(configuration); } catch (final Throwable t) { logger.error("An unexpected error occurred: {}", t.getMessage(), t); } } }, 0, TimeUnit.SECONDS); } }</code><technical_language>Java8 syntax here? (schedule(() -> {... }, 0, TimeUnit.SECONDS);)</technical_language>

Target:
public void initialize() { GatewayConfig configuration = getConfigAs(GatewayConfig.class); if (configuration.host == null || configuration.host.isEmpty()) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Host must be specified in the configuration!"); return; } if (configuration.code == null || configuration.code.isEmpty()) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Security code must be provided in the configuration!"); return; } this.gatewayURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + DEVICES; this.gatewayInfoURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + GATEWAY + "/" + GATEWAY_DETAILS; try { URI uri = new URI(gatewayURI); deviceClient = new TradfriCoapClient(uri); } catch (URISyntaxException e) { logger.debug("Illegal gateway URI `{}`: {}", gatewayURI, e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage()); return; } DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0)); builder.setPskStore(new StaticPskStore("", configuration.code.getBytes())); dtlsConnector = new DTLSConnector(builder.build()); endPoint = new CoapEndpoint(dtlsConnector, NetworkConfig.getStandard()); deviceClient.setEndpoint(endPoint); updateStatus(ThingStatus.UNKNOWN); scanJob = scheduler.scheduleWithFixedDelay(() -> { startScan(); }, 0, 1, TimeUnit.MINUTES); }
Source:
<code>public void dropSegment(DataSegment segment, LoadPeonCallback callback) { synchronized (lock) { if (stopped) { log.warn( <START> "Server[%s] failed to drop segment[%s] because load queue peon is stopped.", <END> serverId, segment.getIdentifier() ); callback.execute(); return; } SegmentHolder holder = segmentsToDrop.get(segment); if (holder == null) { log.info("Server[%s] to drop segment[%s] queued.", serverId, segment.getIdentifier()); segmentsToDrop.put(segment, new DropSegmentHolder(segment, callback)); processingExecutor.execute(this::doSegmentManagement); } else { holder.addCallback(callback); } } }</code><technical_language>Instead of "failed drop", "cannot drop" is a log message</technical_language>

Target:
public void dropSegment(DataSegment segment, LoadPeonCallback callback) { synchronized (lock) { if (stopped) { log.warn( "Server[%s] cannot drop segment[%s] because load queue peon is stopped.", serverId, segment.getIdentifier() ); callback.execute(); return; } SegmentHolder holder = segmentsToDrop.get(segment); if (holder == null) { log.info("Server[%s] to drop segment[%s] queued.", serverId, segment.getIdentifier()); segmentsToDrop.put(segment, new DropSegmentHolder(segment, callback)); processingExecutor.execute(this::doSegmentManagement); } else { holder.addCallback(callback); } } }
Source:
<code>int getToWeight(int landmarkIndex, int node) { int res = landmarkWeightDA.getInt((long) node * LM_ROW_LENGTH + landmarkIndex * 4); <START> int from = res & FROM_WEIGHT_INF; <END> int delta = res >> FROM_WEIGHT_BITS; if (delta == DELTA_INF) return DELTA_MAX; res = from + delta; assert res >= 0 : "Negative forward weight " + res + ", landmark index:" + landmarkIndex + ", node:" + node; return res; }</code><technical_language>This statement moved if avoid this in case of specific delta (?)</technical_language>

Target:
int getToWeight(int landmarkIndex, int node) { int res = landmarkWeightDA.getInt((long) node * LM_ROW_LENGTH + landmarkIndex * 4); int delta = res >> FROM_WEIGHT_BITS; if (delta == DELTA_INF) return Integer.MAX_VALUE; int from = res & FROM_WEIGHT_INF; if (from == FROM_WEIGHT_INF) { from = DELTA_INF + 1; } res = from + delta; assert res >= 0 : "Negative forward weight " + res + ", landmark index:" + landmarkIndex + ", node:" + node; return res; }
Source:
<code>private void recordEventWithIdAndSource(final byte eventMarker, final int eventSize, final long id, final SourceSection section, final Activity current) { ensureSufficientSpace(eventSize, current); final int start = position; put(eventMarker); putLong(id); <START> if (VmSettings.TRUFFLE_DEBUGGER_ENABLED || VmSettings.KOMPOS_TRACING) { <END> writeSourceSection(section); } assert position == start + eventSize; }</code><technical_language>Is KOMPOS_TRACING required reach code? question above</technical_language>

Target:
private void recordEventWithIdAndSource(final byte eventMarker, final int eventSize, final long id, final SourceSection section, final Activity current) { ensureSufficientSpace(eventSize, current); final int start = position; put(eventMarker); putLong(id); if (VmSettings.KOMPOS_TRACING) { writeSourceSection(section); } assert position == start + eventSize; }
Source:
<code><START> public SegmentHandoffNotifier createSegmentHandoffNotifier(String dataSource) <END> { return new SegmentHandoffNotifier() { @Override public boolean registerSegmentHandoffCallback( SegmentDescriptor descriptor, Executor exec, Runnable handOffRunnable ) { log.info("Not waiting for segment to be handed off, executing handOffRunnable"); exec.execute(handOffRunnable); return true; } @Override public void start() @Override public void close() }; }</code><technical_language>dataSource is in returned SegmentHandoffNotifier. if is intended not. If is not, cache a SegmentHandoffNotifier in a static field</technical_language>

Target:
public SegmentHandoffNotifier createSegmentHandoffNotifier(String dataSource) { return NOTIFIER; }
Source:
<code>public void onStdOut(String message) { <START> System.err.println( "onStdOut: " + message ); <END> message = message.trim(); if ( message.isEmpty() == false ) { messages.add( PodExec.CHANNEL_STDOUT+message ); } }</code><technical_language>Please replace logger... debug level? maybe</technical_language>

Target:
public void onStdOut(String message) { LOG.debug( "onStdOut: " + message ); message = message.trim(); if ( message.isEmpty() == false ) { messages.add( PodExec.CHANNEL_STDOUT+message ); } }
Source:
<code>public static int hammingDistance(final String s1, final String s2) { if (s1.length() != s2.length()) { <START> throw new IllegalArgumentException("Attempted to determine Hamming distance of strings with differing lengths."); <END> } int measuredDistance = 0; for (int i = 0;i < s1.length();i++) { if (s1.charAt(i) != s2.charAt(i)) { measuredDistance++; } } return measuredDistance; }</code><technical_language>include actual length of strings in error message easier debug happened</technical_language>

Target:
public static int hammingDistance(final String s1, final String s2) { if (s1.length() != s2.length()) { throw new IllegalArgumentException("Attempted to determine Hamming distance of strings with differing lengths. " + "The first string has length " + s1.length() + " and the second string has length " + s2.length() + "."); } int measuredDistance = 0; for (int i = 0;i < s1.length();i++) { if (s1.charAt(i) != s2.charAt(i)) { measuredDistance++; } } return measuredDistance; }
Source:
<code>public void match(final MethodNode methodNode, final IFilterOutput output) { cursor = methodNode.instructions.getFirst(); final Set<AbstractInsnNode> ignore = new HashSet<AbstractInsnNode>(); final int maskVar = Type.getMethodType(methodNode.desc) .getArgumentTypes().length - 2; while (true) { if (cursor.getOpcode() != Opcodes.ILOAD) { break; } if (((VarInsnNode) cursor).var != maskVar) { break; } next(); nextIs(Opcodes.IAND); nextIs(Opcodes.IFEQ); if (cursor == null) { return; } ignore.add(cursor); <START> cursor = instructionAfterLabel(((JumpInsnNode) cursor).label); <END> } for (AbstractInsnNode i : ignore) { output.ignore(i, i); } }</code><technical_language>If skipNonOpcodes() of base class visible this method here: cursor = ((JumpInsnNode) cursor).label; skipNonOpcodes();</technical_language>

Target:
public void match(final MethodNode methodNode, final IFilterOutput output) { cursor = methodNode.instructions.getFirst(); final Set<AbstractInsnNode> ignore = new HashSet<AbstractInsnNode>(); final int maskVar = Type.getMethodType(methodNode.desc) .getArgumentTypes().length - 2; while (true) { if (cursor.getOpcode() != Opcodes.ILOAD) { break; } if (((VarInsnNode) cursor).var != maskVar) { break; } next(); nextIs(Opcodes.IAND); nextIs(Opcodes.IFEQ); if (cursor == null) { return; } ignore.add(cursor); cursor = ((JumpInsnNode) cursor).label; skipNonOpcodes(); } for (AbstractInsnNode i : ignore) { output.ignore(i, i); } }
Source:
<code>public boolean equals(Object o) { if (o instanceof PartitionKey) { PartitionKey another = (PartitionKey) o; <START> boolean eq = ((columnName != null && another.columnName != null <END> && columnName.equals(another.columnName)) || (columnName == null && another.columnName == null)); eq = eq && ((partitionValue != null && another.partitionValue != null && partitionValue.equals(another.partitionValue)) || (partitionValue == null && another.partitionValue == null)); return eq; } return false; }</code><technical_language>TUtil.checkEquals()</technical_language>

Target:
public boolean equals(Object o) { if (o instanceof PartitionKey) { PartitionKey another = (PartitionKey) o; return TUtil.checkEquals(columnName, another.columnName) && TUtil.checkEquals(partitionValue, another.partitionValue); } return false; }
Source:
<code>public void afterSuite() throws IOException { <START> System.out.println("afterSuite " + getClass().getName()); <END> for (ObjectName mbean : _server.queryNames(null, null)) { try { _server.unregisterMBean(mbean); } catch (Exception e) { } } _baseDataAccessorMap.values().forEach(BaseDataAccessor::close); _clusterSetupMap.values().forEach(ClusterSetup::close); _helixZkClientMap.values().forEach(HelixZkClient::close); _zkServerMap.values().forEach(TestHelper::stopZkServer); System.out.println("last line"); }</code><technical_language>AfterSuite is done test classes executed. if attach class name, informative, IMHO. usage of this log</technical_language>

Target:
public void afterSuite() throws IOException { for (ObjectName mbean : _server.queryNames(null, null)) { try { _server.unregisterMBean(mbean); } catch (Exception e) { } } _baseDataAccessorMap.values().forEach(BaseDataAccessor::close); _clusterSetupMap.values().forEach(ClusterSetup::close); _helixZkClientMap.values().forEach(HelixZkClient::close); _zkServerMap.values().forEach(TestHelper::stopZkServer); }
Source:
<code>public void stripeRefund() { String externalChargeId = defaultTestCharge.getExternalChargeId(); long amount = 10L; stripeMockClient.mockCancelCharge(); ImmutableMap<String, Long> refundData = ImmutableMap.of("amount", amount, "refund_amount_available", defaultTestCharge.getAmount()); String refundPayload = new Gson().toJson(refundData); ValidatableResponse response = given().port(testContext.getPort()) .body(refundPayload) .accept(ContentType.JSON) .contentType(ContentType.JSON) .post("/v1/api/accounts/{accountId}/charges/{chargeId}/refunds" .replace("{accountId}", accountId) .replace("{chargeId}", externalChargeId)) .then() .statusCode(ACCEPTED_202); List<Map<String, Object>> refundsFoundByChargeId = databaseTestHelper.getRefundsByChargeId(defaultTestCharge.getChargeId()); assertThat(refundsFoundByChargeId.size(), is(1)); Long chargeId = databaseTestHelper.getChargeIdByExternalId(externalChargeId); assertEquals(databaseTestHelper.getChargeStatus(chargeId), CAPTURED.getValue()); String refundId = response.extract().path("refund_id"); verify(postRequestedFor(urlEqualTo("/v1/refunds")) .withHeader("Idempotency-Key", equalTo(refundId)) .withRequestBody(containing("charge=" + defaultTestCharge.getTransactionId())) <START> .withRequestBody(containing("amount=" + amount))); <END> }</code><technical_language>check for refund_application_fee reverse_transfer in payload ? if removed in next PRs. remind update payload for changes</technical_language>

Target:
public void stripeRefund() { String externalChargeId = defaultTestCharge.getExternalChargeId(); long amount = 10L; stripeMockClient.mockCancelCharge(); ImmutableMap<String, Long> refundData = ImmutableMap.of("amount", amount, "refund_amount_available", defaultTestCharge.getAmount()); String refundPayload = new Gson().toJson(refundData); ValidatableResponse response = given().port(testContext.getPort()) .body(refundPayload) .accept(ContentType.JSON) .contentType(ContentType.JSON) .post("/v1/api/accounts/{accountId}/charges/{chargeId}/refunds" .replace("{accountId}", accountId) .replace("{chargeId}", externalChargeId)) .then() .statusCode(ACCEPTED_202); List<Map<String, Object>> refundsFoundByChargeId = databaseTestHelper.getRefundsByChargeId(defaultTestCharge.getChargeId()); assertThat(refundsFoundByChargeId.size(), is(1)); Long chargeId = databaseTestHelper.getChargeIdByExternalId(externalChargeId); assertEquals(databaseTestHelper.getChargeStatus(chargeId), CAPTURED.getValue()); String refundId = response.extract().path("refund_id"); verify(postRequestedFor(urlEqualTo("/v1/refunds")) .withHeader("Idempotency-Key", equalTo(refundId)) .withRequestBody(containing("charge=" + defaultTestCharge.getTransactionId())) .withRequestBody(containing("amount=" + amount)) .withRequestBody(containing("reverse_transfer=true")) .withRequestBody(containing("refund_application_fee=true"))); }
Source:
<code>public void createTopic(final EventType eventType) throws TopicCreationException, DuplicatedEventTypeNameException { createTopic(eventType.getTopic(), calculateKafkaPartitionCount(eventType.getDefaultStatistic()), nakadiSettings.getDefaultTopicReplicaFactor(), <START> eventType.getOptions().getRetentionTime(), <END> nakadiSettings.getDefaultTopicRotationMs()); }</code><technical_language>check retentionTime for null is nullable. I understand expect null this method is called, declare nullable - check for null. If is null - I throw exception Nakadi return 500 (because wrong if null here)</technical_language>

Target:
public void createTopic(final EventType eventType) throws TopicCreationException, DuplicatedEventTypeNameException { if (eventType.getOptions().getRetentionTime() == null) { throw new IllegalArgumentException("Retention time can not be null"); } createTopic(eventType.getTopic(), calculateKafkaPartitionCount(eventType.getDefaultStatistic()), nakadiSettings.getDefaultTopicReplicaFactor(), eventType.getOptions().getRetentionTime(), nakadiSettings.getDefaultTopicRotationMs()); }
Source:
<code>public List<String> listAll(String path) { List<String> objects = new ArrayList<String>(); <START> List<String> pathParts = Splitter.on('/').splitToList(ensureTrailingSlashRemoved(path)); <END> int pathCount = pathParts.size(); for (String object : getAllObjects(ensureTrailingSlashPresent(path))) { List<String> objectParts = Splitter.on('/').splitToList(ensureTrailingSlashRemoved(object)); if (objectParts.size() == pathCount + 1) { objects.add(object); } } return objects; }</code><technical_language>Splitter.on('/').omitEmptyStrings() skip ensure.... splitter is immutable thread safe object store instance constant private statice final Splitter PATH_SPLITTER = Splitter.on('/').omitEmptyStrings()</technical_language>

Target:
public List<String> listAll(String path) { return Stream.concat(listFolders(path).stream(), listFiles(path).stream()) .collect(Collectors.toList()); }
Source:
<code>public void setDevMode(String mode) { <START> final boolean booleanMode = BooleanUtils.toBoolean(mode); <END> if (!this.devModeValueSet) { this.devMode = booleanMode; this.devModeValueSet = true; if (this.devMode) { LOG.warn("Setting development mode affects the safety of your application!", this.devMode); } } else { LOG.debug("Error setting development mode value [{}], already previously set to [{}]", mode, this.devMode); } }</code><technical_language>Why? If I remember correctly injection happen multiple times some plugins, for example, override injected properties. is some work (disallowProxyMemberAccess is of this things)</technical_language>

Target:
protected void setDevMode(String mode) { this.devMode = BooleanUtils.toBoolean(mode); if (this.devMode) { LOG.warn("Setting development mode affects the safety of your application!", this.devMode); } }
Source:
<code>private Client delegate() { long currentCount = counter.get(); if (currentCount >= exceptionCountBeforeRefresh && counter.compareAndSet(currentCount, 0)) { log.info("Creating a new Feign client, as exceptions have been thrown in a row by old client", SafeArg.of("count", currentCount)); try { currentClient = refreshingSupplier.get(); } catch (RuntimeException e) { <START> log.warn("An error occurred whilst trying to re-create an OkHttpClient, because exceptions have been thrown in a row by old client." <END> + " Continuing operation with the old client...", SafeArg.of("count", currentCount), e); } } return currentClient; }</code><technical_language>part of log message "because exceptions thrown in a row client" sound Exceptions thrown client reason a new one. delete this part of message counter is logged anyway</technical_language>

Target:
private Client delegate() { long currentCount = counter.get(); if (currentCount >= exceptionCountBeforeRefresh && counter.compareAndSet(currentCount, 0)) { log.info("Creating a new Feign client, as exceptions have been thrown in a row by old client", SafeArg.of("count", currentCount)); try { currentClient = refreshingSupplier.get(); } catch (RuntimeException e) { log.warn("An error occurred whilst trying to re-create an OkHttpClient." + " Continuing operation with the old client...", SafeArg.of("count", currentCount), e); } } return currentClient; }
Source:
<code>private FirewallRule findById(List<FirewallRule> collection, String id) { FirewallRule result = null; for (FirewallRule rule : collection) { if (rule.id().equals(id)) { <START> result = rule; <END> } } return result; }</code><technical_language>return rule</technical_language>

Target:
private FirewallRule findById(List<FirewallRule> collection, String id) { for (FirewallRule rule : collection) { if (rule.id().equals(id)) { return rule; } } return null; }
Source:
<code>public void truncateAllRounds() { lock.writeLock().lock(); try { File dir = new File(path); boolean success = getLogEntries(dir).stream().map(File::delete).reduce(true, (x, y) -> x && y); if (!success) { <START> log.warn("failed to delete all log files."); <END> } } finally { lock.writeLock().unlock(); } }</code><technical_language>nit: include, Unsafe level, directory involved</technical_language>

Target:
public void truncateAllRounds() { lock.writeLock().lock(); try { File dir = new File(path); getLogEntries(dir).forEach(PaxosStateLogImpl::deleteLogFile); } finally { lock.writeLock().unlock(); } }
Source:
<code>public Image getImage(Object element) { RepositoryTreeNode node = (RepositoryTreeNode) element; if (node.getType() == RepositoryTreeNodeType.TAG) { try { ObjectId id = node.getRepository().resolve( ((Ref) node.getObject()).getName()); <START> new RevWalk(node.getRepository()).parseTag(id); <END> return decorateImage(node.getType().getIcon(), element); } catch (AmbiguousObjectException e) { return decorateImage(node.getType().getIcon(), element); } catch (IOException e) { return decorateImage(lightweightTagImage, element); } } else return decorateImage(node.getType().getIcon(), element); }</code><technical_language>I playing Exceptions in way, I do RevObject = rw.parseAny(ref.getLeaf().getObjectId()); if (any instanceof RevCommit) { // a lightweight tag } else if (any instanceof RevTag) { // annotated signed tag }</technical_language>

Target:
public Image getImage(Object element) { RepositoryTreeNode node = (RepositoryTreeNode) element; if (node.getType() == RepositoryTreeNodeType.TAG) { RevObject any; try { ObjectId id = node.getRepository().resolve( ((Ref) node.getObject()).getName()); any = new RevWalk(node.getRepository()).parseAny(id); } catch (MissingObjectException e) { Activator.logError(e.getMessage(), e); return null; } catch (IOException e) { Activator.logError(e.getMessage(), e); return null; } if (any instanceof RevCommit) return decorateImage(lightweightTagImage, element); else return decorateImage(node.getType().getIcon(), element); } else return decorateImage(node.getType().getIcon(), element); }
Source:
<code>public <START> SecureStoreData(String pluginName, String <END> className, File jarFile, String storeName) { super(storeName, "", jarFile); this.className = className; this.storeName = storeName; }</code><technical_language>plugin name is here. a number of secure-store-providers, protect namespace plugin name. do that, URI capability names. holds true for secure stores: * plugin name "foo" exposes secure store "baz" * plugin name "bar" exposes secure store "baz" in config this as: <foo.baz> <bar.baz> Currently namepsaces names plugins collides plugin is suggested</technical_language>

Target:
public SecureStoreData(String pluginName, String className, File jarFile, String storeName) { super(pluginName, "", jarFile); this.className = className; this.storeName = String.format("%s/%s", pluginName, storeName); }
Source:
<code>private void deliverMessages() { try { log.trace("{} Delivering batch of messages to task", this, messageBatch.size()); long start = time.milliseconds(); task.put(new ArrayList<>(messageBatch)); recordBatch(messageBatch.size()); sinkTaskMetricsGroup.recordPut(time.milliseconds() - start); currentOffsets.putAll(origOffsets); messageBatch.clear(); if (pausedForRedelivery) { if (!shouldPause()) resumeAll(); pausedForRedelivery = false; } } catch (RetriableException e) { log.error("{} RetriableException from SinkTask:", this, e); pausedForRedelivery = true; pauseAll(); } catch (Throwable t) { log.error("{} Task threw an uncaught and unrecoverable exception. Task is being killed and will not " <START> + "recover until manually restarted. {}", this, t.getMessage()); <END> throw new ConnectException("Exiting WorkerSinkTask due to unrecoverable exception.", t); } }</code><technical_language>Thanks for suggested fix, @NarekDW. convention for Log4J method calls is exception is passed _(n+1)_ parameter _n_ is number of placeholders in message string, exception's stack trace is included in log immediately error message. In this case, placeholder is replaced result of this.toString(), this change is placeholder error(...) method call generate a stack trace exception t. correct in error returned Connect API include message of original exception. is helpful, proposed change Log4J log stack trace. I change give modify message identify problem: suggestion + "recover manually restarted. Error: {}", this, t.getMessage(), t);</technical_language>

Target:
private void deliverMessages() { try { log.trace("{} Delivering batch of messages to task", this, messageBatch.size()); long start = time.milliseconds(); task.put(new ArrayList<>(messageBatch)); recordBatch(messageBatch.size()); sinkTaskMetricsGroup.recordPut(time.milliseconds() - start); currentOffsets.putAll(origOffsets); messageBatch.clear(); if (pausedForRedelivery) { if (!shouldPause()) resumeAll(); pausedForRedelivery = false; } } catch (RetriableException e) { log.error("{} RetriableException from SinkTask:", this, e); pausedForRedelivery = true; pauseAll(); } catch (Throwable t) { log.error("{} Task threw an uncaught and unrecoverable exception. Task is being killed and will not " + "recover until manually restarted. Error: {}", this, t.getMessage(), t); throw new ConnectException("Exiting WorkerSinkTask due to unrecoverable exception.", t); } }
Source:
<code>private static String getDensityString(DisplayMetrics displayMetrics) { switch (displayMetrics.densityDpi) { case DisplayMetrics.DENSITY_LOW: return "ldpi"; case DisplayMetrics.DENSITY_MEDIUM: return "mdpi"; case DisplayMetrics.DENSITY_HIGH: return "hdpi"; case DisplayMetrics.DENSITY_XHIGH: return "xhdpi"; case DisplayMetrics.DENSITY_XXHIGH: return "xxhdpi"; case DisplayMetrics.DENSITY_XXXHIGH: return "xxxhdpi"; case DisplayMetrics.DENSITY_TV: return "tvdpi"; default: <START> return "unknown"; <END> } }</code><technical_language>String.valueOf(dpi)</technical_language>

Target:
private static String getDensityString(DisplayMetrics displayMetrics) { switch (displayMetrics.densityDpi) { case DisplayMetrics.DENSITY_LOW: return "ldpi"; case DisplayMetrics.DENSITY_MEDIUM: return "mdpi"; case DisplayMetrics.DENSITY_HIGH: return "hdpi"; case DisplayMetrics.DENSITY_XHIGH: return "xhdpi"; case DisplayMetrics.DENSITY_XXHIGH: return "xxhdpi"; case DisplayMetrics.DENSITY_XXXHIGH: return "xxxhdpi"; case DisplayMetrics.DENSITY_TV: return "tvdpi"; default: return String.valueOf(displayMetrics.densityDpi); } }
Source:
<code>public List<IProject> importToWorkspace(IProgressMonitor monitor) throws CoreException, InterruptedException { MavenPluginActivator mavenPlugin = MavenPluginActivator.getDefault(); IProjectConfigurationManager configurationManager = mavenPlugin.getProjectConfigurationManager(); MavenModelManager modelManager = mavenPlugin.getMavenModelManager(); Set<MavenProjectInfo> projectInfos = getMavenProjects(getProjectDirectory(), filters, modelManager, monitor); ProjectImportConfiguration projectImportConfiguration = new ProjectImportConfiguration(); if (overwriteMavenProjects(projectInfos, projectImportConfiguration, monitor)) { List<IMavenProjectImportResult> importResults = configurationManager.importProjects(projectInfos, projectImportConfiguration, monitor); return validate(toProjects(importResults)); } else { <START> return Collections.EMPTY_LIST; <END> } }</code><technical_language>replace Collections.emptyList() avoid a compiler warning unchecked conversion List<IProject></technical_language>

Target:
public List<IProject> importToWorkspace(IProgressMonitor monitor) throws CoreException, InterruptedException { MavenPluginActivator mavenPlugin = MavenPluginActivator.getDefault(); IProjectConfigurationManager configurationManager = mavenPlugin.getProjectConfigurationManager(); MavenModelManager modelManager = mavenPlugin.getMavenModelManager(); Set<MavenProjectInfo> projectInfos = getMavenProjects(getProjectDirectory(), filters, modelManager, monitor); ProjectImportConfiguration projectImportConfiguration = new ProjectImportConfiguration(); if (overwriteMavenProjects(projectInfos, projectImportConfiguration, monitor)) { List<IMavenProjectImportResult> importResults = configurationManager.importProjects(projectInfos, projectImportConfiguration, monitor); return validate(toProjects(importResults)); } else { return Collections.emptyList(); } }