auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testEventIterator() { AnalysisScriptingModule scriptModule = new AnalysisScriptingModule(); TmfXmlTraceStub trace = new TmfXmlTraceStubNs(); try { IPath filePath = ActivatorTest.getAbsoluteFilePath(CALLSTACK_FILE); IStatus status = trace.validate(null, filePath.toOSString()); if (!status.isOK()) { fail(status.getException().getMessage()); } try { trace.initTrace(null, filePath.toOSString(), TmfEvent.class); } catch (TmfTraceException e) { fail(e.getMessage()); } TmfTraceOpenedSignal signal = new TmfTraceOpenedSignal(this, trace, null); trace.traceOpened(signal); TmfTraceManager.getInstance().traceOpened(signal); ScriptedAnalysis analysis = scriptModule.getAnalysis(ANALYSIS_NAME); assertNotNull(analysis); Iterator<ITmfEvent> eventIterator = analysis.getEventIterator(); assertNotNull(eventIterator); int count = 0; while (eventIterator.hasNext()) { eventIterator.next(); count++; } <START> assertTrue(count <END> > 0); } finally { trace.dispose(); } }</code><technical_language>assertTrue(eventIterator.hasNext()) is a point iteratre throught trace? assertEquals (65535, count)</technical_language>

Target:
public void testEventIterator() { AnalysisScriptingModule scriptModule = new AnalysisScriptingModule(); TmfXmlTraceStub trace = new TmfXmlTraceStubNs(); try { IPath filePath = ActivatorTest.getAbsoluteFilePath(CALLSTACK_FILE); IStatus status = trace.validate(null, filePath.toOSString()); if (!status.isOK()) { fail(status.getException().getMessage()); } try { trace.initTrace(null, filePath.toOSString(), TmfEvent.class); } catch (TmfTraceException e) { fail(e.getMessage()); } TmfTraceOpenedSignal signal = new TmfTraceOpenedSignal(this, trace, null); trace.traceOpened(signal); TmfTraceManager.getInstance().traceOpened(signal); ScriptedAnalysis analysis = scriptModule.getAnalysis(ANALYSIS_NAME); assertNotNull(analysis); Iterator<ITmfEvent> eventIterator = analysis.getEventIterator(); assertNotNull(eventIterator); int count = 0; while (eventIterator.hasNext()) { eventIterator.next(); count++; } assertEquals(36, count); } finally { trace.dispose(); } }
Source:
<code>public String apply(final String key) { if (key == null) { return null; } final String presentVal; try { <START> presentVal = loadingCache.get(key, new Callable<String>() <END> { @Override public String call() throws Exception { return Strings.nullToEmpty(dataFetcher.fetch(key)); } }); return Strings.emptyToNull(presentVal); } catch (ExecutionException e) { LOGGER.debug("value not found for key [%s]", key); return null; } }</code><technical_language>this Callable a class field</technical_language>

Target:
public String apply(final String key) { if (key == null) { return null; } final String presentVal; try { presentVal = loadingCache.get(key, new applyCallable(key)); return Strings.emptyToNull(presentVal); } catch (ExecutionException e) { LOGGER.debug("value not found for key [%s]", key); return null; } }
Source:
<code>public int read() throws IOException { try { int b = this.currentStream.read(); nextBytePos++; return b; } catch (IOException ex) { <START> log.warn( <END> "Failed to read byte at position (space: {}, contentId: {}, startByte:{}, endByte: {}. " + "Starting attempts to re-acquire stream from current position.", nextBytePos, spaceId, contentId, startByte, endByte); try { new Retrier(3, 1000, 2).execute(() -> { RestHttpHelper.HttpResponse response = contentStore.doGetContent(spaceId, contentId, nextBytePos, endByte); currentStream = response.getResponseStream(); log.info( "Successfully re-acquired stream (space: {}, contentId: {}, nextBytePos:{}," + " endByte: {}. ", spaceId, contentId, nextBytePos, endByte); return null; }); return read(); } catch (Exception e) { log.error( "Exhausted max retries to re-acquire stream (space: {}, contentId: {}, nextBytePos:{}," + " endByte: {}. ", spaceId, contentId, nextBytePos, endByte, e); throw new IOException(e.getMessage(), e); } } }</code><technical_language>retries occur, need warn this point, simply notify. suggestion log.info(</technical_language>

Target:
public int read() throws IOException { try { int b = this.currentStream.read(); nextBytePos++; return b; } catch (IOException ex) { retryFromNextByte(); return read(); } }
Source:
<code>public void init(MonthDescriptor month, List<List<MonthCellDescriptor>> cells, boolean displayOnly) { Logr.d("Initializing MonthView (%d) for %s", System.identityHashCode(this), month); long start = System.currentTimeMillis(); title.setText(month.getLabel()); final int numRows = cells.size(); grid.setNumRows(numRows); for (int i = 0; i < 6; i++) { CalendarRowView weekRow = (CalendarRowView) grid.getChildAt(i + 1); weekRow.setListener(listener); if (i < numRows) { weekRow.setVisibility(VISIBLE); List<MonthCellDescriptor> week = cells.get(i); for (int c = 0; c < week.size(); c++) { MonthCellDescriptor cell = week.get(c); CalendarCellView cellView = (CalendarCellView) weekRow.getChildAt(c); <START> if(cellView.getText().equals("")) <END> cellView.setText(Integer.toString(cell.getValue())); cellView.setEnabled(cell.isCurrentMonth()); cellView.setClickable(!displayOnly); cellView.setSelectable(cell.isSelectable()); cellView.setSelected(cell.isSelected()); cellView.setCurrentMonth(cell.isCurrentMonth()); cellView.setToday(cell.isToday()); cellView.setRangeState(cell.getRangeState()); cellView.setHighlighted(cell.isHighlighted()); cellView.setTag(cell); } } else { weekRow.setVisibility(GONE); } } Logr.d("MonthView.init took %d ms", System.currentTimeMillis() - start); }</code><technical_language>nit: space if, curly braces body</technical_language>

Target:
public void init(MonthDescriptor month, List<List<MonthCellDescriptor>> cells, boolean displayOnly) { Logr.d("Initializing MonthView (%d) for %s", System.identityHashCode(this), month); long start = System.currentTimeMillis(); title.setText(month.getLabel()); final int numRows = cells.size(); grid.setNumRows(numRows); for (int i = 0; i < 6; i++) { CalendarRowView weekRow = (CalendarRowView) grid.getChildAt(i + 1); weekRow.setListener(listener); if (i < numRows) { weekRow.setVisibility(VISIBLE); List<MonthCellDescriptor> week = cells.get(i); for (int c = 0; c < week.size(); c++) { MonthCellDescriptor cell = week.get(c); CalendarCellView cellView = (CalendarCellView) weekRow.getChildAt(c); String cellDate = Integer.toString(cell.getValue()); if (!cellView.getText().equals(cellDate)) { cellView.setText(cellDate); } cellView.setEnabled(cell.isCurrentMonth()); cellView.setClickable(!displayOnly); cellView.setSelectable(cell.isSelectable()); cellView.setSelected(cell.isSelected()); cellView.setCurrentMonth(cell.isCurrentMonth()); cellView.setToday(cell.isToday()); cellView.setRangeState(cell.getRangeState()); cellView.setHighlighted(cell.isHighlighted()); cellView.setTag(cell); } } else { weekRow.setVisibility(GONE); } } Logr.d("MonthView.init took %d ms", System.currentTimeMillis() - start); }
Source:
<code>private void upgradeToResourcesV10(String tableName, SQLiteDatabase db) { <START> try { <END> upgradeXFormAndroidInstallerV1(tableName, db); } catch (Exception e) { try { SqlStorage<Resource> newResourceStorage = new SqlStorage<>( tableName, Resource.class, new ConcreteAndroidDbHelper(context, db)); for (Resource resource : newResourceStorage) { } } catch (Exception ex) { SqlStorage.wipeTable(db, tableName); Logger.log(LogTypes.SOFT_ASSERT, "Wiped table on upgrade " + tableName); } } }</code><technical_language>This sound insane, I worth adding assertion kicks out of this method if tableName is global resource table. kind of innocuous name possibility fully wipes table dangerous if global resource table</technical_language>

Target:
private void upgradeToResourcesV10(String tableName, SQLiteDatabase db) { if (tableName.contentEquals(GLOBAL_RESOURCE_TABLE_NAME)) { return; } try { upgradeXFormAndroidInstallerV1(tableName, db); } catch (Exception e) { try { SqlStorage<Resource> newResourceStorage = new SqlStorage<>( tableName, Resource.class, new ConcreteAndroidDbHelper(context, db)); for (Resource resource : newResourceStorage) { } } catch (Exception ex) { SqlStorage.wipeTable(db, tableName); Logger.log(LogTypes.SOFT_ASSERT, "Wiped table on upgrade " + tableName); } } }
Source:
<code>public void status_filter_only_shows_enabled_jobs() { List<Job> jobs = createAmountOfJobs(3, false); String jobDisabled = "exampled-disabled"; String jobDslScript = "job('"+jobDisabled+"') {\n" + " disabled()\n" + "}\n" + "listView('"+ LIST_VIEW_NAME +"') {\n" + " statusFilter(StatusFilter.ENABLED)\n" + " columns {\n" + " name()\n" + " }\n" + " jobs {\n" + " names('"+jobs.get(0).name+"', '"+jobs.get(1).name+"', '"+jobs.get(2).name+"', '"+jobDisabled+"')\n" + " }\n" + "}"; openNewlyCreatedListView(jobDslScript, LIST_VIEW_NAME); Assert.assertThat(driver, not(hasElement(By.xpath(" <START> Assert.assertThat(driver, hasElement(By.xpath(" END> Assert.assertThat(driver, hasElement(By.xpath(" Assert.assertThat(driver, hasElement(By.xpath(" }</code><technical_language>if right part of this line a method in View class a helper method in this test case avoids duplications</technical_language>

Target:
public void status_filter_only_shows_enabled_jobs() { List<Job> jobs = createAmountOfJobs(3, false); Job jobDisabled = createDisabledJob(); String jobDslScript = "listView('"+ LIST_VIEW_NAME +"') {\n" + " statusFilter(StatusFilter.ENABLED)\n" + " columns {\n" + " name()\n" + " }\n" + " jobs {\n" + " names('"+jobs.get(0).name+"', '"+jobs.get(1).name+"', '"+jobs.get(2).name+"', '"+jobDisabled.name+"')\n" + " }\n" + "}"; View view = openNewlyCreatedListView(jobDslScript, LIST_VIEW_NAME); assertThat(view, not(containsJob(jobDisabled))); assertThat(view, containsJob(jobs.get(0))); assertThat(view, containsJob(jobs.get(1))); assertThat(view, containsJob(jobs.get(2))); }
Source:
<code>public int hashCode() { <START> return Arrays.hashCode(new Object[]{ <END> name, prefetchCount, prefetchValidityMillis, epochStart, nodeIdOffset, bitsSequence, bitsNodeId, allowedFutureMillis, statisticsEnabled}); }</code><technical_language>Minor: for simplicity, Objects.hash</technical_language>

Target:
public int hashCode() { return Objects.hash( name, prefetchCount, prefetchValidityMillis, epochStart, nodeIdOffset, bitsSequence, bitsNodeId, allowedFutureMillis, statisticsEnabled); }
Source:
<code><START> private List<Object> serialize() { <END> return Lists.newArrayList(_time.getMillis(), _value); }</code><technical_language>ImmutableList.of() (should return ImmutableList)</technical_language>

Target:
private ImmutableList<Object> serialize() { return ImmutableList.of(_time.getMillis(), _value); }
Source:
<code>public TopicRepository getTopicRepository(final Storage storage) throws TopicRepositoryException { readWriteLock.readLock().lock(); try { final TopicRepository topicRepository = storageTopicRepository.get(storage); if (topicRepository != null) { return topicRepository; } } finally { readWriteLock.readLock().unlock(); } readWriteLock.writeLock().lock(); try { TopicRepository topicRepository = storageTopicRepository.get(storage); if (topicRepository != null) { return topicRepository; } <START> topicRepository = createTopicRepository(storage); <END> storageTopicRepository.put(storage, topicRepository); return topicRepository; } finally { readWriteLock.writeLock().unlock(); } }</code><technical_language>calling getTopicRepository creates a new repository? creation done in a separated operation</technical_language>

Target:
public TopicRepository getTopicRepository(final Storage storage) throws TopicRepositoryException { readWriteLock.readLock().lock(); try { final TopicRepository topicRepository = storageTopicRepository.get(storage); if (topicRepository != null) { return topicRepository; } } finally { readWriteLock.readLock().unlock(); } readWriteLock.writeLock().lock(); try { TopicRepository topicRepository = storageTopicRepository.get(storage); if (topicRepository != null) { return topicRepository; } topicRepository = getTopicRepositoryCreator(storage.getType()).createTopicRepository(storage); storageTopicRepository.put(storage, topicRepository); return topicRepository; } finally { readWriteLock.writeLock().unlock(); } }
Source:
<code>public static AssociationList fromString(String encoded) { if (encoded.isEmpty()) return new AssociationList(); else return new AssociationList( <START> Arrays.asList(encoded.split(",")).stream() <END> .map(AssociationDeclaration::fromString) .collect(Collectors.toList())); }</code><technical_language>Arrays.asList(encoded.split(",")).stream() replaced Arrays.stream(encoded.split(","))</technical_language>

Target:
public static AssociationList fromString(String encoded) { if (encoded.isEmpty()) { return new AssociationList(); } else { return new AssociationList( Arrays.stream(encoded.split(",")) .map(AssociationDeclaration::fromString) .collect(Collectors.toList())); } }
Source:
<code>public void startExport(Iterable<Process> processList, OutputStream outputStream, String xslt) { Document answer = new Document(); Element root = new Element("processes"); answer.setRootElement(root); Namespace xmlns = Namespace.getNamespace(NAMESPACE); Namespace xsi = Namespace.getNamespace("xsi", "<LINK_0>"); root.addNamespaceDeclaration(xsi); root.setNamespace(xmlns); Attribute attSchema = new Attribute("schemaLocation", NAMESPACE + " XML-logfile.xsd", xsi); root.setAttribute(attSchema); for (Process p : processList) { Document doc = createDocument(p, false); Element processRoot = doc.getRootElement(); processRoot.detach(); root.addContent(processRoot); } XMLOutputter outp = new XMLOutputter(); outp.setFormat(Format.getPrettyFormat()); try { outp.output(answer, outputStream); <START> outputStream.close(); <END> } catch (IOException e) { logger.error(e.getMessage(), e); } }</code><technical_language>move here? If exception is thrown in line above, stream is closed. Is try-with-ressource working here</technical_language>

Target:
public void startExport(Iterable<Process> processList, OutputStream outputStream, String xslt) throws IOException { Document answer = new Document(); Element root = new Element("processes"); answer.setRootElement(root); Namespace xmlns = Namespace.getNamespace(NAMESPACE); Namespace xsi = Namespace.getNamespace("xsi", "<LINK_0>"); root.addNamespaceDeclaration(xsi); root.setNamespace(xmlns); Attribute attSchema = new Attribute("schemaLocation", NAMESPACE + " XML-logfile.xsd", xsi); root.setAttribute(attSchema); for (Process p : processList) { Document doc = createDocument(p, false); Element processRoot = doc.getRootElement(); processRoot.detach(); root.addContent(processRoot); } XMLOutputter outp = new XMLOutputter(); outp.output(answer, outputStream); }
Source:
<code>public static boolean isSane(String path) { final int lenght = path.length(); if (lenght > PATH_MAX) { <START> log.error("The path is " + lenght + " characters long, which is longer than the maximum allowed " + PATH_MAX + "."); <END> return false; } if (path.contains("..") || path.contains(" log.error("The path contains potentially dangerous directory navigation sequences."); return false; } return true; }</code><technical_language>s/lenght/length</technical_language>

Target:
public static boolean isSane(String path) { final int length = path.length(); if (length > PATH_MAX) { log.error("The path is " + length + " characters long, which is longer than the maximum allowed " + PATH_MAX + "."); return false; } if (path.contains("..") || path.contains(" log.error("The path contains potentially dangerous directory navigation sequences."); return false; } return true; }
Source:
<code>public long getSerializedSize() { <START> return baseIntBuffers.getSerializedSize() + 1 + 4 + 4 + 1; <END> }</code><technical_language>get some more information magic numbers here</technical_language>

Target:
public long getSerializedSize() { return 1 + 4 + 4 + 1 + baseIntBuffers.getSerializedSize(); }
Source:
<code>public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { try { final Player player = getPlayer(args[0]); if (args.length < 2) { return false; } if (player == null) { sender.sendMessage(FreedomCommand.PLAYER_NOT_FOUND); return true; } String outCommand = StringUtils.join(args, " ", 1, args.length); if (BLOCKED_COMMANDS.contains(outCommand)) { msg("Blocked. Yes, I mean blocked.", ChatColor.RED); return true; } if (plugin.cb.isCommandBlocked(outCommand, sender)) { return true; } try { msg("Sending command as " + player.getName() + ": " + outCommand); if (server.dispatchCommand(player, outCommand)) { msg("Command sent."); } else { msg("Unknown error sending command."); } } catch (Throwable ex) { msg("Error sending command: " + ex.getMessage()); } } catch (Exception e) { <START> msg("/gcmd <fromname> <outcommand>"); <END> } return true; }</code><technical_language>return false</technical_language>

Target:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length < 2) { return false; } final Player player = getPlayer(args[0]); if (player == null) { sender.sendMessage(FreedomCommand.PLAYER_NOT_FOUND); return true; } final String outCommand = StringUtils.join(args, " ", 1, args.length); if (plugin.cb.isCommandBlocked(outCommand, sender)) { return true; } try { msg("Sending command as " + player.getName() + ": " + outCommand); if (server.dispatchCommand(player, outCommand)) { msg("Command sent."); } else { msg("Unknown error sending command."); } } catch (Throwable ex) { msg("Error sending command: " + ex.getMessage()); } return true; }
Source:
<code>public boolean checkIfDnsZonesDeployed(String resourceGroupName, List<AzurePrivateDnsZoneServiceEnum> services) { LOGGER.debug("Checking DNS Zones for services {}", services.stream() .map(AzurePrivateDnsZoneServiceEnum::getDnsZoneName) .collect(Collectors.toList())); PagedList<PrivateZone> dnsZones = listPrivateDnsZonesByResourceGroup(resourceGroupName); for (AzurePrivateDnsZoneServiceEnum service : services) { String dnsZoneName = service.getDnsZoneName(); Optional<PrivateZone> foundDnsZone = dnsZones.stream() .filter(dnsZone -> dnsZone.name().equals(dnsZoneName)) <START> .filter(dnsZone -> dnsZone.provisioningState() == SUCCEEDED) <END> .findAny(); if (foundDnsZone.isEmpty()) { LOGGER.info("DNS Zone is not provisioned successfully yet!", dnsZoneName); return false; } } return true; }</code><technical_language>equals instead of ==</technical_language>

Target:
public boolean checkIfDnsZonesDeployed(String resourceGroupName, List<AzurePrivateDnsZoneServiceEnum> services) { LOGGER.debug("Checking DNS Zones for services {}", services.stream() .map(AzurePrivateDnsZoneServiceEnum::getDnsZoneName) .collect(Collectors.toList())); PagedList<PrivateZone> dnsZones = listPrivateDnsZonesByResourceGroup(resourceGroupName); for (AzurePrivateDnsZoneServiceEnum service : services) { String dnsZoneName = service.getDnsZoneName(); boolean dnsZoneFound = dnsZones.stream() .filter(dnsZone -> dnsZone.name().equals(dnsZoneName)) .anyMatch(dnsZone -> dnsZone.provisioningState().equals(SUCCEEDED)); if (!dnsZoneFound) { LOGGER.info("DNS Zone is not provisioned successfully yet!", dnsZoneName); return false; } } return true; }
Source:
<code>public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames) { <START> if (selectedFieldNames != null && !selectedFieldNames.contains(DISORDER_PROPERTIES)) { <END> return; } PatientData<Disorder> data = patient.getData(getName()); json.put(JSON_KEY_DISORDERS, diseasesToJSON(data, selectedFieldNames)); }</code><technical_language>I this works, contains(DISORDER_PROPERTIES_OMIMID)</technical_language>

Target:
public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames) { if (!isFieldIncluded(selectedFieldNames, DISORDER_PROPERTIES)) { return; } PatientData<Disorder> data = patient.getData(getName()); json.put(JSON_KEY_DISORDERS, diseasesToJSON(data, selectedFieldNames)); }
Source:
<code>void handleContainerLaunchFail(String processorId, String containerId, String preferredHost, ContainerAllocator containerAllocator) { if (processorId != null && hasActiveContainerPlacementAction(processorId)) { ContainerPlacementMetadata metaData = getPlacementActionMetadata(processorId).get(); String sourceHost = hostAffinityEnabled ? metaData.getSourceHost() : ResourceRequestState.ANY_HOST; handleControlActionFailure(processorId, metaData, <START> String.format("failed to start container on destination host %s, attempting to start on source host %s", preferredHost, sourceHost)); <END> containerAllocator.requestResource(processorId, sourceHost); } else if (processorId != null && standbyContainerManager.isPresent()) { standbyContainerManager.get().handleContainerLaunchFail(processorId, containerId, containerAllocator); } else if (processorId != null) { LOG.info("Falling back to ANY_HOST for Processor ID: since launch failed for Container ID: on host: {}", processorId, containerId, preferredHost); containerAllocator.requestResource(processorId, ResourceRequestState.ANY_HOST); } else { LOG.warn("Did not find a pending Processor ID for Container ID: on host: {}. " + "Ignoring invalid/redundant notification.", containerId, preferredHost); } }</code><technical_language>Update container-placement-metadata making a resourceRequest, allocator do resource</technical_language>

Target:
void handleContainerLaunchFail(String processorId, String containerId, String preferredHost, ContainerAllocator containerAllocator) { if (processorId != null && hasActiveContainerPlacementAction(processorId)) { ContainerPlacementMetadata metaData = getPlacementActionMetadata(processorId).get(); String sourceHost = hostAffinityEnabled ? metaData.getSourceHost() : ResourceRequestState.ANY_HOST; markContainerPlacementActionFailed(metaData, String.format("failed to start container on destination host %s, attempting to start on source host %s", preferredHost, sourceHost)); containerAllocator.requestResource(processorId, sourceHost); } else if (processorId != null && standbyContainerManager.isPresent()) { standbyContainerManager.get().handleContainerLaunchFail(processorId, containerId, containerAllocator); } else if (processorId != null) { LOG.info("Falling back to ANY_HOST for Processor ID: since launch failed for Container ID: on host: {}", processorId, containerId, preferredHost); containerAllocator.requestResource(processorId, ResourceRequestState.ANY_HOST); } else { LOG.warn("Did not find a pending Processor ID for Container ID: on host: {}. " + "Ignoring invalid/redundant notification.", containerId, preferredHost); } }
Source:
<code>public CompositeDriverExecutionProfile( @NonNull DriverConfig primaryConfig, @NonNull DriverConfig fallbackConfig, @NonNull String profileName) { this.primaryConfig = Objects.requireNonNull(primaryConfig); this.fallbackConfig = Objects.requireNonNull(fallbackConfig); this.profileName = Objects.requireNonNull(profileName); <START> refresh(); <END> }</code><technical_language>Calling a public method a constructor is error-prone, extract default implementation of refresh() a private method?</technical_language>

Target:
public CompositeDriverExecutionProfile( @NonNull DriverConfig primaryConfig, @NonNull DriverConfig fallbackConfig, @NonNull String profileName) { this.primaryConfig = Objects.requireNonNull(primaryConfig); this.fallbackConfig = Objects.requireNonNull(fallbackConfig); this.profileName = Objects.requireNonNull(profileName); refreshInternal(); }
Source:
<code>protected void configure(ServerHttpSecurity http) { this.reactiveAuthenticationManagerResolver = this.reactiveAuthenticationManagerResolver != null ? this.reactiveAuthenticationManagerResolver <START> : request -> getAuthenticationManager(); <END> AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(reactiveAuthenticationManagerResolver); oauth2.setServerAuthenticationConverter(bearerTokenConverter); oauth2.setAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(entryPoint)); http .addFilterAt(oauth2, SecurityWebFiltersOrder.AUTHENTICATION); }</code><technical_language>resolve authentication manager configuration time instead of request time, so: java if (this.reactiveAuthenticationManagerResolver == null) { AuthenticationManager authenticationManager = getAuthenticationManager(); this.reactiveAuthenticationManagerResolver = request -> authenticationManager; }</technical_language>

Target:
protected void configure(ServerHttpSecurity http) { ReactiveAuthenticationManager authenticationManager = getAuthenticationManager(); AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(authenticationManager); oauth2.setServerAuthenticationConverter(bearerTokenConverter); oauth2.setAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(entryPoint)); http .addFilterAt(oauth2, SecurityWebFiltersOrder.AUTHENTICATION); }
Source:
<code>public int hashCode() { int hash = 1; hash = hash * 31 + command.hashCode(); hash = hash * 31 + spec.hashCode(); <START> return hash; <END> }</code><technical_language>Alternatively do: Arrays.hashCode(new Object[]{command, spec});</technical_language>

Target:
public int hashCode() { return Arrays.hashCode(new Object[] { command, spec }); }
Source:
<code>private Guid getNewMacPoolId() { <START> return getParameters().getStoragePool().getMacPoolId(); <END> }</code><technical_language>"getNewMacPoolId()" in getPermissionCheckSubjects (please notice is a null check- 'getParameters().getStoragePool() == null', please add well)</technical_language>

Target:
private Guid getNewMacPoolId() { return getParameters().getStoragePool() == null ? null : getParameters().getStoragePool().getMacPoolId(); }
Source:
<code>public void onReceive(Context ctx, Intent intent) { String referrerStr = intent.getStringExtra(REFERRER_KEY); <START> L.d(">>>>> Received install referrer: " + referrerStr); <END> if (!INSTALL_ACTION.equals(intent.getAction()) || TextUtils.isEmpty(referrerStr)) { return; } Uri uri = Uri.parse("/?" + referrerStr); InstallReferrerFunnel funnel = new InstallReferrerFunnel(WikipediaApp.getInstance(), Site.forLanguage("test")); funnel.logInstall(uri.getQueryParameter(InstallReferrerFunnel.PARAM_REFERRER_URL), uri.getQueryParameter(InstallReferrerFunnel.PARAM_CAMPAIGN_ID), uri.getQueryParameter(InstallReferrerFunnel.PARAM_CAMPAIGN_INSTALL_ID)); }</code><technical_language>Is >>>>> for debugging current code? Do need this for final code</technical_language>

Target:
public void onReceive(Context ctx, Intent intent) { String referrerStr = intent.getStringExtra(REFERRER_KEY); L.d("Received install referrer: " + referrerStr); if (!INSTALL_ACTION.equals(intent.getAction()) || TextUtils.isEmpty(referrerStr)) { return; } Uri uri = Uri.parse("/?" + referrerStr); InstallReferrerFunnel funnel = new InstallReferrerFunnel(WikipediaApp.getInstance(), Site.forLanguage("test")); funnel.logInstall(uri.getQueryParameter(InstallReferrerFunnel.PARAM_REFERRER_URL), uri.getQueryParameter(InstallReferrerFunnel.PARAM_CAMPAIGN_ID), uri.getQueryParameter(InstallReferrerFunnel.PARAM_CAMPAIGN_INSTALL_ID)); }
Source:
<code>public static SkullType getSkullType(int skullType) { <START> return SpongeImpl.getRegistry().getAllOf(SkullType.class).stream() <END> .filter(type -> type instanceof SpongeSkullType && ((SpongeSkullType) type).getByteId() == skullType) .findAny().orElse(DEFAULT_TYPE); }</code><technical_language>I want a traditional for loop a stream, streams optimized. potential requirement of this considered a "hot" method in some cases, fast fancy new API's, in current implementation streams</technical_language>

Target:
public static SkullType getSkullType(int skullType) { for(SkullType type : SpongeImpl.getRegistry().getAllOf(SkullType.class)){ if((type instanceof SpongeSkullType) && (((SpongeSkullType) type).getByteId() == skullType)) { return type; } } return DEFAULT_TYPE; }
Source:
<code>public void channelActive(ChannelHandlerContext ctx) throws Exception { final long count = counter.incrementAndGet(); long limit = DatabaseDescriptor.getNativeTransportMaxConcurrentConnections(); if(limit < 0) { limit = Long.MAX_VALUE; } if (count > limit) { <START> noSpamLogger.error("Exceeded maximum native connection limit of by using connections", limit, count); <END> ctx.close(); } else { long perIpLimit = DatabaseDescriptor.getNativeTransportMaxConcurrentConnectionsPerIp(); if (perIpLimit > 0) { InetAddress address = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress(); AtomicLong perIpCount = connectionsPerClient.get(address); if (perIpCount == null) { perIpCount = new AtomicLong(0); AtomicLong old = connectionsPerClient.putIfAbsent(address, perIpCount); if (old != null) { perIpCount = old; } } if (perIpCount.incrementAndGet() > perIpLimit) { noSpamLogger.error("Exceeded maximum native connection limit per ip of by using connections", perIpLimit, perIpCount); ctx.close(); return; } } ctx.fireChannelActive(); } }</code><technical_language>noSpamLogger globally, loggings confusing folks a lot. error messages ignore (like allocation for chunk cache impossible, is actionable). intent noSpamLogger operators supposed do messages raising warn error here? Is ConnectionLimitHandler in incremental repair</technical_language>

Target:
public void channelActive(ChannelHandlerContext ctx) throws Exception { final long count = counter.incrementAndGet(); long limit = DatabaseDescriptor.getNativeTransportMaxConcurrentConnections(); if(limit < 0) { limit = Long.MAX_VALUE; } if (count > limit) { noSpamLogger.error("Exceeded maximum native connection limit of by using connections (see native_transport_max_concurrent_connections in cassandra.yaml)", limit, count); ctx.close(); } else { long perIpLimit = DatabaseDescriptor.getNativeTransportMaxConcurrentConnectionsPerIp(); if (perIpLimit > 0) { InetAddress address = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress(); AtomicLong perIpCount = connectionsPerClient.get(address); if (perIpCount == null) { perIpCount = new AtomicLong(0); AtomicLong old = connectionsPerClient.putIfAbsent(address, perIpCount); if (old != null) { perIpCount = old; } } if (perIpCount.incrementAndGet() > perIpLimit) { noSpamLogger.error("Exceeded maximum native connection limit per ip of by using connections (see native_transport_max_concurrent_connections_per_ip)", perIpLimit, perIpCount); ctx.close(); return; } } ctx.fireChannelActive(); } }
Source:
<code>@Test public void shouldHandleBookingErrorResponse() { String responseError = "{\"error\":\"That userToken is unrecognised.\",\"errorCode\":401,\"usererror\":false}"; ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json"), responseError); final Response<BookingForm> response = Response.error(401, responseBody); final TestSubscriber<BookingForm> subscriber = new TestSubscriber<>(); service.handleBookingResponse.call(response).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertError(BookingError.class); Throwable error = subscriber.getOnErrorEvents().get(0); <START> assertThat(error instanceof BookingError).isTrue(); <END> }</code><technical_language>if test specifics of error as: assertThat(error.getError()).isEqualsTo("That userToken is unrecognised");</technical_language>

Target:
@Test public void shouldHandleBookingErrorResponse() { String responseError = "{\"error\":\"That userToken is unrecognised.\",\"errorCode\":401,\"usererror\":false}"; ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json"), responseError); final Response<BookingForm> response = Response.error(401, responseBody); final TestSubscriber<BookingForm> subscriber = new TestSubscriber<>(); service.handleBookingResponse.call(response).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertError(BookingError.class); Throwable error = subscriber.getOnErrorEvents().get(0); assertThat(error.getMessage()).isEqualTo("That userToken is unrecognised."); }
Source:
<code>public static WebArchive createDeployment() { File[] testDeps = Maven.configureResolver() .workOffline() .loadPomFromFile("pom.xml") .resolve("org.modeshape:modeshape-jcr:test-jar:tests:?").withTransitivity().asFile(); return ShrinkWrap.create(WebArchive.class, "query-test.war").addAsLibraries(testDeps) .addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml")) <START> .addAsWebInfResource(new File("src/main/webapp/WEB-INF/jboss-deployment-structure.xml"), ArchivePaths.create("jboss-deployment-structure.xml")) <END> .addAsResource(new File("src/test/resources/text-extractor/text-file.txt")) .setManifest(new File("src/main/webapp/META-INF/MANIFEST.MF")); }</code><technical_language>ES test moved another class, this required here, right</technical_language>

Target:
public static WebArchive createDeployment() { File[] testDeps = Maven.configureResolver() .workOffline() .loadPomFromFile("pom.xml") .resolve("org.modeshape:modeshape-jcr:test-jar:tests:?").withTransitivity().asFile(); return ShrinkWrap.create(WebArchive.class, "query-test.war").addAsLibraries(testDeps) .addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml")) .addAsResource(new File("src/test/resources/text-extractor/text-file.txt")) .setManifest(new File("src/main/webapp/META-INF/MANIFEST.MF")); }
Source:
<code>protected void endWithFailure() { if (getMoveOrCopyImageOperation() == ImageOperation.Copy) { unLockImage(); if (getParameters().getAddImageDomainMapping()) { getImageStorageDomainMapDao().remove (new image_storage_domain_map_id(getParameters().getImageId(), getParameters().getStorageDomainId())); } revertTasks(); <START> } else { <END> unLockImage(); } setSucceeded(true); }</code><technical_language>UnlockImage is performed anyway, removed out of if-else</technical_language>

Target:
protected void endWithFailure() { unLockImage(); if (getMoveOrCopyImageOperation() == ImageOperation.Copy) { if (getParameters().getAddImageDomainMapping()) { getImageStorageDomainMapDao().remove (new image_storage_domain_map_id(getParameters().getImageId(), getParameters().getStorageDomainId())); } revertTasks(); } setSucceeded(true); }
Source:
<code>public void setupDB() throws DockerException, InterruptedException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader()); client = new DBDockerClient(dbi); client.createContainer(); client.startContainer(); } finally { Thread.currentThread().setContextClassLoader(cl); } jdbcUri = URI.create(dbi.getJDBCURL( client.getHostPort(dbi.getDBPort()), client.getHostName())); <START> jdbcUri = URI.create("jdbc:oracle:thin:@ END> TestUtil.startConversionService(); TestUtil.startService( Arrays.asList("eu.esdihumboldt.hale.io.jdbc.oracle"), ConversionService.class); }</code><technical_language>This testing code in commit</technical_language>

Target:
public void setupDB() throws DockerException, InterruptedException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader()); client = new DBDockerClient(dbi); client.createContainer(); client.startContainer(); } finally { Thread.currentThread().setContextClassLoader(cl); } jdbcUri = URI.create(dbi.getJDBCURL( client.getHostPort(dbi.getDBPort()), client.getHostName())); TestUtil.startConversionService(); }
Source:
<code><START> public LRAParticipantRegistry(Map<String, LRAParticipant> lraParticipants) { <END> this.lraParticipants = new HashMap<>(lraParticipants); }</code><technical_language>this package private</technical_language>

Target:
LRAParticipantRegistry(Map<String, LRAParticipant> lraParticipants) { this.lraParticipants = new HashMap<>(lraParticipants); }
Source:
<code>private static String parseFields(SimpleFeatureType schema) { JSONArray jsfields = new JSONArray(); try { Collection<PropertyDescriptor> types = schema.getDescriptors(); for (PropertyDescriptor type : types) { JSONObject obj = new JSONObject(); String name = type.getName().getLocalPart(); obj.put("name", name); obj.put("type", type.getType().getBinding().getSimpleName()); JSONObject locales = new JSONObject(); if (KMLParser.KML_NAME.equals(name)){ <START> locales.put("fi", "Nimi"); <END> locales.put("en", "Name"); locales.put("sv", "Namn"); } else if (KMLParser.KML_DESC.equals(name)){ locales.put("fi", "Kuvaus"); locales.put("en", "Description"); locales.put("sv", "Beskrivning"); } else { locales.put("fi", name); locales.put("en", name); locales.put("sv", name); } obj.put("locales", locales); jsfields.put(obj); } } catch (Exception ex) { log.error(ex, "Couldn't parse field schema"); } return JSONHelper.getStringFromJSON(jsfields, "[]"); }</code><technical_language>a big fan localization in code, put either</technical_language>

Target:
private static String parseFields(SimpleFeatureType schema) { JSONArray jsfields = new JSONArray(); try { Collection<PropertyDescriptor> types = schema.getDescriptors(); for (PropertyDescriptor type : types) { JSONObject obj = new JSONObject(); String name = type.getName().getLocalPart(); obj.put("name", name); obj.put("type", type.getType().getBinding().getSimpleName()); if (!KMLParser.KML_GEOM.equals(name)){ JSONObject locales = new JSONObject(); String localizedName = name; if (KMLParser.KML_NAME.equals(name)){ localizedName = "Name"; } else if (KMLParser.KML_DESC.equals(name)){ localizedName = "Description"; } locales.put(DEFAULT_LOCALES_LANGUAGE, localizedName); obj.put("locales", locales); } jsfields.put(obj); } } catch (Exception ex) { log.error(ex, "Couldn't parse field schema"); } return JSONHelper.getStringFromJSON(jsfields, "[]"); }
Source:
<code><START> public void validate(final List<Throwable> errors, final Configuration configuration) { <END> final In inputParameter = createInputParameter(); final Set<String> allInputAttributeNames; if (inputParameter != null) { allInputAttributeNames = ParserUtils.getAllAttributeNames(inputParameter.getClass()); } else { allInputAttributeNames = Collections.emptySet(); } for (String inputAttributeName : this.inputMapper.values()) { if (!allInputAttributeNames.contains(inputAttributeName)) { errors.add(new ConfigurationException(inputAttributeName + " is not defined in processor '" + this + "'. Check for typos. Options are " + allInputAttributeNames)); } } Set<String> allOutputAttributeNames = ParserUtils.getAllAttributeNames(getOutputType()); for (String outputAttributeName : this.outputMapper.keySet()) { if (!allOutputAttributeNames.contains(outputAttributeName)) { errors.add(new ConfigurationException(outputAttributeName + " is not defined in processor " + "'" + this + "' as an output attribute. Check for typos. Options are " + allOutputAttributeNames)); } } extraValidation(errors, configuration); }</code><technical_language>final put</technical_language>

Target:
public final void validate(final List<Throwable> errors, final Configuration configuration) { final In inputParameter = createInputParameter(); final Set<String> allInputAttributeNames; if (inputParameter != null) { allInputAttributeNames = ParserUtils.getAllAttributeNames(inputParameter.getClass()); } else { allInputAttributeNames = Collections.emptySet(); } for (String inputAttributeName : this.inputMapper.values()) { if (!allInputAttributeNames.contains(inputAttributeName)) { errors.add(new ConfigurationException(inputAttributeName + " is not defined in processor '" + this + "'. Check for typos. Options are " + allInputAttributeNames)); } } Set<String> allOutputAttributeNames = ParserUtils.getAllAttributeNames(getOutputType()); for (String outputAttributeName : this.outputMapper.keySet()) { if (!allOutputAttributeNames.contains(outputAttributeName)) { errors.add(new ConfigurationException(outputAttributeName + " is not defined in processor " + "'" + this + "' as an output attribute. Check for typos. Options are " + allOutputAttributeNames)); } } extraValidation(errors, configuration); }
Source:
<code>public void handleSetAdministrativeStatusResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleSetAdministrativeStatusResponse for MessageType: {}, with result: {}", deviceMessageMetadata.getMessageType(), deviceResult.toString()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleSetAdministrativeStatusResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleSetAdministrativeStatusResponse for MessageType: {}, with result: {}", deviceMessageMetadata.getMessageType(), deviceResult.toString()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>public GridSearch(Map<String, Object> rawParams, List<String> configFileContent) { this.rawParams = rawParams; List<Map<String, Object>> gridParams = parseParams(configFileContent); if(gridParams != null && gridParams.size() > 0) { assert this.hasHyperParam(rawParams) == false; Set<String> hyperParams = new HashSet<String>(); for(Map<String, Object> map: gridParams) { for(Map.Entry<String, Object> gridEntry: map.entrySet()) { hyperParams.add(gridEntry.getKey()); } for(Map.Entry<String, Object> kvEntry: this.rawParams.entrySet()) { map.put(kvEntry.getKey(), kvEntry.getValue()); <START> } <END> } this.flattenParams = gridParams; this.hyperParamCount = hyperParams.size(); this.flattenParamsCount = this.flattenParams.size(); } else { assert rawParams != null; this.hyperParamCount = 0; parseParams(this.rawParams); } }</code><technical_language>parameter set in grid search file overrided in parameters, add check if existing in rawParams put t map</technical_language>

Target:
public GridSearch(Map<String, Object> rawParams, List<String> configFileContent) { this.rawParams = rawParams; List<Map<String, Object>> gridParams = parseParams(configFileContent); if(gridParams != null && gridParams.size() > 0) { assert this.hasHyperParam(rawParams) == false; Set<String> hyperParams = new HashSet<String>(); for(Map<String, Object> map: gridParams) { for(Map.Entry<String, Object> gridEntry: map.entrySet()) { hyperParams.add(gridEntry.getKey()); } for(Map.Entry<String, Object> kvEntry: this.rawParams.entrySet()) { if(!map.containsKey(kvEntry.getKey())) { map.put(kvEntry.getKey(), kvEntry.getValue()); } } } this.flattenParams = gridParams; this.hyperParamCount = hyperParams.size(); this.flattenParamsCount = this.flattenParams.size(); } else { assert rawParams != null; this.hyperParamCount = 0; parseParams(this.rawParams); } checkParamsThreshold(); }
Source:
<code>public Health health() { ZkClient zkClient = new ZkClient(binder.getZkAddress(), 10000, 10000, ZKStringSerializer$.MODULE$); Seq<Broker> allBrokersInCluster = ZkUtils$.MODULE$.getAllBrokersInCluster(zkClient); Collection<Broker> brokersInCluster = JavaConversions.asJavaCollection(allBrokersInCluster); Set<String> brokersInClusterSet = new HashSet<>(); for (Broker broker: brokersInCluster) { brokersInClusterSet.add(broker.connectionString()); } List<String> downMessages = new ArrayList<>(); for (Map.Entry<String, Collection<Partition>> entry : binder.getTopicsInUse().entrySet()) { for (Partition partition : entry.getValue()) { BrokerAddress address = binder.getConnectionFactory().getLeader(partition); if (!brokersInClusterSet.contains(address.toString())) { <START> downMessages.add(address.toString()); <END> } } } if (downMessages.isEmpty()) { return Health.up().build(); } return Health.down().withDetail("Following brokers are down: ", downMessages.toString()).build(); }</code><technical_language>generate a message broker - i.e. a Set for storing error messages</technical_language>

Target:
public Health health() { ZkClient zkClient = new ZkClient(binder.getZkAddress(), binder.getZkSessionTimeout(), binder.getZkConnectionTimeout(), ZKStringSerializer$.MODULE$); Set<String> brokersInClusterSet = new HashSet<>(); try { Seq<Broker> allBrokersInCluster = ZkUtils$.MODULE$.getAllBrokersInCluster(zkClient); Collection<Broker> brokersInCluster = JavaConversions.asJavaCollection(allBrokersInCluster); for (Broker broker : brokersInCluster) { brokersInClusterSet.add(broker.connectionString()); } } catch (Exception e) { return Health.down(e).build(); } finally { if (zkClient != null) { try { zkClient.close(); } catch (Exception e) { } } } Set<String> downMessages = new HashSet<>(); for (Map.Entry<String, Collection<Partition>> entry : binder.getTopicsInUse().entrySet()) { for (Partition partition : entry.getValue()) { BrokerAddress address = binder.getConnectionFactory().getLeader(partition); if (!brokersInClusterSet.contains(address.toString())) { downMessages.add(address.toString()); } } } if (downMessages.isEmpty()) { return Health.up().build(); } return Health.down().withDetail("Following brokers are down: ", downMessages.toString()).build(); }
Source:
<code><START> public ViewMode getViewMode() { <END> return viewMode.get(); }</code><technical_language>This synchronized</technical_language>

Target:
synchronized public ViewMode getViewMode() { return viewMode.get(); }