auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static RepositoryMapping getMapping(@NonNull IPath path) { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); IPath bestWorkingTree = null; RepositoryMapping bestMapping = null; for (IProject project : projects) { if (isNonWorkspace(project)) { continue; } Map<IPath, RepositoryMapping> mappings = <START> getMappings(project); <END> for (RepositoryMapping mapping : mappings.values()) { File workTree = mapping.getWorkTree(); if (workTree == null) { continue; } IPath workingTree = new Path(workTree.toString()); if (workingTree.isPrefixOf(path)) { if (bestWorkingTree == null || workingTree .segmentCount() > bestWorkingTree.segmentCount()) { bestWorkingTree = workingTree; bestMapping = mapping; } } } } return bestMapping; }</code><technical_language>inlined: for (RepositoryMapping mmapping : getMappings(project).values())</technical_language>

Target:
public static RepositoryMapping getMapping(@NonNull IPath path) { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); IPath bestWorkingTree = null; RepositoryMapping bestMapping = null; for (IProject project : projects) { if (isNonWorkspace(project)) { continue; } for (RepositoryMapping mapping : getMappings(project).values()) { File workTree = mapping.getWorkTree(); if (workTree == null) { continue; } IPath workingTree = new Path(workTree.toString()); if (workingTree.isPrefixOf(path)) { if (bestWorkingTree == null || workingTree .segmentCount() > bestWorkingTree.segmentCount()) { bestWorkingTree = workingTree; bestMapping = mapping; } } } } return bestMapping; }
Source:
<code><START> public Coordinator(CoordinatorConfig config) throws Exception { <END> _config = config; _adapter = new ZkAdapter(_config.getZkAddress(), _config.getCluster(), _config.getZkSessionTimeout(), _config.getZkConnectionTimeout(), this); _adapter.setListener(this); _eventCollectorFactory = new DatastreamEventCollectorFactory(config.getConfigProperties()); }</code><technical_language>Throwing generic Exception is a great idea. a specific exception</technical_language>

Target:
public Coordinator(CoordinatorConfig config) throws DatastreamException { _config = config; _adapter = new ZkAdapter(_config.getZkAddress(), _config.getCluster(), _config.getZkSessionTimeout(), _config.getZkConnectionTimeout(), this); _adapter.setListener(this); _eventCollectorFactory = new DatastreamEventCollectorFactory(config.getConfigProperties()); }
Source:
<code>public TmfViewsElement getParent() { for (TmfAnalysisElement analysis : fContainedAnalyses) { if (analysis.hasChildren()) { return <START> super.getParent(); <END> } } return super.getParent(); }</code><technical_language>analysis.getParent() here? Although, if this parent is in code (when I this patch this method is called), I return experiment's Views element</technical_language>

Target:
public TmfViewsElement getParent() { return fExperimentParent.getChildElementViews(); }
Source:
<code>private static ObjectStream<POSSample> createSampleStream() throws IOException { MarkableFileInputStreamFactory sampleDataIn; try { <START> sampleDataIn = <END> new MarkableFileInputStreamFactory( new File(POSTaggerFactory.class.getResource( "/AnnotatedSentences.txt").toURI().getPath())); } catch (URISyntaxException e) { throw new IOException(e); } ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, "UTF-8"); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new WordTagSampleStream(lineStream); }</code><technical_language>Do need changes build windows? test this more? A problems fixed in master</technical_language>

Target:
private static ObjectStream<POSSample> createSampleStream() throws IOException { MarkableFileInputStreamFactory sampleDataIn; try { sampleDataIn = new MarkableFileInputStreamFactory( new File(POSTaggerFactory.class.getResource( "/AnnotatedSentences.txt").toURI().getPath())); } catch (URISyntaxException e) { throw new IOException(e); } ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, StandardCharsets.UTF_8); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new WordTagSampleStream(lineStream); }
Source:
<code>public void testDescribeImages() { String region = getFirst(ec2Api.getConfiguredRegions(), null); <START> if (region != null) { <END> Set<? extends Image> allResults = client.describeImagesInRegion(region); assertNotNull(allResults); assert allResults.size() >= 2 : allResults.size(); Iterator<? extends Image> iterator = allResults.iterator(); String id1 = iterator.next().getId(); String id2 = iterator.next().getId(); Set<? extends Image> twoResults = client.describeImagesInRegion(region, imageIds(id1, id2)); assertNotNull(twoResults); assertEquals(twoResults.size(), 2); iterator = twoResults.iterator(); assertEquals(iterator.next().getId(), id1); assertEquals(iterator.next().getId(), id2); } }</code><technical_language>Functional change in test here...are result regions</technical_language>

Target:
public void testDescribeImages() { String region = getFirst(ec2Api.getConfiguredRegions(), null); assertNotNull(region, "region should not be null"); Set<? extends Image> allResults = client.describeImagesInRegion(region); assertNotNull(allResults); assertTrue(allResults.size() >= 2); Iterator<? extends Image> iterator = allResults.iterator(); String id1 = iterator.next().getId(); String id2 = iterator.next().getId(); Set<? extends Image> twoResults = client.describeImagesInRegion(region, imageIds(id1, id2)); assertNotNull(twoResults); assertEquals(twoResults.size(), 2); iterator = twoResults.iterator(); assertEquals(iterator.next().getId(), id1); assertEquals(iterator.next().getId(), id2); }
Source:
<code>private void showLocationPicker() { if (!isAdded()) { return; } PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); LatLng latLng = null; <START> if (mPostLocation != null) { <END> latLng = new LatLng(mPostLocation.getLatitude(), mPostLocation.getLongitude()); } else if (mPost.hasLocation()) { PostLocation location = mPost.getLocation(); latLng = new LatLng(location.getLatitude(), location.getLongitude()); } if (latLng != null) { builder.setLatLngBounds(new LatLngBounds(latLng, latLng)); } try { startActivityForResult(builder.build(getActivity()), ACTIVITY_REQUEST_CODE_PICK_LOCATION); } catch (GooglePlayServicesNotAvailableException nae) { ToastUtils.showToast(getActivity(), R.string.post_settings_error_placepicker_missing_play_services); } catch (GooglePlayServicesRepairableException re) { GooglePlayServicesUtil.getErrorDialog(re.getConnectionStatusCode(), getActivity(), 0); } }</code><technical_language>This is good for now, get rid of mPostLocation completely rely mPost object updating immediately a change. This is a reference intended change</technical_language>

Target:
private void showLocationPicker() { if (!isAdded()) { return; } PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); LatLng latLng = null; if (mPostLocation != null) { latLng = new LatLng(mPostLocation.getLatitude(), mPostLocation.getLongitude()); } else if (mPost.hasLocation()) { PostLocation location = mPost.getLocation(); latLng = new LatLng(location.getLatitude(), location.getLongitude()); } if (latLng != null) { builder.setLatLngBounds(new LatLngBounds(latLng, latLng)); } try { startActivityForResult(builder.build(getActivity()), ACTIVITY_REQUEST_CODE_PICK_LOCATION); } catch (GooglePlayServicesNotAvailableException nae) { ToastUtils.showToast(getActivity(), R.string.post_settings_error_placepicker_missing_play_services); } catch (GooglePlayServicesRepairableException re) { GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), re.getConnectionStatusCode(), ACTIVITY_REQUEST_PLAY_SERVICES_RESOLUTION); } }
Source:
<code>protected Object getExportResult(final URI address, final String serviceName, final Object... args) { final String scheme = address.getScheme() == null ? "irc" : address.getScheme(); try { final Service service = serviceManager.getService("parser", scheme); if (service != null && !service.getProviders().isEmpty()) { final ServiceProvider provider = service.getProviders().get(0); if (provider != null) { provider.activateServices(); return provider.getExportedService(serviceName) .execute(args); } } } catch (NoSuchProviderException nspe) { <START> LOG.warn(USER_ERROR, "No parser found for " + address.getScheme(), nspe); <END> } return null; }</code><technical_language>LOG.warn(USER_ERROR, "No parser for {}", address.getScheme(), nspe);</technical_language>

Target:
protected Object getExportResult(final URI address, final String serviceName, final Object... args) { final String scheme = address.getScheme() == null ? "irc" : address.getScheme(); try { final Service service = serviceManager.getService("parser", scheme); if (service != null && !service.getProviders().isEmpty()) { final ServiceProvider provider = service.getProviders().get(0); if (provider != null) { provider.activateServices(); return provider.getExportedService(serviceName) .execute(args); } } } catch (NoSuchProviderException nspe) { LOG.warn(USER_ERROR, "No parser found for {}", address.getScheme(), nspe); } return null; }
Source:
<code>public void deleteBucketJson() throws Exception { final String bucketName = "test_delete_bucket_json"; try { final String expected = "\"Message\" : \"Success: Deleted " + bucketName + " and all the objects contained in it.\"\n}"; Util.createBucket(client, bucketName); final Arguments args = new Arguments(new String[]{"--http", "-c", "delete_bucket", "-b", bucketName, "--force", "--output-format", "json"}); final CommandResponse response = Util.command(client, args); assertTrue(response.getMessage().endsWith(expected)); <START> } finally { <END> } }</code><technical_language>question this finally</technical_language>

Target:
public void deleteBucketJson() throws Exception { final String bucketName = "test_delete_bucket_json"; final String expected = "\"Message\" : \"Success: Deleted " + bucketName + " and all the objects contained in it.\"\n}"; Util.createBucket(client, bucketName); final Arguments args = new Arguments(new String[]{"--http", "-c", "delete_bucket", "-b", bucketName, "--force", "--output-format", "json"}); final CommandResponse response = Util.command(client, args); assertTrue(response.getMessage().endsWith(expected)); }
Source:
<code>public static Variant makeVariant(String referenceName, long start, long end, String referenceBases, List<String> alternateBases, Call... calls) { Variant variant = new Variant().setReferenceName(referenceName).setStart(start).setEnd(end) .setReferenceBases(referenceBases).setAlternateBases(alternateBases); if (null != calls) { <START> variant.setCalls(newArrayList(calls)); <END> } return variant; }</code><technical_language>Arrays.asList instead of newArrayList Also, calls null (unless user specifically passes in (Call[]) null), want test for length == 0</technical_language>

Target:
public static Variant makeVariant(String referenceName, long start, long end, String referenceBases, List<String> alternateBases, Call... calls) { Variant variant = new Variant().setReferenceName(referenceName).setStart(start).setEnd(end) .setReferenceBases(referenceBases).setAlternateBases(alternateBases); if (null != calls) { variant.setCalls(Arrays.asList(calls)); } return variant; }
Source:
<code>public void testBaselineAdjusment() throws Exception { byte[] buckets = new byte[] {0x45, 0x23, 0x01, 0x31, 0x22, 0x05, 0x04, 0x01}; Slice expected = new DynamicSliceOutput(1) .appendByte(3) .appendByte(4) .appendByte(2) .appendBytes(buckets) .appendByte(0) .appendByte(0) .slice(); DenseHll hll = new DenseHll(4); for (int i = 0; i < 100; i++) { <START> hll.insertHash(Murmur3Hash128.hash64((long) i)); <END> } assertSlicesEqual(hll.serialize(), expected); }</code><technical_language>casts needed in these</technical_language>

Target:
public void testBaselineAdjusment() throws Exception { byte[] buckets = new byte[] {0x45, 0x23, 0x01, 0x31, 0x22, 0x05, 0x04, 0x01}; Slice expected = new DynamicSliceOutput(1) .appendByte(3) .appendByte(4) .appendByte(2) .appendBytes(buckets) .appendByte(0) .appendByte(0) .slice(); DenseHll hll = new DenseHll(4); for (int i = 0; i < 100; i++) { hll.insertHash(Murmur3Hash128.hash64(i)); } assertSlicesEqual(hll.serialize(), expected); }
Source:
<code><START> public void unbuffer() { <END> buffer = null; fCursor = fCursor - limit + bCursor; fCursorAfterLastRead = -1; bCursor = 0; limit = 0; }</code><technical_language>synchronized</technical_language>

Target:
public synchronized void unbuffer() { buffer = null; fCursor = fCursor - limit + bCursor; fCursorAfterLastRead = -1; bCursor = 0; limit = 0; }
Source:
<code>void validateFileDetails(FormDataContentDisposition fileDetail) { FileValidator validator = new FileValidator(); <START> boolean validName = validator.isValidFileName("validating uploaded file name", fileDetail.getFileName(), true); <END> if (!validName) { throw new IllegalArgumentException("File name is invalid"); } boolean validSize = validator.getMaxFileUploadSize() >= fileDetail.getSize(); if (!validSize) { throw new IllegalArgumentException("File size is invalid. Max size is: " + validator.getMaxFileUploadSize()/1000000 + " MB"); } }</code><technical_language>validator ensure filename a uuid format? constitutes a valid filename</technical_language>

Target:
protected void validateFileDetails(FormDataContentDisposition fileDetail) { FileValidator validator = new FileValidator(); boolean validName = validator.isValidFileName("validating uploaded file name", fileDetail.getFileName(), true); if (!validName) { throw new IllegalArgumentException("File name is invalid"); } boolean validSize = validator.getMaxFileUploadSize() >= fileDetail.getSize(); if (!validSize) { throw new IllegalArgumentException("File size is invalid. Max size is: " + validator.getMaxFileUploadSize()/1000000 + " MB"); } }
Source:
<code><START> public synchronized DataSize getTotalPendingSize() <END> { return new DataSize(pendingPages.stream().mapToLong(DataSize::toBytes).sum(), BYTE); }</code><technical_language>this return long rename getTotalPendingBytes forth</technical_language>

Target:
public synchronized long getTotalPendingSize() { return pendingPageSizesInBytes.stream().mapToLong(Long::longValue).sum(); }
Source:
<code>private boolean userRequestedSpecificFile(MIBreakpoint miBpt) { assert isFunctionBreakpoint(miBpt); String originalLocation = miBpt.getOriginalLocation(); boolean userRequestedSpecificFile = originalLocation != null && originalLocation.contains(":"); <START> return userRequestedSpecificFile; <END> }</code><technical_language>need for 'userRequestedSpecificFile', 'return originalLocation...'</technical_language>

Target:
private boolean userRequestedSpecificFile(MIBreakpoint miBpt) { assert isFunctionBreakpoint(miBpt); String originalLocation = miBpt.getOriginalLocation(); return originalLocation != null && originalLocation.contains(":"); }
Source:
<code><START> private boolean areNetworksValid(QualifiedNetworks <END> networks) { if (networks.qualifiedNetworks == null) { return true; } for (int network : networks.qualifiedNetworks) { if (!ACCESS_NETWORK_TRANSPORT_TYPE_MAP.containsKey(network)) { return false; } } return true; }</code><technical_language>static</technical_language>

Target:
private static boolean areNetworksValid(QualifiedNetworks networks) { if (networks.qualifiedNetworks == null) { return false; } for (int network : networks.qualifiedNetworks) { if (!ACCESS_NETWORK_TRANSPORT_TYPE_MAP.containsKey(network)) { return false; } } return true; }
Source:
<code><START> public int getGarbageSizeUpTo(long addressUpTo) { <END> return streamIdToGarbageMap.values().stream() .flatMap(multiSMRGarbage -> multiSMRGarbage.values().stream()) .map(smrRecordGarbage -> smrRecordGarbage.getSmrEntrySize()) .reduce(0, (a, b) -> a + b); }</code><technical_language>addressUpTo is used? For reference, codes I use: java public int getGarbageSizeUpTo(long addressUpTo) { return streamIdToGarbageMap.values().stream() .map(multiSmr -> multiSmr.getGarbageSizeUpTo(addressUpTo)) .reduce(0, (a, b) -> a + b); }</technical_language>

Target:
public int getGarbageSizeUpTo(long addressUpTo) { return streamIdToGarbageMap.values().stream() .flatMap(multiSMRGarbage -> multiSMRGarbage.values().stream()) .map(smrRecordGarbage -> smrRecordGarbage.getGarbageSizeUpTo(addressUpTo)) .reduce(0, (a, b) -> a + b); }
Source:
<code>public void run_cukes() { runtime.run(); if (!runtime.getErrors().isEmpty()) { <START> throw new RuntimeException(runtime.getErrors().get(0)); <END> } }</code><technical_language>throw CucumberException here</technical_language>

Target:
public void run_cukes() { runtime.run(); if (!runtime.getErrors().isEmpty()) { throw new CucumberException(runtime.getErrors().get(0)); } }
Source:
<code>public boolean adjustSelection(final SelectionExtension direction, final boolean isShiftKeyDown) { final boolean selectionChanged = super.adjustSelection(direction, isShiftKeyDown); scenarioGridPanel.signalRightPanelNoHeaderCellSelected(); if (getModel().getSelectedHeaderCells().size() > 0) { final GridData.SelectedCell cell = getModel().getSelectedHeaderCells().get(0); final int uiColumnIndex = ColumnIndexUtilities.findUiColumnIndex(getModel().getColumns(), cell.getColumnIndex()); final int uiRowIndex = cell.getRowIndex(); setSelectedColumnAndHeader(uiRowIndex, uiColumnIndex); final GridColumn column = getModel().getColumns().get(uiColumnIndex); if (uiRowIndex > 0 && column instanceof ScenarioGridColumn) { final EnableRightPanelEvent enableRightPanelEvent = enableRightPanelEvent((ScenarioGridColumn) column, cell, uiColumnIndex); <START> scenarioGridPanel.signalRightPanelHeaderCellSelected(enableRightPanelEvent); <END> } } return selectionChanged; }</code><technical_language>This is un-consistent previous code (*scenarioGridPanel.signalRightPanelNoHeaderCellSelected();*) and, for readability/debug/management, is create events soon usage in eventbus; in case, instantiate EnableRightPanelEvent scenarioGridPanel.signalRightPanelHeaderCellSelected() (as done for scenarioGridPanel.signalRightPanelNoHeaderCellSelected())</technical_language>

Target:
public boolean adjustSelection(final SelectionExtension direction, final boolean isShiftKeyDown) { final boolean selectionChanged = super.adjustSelection(direction, isShiftKeyDown); signalRightPanelAboutSelectedHeaderCells(); return selectionChanged; }
Source:
<code>public long toBytes() { double bytes = getValue(Unit.BYTE); <START> Preconditions.checkArgument(bytes <= Long.MAX_VALUE, <END> "size is too large to be represented in requested unit as a long"); return (long) bytes; }</code><technical_language>This checkState</technical_language>

Target:
public long toBytes() { double bytes = getValue(Unit.BYTE); Preconditions.checkState(bytes <= Long.MAX_VALUE, "size is too large to be represented in bytes as a long"); return (long) bytes; }
Source:
<code>private boolean deQueueAction(ContainerPlacementRequestMessage requestMessage) { <START> if (hasActiveContainerPlacementAction(requestMessage.getProcessorId())) { return false; } if (!samzaApplicationState.runningProcessors.containsKey(requestMessage.getProcessorId()) || samzaApplicationState.pendingProcessors.containsKey(requestMessage.getProcessorId())) { return false; <END> } return true; }</code><technical_language>info logging useful here</technical_language>

Target:
private boolean deQueueAction(ContainerPlacementRequestMessage requestMessage) { if (hasActiveContainerPlacementAction(requestMessage.getProcessorId())) { LOG.info("ContainerPlacement request: is en-queued because container has an in-progress placement action", requestMessage); return false; } if (!samzaApplicationState.runningProcessors.containsKey(requestMessage.getProcessorId()) || samzaApplicationState.pendingProcessors.containsKey(requestMessage.getProcessorId())) { LOG.info("ContainerPlacement request: is en-queued because container is pending start", requestMessage); return false; } return true; }
Source:
<code>private void buildCharacters(String pattern) { codePointSet = new HashSet<>(); <START> codePointList = new ArrayList<>(); <END> for (String subPattern : pattern.substring(1, pattern.length() - 1).split("\\|")) { if (isInterval(subPattern)) { String[] startEnd = subPattern.split("-"); Integer start = getCodePointAt(startEnd[0].substring(1)); Integer end = getCodePointAt(startEnd[1].substring(0, startEnd[1].length() - 1)); for (int i = start; i <= end; i++) { fillSetAndList(i, subPattern); } } else { Integer codePoint = getCodePointAt(subPattern); fillSetAndList(codePoint, subPattern); } } }</code><technical_language>varaibles intialized declaration</technical_language>

Target:
private void buildCharacters(String pattern) { for (String subPattern : pattern.substring(1, pattern.length() - 1).split("\\|")) { if (isInterval(subPattern)) { String[] startEnd = subPattern.split("-"); Integer start = getCodePointAt(startEnd[0].substring(1)); Integer end = getCodePointAt(startEnd[1].substring(0, startEnd[1].length() - 1)); for (int i = start; i <= end; i++) { fillSetAndList(i, subPattern); } } else { Integer codePoint = getCodePointAt(subPattern); fillSetAndList(codePoint, subPattern); } } }
Source:
<code>public void get_schema() { Configuration configuration = new Configuration(new H2Templates()); configuration.registerSchemaOverride("public", "pub"); configuration.registerTableOverride("employee", "emp"); configuration.registerTableOverride("public", "employee", "employees"); assertEquals("pub", configuration.getOverride(new SchemaAndTable("public", "")).getSchema()); assertEquals("emp", configuration.getOverride(new SchemaAndTable("", "employee")).getTable()); assertEquals("employees", configuration.getOverride(new SchemaAndTable("public", "employee")).getTable()); configuration.setDynamicNameMapping(new ChangeCaseNameMapping(LetterCase.UPPER)); String notDirectOverriden = "notDirectOverriden"; <START> assertEquals(notDirectOverriden.toUpperCase(), <END> configuration.getOverride(new SchemaAndTable("public", notDirectOverriden)).getTable()); }</code><technical_language>a toUpperCase() call a Locale fails Turkey test</technical_language>

Target:
public void get_schema() { Configuration configuration = new Configuration(new H2Templates()); configuration.registerSchemaOverride("public", "pub"); configuration.registerTableOverride("employee", "emp"); configuration.registerTableOverride("public", "employee", "employees"); assertEquals("pub", configuration.getOverride(new SchemaAndTable("public", "")).getSchema()); assertEquals("emp", configuration.getOverride(new SchemaAndTable("", "employee")).getTable()); assertEquals("employees", configuration.getOverride(new SchemaAndTable("public", "employee")).getTable()); configuration.setDynamicNameMapping(new PreConfiguredNameMapping()); SchemaAndTable notOverriddenSchemaAndTable = new SchemaAndTable("notoverridden", "notoverridden"); assertEquals(notOverriddenSchemaAndTable, configuration.getOverride(notOverriddenSchemaAndTable)); configuration.setDynamicNameMapping(new ChangeLetterCaseNameMapping(LetterCase.UPPER, Locale.ENGLISH)); String notDirectOverriden = "notDirectOverriden"; assertEquals(notDirectOverriden.toUpperCase(Locale.ENGLISH), configuration.getOverride(new SchemaAndTable("public", notDirectOverriden)).getTable()); }
Source:
<code>public boolean exists( String fileSystem, String path ) { PathMap pathMap = getPathMap( fileSystem, path ); if ( pathMap != null ) { return true; } <START> return false; <END> }</code><technical_language>nitpick. single statement is enough: return getPathMap(fileSystem, path)!=null</technical_language>

Target:
public boolean exists( String fileSystem, String path ) { return getPathMap( fileSystem, path ) != null; }
Source:
<code>public void validate() throws Exception { boolean contactPhotoFound = false; for (int attachmentIndex = 0; attachmentIndex < this.getAddedItems() .size(); attachmentIndex++) { Attachment attachment = this.getAddedItems().get(attachmentIndex); if (attachment != null && attachment.isNew()) { if (this.owner.isNew() && this.owner.getService().getRequestedServerVersion() .ordinal() >= ExchangeVersion.Exchange2010_SP2 .ordinal()) { <START> if (attachment instanceof FileAttachment) { <END> FileAttachment fileAttachment = (FileAttachment) attachment; if (fileAttachment.isContactPhoto()) { if (contactPhotoFound) { throw new ServiceValidationException( Strings.MultipleContactPhotosInAttachment); } contactPhotoFound = true; } } } attachment.validate(attachmentIndex); } } }</code><technical_language>perhabs ifs combined for overview</technical_language>

Target:
public void validate() throws Exception { if (this.owner.isNew() && this.owner.getService().getRequestedServerVersion() .ordinal() >= ExchangeVersion.Exchange2010_SP2 .ordinal()) { boolean contactPhotoFound = false; for (int attachmentIndex = 0; attachmentIndex < this.getAddedItems() .size(); attachmentIndex++) { final Attachment attachment = this.getAddedItems().get(attachmentIndex); if (attachment != null && attachment.isNew() && attachment instanceof FileAttachment) { if (((FileAttachment) attachment).isContactPhoto()) { if (contactPhotoFound) { throw new ServiceValidationException( Strings.MultipleContactPhotosInAttachment); } contactPhotoFound = true; } } attachment.validate(attachmentIndex); } } }
Source:
<code>public void testPrependsCorrectName() throws NoSuchMethodException { final TemplateEngine original = mock(TemplateEngine.class); final StatementContext ctx = mock(StatementContext.class); final String template = UUID.randomUUID().toString(); <START> final String originalRendered = UUID.randomUUID().toString(); <END> final ExtensionMethod extensionMethod = new ExtensionMethod(MyDao.class, MyDao.class.getMethod("myDbCall")); when(ctx.getExtensionMethod()).thenReturn(extensionMethod); when(original.render(template, ctx)).thenReturn(originalRendered); final NamePrependingTemplateEngine sut = new NamePrependingTemplateEngine(original); final String result = sut.render(template, ctx); assertThat(result).containsSequence( " ", originalRendered); }</code><technical_language>I extract preparing of variables a setup method share tests</technical_language>

Target:
public void testPrependsCorrectName() throws NoSuchMethodException { final ExtensionMethod extensionMethod = new ExtensionMethod(MyDao.class, MyDao.class.getMethod("myDbCall")); when(ctx.getExtensionMethod()).thenReturn(extensionMethod); final String result = sut.render(TEMPLATE, ctx); assertThat(result).containsSequence( " ", ORIGINAL_RENDERED); }
Source:
<code>public static SshConnection getConnection(String host, int port, String proxy, Authentication authentication) throws IOException { <START> return getConnection(host, port, proxy, authentication, null, 0); <END> }</code><technical_language>GerritDefaultValues.DEFAULT_GERRIT_SSH_CONNECTION_TIMEOUT I guess</technical_language>

Target:
public static SshConnection getConnection(String host, int port, String proxy, Authentication authentication) throws IOException { return getConnection(host, port, proxy, authentication, null, GerritDefaultValues.DEFAULT_GERRIT_SSH_CONNECTION_TIMEOUT); }
Source:
<code>protected void initFrontend() { super.initFrontend(); Frontend.setLoginHandler(new FrontendLoginHandler() { @Override public void onLoginSuccess(String userName, String password, String domain) { <START> acquireRestApiSession(Base64Utils.getBasicAuthString(userName, password, domain)); <END> } @Override public void onLogout() { releaseRestApiSession(); } }); }</code><technical_language>this? RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); builder.setHeader("Prefer", "persistent-auth"); builder.setUser(userName + "@" + domain); builder.setPassword(password); GWT browser translate right authentication header, basic server requires. In addition woudn't need include Base64Utils class license is clear. Saving this auth string in memory is safer saving password itself</technical_language>

Target:
protected void initFrontend() { super.initFrontend(); Frontend.setLoginHandler(new FrontendLoginHandler() { @Override public void onLoginSuccess(final String userName, final String password, final String domain) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { final String domainToken = "@"; restApiSessionManager.acquireSession( userName.contains(domainToken) ? userName : userName + domainToken + domain, password); } }); } @Override public void onLogout() { restApiSessionManager.releaseSession(); } }); }
Source:
<code><START> public void updatePhysics(GlowBlock me) { <END> me.getWorld().requestPulse(me, 2); }</code><technical_language>call super.updatePhysics(me) properly breaks block is attached breaks</technical_language>

Target:
public void updatePhysics(GlowBlock me) { super.updatePhysics(me); me.getWorld().requestPulse(me, 2); }
Source:
<code>private static void assertFunctionEquals(BiFunction<Object, Object, Boolean> isEqual, String testDescription, Object expectedValue, Object actualValue) { StringBuilder sb = new StringBuilder(); if (testDescription != null) { sb.append(String.format("Test: %s, ", testDescription)); } sb.append(String.format("Expected: %s, actual: %s", expectedValue, actualValue)); <START> assertTrue(isEqual.apply(actualValue, expectedValue), sb.toString()); <END> }</code><technical_language>nit: avoid composing error message for happy cases, consider changing logic do if isEqual return false</technical_language>

Target:
private static void assertFunctionEquals(BiFunction<Object, Object, Boolean> isEqual, String testDescription, Object expectedValue, Object actualValue) { if (!isEqual.apply(actualValue, expectedValue)) { StringBuilder sb = new StringBuilder(); if (testDescription != null) { sb.append(String.format("Test: %s, ", testDescription)); } sb.append(String.format("Expected: %s, actual: %s", expectedValue, actualValue)); fail(sb.toString()); } }
Source:
<code>public void testOTAPublicRelease() { BaseResourceTestHelper.stubGetClientDetails(this.oAuthTokenStore, Optional.of(BaseResourceTestHelper.getAccessToken())); BaseResourceTestHelper.stubKeyFromKeyStore(this.keyStore, SENSE_ID, Optional.of(KEY)); BaseResourceTestHelper.stubGetHeader(this.httpServletRequest, HelloHttpHeader.SENSE_ID, SENSE_ID); stubGetUserInfo(this.mergedUserInfoDynamoDB, userInfoList); stubGetFeatureActive(featureFlipper, FeatureFlipper.ENABLE_OTA_UPDATES, Collections.EMPTY_LIST, true); stubGetFeatureActive(featureFlipper, FeatureFlipper.OTA_RELEASE, Collections.EMPTY_LIST, true); stubGetOTAWindowStart(otaConfiguration, 11); stubGetOTAWindowEnd(otaConfiguration, 20); stubGetPopulatedFirmwareFileListForGroup(this.firmwareUpdateStore, FeatureFlipper.OTA_RELEASE, FIRMWARE_VERSION, fileList); final long unixTime = new Date().getTime() / 1000L; final byte[] data = this.receiveResource.receiveBatchSenseData(generateValidProtobufWithSignature(KEY, 3600, FIRMWARE_VERSION, (int)unixTime)); final byte[] protobufBytes = Arrays.copyOfRange(data, 16 + 32, data.length); final OutputProtos.SyncResponse syncResponse; try { syncResponse = OutputProtos.SyncResponse.parseFrom(protobufBytes); <START> assertThat(syncResponse.hasResetMcu(), is(true)); <END> assertThat(syncResponse.getFilesCount(), is(1)); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); assertThat(true, is(false)); } }</code><technical_language>test syncResponse.getResetMcu() is false</technical_language>

Target:
public void testOTAPublicRelease() { BaseResourceTestHelper.stubGetClientDetails(oAuthTokenStore, Optional.of(BaseResourceTestHelper.getAccessToken())); BaseResourceTestHelper.stubKeyFromKeyStore(keyStore, SENSE_ID, Optional.of(KEY)); BaseResourceTestHelper.stubGetHeader(httpServletRequest, HelloHttpHeader.SENSE_ID, SENSE_ID); stubGetUserInfo(mergedUserInfoDynamoDB, userInfoList); stubGetFeatureActive(featureFlipper, FeatureFlipper.ENABLE_OTA_UPDATES, Collections.EMPTY_LIST, true); stubGetFeatureActive(featureFlipper, FeatureFlipper.OTA_RELEASE, Collections.EMPTY_LIST, true); stubGetOTAWindowStart(otaConfiguration, 11); stubGetOTAWindowEnd(otaConfiguration, 20); stubGetPopulatedFirmwareFileListForGroup(firmwareUpdateStore, FeatureFlipper.OTA_RELEASE, FIRMWARE_VERSION, fileList); final long unixTime = DateTime.now().withZone(userTimeZone).getMillis() / 1000L; final byte[] data = receiveResource.receiveBatchSenseData(generateValidProtobufWithSignature(KEY, 3600, FIRMWARE_VERSION, (int)unixTime)); final byte[] protobufBytes = Arrays.copyOfRange(data, 16 + 32, data.length); final OutputProtos.SyncResponse syncResponse; try { syncResponse = OutputProtos.SyncResponse.parseFrom(protobufBytes); assertThat(syncResponse.hasResetMcu(), is(true)); assertThat(syncResponse.getResetMcu(), is(false)); assertThat(syncResponse.getFilesCount(), is(1)); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); assertThat(true, is(false)); } }
Source:
<code>private void executeTool(Connection conn, ConnectionQueryServices queryServices, Configuration conf) { LOGGER.info("Executing "+ operation); for (Map.Entry<String, ArrayList<String>> entry: tablesAndIndexes.entrySet()) { String dataTableFullName = entry.getKey(); ArrayList<String> indexes = entry.getValue(); try (Admin admin = queryServices.getAdmin()) { PTable dataTable = PhoenixRuntime.getTableNoCache(conn, dataTableFullName); LOGGER.fine("Executing "+operation+" for " + dataTableFullName); boolean mutable = !(dataTable.isImmutableRows()); if (upgrade) { <START> setCompactionEnabled(admin, entry, false); <END> checkAndWaitForMajorCompaction(admin, entry); disableTable(admin, entry); modifyIndexTable(admin, indexes); if (mutable) { modifyDataTable(admin, dataTableFullName); } enableTable(admin, entry); rebuildIndexes(entry, conf); setCompactionEnabled(admin, entry, true); } else { disableTable(admin, entry); if(mutable) { modifyDataTable(admin, dataTableFullName); } modifyIndexTable(admin, indexes); enableTable(admin, entry); } } catch (IOException | SQLException e) { LOGGER.severe("Something went wrong while executing "+operation+" steps " + e); } } }</code><technical_language>Nit: Instead of passing-around entry helper functions, more intuitive if passed (String tableName, ArrayList<String> indexNames) explicitly - of of them, needed functions</technical_language>

Target:
private int executeTool(Connection conn, ConnectionQueryServices queryServices, Configuration conf) { LOGGER.info("Executing " + operation); List<Integer> statusList = tablesAndIndexes.entrySet().parallelStream().map(entry -> { String dataTableFullName = entry.getKey(); HashSet<String> indexes = entry.getValue(); try (Admin admin = queryServices.getAdmin()) { PTable dataTable = PhoenixRuntime.getTableNoCache(conn, dataTableFullName); LOGGER.fine("Executing " + operation + " for " + dataTableFullName); boolean mutable = !(dataTable.isImmutableRows()); if (!mutable) { LOGGER.fine("Data table is immutable, waiting for " + GLOBAL_INDEX_CHECKER_ENABLED_MAP_EXPIRATION_MIN + 1 + " minutes for client cache to expire"); if (!test) { Thread.sleep( (GLOBAL_INDEX_CHECKER_ENABLED_MAP_EXPIRATION_MIN + 1) * 60 * 1000); } } disableTable(admin, dataTableFullName, indexes); modifyTable(admin, dataTableFullName, indexes); enableTable(admin, dataTableFullName, indexes); if (upgrade) { rebuildIndexes(dataTableFullName, conf); } } catch (IOException | SQLException | InterruptedException e) { LOGGER.severe("Something went wrong while executing " + operation + " steps " + e); return -1; } return 0; }).collect(Collectors.toList()); return statusList.parallelStream().anyMatch(p -> p == -1) ? -1 : 0; }
Source:
<code>public Image getColumnImage(final Object element, final int columnIndex) { if (columnIndex == 0) { final FileDiff c = (FileDiff) element; switch (c.getChange()) { case ADD: return getDecoratedImage(getEditorImage(c), UIIcons.OVR_STAGED_ADD); case COPY: <START> return COPY; <END> case DELETE: return getDecoratedImage(getEditorImage(c), UIIcons.OVR_STAGED_REMOVE); case RENAME: case MODIFY: return getEditorImage(c); } } return null; }</code><technical_language>I this case in list of fallback cases (unfortunately, I create a COPY diff)..</technical_language>

Target:
public Image getColumnImage(final Object element, final int columnIndex) { if (columnIndex == 0) { final FileDiff c = (FileDiff) element; switch (c.getChange()) { case ADD: return getDecoratedImage(getEditorImage(c), UIIcons.OVR_STAGED_ADD); case DELETE: return getDecoratedImage(getEditorImage(c), UIIcons.OVR_STAGED_REMOVE); case COPY: case RENAME: case MODIFY: return getEditorImage(c); } } return null; }
Source:
<code><START> protected boolean isVersionSupportedForShareable() { <END> return getStoragePool() != null ?Config.<Boolean> GetValue(ConfigValues.ShareableDiskEnabled, getStoragePool().getcompatibility_version().getValue()) : true; }</code><technical_language>pool null? magic...</technical_language>

Target:
protected boolean isVersionSupportedForShareable() { if (getParameters().getDiskInfo().getDiskStorageType() == DiskStorageType.IMAGE) { return Config.<Boolean> GetValue(ConfigValues.ShareableDiskEnabled, getStoragePool().getcompatibility_version().getValue()); } return true; }
Source:
<code>public void testDelimitedRecords() throws Exception { DelimitedApplication app = new DelimitedApplication(); LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); conf.set("dt.operator.HDFSRecordReaderModule.prop.files", inputDir); conf.set("dt.operator.HDFSRecordReaderModule.prop.blocksThreshold", "1"); conf.set("dt.operator.HDFSRecordReaderModule.prop.scanIntervalMillis", "10000"); lma.prepareDAG(app, conf); LocalMode.Controller lc = lma.getController(); lc.setHeartbeatMonitoringEnabled(true); lc.run(10 * 1000); LOG.debug("Waiting for app to finish"); Thread.sleep(1000 * 1); <START> lc.shutdown(); <END> Set<String> expectedRecords = new HashSet<String>(Arrays.asList(FILE_1_DATA.split("\n"))); expectedRecords.addAll(Arrays.asList(FILE_2_DATA.split("\n"))); Assert.assertEquals(expectedRecords, DelimitedValidator.records); }</code><technical_language>lc.shutdown is required if lc.run time > 0</technical_language>

Target:
public void testDelimitedRecords() throws Exception { DelimitedApplication app = new DelimitedApplication(); LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); conf.set("dt.operator.HDFSRecordReaderModule.prop.files", inputDir); conf.set("dt.operator.HDFSRecordReaderModule.prop.blocksThreshold", "1"); conf.set("dt.operator.HDFSRecordReaderModule.prop.scanIntervalMillis", "10000"); lma.prepareDAG(app, conf); LocalMode.Controller lc = lma.getController(); lc.setHeartbeatMonitoringEnabled(true); lc.runAsync(); Set<String> expectedRecords = new HashSet<String>(Arrays.asList(FILE_1_DATA.split("\n"))); expectedRecords.addAll(Arrays.asList(FILE_2_DATA.split("\n"))); while (DelimitedValidator.records.size() != expectedRecords.size()) { LOG.debug("Waiting for app to finish"); Thread.sleep(1000); } lc.shutdown(); Assert.assertEquals(expectedRecords, DelimitedValidator.records); }
Source:
<code>void onWordCount() { totalWords = 0; selectionWords = 0; Position pos = docDisplay_.getCursorPosition(); TextFileType fileType = docDisplay_.getFileType(); Iterable<Range> wordSource = docDisplay_.getWords( fileType.getTokenPredicate(), docDisplay_.getFileType().getCharPredicate(), pos, null); totalWords = 0; wordSource.forEach((r) -> totalWords++); Range selectionRange = docDisplay_.getSelectionRange(); if (selectionRange.getStart().compareTo(selectionRange.getEnd()) != 0) { wordSource = docDisplay_.getWords( fileType.getTokenPredicate(), docDisplay_.getFileType().getCharPredicate(), docDisplay_.getSelectionStart(), docDisplay_.getSelectionEnd()); <START> selectionWords = 0; <END> wordSource.forEach((r) -> selectionWords++); } String selectedWordsText = selectionWords == 0 ? "" : "\nSelected words: " + selectionWords; globalDisplay_.showMessage(MessageDisplay.MSG_INFO, "Word Count", "Total words: " + totalWords + " " + selectedWordsText); }</code><technical_language>this variable get reset command invocations if selection is present</technical_language>

Target:
void onWordCount() { int totalWords = 0; int selectionWords = 0; Range selectionRange = docDisplay_.getSelectionRange(); TextFileType fileType = docDisplay_.getFileType(); Iterator<Range> wordIter = docDisplay_.getWords( fileType.getTokenPredicate(), docDisplay_.getFileType().getCharPredicate(), Position.create(0, 0), null).iterator(); while (wordIter.hasNext()) { Range r = wordIter.next(); totalWords++; if (selectionRange.intersects(r)) selectionWords++; } String selectedWordsText = selectionWords == 0 ? "" : "\nSelected words: " + selectionWords; globalDisplay_.showMessage(MessageDisplay.MSG_INFO, "Word Count", "Total words: " + totalWords + " " + selectedWordsText); }
Source:
<code>public static void setUp() { try { final URL location = FileLocator.find(TmfCoreTestPlugin.getDefault().getBundle(), new Path(TEST_TRACE.getFullPath()), null); final File test = new File(FileLocator.toFileURL(location).toURI()); fTrace = new TmfTraceStub(test.toURI().getPath(), ITmfTrace.DEFAULT_TRACE_CACHE_SIZE, false, null); TmfSignalManager.deregister(fTrace); fTrace.indexTrace(true); } catch (final TmfTraceException | URISyntaxException | IOException e) { <START> fail(e.toString()); <END> } }</code><technical_language>forgot commit printStackTrace()</technical_language>

Target:
public static void setUp() { try { final URL location = FileLocator.find(TmfCoreTestPlugin.getDefault().getBundle(), new Path(TEST_TRACE.getFullPath()), null); final File test = new File(FileLocator.toFileURL(location).toURI()); fTrace = new TmfTraceStub(test.toURI().getPath(), ITmfTrace.DEFAULT_TRACE_CACHE_SIZE, false, null); TmfSignalManager.deregister(fTrace); fTrace.indexTrace(true); } catch (final TmfTraceException | URISyntaxException | IOException e) { e.printStackTrace(); fail("Error setting up test trace"); } }
Source:
<code>public void handleLevelChunk(ClientboundLevelChunkPacket clientboundLevelChunkPacket, CallbackInfo ci) { ci.cancel(); PacketUtils.ensureRunningOnSameThread(clientboundLevelChunkPacket, (ClientPacketListener)(Object)this, this.minecraft); int chunkX = clientboundLevelChunkPacket.getX(); int chunkZ = clientboundLevelChunkPacket.getZ(); @SuppressWarnings("ConstantConditions") ColumnBiomeContainer biomeContainer = new ColumnBiomeContainer(minecraft.level.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY), new int[ColumnBiomeContainer.BIOMES_SIZE]); biomeContainer.setLevel(minecraft.level); LevelChunk levelChunk = this.level.getChunkSource().replaceWithPacketData(chunkX, chunkZ, biomeContainer, clientboundLevelChunkPacket.getReadBuffer(), clientboundLevelChunkPacket.getHeightmaps(), clientboundLevelChunkPacket.getAvailableSections()); for (int k = this.level.getMinSection(); k < this.level.getMinSection() - 1; ++k) { this.level.setSectionDirtyWithNeighbors(chunkX, k, chunkZ); <START> } <END> if (levelChunk != null) { for (CompoundTag compoundTag : clientboundLevelChunkPacket.getBlockEntitiesTags()) { BlockPos blockPos = new BlockPos(compoundTag.getInt("x"), compoundTag.getInt("y"), compoundTag.getInt("z")); BlockEntity blockEntity = levelChunk.getBlockEntity(blockPos, LevelChunk.EntityCreationType.IMMEDIATE); if (blockEntity != null) { blockEntity.load(compoundTag); } } } }</code><technical_language>Delete loop</technical_language>

Target:
public void handleLevelChunk(ClientboundLevelChunkPacket clientboundLevelChunkPacket, CallbackInfo ci) { ci.cancel(); PacketUtils.ensureRunningOnSameThread(clientboundLevelChunkPacket, (ClientPacketListener)(Object)this, this.minecraft); int chunkX = clientboundLevelChunkPacket.getX(); int chunkZ = clientboundLevelChunkPacket.getZ(); @SuppressWarnings("ConstantConditions") ColumnBiomeContainer biomeContainer = new ColumnBiomeContainer(minecraft.level.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY), level); this.level.getChunkSource().replaceWithPacketData(chunkX, chunkZ, biomeContainer, clientboundLevelChunkPacket.getReadBuffer(), clientboundLevelChunkPacket.getHeightmaps(), clientboundLevelChunkPacket.getAvailableSections()); }
Source:
<code>public final boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) { RayTraceResult hit = reTraceAll(world, pos, player); if (hit instanceof RayTraceResult) <START> { <END> IMicroblockContainerTile tile = getMicroblockTile(world, pos); if (tile != null) { tile.getMicroblockContainer().getPartContainer().harvest(player, (RayTraceResult) hit); } return false; } else { IMicroblockContainerTile tile = getMicroblockTile(world, pos); MultipartContainer container = tile != null ? tile.getMicroblockContainer().getPartContainer() : null; if (container.getParts().isEmpty()) { return removedByPlayerDefault(state, world, pos, player, willHarvest); } else { if (!removedByPlayerDefault(state, world, pos, player, willHarvest)) { return false; } world.removeTileEntity(pos); if (!world.setBlockState(pos, ForgeMultipart.multipart.getDefaultState(), 0)) { return false; } world.removeTileEntity(pos); world.setTileEntity(pos, new TileMultipartContainer(container)); world.notifyBlockUpdate(pos, state, ForgeMultipart.multipart.getDefaultState(), 0); harvestingWrapper = true; if (!player.capabilities.isCreativeMode) { harvestBlock(world, player, pos, world.getBlockState(pos), world.getTileEntity(pos), player.getActiveItemStack()); } harvestingWrapper = false; return false; } } }</code><technical_language>Again</technical_language>

Target:
public final boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) { RayTraceResult hit = reTraceAll(world, pos, player); if (hit.partHit != null) { IMicroblockContainerTile tile = getMicroblockTile(world, pos); if (tile != null) { tile.getMicroblockContainer().getPartContainer().harvest(player, (RayTraceResult) hit); } return false; } else { IMicroblockContainerTile tile = getMicroblockTile(world, pos); MultipartContainer container = tile != null ? tile.getMicroblockContainer().getPartContainer() : null; if (container.getParts().isEmpty()) { return removedByPlayerDefault(state, world, pos, player, willHarvest); } else { if (!removedByPlayerDefault(state, world, pos, player, willHarvest)) { return false; } if (!world.setBlockState(pos, ForgeMultipartModContainer.multipart.getDefaultState(), 0)) { return false; } world.removeTileEntity(pos); world.setTileEntity(pos, new TileMultipartContainer(container)); world.notifyBlockUpdate(pos, state, ForgeMultipartModContainer.multipart.getDefaultState(), 0); harvestingWrapper = true; if (!player.capabilities.isCreativeMode) { harvestBlock(world, player, pos, world.getBlockState(pos), world.getTileEntity(pos), player.getActiveItemStack()); } harvestingWrapper = false; return false; } } }