auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_style_variable_text_placement); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { mapboxMap.setStyle(new Style.Builder().fromUrl(Style.LIGHT) .withSource(new GeoJsonSource(GEOJSON_SRC_ID)) .withLayer(new SymbolLayer(POI_LABELS_LAYER_ID, GEOJSON_SRC_ID) .withProperties( textField(get("description")), textSize(17f), textColor(Color.RED), textVariableAnchor( new String[]{TEXT_ANCHOR_TOP, TEXT_ANCHOR_BOTTOM, TEXT_ANCHOR_LEFT, TEXT_ANCHOR_RIGHT}), textJustify(TEXT_JUSTIFY_AUTO), textRadialOffset(0.5f))), new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull final Style style) { VariableLabelPlacementActivity.this.mapboxMap = mapboxMap; <START> new LoadGeoJson(style,VariableLabelPlacementActivity.this).execute(); <END> } }); } }); }</code><technical_language>currently load a local geojson file manipulating contet. remove a lot of this boilerplate code if rely loading map resources assets. asset://poi_places.geojson url for parameter of geojsonsource constructor. json loader removed asynctask setup</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_style_variable_text_placement); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { GeoJsonSource source = new GeoJsonSource(GEOJSON_SRC_ID); source.setUrl("asset://poi_places.geojson"); mapboxMap.setStyle(new Style.Builder().fromUrl(Style.LIGHT) .withSource(source) .withLayer(new SymbolLayer(POI_LABELS_LAYER_ID, GEOJSON_SRC_ID) .withProperties( textField(get("description")), textSize(17f), textColor(Color.RED), textVariableAnchor( new String[]{TEXT_ANCHOR_TOP, TEXT_ANCHOR_BOTTOM, TEXT_ANCHOR_LEFT, TEXT_ANCHOR_RIGHT}), textJustify(TEXT_JUSTIFY_AUTO), textRadialOffset(0.5f))), new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull final Style style) { Toast.makeText(VariableLabelPlacementActivity.this, getString(R.string.zoom_map_in_and_out_variable_label_instruction), Toast.LENGTH_SHORT).show(); } }); } }); }
Source:
<code>private String waitAndRetrieveContainerID(String deploymentName) { for (int i = 0; i < OPENSHIFT_WAIT_POD_TIMEOUT; i++) { try { <START> Thread.sleep(OPENSHIFT_WAIT_POD_DELAY); <END> } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } PodList pods = openShiftClient.pods() .inNamespace(this.cheOpenShiftProjectName) .list(); for (Pod p : pods.getItems()) { String status = p.getStatus().getPhase(); String dc = p.getMetadata().getLabels().get(OPENSHIFT_DEPLOYMENT_LABEL); if (OPENSHIFT_POD_STATUS_RUNNING.equals(status) && deploymentName.equals(dc)) { String containerID = p.getStatus().getContainerStatuses().get(0).getContainerID(); String normalizedID = normalizeContainerID(containerID); openShiftClient.pods() .inNamespace(this.cheOpenShiftProjectName) .withName(p.getMetadata().getName()) .edit() .editMetadata() .addToLabels(CHE_CONTAINER_IDENTIFIER_LABEL_KEY, getLabelFromContainerID(normalizedID)) .endMetadata() .done(); return normalizedID; } } } return null; }</code><technical_language>do need wait</technical_language>

Target:
private String waitAndRetrieveContainerID(String deploymentName) { for (int i = 0; i < OPENSHIFT_WAIT_POD_TIMEOUT; i++) { try { Thread.sleep(OPENSHIFT_WAIT_POD_DELAY); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } PodList pods = openShiftClient.pods() .inNamespace(this.openShiftCheProjectName) .list(); for (Pod p : pods.getItems()) { String status = p.getStatus().getPhase(); String dc = p.getMetadata().getLabels().get(OPENSHIFT_DEPLOYMENT_LABEL); if (OPENSHIFT_POD_STATUS_RUNNING.equals(status) && deploymentName.equals(dc)) { String containerID = p.getStatus().getContainerStatuses().get(0).getContainerID(); String normalizedID = normalizeContainerID(containerID); openShiftClient.pods() .inNamespace(this.openShiftCheProjectName) .withName(p.getMetadata().getName()) .edit() .editMetadata() .addToLabels(CHE_CONTAINER_IDENTIFIER_LABEL_KEY, getLabelFromContainerID(normalizedID)) .endMetadata() .done(); return normalizedID; } } } return null; }
Source:
<code>SetAnonymousAuthenticationConfiguration(final AuthenticationConfiguration parent) { <START> super(parent.without(SetCallbackHandlerAuthenticationConfiguration.class).useName(AnonymousPrincipal.getInstance().getName())); <END> }</code><technical_language>do this, I set name SetNamePrincipalAuthenticationConfiguration does, hard-coded name</technical_language>

Target:
SetAnonymousAuthenticationConfiguration(final AuthenticationConfiguration parent) { super(parent.without(SetCallbackHandlerAuthenticationConfiguration.class).without(SetNamePrincipalAuthenticationConfiguration.class)); }
Source:
<code>public boolean isAnyExpression() { <START> return "*".equals(ecl); <END> }</code><technical_language>constant</technical_language>

Target:
public boolean isAnyExpression() { return Ecl.ANY.equals(ecl); }
Source:
<code>public void testSTPoints() { assertFunction("transform(ST_Points(ST_GeometryFromText('LINESTRING (8 4)')), x -> ST_AsText(x))", new ArrayType(VARCHAR), ImmutableList.of("POINT (8 4)", "POINT (8 4)")); assertFunction("transform(ST_Points(ST_GeometryFromText('LINESTRING (8 4, 3 9, 5 6)')), x -> ST_AsText(x))", new ArrayType(VARCHAR), ImmutableList.of("POINT (8 4)", "POINT (3 9)", "POINT (5 6)")); <START> assertInvalidFunction("transform(ST_Points(ST_GeometryFromText('POLYGON ((8 4, 3 9, 5 6))')), x -> ST_AsText(x))", "ST_Points only applies to LINE_STRING. Input type is: POLYGON"); <END> }</code><technical_language>transform is unnecessary assertInvalidFunction("ST_Points(ST_GeometryFromText('POLYGON ((8 4, 3 9, 5 6))'))", "ST_Points applies LINE_STRING. Input type is: POLYGON");</technical_language>

Target:
public void testSTPoints() { assertFunction("ST_Points(ST_GeometryFromText('LINESTRING EMPTY'))", new ArrayType(GEOMETRY), null); assertSTPoints("LINESTRING (0 0, 0 0)", "0 0", "0 0"); assertSTPoints("LINESTRING (8 4, 3 9, 8 4)", "8 4", "3 9", "8 4"); assertSTPoints("LINESTRING (8 4, 3 9, 5 6)", "8 4", "3 9", "5 6"); assertSTPoints("LINESTRING (8 4, 3 9, 5 6, 3 9, 8 4)", "8 4", "3 9", "5 6", "3 9", "8 4"); assertInvalidFunction("ST_Points(ST_GeometryFromText('POLYGON ((8 4, 3 9, 5 6))'))", "ST_Points only applies to LINE_STRING. Input type is: POLYGON"); }
Source:
<code>private void getDirectionsRoute(Point origin, Point destination) { mapboxDirectionsClient = MapboxDirections.builder() .origin(origin) .destination(destination) .overview(DirectionsCriteria.OVERVIEW_FULL) .profile(DirectionsCriteria.PROFILE_DRIVING) .geometries(GEOMETRY_POLYLINE) .alternatives(true) .steps(true) .accessToken(getString(R.string.access_token)) .build(); mapboxDirectionsClient.enqueueCall(new Callback<DirectionsResponse>() { @Override public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) { if (response.body() == null) { <START> Timber.d( "No routes found, make sure you set the right user and access token."); <END> return; } else if (response.body().routes().size() < 1) { Timber.d( "No routes found"); return; } DirectionsRoute currentRoute = response.body().routes().get(0); runnable = new DrawRouteRunnable(mapboxMap, currentRoute.legs().get(0).steps(), handler = new Handler()); handler.postDelayed(runnable, DRAW_SPEED_MILLISECONDS); } @Override public void onFailure(Call<DirectionsResponse> call, Throwable throwable) { Toast.makeText(SnakingDirectionsRouteActivity.this, R.string.snaking_directions_activity_error, Toast.LENGTH_SHORT).show(); } }); }</code><technical_language>space</technical_language>

Target:
private void getDirectionsRoute(Point origin, Point destination) { mapboxDirectionsClient = MapboxDirections.builder() .origin(origin) .destination(destination) .overview(DirectionsCriteria.OVERVIEW_FULL) .profile(DirectionsCriteria.PROFILE_DRIVING) .geometries(GEOMETRY_POLYLINE) .alternatives(true) .steps(true) .accessToken(getString(R.string.access_token)) .build(); mapboxDirectionsClient.enqueueCall(new Callback<DirectionsResponse>() { @Override public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) { if (response.body() == null) { Timber.d("No routes found, make sure you set the right user and access token."); return; } else if (response.body().routes().size() < 1) { Timber.d("No routes found"); return; } DirectionsRoute currentRoute = response.body().routes().get(0); runnable = new DrawRouteRunnable(mapboxMap, currentRoute.legs().get(0).steps(), handler); handler.postDelayed(runnable, DRAW_SPEED_MILLISECONDS); } @Override public void onFailure(Call<DirectionsResponse> call, Throwable throwable) { Toast.makeText(SnakingDirectionsRouteActivity.this, R.string.snaking_directions_activity_error, Toast.LENGTH_SHORT).show(); } }); }
Source:
<code>public void selectTargetBoard(TargetBoard targetBoard) { for (int i = 0; i < boardMenu.getItemCount(); i++) { JMenuItem menuItem = boardMenu.getItem(i); if (!(menuItem instanceof JRadioButtonMenuItem)) { continue; } JRadioButtonMenuItem radioButtonMenuItem = ((JRadioButtonMenuItem) menuItem); if (targetBoard.getName().equals(radioButtonMenuItem.getText())) { radioButtonMenuItem.setSelected(true); break; } } BaseNoGui.selectBoard(targetBoard); filterVisibilityOfSubsequentBoardMenus(boardsCustomMenus, targetBoard, 1); onBoardOrPortChange(); rebuildImportMenu(Editor.importMenu); rebuildExamplesMenu(Editor.examplesMenu); try { rebuildRecentBoardsMenu(); } catch (Exception e) { <START> e.printStackTrace(); <END> } }</code><technical_language>is this try block needed? I suppose GUI modifications throw, hold for e.g. rebuildExamplesMenu()? catch exceptions internally? rebuildRecentBoardsMenu() do same</technical_language>

Target:
public void selectTargetBoard(TargetBoard targetBoard) { for (int i = 0; i < boardMenu.getItemCount(); i++) { JMenuItem menuItem = boardMenu.getItem(i); if (!(menuItem instanceof JRadioButtonMenuItem)) { continue; } JRadioButtonMenuItem radioButtonMenuItem = ((JRadioButtonMenuItem) menuItem); if (targetBoard.getName().equals(radioButtonMenuItem.getText())) { radioButtonMenuItem.setSelected(true); break; } } BaseNoGui.selectBoard(targetBoard); filterVisibilityOfSubsequentBoardMenus(boardsCustomMenus, targetBoard, 1); onBoardOrPortChange(); rebuildImportMenu(Editor.importMenu); rebuildExamplesMenu(Editor.examplesMenu); try { rebuildRecentBoardsMenu(); } catch (Exception e) { } }
Source:
<code>public void setDenominator(final long value) { denominator.dec(denominator.getCount()); <START> denominator.inc(value); <END> }</code><technical_language>avoid awkward blocks making numerator denominator AtomicLong</technical_language>

Target:
public void setDenominator(final long value) { denominator.set(value); }
Source:
<code>public List<FragmentItemModel> getFragmentItems() { ArrayList<FragmentItemModel> items = new ArrayList<>(); items.add(new FragmentItemModel(MyCoursesListFragment.class, getResources().getString(R.string.label_my_courses), FontAwesomeIcons.fa_list_alt, new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { environment.getAnalyticsRegistry().trackScreenView(Analytics.Screens.MY_COURSES); } })); if (environment.getConfig().getProgramConfig().isEnabled() && <START> (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT || <END> environment.getConfig().getProgramConfig().isKitKatEnabled())) { items.add(new FragmentItemModel(WebViewProgramFragment.class, getResources().getString(R.string.label_my_programs), FontAwesomeIcons.fa_clone, WebViewProgramFragment.makeArguments(environment.getConfig().getProgramConfig().getUrl(), null, true), new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { } })); } if (environment.getConfig().getCourseDiscoveryConfig().isCourseDiscoveryEnabled()) { items.add(new FragmentItemModel( environment.getConfig().getCourseDiscoveryConfig().isWebviewCourseDiscoveryEnabled() ? WebViewDiscoverCoursesFragment.class : NativeFindCoursesFragment.class, getResources().getString(R.string.label_discovery), FontAwesomeIcons.fa_search, new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { environment.getAnalyticsRegistry().trackScreenView(Analytics.Screens.FIND_COURSES); } })); } return items; }</code><technical_language>more better, if add KitKat OS flag getProgramConfig().isEnabled()</technical_language>

Target:
public List<FragmentItemModel> getFragmentItems() { ArrayList<FragmentItemModel> items = new ArrayList<>(); items.add(new FragmentItemModel(MyCoursesListFragment.class, getResources().getString(R.string.label_my_courses), FontAwesomeIcons.fa_list_alt, new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { environment.getAnalyticsRegistry().trackScreenView(Analytics.Screens.MY_COURSES); } })); if (environment.getConfig().getProgramConfig().isEnabled()) { items.add(new FragmentItemModel(WebViewProgramFragment.class, getResources().getString(R.string.label_my_programs), FontAwesomeIcons.fa_clone, WebViewProgramFragment.makeArguments(environment.getConfig().getProgramConfig().getUrl(), null, true), new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { } })); } if (environment.getConfig().getCourseDiscoveryConfig().isCourseDiscoveryEnabled()) { items.add(new FragmentItemModel( environment.getConfig().getCourseDiscoveryConfig().isWebviewCourseDiscoveryEnabled() ? WebViewDiscoverCoursesFragment.class : NativeFindCoursesFragment.class, getResources().getString(R.string.label_discovery), FontAwesomeIcons.fa_search, new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { environment.getAnalyticsRegistry().trackScreenView(Analytics.Screens.FIND_COURSES); } })); } return items; }
Source:
<code><START> private VmDevice createVmDevice() { <END> return new VmDevice(new VmDeviceId(Guid.newGuid(), vm.getId()), VmDeviceGeneralType.DISK, "device", "address", 1, new HashMap<String, Object>(), true, true, true, "alias", new HashMap<String, String>(), Guid.newGuid(), "logical", true); }</code><technical_language>Guid.emptyGuid</technical_language>

Target:
private VmDevice createVmDevice() { return new VmDevice(new VmDeviceId(Guid.Empty, vm.getId()), VmDeviceGeneralType.DISK, "device", "address", 1, new HashMap<String, Object>(), true, true, true, "alias", new HashMap<String, String>(), Guid.newGuid(), "logical", true); }
Source:
<code>public void run() { <START> @SuppressWarnings("resource") <END> AbstractApplicationContext ctx = new ClassPathXmlApplicationContext( "testIp-in-context.xml", UdpUnicastEndToEndTests.class); UnicastReceivingChannelAdapter inbound = ctx.getBean(UnicastReceivingChannelAdapter.class); int n = 0; try { while (!inbound.isListening()) { Thread.sleep(100); if (n++ > 100) { throw new RuntimeException("Failed to start listening"); } } } catch (Exception e) { } while (okToRun) { try { readyToReceive.countDown(); sentFirst.await(); } catch (InterruptedException e) { e.printStackTrace(); } QueueChannel channel = ctx.getBean("udpOutChannel", QueueChannel.class); finalMessage = (Message<byte[]>) channel.receive(); MessageHistory history = MessageHistory.read(finalMessage); Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "udpReceiver", 0); assertNotNull(componentHistoryRecord); assertEquals("ip:udp-inbound-channel-adapter", componentHistoryRecord.get("type")); firstReceived.countDown(); try { doneProcessing.await(); } catch (InterruptedException e) { e.printStackTrace(); } } ctx.stop(); ctx.close(); ctx.destroy(); }</code><technical_language>I asked Oleg you: mean</technical_language>

Target:
public void run() { @SuppressWarnings("resource") AbstractApplicationContext ctx = new ClassPathXmlApplicationContext( "testIp-in-context.xml", UdpUnicastEndToEndTests.class); UnicastReceivingChannelAdapter inbound = ctx.getBean(UnicastReceivingChannelAdapter.class); int n = 0; try { while (!inbound.isListening()) { Thread.sleep(100); if (n++ > 100) { throw new RuntimeException("Failed to start listening"); } } } catch (Exception e) { } while (okToRun) { try { readyToReceive.countDown(); sentFirst.await(); } catch (InterruptedException e) { e.printStackTrace(); } QueueChannel channel = ctx.getBean("udpOutChannel", QueueChannel.class); finalMessage = (Message<byte[]>) channel.receive(); MessageHistory history = MessageHistory.read(finalMessage); Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "udpReceiver", 0); assertNotNull(componentHistoryRecord); assertEquals("ip:udp-inbound-channel-adapter", componentHistoryRecord.get("type")); firstReceived.countDown(); try { doneProcessing.await(); } catch (InterruptedException e) { e.printStackTrace(); } } ctx.stop(); ctx.close(); }
Source:
<code>double stringToMeter(String value) { <START> value = value.toLowerCase().replaceAll(" ", "").replaceAll("(meters|meter|mtrs|mtr|mt|m\\.)", "m"); <END> double factor = 1; double offset = 0; value = value.replaceAll("(\\\"|\'\')", "in").replaceAll("(\'|feet)", "ft"); if (value.endsWith("in")) { int startIndex = value.indexOf("ft"); String inchValue; if (startIndex < 0) { startIndex = 0; } else { startIndex += 2; } inchValue = value.substring(startIndex, value.length() - 2); value = value.substring(0, startIndex); offset = Double.parseDouble(inchValue) * 0.0254; } if (value.endsWith("ft")) { value = value.substring(0, value.length() - 2); factor *= 0.3048; } else if (value.endsWith("m")) { value = value.substring(0, value.length() - 1); } if (value.isEmpty()) { return offset; } else { return Double.parseDouble(value) * factor + offset; } }</code><technical_language>[Wiki](<LINK_0> vales happen: metre, metres, meter, meters. find Taginfo, if this is relevant</technical_language>

Target:
public static double stringToMeter(String value) { value = value.toLowerCase().replaceAll(" ", "").replaceAll("(meters|meter|mtrs|mtr|mt|m\\.)", "m"); double factor = 1; double offset = 0; value = value.replaceAll("(\\\"|\'\')", "in").replaceAll("(\'|feet)", "ft"); if (value.startsWith("~") || value.contains("approx")) { value = value.replaceAll("(\\~|approx)", "").trim(); factor = 0.8; } if (value.endsWith("in")) { int startIndex = value.indexOf("ft"); String inchValue; if (startIndex < 0) { startIndex = 0; } else { startIndex += 2; } inchValue = value.substring(startIndex, value.length() - 2); value = value.substring(0, startIndex); offset = Double.parseDouble(inchValue) * 0.0254; } if (value.endsWith("ft")) { value = value.substring(0, value.length() - 2); factor *= 0.3048; } else if (value.endsWith("m")) { value = value.substring(0, value.length() - 1); } if (value.isEmpty()) { return offset; } else { return Double.parseDouble(value) * factor + offset; } }
Source:
<code>public String getMimeTypeForStoreResponse(String id) { String mimeType = null; try (Connection connection = getConnection(); PreparedStatement mySelectSQL = connection.prepareStatement(selectionString)) { mySelectSQL.setString(SELECT_COLUMN_RESPONSE, id); try (ResultSet rs = mySelectSQL.executeQuery()) { if (null == rs || !rs.next()) { LOGGER.warn("No response found for request id " + id); } else { <START> mimeType = rs.getString(2); <END> } } } catch (SQLException ex) { LOGGER.error("Could not look up response in database", ex); } return mimeType; }</code><technical_language>Magic number</technical_language>

Target:
public String getMimeTypeForStoreResponse(String id) { String mimeType = null; try (Connection connection = getConnection(); PreparedStatement selectStatement = connection.prepareStatement(selectionString)) { selectStatement.setString(SELECTION_STRING_REQUEST_ID_PARAM_INDEX, id); try (ResultSet rs = selectStatement.executeQuery()) { if (null == rs || !rs.next()) { LOGGER.warn("No response found for request id " + id); } else { mimeType = rs.getString(SELECTION_STRING_RESPONSE_MIMETYPE_COLUMN_INDEX); } } } catch (SQLException ex) { LOGGER.error("Could not look up response in database", ex); } return mimeType; }
Source:
<code>public void testMissingOperation() throws Exception { Map<String, String> expectedResponseHeaders = new HashMap<String, String>(); expectedResponseHeaders.put("Cache-Control", "must-revalidate,no-cache,no-store"); expectedResponseHeaders.put("Content-Type", "text/html;charset=ISO-8859-1"); expectedResponseHeaders.put("Content-Length", "1327"); expectedResponseHeaders.put("Server", "Jetty(7.6.4.v20120524)"); <START> String expectedResponseBody = <END> "<html>\n" + "<head>\n" + "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\"/>\n" + "<title>Error 400 Missing \"operation\" parameter.</title>\n" + "</head>\n" + "<body>\n" + "<h2>HTTP ERROR: 400</h2>\n" + "<p>Problem accessing /scep/pkiclient.exe. Reason:\n" + "<pre> Missing \"operation\" parameter.</pre></p>\n" + "<hr /><i><small>Powered by Jetty://</small></i>\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "</body>\n" + "</html>\n"; verifyResponse(getURL(), 400, "Missing \"operation\" parameter.", expectedResponseHeaders, expectedResponseBody); }</code><technical_language>I checking response contains string more resilient Jetty changes</technical_language>

Target:
public void testMissingOperation() throws Exception { Map<String, String> expectedResponseHeaders = new HashMap<String, String>(); expectedResponseHeaders.put("Cache-Control", "must-revalidate,no-cache,no-store"); expectedResponseHeaders.put("Content-Type", "text/html;charset=ISO-8859-1"); expectedResponseHeaders.put("Content-Length", "1327"); expectedResponseHeaders.put("Server", "Jetty(7.6.4.v20120524)"); String errorMessage = "Missing \"operation\" parameter."; String response = verifyResponse(getURL(), 400, errorMessage, expectedResponseHeaders); assertThat(response, containsString(errorMessage)); assertThat(response, containsString("Jetty")); }
Source:
<code>private void assertRunning() { if ( stopped ) { throw new IllegalStateException( "Can't start new transaction with stopped " + getClass() ); } <START> } <END></code><technical_language>I KernelTransactionsTest.exceptionWhenStartingNewTransactionOnShutdownInstance is failing of this change</technical_language>

Target:
private void assertRunning() { if ( availabilityGuard.isShutdown() ) { throw new DatabaseShutdownException(); } if ( stopped ) { throw new IllegalStateException( "Can't start new transaction with stopped " + getClass() ); } }
Source:
<code>public void getFreshTimestampShouldFail() { getIndividualTimestamps(20); goBackInTimeFor(10); assertThatThrownBy(timelockService::getFreshTimestamp) .isInstanceOf(AssertionError.class) <START> .hasMessage(generateClocksWentBackwardsMessage(20, 11)); <END> }</code><technical_language>do this, do a hasMessageContaining/hasMessageStartingWith instead of exact match, I idea this this message is supposed be</technical_language>

Target:
public void getFreshTimestampShouldFail() { when(rawTimelockService.getFreshTimestamp()).thenReturn(1L); assertThrowsOnSecondCall(timelockService::getFreshTimestamp); }
Source:
<code>public Collection<PluginInfo> getDownloadedPlugins() { return listPlugins(this.downloadDir) .stream() .map(PluginInfo::create) <START> .collect(Collectors.toList()); <END> }</code><technical_language>MoreCollectors (use Guava hood) return immutable list</technical_language>

Target:
public Collection<PluginInfo> getDownloadedPlugins() { return listPlugins(this.downloadDir) .stream() .map(PluginInfo::create) .collect(MoreCollectors.toList()); }
Source:
<code>private static File initKeystoreDir() { <START> final File target = new File(System.getProperty("user.dir"), "target"); <END> assertTrue(target.exists()); String dataTestDir = TEST_UTIL.getDataTestDir().toString(); File keystoreDir = new File(dataTestDir, TestRESTServerSSL.class.getSimpleName() + "_keys"); keystoreDir.mkdirs(); return keystoreDir; }</code><technical_language>Please create a temporary directory remove in @AfterClass</technical_language>

Target:
private static File initKeystoreDir() { String dataTestDir = TEST_UTIL.getDataTestDir().toString(); File keystoreDir = new File(dataTestDir, TestRESTServerSSL.class.getSimpleName() + "_keys"); keystoreDir.mkdirs(); return keystoreDir; }
Source:
<code>public void propagate(int idxVarInProp, int mask) throws ContradictionException { sdm[idxVarInProp].freeze(); if (idxVarInProp < k) { SetVar intersection = vars[k]; sdm[idxVarInProp].forEach(j -> { if (!intersection.getUB().contains(j)) { SetVar uniqueSet = findUniqueSetThatDoesNotContainJInLB(j); if (uniqueSet != null) { uniqueSet.remove(j, this); } } }, SetEventType.ADD_TO_KER); } else { <START> sdm[idxVarInProp].forEach(j -> { <END> SetVar uniqueSet = findUniqueSetThatDoesNotContainJInLB(j); if (uniqueSet != null) { uniqueSet.remove(j, this); } }, SetEventType.REMOVE_FROM_ENVELOPE); } sdm[idxVarInProp].unfreeze(); }</code><technical_language>this create a new lambda propagation? overhead compared creating object for in constructor</technical_language>

Target:
public void propagate(int idxVarInProp, int mask) throws ContradictionException { sdm[idxVarInProp].freeze(); if (idxVarInProp < k) { sdm[idxVarInProp].forEach(onSetAddToKer, SetEventType.ADD_TO_KER); } else { sdm[idxVarInProp].forEach(onIntersectionRemoveFromEnv, SetEventType.REMOVE_FROM_ENVELOPE); } sdm[idxVarInProp].unfreeze(); }
Source:
<code>public KafkaConnectorTask(KafkaConsumerFactory<?, ?> factory, Properties consumerProps, DatastreamTask task, long commitIntervalMillis, Duration retrySleepDuration, int retryCount) { LOG.info("Creating kafka connector task for datastream task with commit interval {}Ms", task, commitIntervalMillis); _consumerProps = consumerProps; VerifiableProperties properties = new VerifiableProperties(_consumerProps); _processingDelayLogThresholdMs = properties.containsKey(PROCESSING_DELAY_LOG_TRESHOLD_MS) ? properties.getLong(PROCESSING_DELAY_LOG_TRESHOLD_MS) : DEFAULT_PROCESSING_DELAY_LOG_TRESHOLD_MS; _consumerFactory = factory; _datastream = task.getDatastreams().get(0); _task = task; _retryCount = retryCount; _startOffsets = Optional.ofNullable(_datastream.getMetadata().get(DatastreamMetadataConstants.START_POSITION)) .map(json -> JsonUtils.fromJson(json, new TypeReference<Map<Integer, Long>>() { })); _offsetCommitInterval = commitIntervalMillis; _retrySleepDuration = retrySleepDuration; _datastreamName = task.getDatastreams().get(0).getName(); _consumerMetrics = new CommonConnectorMetrics(CLASS_NAME, _datastreamName); <START> _consumerMetrics.createEventProcessingMetrics(); <END> _consumerMetrics.createPollMetrics(); _consumerMetrics.createPartitionMetrics(); }</code><technical_language>good combine "createXXXMetrics" "getXXXMetrics"</technical_language>

Target:
public KafkaConnectorTask(KafkaConsumerFactory<?, ?> factory, Properties consumerProps, DatastreamTask task, long commitIntervalMillis, Duration retrySleepDuration, int retryCount) { LOG.info("Creating kafka connector task for datastream task with commit interval {}Ms", task, commitIntervalMillis); _consumerProps = consumerProps; VerifiableProperties properties = new VerifiableProperties(_consumerProps); _processingDelayLogThresholdMs = properties.containsKey(PROCESSING_DELAY_LOG_TRESHOLD_MS) ? properties.getLong(PROCESSING_DELAY_LOG_TRESHOLD_MS) : DEFAULT_PROCESSING_DELAY_LOG_TRESHOLD_MS; _consumerFactory = factory; _datastream = task.getDatastreams().get(0); _task = task; _retryCount = retryCount; _startOffsets = Optional.ofNullable(_datastream.getMetadata().get(DatastreamMetadataConstants.START_POSITION)) .map(json -> JsonUtils.fromJson(json, new TypeReference<Map<Integer, Long>>() { })); _offsetCommitInterval = commitIntervalMillis; _retrySleepDuration = retrySleepDuration; _datastreamName = task.getDatastreams().get(0).getName(); _consumerMetrics = new CommonConnectorMetrics(CLASS_NAME, _datastreamName, LOG); _consumerMetrics.createEventProcessingMetrics(); _consumerMetrics.createPollMetrics(); _consumerMetrics.createPartitionMetrics(); }
Source:
<code>private <T extends Tree> void checkStatements(List<T> statements) { Map<String, KeyWriteCollectionUsage> usedKeys = new HashMap<>(); Symbol collection = null; for (T statement : statements) { KeyWriteCollectionUsage keyWriteUsage = keyWriteUsage(statement); if (keyWriteUsage != null) { if (collection != null && keyWriteUsage.collectionSymbol != collection) { usedKeys.clear(); } KeyWriteCollectionUsage sameKeyWriteUsage = usedKeys.get(keyWriteUsage.indexOrKey); if (sameKeyWriteUsage != null) { <START> this.addIssue(keyWriteUsage.tree, message(keyWriteUsage.indexOrKey, sameKeyWriteUsage.tree)); <END> } usedKeys.put(keyWriteUsage.indexOrKey, keyWriteUsage); collection = keyWriteUsage.collectionSymbol; } else { usedKeys.clear(); } } }</code><technical_language>Consider secondary locations point overwritten index other occurrences for collection</technical_language>

Target:
private <T extends Tree> void checkStatements(List<T> statements) { Map<String, KeyWriteCollectionUsage> usedKeys = new HashMap<>(); Symbol collection = null; for (T statement : statements) { KeyWriteCollectionUsage keyWriteUsage = keyWriteUsage(statement); if (keyWriteUsage != null) { if (collection != null && keyWriteUsage.collectionSymbol != collection) { usedKeys.clear(); } KeyWriteCollectionUsage sameKeyWriteUsage = usedKeys.get(keyWriteUsage.indexOrKey); if (sameKeyWriteUsage != null) { addIssue(keyWriteUsage.tree, message(keyWriteUsage.indexOrKey, sameKeyWriteUsage.tree)).secondary(sameKeyWriteUsage.tree); } usedKeys.put(keyWriteUsage.indexOrKey, keyWriteUsage); collection = keyWriteUsage.collectionSymbol; } else { usedKeys.clear(); } } }
Source:
<code>public SecureStore get() { String secureStore = getCurrentSecureStoreName(); if (DefaultSecureStore.NAME.equals(secureStore)) { return defaultSecureStore; } int separatorPosition = secureStore.lastIndexOf("/"); if (separatorPosition < 0) { throw new SecureStoreException(String.format( "Unsupported secure store format %s." + "Proper format is: $plugin_name/$secure_store_name", secureStore)); } String storeName = secureStore.substring(separatorPosition + 1); String pluginName = secureStore.substring(0, separatorPosition); <START> Set<SecureStoreData> stores = getSecureStores(pluginName); for (SecureStoreData store : stores) { if (store.getStoreName().equals(secureStore)) { Class<? extends SecureStore> secureStoreImpl = store.load(); return new SecureStoreWrapper(injector.getInstance(secureStoreImpl)); } } <END> throw new SecureStoreException(String.format( "Cannot find secure store with name %s in plugin %s", storeName, pluginName)); }</code><technical_language>sense a plugin multiple secure-stores ? rationale</technical_language>

Target:
public SecureStore get() { String secureStore = getCurrentSecureStoreName(); if (DefaultSecureStore.NAME.equals(secureStore)) { log.debug("Default SecureStore was selected"); return defaultSecureStore; } int separatorPosition = secureStore.lastIndexOf("/"); if (separatorPosition < 0) { throw new SecureStoreException(String.format( "Unsupported secure store format %s." + "Proper format is: $plugin_name/$secure_store_name", secureStore)); } String storeName = secureStore.substring(separatorPosition + 1); String pluginName = secureStore.substring(0, separatorPosition); Set<SecureStoreData> stores = getSecureStores(pluginName); for (SecureStoreData store : stores) { if (store.getStoreName().equals(secureStore)) { Class<? extends SecureStore> secureStoreImpl = store.load(); log.info("Custom secure store '{}' was selected.", secureStore); return new SecureStoreWrapper(injector.getInstance(secureStoreImpl)); } } throw new SecureStoreException(String.format( "Cannot find secure store with name %s in plugin %s", storeName, pluginName)); }
Source:
<code>public RuleProcessorRuntime(RuleProcessorRuntimeDependenciesBuilder builder) { this.rulesProcessor = builder.getRulesProcessor(); this.rulesRuntime = builder.getRulesRuntime(); buildStreamToRulesRuntime(); <START> rulesProcessor.getConfig().getBoolean("flag"); <END> this.processAll = rulesProcessor.getProcessAll(); }</code><technical_language>I this assigned anywhere. Is this needed</technical_language>

Target:
public RuleProcessorRuntime(RuleProcessorRuntimeDependenciesBuilder builder) { this.rulesProcessor = builder.getRulesProcessor(); this.rulesRuntime = builder.getRulesRuntime(); buildStreamToRulesRuntime(); this.processAll = rulesProcessor.getProcessAll(); }
Source:
<code>private void checkServerState(ControllableServerBehavior beh, String oldMode, String mode) { int state = pollState(); if (!Objects.equals(oldMode, mode)) { IModule[] modules = getServer().getModules(); for( int i = 0; i < modules.length; i++ ) { ((Server)getServer()).setModulePublishState(new IModule[]{modules[i]}, IServer.PUBLISH_STATE_FULL); } <START> new Job("Publishing server " + getServer().getName()) { <END> @Override protected IStatus run(IProgressMonitor monitor) { return getServer().publish(IServer.PUBLISH_INCREMENTAL, monitor); } }.schedule(3000); } if( state == IServer.STATE_STARTED) { beh.setServerStarted(); beh.setRunMode(mode); } else { beh.setServerStopped(); ((ControllableServerBehavior)getControllableBehavior()).setRunMode(null); } }</code><technical_language>prolly want publish server stopped</technical_language>

Target:
private void checkServerState(ControllableServerBehavior beh, String oldMode, String mode) { int state = pollState(); if (!Objects.equals(oldMode, mode)) { IModule[] modules = getServer().getModules(); for( int i = 0; i < modules.length; i++ ) { ((Server)getServer()).setModulePublishState(new IModule[]{modules[i]}, IServer.PUBLISH_STATE_FULL); } if( state == IServer.STATE_STARTED && Boolean.TRUE.equals(beh.getSharedData(OpenShiftServerBehaviour.CURRENTLY_RESTARTING))) { Job j = new Job("Publishing server " + getServer().getName()) { @Override protected IStatus run(IProgressMonitor monitor) { return getServer().publish(IServer.PUBLISH_INCREMENTAL, monitor); } }; j.schedule(3000); beh.putSharedData(OpenShiftServerBehaviour.CURRENTLY_RESTARTING, null); } } if( state == IServer.STATE_STARTED) { beh.setServerStarted(); beh.setRunMode(mode); } else { beh.setServerStopped(); ((ControllableServerBehavior)getControllableBehavior()).setRunMode(null); } }
Source:
<code>public void removeAgent(String uuid) { <START> agentInstanceMap.remove(uuid); <END> }</code><technical_language>I prefer do change behaviour of this method is. tests for changes</technical_language>

Target:
public void removeAgent(String uuid) { uuidToAgentInstanceMap.remove(uuid); }
Source:
<code>public Instant getDeletedAt() { <START> if (this.deletedAt == null) { <END> return Instant.EPOCH; } return deletedAt; }</code><technical_language>This conversion response DTO? Put a lot of regression</technical_language>

Target:
public Instant getDeletedAt() { return deletedAt; }
Source:
<code>public String getJavaString(final ExpressionOperatorParameter parameters) { final Type castFrom = getLeft().getOutputType(parameters); final Type castTo = getRight().getOutputType(parameters); switch (getCastType(castFrom, castTo)) { case NUMTOINT: <START> return new StringBuilder().append("((int)(").append(getLeft().getJavaString(parameters)).append("))") <END> .toString(); case NUMTOFLOAT: return new StringBuilder().append("((float)(").append(getLeft().getJavaString(parameters)).append("))") .toString(); case NUMTODOUBLE: return new StringBuilder().append("((double)(").append(getLeft().getJavaString(parameters)).append("))") .toString(); case NUMTOLONG: return new StringBuilder().append("((long)(").append(getLeft().getJavaString(parameters)).append("))") .toString(); case TOSTR: return new StringBuilder().append("String.valueOf(").append(getLeft().getJavaString(parameters)).append(")") .toString(); case STRTOINT: return new StringBuilder().append("Integer.parseInt(").append(getLeft().getJavaString(parameters)).append(")") .toString(); case STRTOFLOAT: return new StringBuilder().append("Float.parseFloat(").append(getLeft().getJavaString(parameters)).append(")") .toString(); case STRTODOUBLE: return new StringBuilder().append("Double.parseDouble(").append(getLeft().getJavaString(parameters)) .append(")").toString(); case STRTOLONG: return new StringBuilder().append("Long.parseLong(").append(getLeft().getJavaString(parameters)).append(")") .toString(); default: throw new IllegalStateException("should not reach here."); } }</code><technical_language>refactor this create a string builder case append part is in case? Adding ) done a check contains</technical_language>

Target:
public String getJavaString(final ExpressionOperatorParameter parameters) { final Type castFrom = getLeft().getOutputType(parameters); final Type castTo = getRight().getOutputType(parameters); switch (getCastType(castFrom, castTo)) { case NUMTOINT: return getPrimitiveTypeCastString("int", parameters); case NUMTOFLOAT: return getPrimitiveTypeCastString("float", parameters); case NUMTODOUBLE: return getPrimitiveTypeCastString("double", parameters); case NUMTOLONG: return getPrimitiveTypeCastString("long", parameters); case TOSTR: return getLeftFunctionCallString("String.valueOf", parameters); case STRTOINT: return getLeftFunctionCallString("Integer.parseInt", parameters); case STRTOFLOAT: return getLeftFunctionCallString("Float.parseFloat", parameters); case STRTODOUBLE: return getLeftFunctionCallString("Double.parseDouble", parameters); case STRTOLONG: return getLeftFunctionCallString("Long.parseLong", parameters); default: throw new IllegalStateException("should not reach here."); } }
Source:
<code><START> public String describe() { <END> return "DatasetVersion: " + version.getId() + " " + version.getDataset().getDisplayName() + ".v" + version.getFriendlyVersionNumber(); }</code><technical_language>@qqmyers this is ActionLogRecord; is a generic implementation in AbstractCommand</technical_language>

Target:
public String describe() { return super.describe() + "DatasetVersion: [" + version.getId() + " (v" + version.getFriendlyVersionNumber()+")]"; }
Source:
<code>public SubscriptionHealthProblemIndicator laggingIndicator() { if (healthProperties.isLaggingIndicatorEnabled()) { return new LaggingIndicator(healthProperties.getMaxLagInSeconds()); } <START> return new DisabledIndicator(); <END> }</code><technical_language>store a single static instance of DisabledIndicator return everywhere</technical_language>

Target:
public SubscriptionHealthProblemIndicator laggingIndicator() { if (healthProperties.isLaggingIndicatorEnabled()) { return new LaggingIndicator(healthProperties.getMaxLagInSeconds()); } return DISABLED_INDICATOR; }
Source:
<code>public BufferAggregator factorizeBuffered(final ColumnSelectorFactory columnSelectorFactory) { <START> compiledScript = getCompiledScript(); <END> return new JavaScriptBufferAggregator( fieldNames.stream().map(columnSelectorFactory::makeColumnValueSelector).collect(Collectors.toList()), compiledScript ); }</code><technical_language>reassign. other occurrences in this PR</technical_language>

Target:
public BufferAggregator factorizeBuffered(final ColumnSelectorFactory columnSelectorFactory) { JavaScriptAggregator.ScriptAggregator compiledScript = getCompiledScript(); return new JavaScriptBufferAggregator( fieldNames.stream().map(columnSelectorFactory::makeColumnValueSelector).collect(Collectors.toList()), compiledScript ); }
Source:
<code>public String toString() { <START> StringBuilder sb = new StringBuilder(); <END> sb.append(getName()).append(": "); sb.append("(volume: ").append(getVolume()); sb.append("logicalVolume: ").append(getLogicalVolume()); sb.append("mount: ").append(getMount()); sb.append("description: ").append(getDescription()); sb.append("fileSystemType: ").append(getType()); sb.append("total space: ").append(getTotalSpace()); sb.append("free Space available: ").append(getFreeSpace()); sb.append("usable space available: ").append(getUsableSpace()); sb.append("total Inodes: ").append(getTotalInodes()); sb.append("free Inodes: ").append(getFreeInodes()); return sb.toString(); }</code><technical_language>including punctuation entries here. prefer formatted output (GB entire integer) percentage [existing output](<LINK_0> here</technical_language>

Target:
public String toString() { return String.format( " %s (%s) [%s] %s of %s free (%.1f%%), %s of %s files free (%.1f%%) is %s " + (getLogicalVolume() != null && getLogicalVolume().length() > 0 ? "[%s]" : "%s") + " and is mounted at %s", getName(), getDescription().isEmpty() ? "file system" : getDescription(), getType(), FormatUtil.formatBytes(getUsableSpace()), FormatUtil.formatBytes(getTotalSpace()), 100d * getUsableSpace() / getTotalSpace(), FormatUtil.formatValue(getFreeInodes(), ""), FormatUtil.formatValue(getTotalInodes(), ""), 100d * getFreeInodes() / getTotalInodes(), getVolume(), getLogicalVolume(), getMount()); }
Source:
<code>public static String rangeParser(List<String> values) { return <START> String.valueOf(ThreadLocalRandom.current().nextInt(Integer.valueOf(values.get(0)), <END> Integer.valueOf(values.get(1))) ); }</code><technical_language>get NFE values config need account numbers</technical_language>

Target:
public static String rangeParser(List<String> values) { if (values == null) { return "0"; } return String.valueOf(ThreadLocalRandom.current().nextInt(Integer.valueOf(values.get(0)), Integer.valueOf(values.get(1))) ); }
Source:
<code>public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { <START> if (certificates != null) { <END> if (LOG.isDebugEnabled()) { for (int c = 0; c < certificates.length; c++) { X509Certificate cert = certificates[c]; LOG.debug(" Client certificate " + (c + 1) + ":"); LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } defaultTrustManager.checkClientTrusted(certificates, authType); } }</code><technical_language>If certificates null tagged @Nullable</technical_language>

Target:
public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { if (certificates != null) { if (LOGGER.isDebugEnabled()) { for (int c = 0; c < certificates.length; c++) { X509Certificate cert = certificates[c]; LOGGER.debug(" Client certificate " + (c + 1) + ":"); LOGGER.debug(" Subject DN: " + cert.getSubjectDN()); LOGGER.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOGGER.debug(" Valid from: " + cert.getNotBefore()); LOGGER.debug(" Valid until: " + cert.getNotAfter()); LOGGER.debug(" Issuer: " + cert.getIssuerDN()); } } defaultTrustManager.checkClientTrusted(certificates, authType); } }
Source:
<code>public Mono<Void> updateDigitalTwin(String digitalTwinId, List<Object> digitalTwinUpdateOperations) { return updateDigitalTwinWithResponse(digitalTwinId, digitalTwinUpdateOperations, new RequestOptions()) <START> .flatMap(voidResponse -> Mono.empty()); <END> }</code><technical_language>FYI: a map us: .map(voidDigitalTwinsResponse -> null) Mono<Void> is empty Mono -> Mono return anything, I feel Mono.empty() is a representation of transformation here. However, I want point out end result same</technical_language>

Target:
public Mono<Void> updateDigitalTwin(String digitalTwinId, List<Object> digitalTwinUpdateOperations) { return updateDigitalTwinWithResponse(digitalTwinId, digitalTwinUpdateOperations, new UpdateDigitalTwinRequestOptions()) .flatMap(voidResponse -> Mono.empty()); }
Source:
<code>public Void visit(Boolean inTailPosition, FieldGet fieldGet) { <START> fieldGet.getObjectExpr().acceptVisitor(this, inTailPosition); <END> return null; }</code><technical_language>recursive call pass "false" get a field result</technical_language>

Target:
public Void visit(Boolean inTailPosition, FieldGet fieldGet) { fieldGet.getObjectExpr().acceptVisitor(this, false); return null; }
Source:
<code>private CardDetailsEntity buildCardDetailsEntity(AuthCardDetails authCardDetails) { CardDetailsEntity detailsEntity = new CardDetailsEntity(); detailsEntity.setCardBrand(sanitize(authCardDetails.getCardBrand())); detailsEntity.setCardHolderName(sanitize(authCardDetails.getCardHolder())); detailsEntity.setExpiryDate(authCardDetails.getEndDate()); if (hasFullCardNumber(authCardDetails)) { detailsEntity.setFirstDigitsCardNumber(FirstDigitsCardNumber.of(StringUtils.left(authCardDetails.getCardNo(), 6))); } if (hasLastFourCharactersCardNumber(authCardDetails)) { detailsEntity.setLastDigitsCardNumber(LastDigitsCardNumber.of(StringUtils.right(authCardDetails.getCardNo(), 4))); } authCardDetails.getAddress().ifPresent(address -> { <START> AddressEntity addressEntity = new AddressEntity(address); <END> processRegionForCanadaOrUs(addressEntity); detailsEntity.setBillingAddress(addressEntity); }); detailsEntity.setCardType(PayersCardType.toCardType(authCardDetails.getPayersCardType())); return detailsEntity; }</code><technical_language>Good spot! do this: java authCardDetails.getAddress().map(AddressEntity::new).ifPresent(addressEntity -> { // });</technical_language>

Target:
private CardDetailsEntity buildCardDetailsEntity(AuthCardDetails authCardDetails) { CardDetailsEntity detailsEntity = new CardDetailsEntity(); detailsEntity.setCardBrand(sanitize(authCardDetails.getCardBrand())); detailsEntity.setCardHolderName(sanitize(authCardDetails.getCardHolder())); detailsEntity.setExpiryDate(authCardDetails.getEndDate()); if (hasFullCardNumber(authCardDetails)) { detailsEntity.setFirstDigitsCardNumber(FirstDigitsCardNumber.of(StringUtils.left(authCardDetails.getCardNo(), 6))); } if (hasLastFourCharactersCardNumber(authCardDetails)) { detailsEntity.setLastDigitsCardNumber(LastDigitsCardNumber.of(StringUtils.right(authCardDetails.getCardNo(), 4))); } authCardDetails.getAddress().ifPresent(address -> { var addressEntity = new AddressEntity(address); northAmericanRegionMapper.getNorthAmericanRegionForCountry(address) .map(NorthAmericaRegion::getAbbreviation) .ifPresent(stateOrProvinceAbbreviation -> { addressEntity.setStateOrProvince(stateOrProvinceAbbreviation); }); detailsEntity.setBillingAddress(addressEntity); }); detailsEntity.setCardType(PayersCardType.toCardType(authCardDetails.getPayersCardType())); return detailsEntity; }
Source:
<code>public boolean test(final Node<? extends View<?>, ? extends Edge> node, final Node<? extends View<?>, ? extends Edge> node2) { checkNotNull("node", node); checkNotNull("node2", node2); if (!isCandidate.test(node) && !isCandidate.test(node2)) { return true; } <START> boolean matchParent = isCandidate.test(node) <END> ? Objects.equals(GraphUtils.getParent(node2), candidateParent.orElse(null)) : Objects.equals(GraphUtils.getParent(node), candidateParent.orElse(null)); return matchParent && parentsTypeMatchPredicate.test(node, node2); }</code><technical_language>I right knowledge this, sense moving matchParent evaluation parentsTypeMatchPredicate? Again, if sense... giving code "encapsulate" this matchParent evaluation in parentsTypeMatchPredicate, a bit easier follow logic of evaluations done in parentsTypeMatchPredicate, in places (here well). brainstorming... lemme if sense for :) Thx</technical_language>

Target:
public boolean test(final Node<? extends View<?>, ? extends Edge> node, final Node<? extends View<?>, ? extends Edge> node2) { checkNotNull("node", node); checkNotNull("node2", node2); if (!isCandidate.test(node) && !isCandidate.test(node2)) { return true; } return parentsMatchPredicate.test(node, node2); }
Source:
<code>public boolean hasTargets() { <START> return !targets.isEmpty(); <END> }</code><technical_language>This code involves a potential NPE</technical_language>

Target:
public boolean hasTargets() { return (targets != null && !targets.isEmpty()); }