auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void test(TestHarness th) { try { String dirPath = System.getProperty("fileconn.dir.private").substring(2); FileConnection dir = (FileConnection)Connector.open(dirPath); th.check(dir.isOpen(), "Directory opened"); th.check(dir.exists(), "Directory exists"); th.check(dir.isDirectory(), "Directory is a directory"); Enumeration files = dir.list(); th.check(!files.hasMoreElements(), "Directory is empty"); FileConnection file = (FileConnection)Connector.open(dirPath + "prova"); th.check(file.isOpen(), "File opened"); th.check(!file.exists(), "File doesn't exist"); th.check(!file.isDirectory(), "File isn't a directory"); file.create(); th.check(file.exists(), "File created"); th.check(!file.isDirectory(), "Check is directory"); th.check(file.fileSize(), 0, "Check file size"); OutputStream out = file.openOutputStream(); out.write(new byte[]{ 5, 4, 3, 2, 1 }); out.close(); th.check(file.fileSize(), 5); InputStream in = file.openInputStream(); th.check(in.read(), 5); th.check(in.read(), 4); th.check(in.read(), 3); th.check(in.read(), 2); th.check(in.read(), 1); th.check(in.read(), -1); in.close(); file.close(); th.check(!file.isOpen()); files = dir.list(); th.check(files.hasMoreElements(), "Directory has one file"); th.check(files.nextElement(), "/prova"); th.check(!files.hasMoreElements(), "Directory has just one file"); dir.close(); th.check(!dir.isOpen()); } catch (Exception e) { <START> th.fail("Unexpected exception"); <END> e.printStackTrace(); } }</code><technical_language>Nit: append exception message log shows name of exception in addition stack trace: th.fail("Unexpected exception: " + e);</technical_language>

Target:
public void test(TestHarness th) { try { String dirPath = System.getProperty("fileconn.dir.private").substring(2); FileConnection dir = (FileConnection)Connector.open(dirPath); th.check(dir.isOpen(), "Directory opened"); th.check(dir.exists(), "Directory exists"); th.check(dir.isDirectory(), "Directory is a directory"); Enumeration files = dir.list(); th.check(!files.hasMoreElements(), "Directory is empty"); FileConnection file = (FileConnection)Connector.open(dirPath + "prova"); th.check(file.isOpen(), "File opened"); th.check(!file.exists(), "File doesn't exist"); th.check(!file.isDirectory(), "File isn't a directory"); file.create(); th.check(file.exists(), "File created"); th.check(!file.isDirectory(), "Check is directory"); th.check(file.fileSize(), 0, "Check file size"); OutputStream out = file.openOutputStream(); out.write(new byte[]{ 5, 4, 3, 2, 1 }); out.close(); th.check(file.fileSize(), 5); InputStream in = file.openInputStream(); th.check(in.read(), 5); th.check(in.read(), 4); th.check(in.read(), 3); th.check(in.read(), 2); th.check(in.read(), 1); th.check(in.read(), -1); in.close(); file.close(); th.check(!file.isOpen()); files = dir.list(); th.check(files.hasMoreElements(), "Directory has one file"); th.check(files.nextElement(), "/prova"); th.check(!files.hasMoreElements(), "Directory has just one file"); dir.close(); th.check(!dir.isOpen()); } catch (Exception e) { th.fail("Unexpected exception: " + e); e.printStackTrace(); } }
Source:
<code>public CharSeq leftPadTo(int length, Character element) { if (length <= back.length()) { return this; } <START> final StringBuilder sb = new StringBuilder(padding(element, length - back.length())).append(back); <END> return new CharSeq(sb.toString()); }</code><technical_language>Is this? java final StringBuilder sb = padding(element, length - back.length()).append(back);</technical_language>

Target:
public CharSeq leftPadTo(int length, Character element) { final int actualLength = back.length(); if (length <= actualLength) { return this; } else { final StringBuilder sb = padding(element, length - actualLength).append(back); return new CharSeq(sb.toString()); } }
Source:
<code>public void updateEndpoints(List<WebServiceEndpoint> endpoints) { dataProvider.setList(endpoints); sortHandler.setList(dataProvider.getList()); ColumnSortEvent.fire(table, table.getColumnSortList()); table.selectDefaultEntity(); <START> SingleSelectionModel<WebServiceEndpoint> selectionModel = <END> (SingleSelectionModel<WebServiceEndpoint>) table.getSelectionModel(); WebServiceEndpoint selection = selectionModel.getSelectedObject(); sampler.addSample( new Metric( selection.getRequestCount(), selection.getResponseCount(), selection.getFaultCount() )); }</code><technical_language>I turn selectionModelinto a member variable</technical_language>

Target:
public void updateEndpoints(List<WebServiceEndpoint> endpoints) { dataProvider.setList(endpoints); sortHandler.setList(dataProvider.getList()); ColumnSortEvent.fire(table, table.getColumnSortList()); table.selectDefaultEntity(); WebServiceEndpoint selection = selectionModel.getSelectedObject(); addSample(selection); }
Source:
<code>private void assertBaseline(String content, int baselineSz, int srvsSz) throws IOException { assertNotNull(content); assertFalse(content.isEmpty()); JsonNode node = JSON_MAPPER.readTree(content); assertEquals(STATUS_SUCCESS, node.get("successStatus").asInt()); assertTrue(node.get("error").isNull()); assertNotSame(securityEnabled(), node.get("sessionToken").isNull()); JsonNode res = node.get("response"); assertFalse(res.isNull()); GridBaselineCommandResponse baseline = JSON_MAPPER.treeToValue(res, GridBaselineCommandResponse.class); assertTrue(baseline.isActive()); assertEquals(grid(0).cluster().topologyVersion(), baseline.getTopologyVersion()); assertEquals(baselineSz, baseline.getBaseline().size()); <START> assertEqualsCollections(consistentIdMapper(grid(0).cluster().currentBaselineTopology()), new HashSet<>(baseline.getBaseline())); <END> assertEquals(srvsSz, baseline.getServers().size()); assertEqualsCollections(consistentIdMapper(grid(0).cluster().nodes()), new HashSet<>(baseline.getServers())); }</code><technical_language>work additional "new HashSet"? If "new HashSet" removed code simpler</technical_language>

Target:
private void assertBaseline(String content, int baselineSz, int srvsSz) throws IOException { assertNotNull(content); assertFalse(content.isEmpty()); JsonNode node = JSON_MAPPER.readTree(content); assertEquals(STATUS_SUCCESS, node.get("successStatus").asInt()); assertTrue(node.get("error").isNull()); assertNotSame(securityEnabled(), node.get("sessionToken").isNull()); JsonNode res = node.get("response"); assertFalse(res.isNull()); GridBaselineCommandResponse baseline = JSON_MAPPER.treeToValue(res, GridBaselineCommandResponse.class); assertTrue(baseline.isActive()); assertEquals(grid(0).cluster().topologyVersion(), baseline.getTopologyVersion()); assertEquals(baselineSz, baseline.getBaseline().size()); assertEqualsCollections(nodeConsistentIds(grid(0).cluster().currentBaselineTopology()), baseline.getBaseline()); assertEquals(srvsSz, baseline.getServers().size()); assertEqualsCollections(nodeConsistentIds(grid(0).cluster().nodes()), baseline.getServers()); }
Source:
<code>public void testSaveOrUpdateExisting() { int sizeBeforeSave = dao.getAll().size(); existingUser.setFirstName("changedname"); existingUser.setLastName("changedsurname"); <START> int sizeAfterSave = dao.getAll().size(); <END> dao.saveOrUpdate(existingUser); DbUser result = dao.get(existingUser.getId()); assertEquals(existingUser, result); assertEquals(0, sizeAfterSave - sizeBeforeSave); }</code><technical_language>this executed dao.saveOrUpdate()</technical_language>

Target:
public void testSaveOrUpdateExisting() { int sizeBeforeSave = dao.getAll().size(); existingUser.setFirstName("changedname"); existingUser.setLastName("changedsurname"); dao.saveOrUpdate(existingUser); int sizeAfterSave = dao.getAll().size(); DbUser result = dao.get(existingUser.getId()); assertEquals(existingUser, result); assertEquals(0, sizeAfterSave - sizeBeforeSave); }
Source:
<code>private String generateNewAnonID() { String uuid = UUID.randomUUID().toString(); <START> String[] uuidSplitted = uuid.split("-"); <END> StringBuilder builder = new StringBuilder(); for (String currentPart : uuidSplitted) { builder.append(currentPart); } uuid = builder.toString(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext); final SharedPreferences.Editor editor = preferences.edit(); editor.putString(TRACKS_ANON_ID, uuid); editor.apply(); mAnonID = uuid; return uuid; }</code><technical_language>please remove String[] uuidSplitted = uuid.split("-"); StringBuilder builder = new StringBuilder(); for (String currentPart : uuidSplitted) { builder.append(currentPart); } uuid = builder.toString(); String uuid = UUID.randomUUID().toString(); is (with dashes string) ? out anonID character in (limited ASCII probably), is need replace dashes. This collision Android app. If is enough entropy in UUID.randomUUID create version of it. @xyu for confirmation anonID</technical_language>

Target:
private String generateNewAnonID() { String uuid = UUID.randomUUID().toString(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext); final SharedPreferences.Editor editor = preferences.edit(); editor.putString(TRACKS_ANON_ID, uuid); editor.apply(); mAnonID = uuid; return uuid; }
Source:
<code>MMappedIndexRowIterable( Iterable<Rowboat> index, List<String> convertedDims, Map<String, IntBuffer> converters, int indexNumber ) { this.index = index; this.convertedDims = convertedDims; this.converters = converters; this.indexNumber = indexNumber; this.converterArray = new IntBuffer[convertedDims.size()]; <START> for(int i = 0; i < convertedDims.size(); ++i){ <END> this.converterArray[i] = converters.get(convertedDims.get(i)); } }</code><technical_language>I prefer if initialization done lazily requesting iterator, construction time avoid reading data needed</technical_language>

Target:
MMappedIndexRowIterable( Iterable<Rowboat> index, List<String> convertedDims, Map<String, IntBuffer> converters, int indexNumber ) { this.index = index; this.convertedDims = convertedDims; this.converters = converters; this.indexNumber = indexNumber; }
Source:
<code>private String getDstRef(Repository repo, boolean launchFetch) { if (launchFetch) { String realName = getRealBranchName(repo); String name = BRANCH_NAME_PATTERN.matcher(realName).replaceAll(""); String remote = repo.getConfig().getString(CONFIG_BRANCH_SECTION, <START> name, CONFIG_KEY_REMOTE); <END> String merge = repo.getConfig().getString(CONFIG_BRANCH_SECTION, name, CONFIG_KEY_MERGE); String mergeBranchName = merge.substring( merge.lastIndexOf("/"), merge.length()); return R_REMOTES + remote + mergeBranchName; } else return HEAD; }</code><technical_language>null if create a branch merge strategy</technical_language>

Target:
private String getDstRef(Repository repo, boolean launchFetch) { if (launchFetch) { String realName = getRealBranchName(repo); String name = BRANCH_NAME_PATTERN.matcher(realName).replaceAll(""); StoredConfig config = repo.getConfig(); String remote = config.getString(CONFIG_BRANCH_SECTION, name, CONFIG_KEY_REMOTE); String merge = config.getString(CONFIG_BRANCH_SECTION, name, CONFIG_KEY_MERGE); if (remote == null || merge == null) return HEAD; String mergeBranchName = merge.substring( merge.lastIndexOf("/"), merge.length()); return R_REMOTES + remote + mergeBranchName; } else return HEAD; }
Source:
<code>private void doUpdate(Exchange exchange) { final Message msg = exchange.getIn(); final String id = msg.getHeader(CinderConstants.ID, msg.getHeader(CinderConstants.VOLUME_ID, String.class), String.class); final Volume vol = messageToVolume(msg); <START> ; <END> ObjectHelper.notEmpty(id, "Cinder Volume ID"); ObjectHelper.notEmpty(vol.getDescription(), "Cinder Volume Description"); ObjectHelper.notEmpty(vol.getName(), "Cinder Volume Name"); final ActionResponse out = os.blockStorage().volumes().update(id, vol.getName(), vol.getDescription()); checkFailure(out, msg, "Update volume " + id); }</code><technical_language>Please remove this semi colon</technical_language>

Target:
private void doUpdate(Exchange exchange) { final Message msg = exchange.getIn(); final String id = msg.getHeader(CinderConstants.ID, msg.getHeader(CinderConstants.VOLUME_ID, String.class), String.class); final Volume vol = messageToVolume(msg); ObjectHelper.notEmpty(id, "Cinder Volume ID"); ObjectHelper.notEmpty(vol.getDescription(), "Cinder Volume Description"); ObjectHelper.notEmpty(vol.getName(), "Cinder Volume Name"); final ActionResponse out = os.blockStorage().volumes().update(id, vol.getName(), vol.getDescription()); checkFailure(out, msg, "Update volume " + id); }
Source:
<code>public Object getValuePreferringCachedDeserializable() { checkEntryDestroyed(); <START> Object v = this.regionEntry.getValue(null); <END> if (v instanceof CachedDeserializable) { return v; } else { return getRawValue(); } }</code><technical_language>Please rename variable more meaningful other character v</technical_language>

Target:
public Object getValuePreferringCachedDeserializable() { checkEntryDestroyed(); Object value = regionEntry.getValue(null); if (value instanceof CachedDeserializable) { return value; } else { return getRawValue(); } }
Source:
<code>private synchronized String requestOAuth2Token() throws ETSdkException { if (clientId == null || clientSecret == null) { return null; } logger.debug("requesting OAuth2 access token..."); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("client_id", clientId); jsonObject.addProperty("client_secret", clientSecret); jsonObject.addProperty("grant_type", "client_credentials"); String requestPayload = gson.toJson(jsonObject); ETRestConnection.Response response = null; response = authConnection.post(PATH_OAUTH2TOKEN, requestPayload); if (response.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new ETSdkException("error obtaining OAuth2 access token " + "(" + response.getResponseCode() + " " + response.getResponseMessage() + ")"); } String responsePayload = response.getResponsePayload(); JsonParser jsonParser = new JsonParser(); jsonObject = jsonParser.parse(responsePayload).getAsJsonObject(); <START> logger.debug("received OAuth2 token:"); <END> this.accessToken = jsonObject.get("access_token").getAsString(); logger.debug(" accessToken: " + this.accessToken); this.expiresIn = jsonObject.get("expires_in").getAsInt(); logger.debug(" expiresIn: " + this.expiresIn); this.endpoint = jsonObject.get("rest_instance_url").getAsString(); this.soapEndpoint = jsonObject.get("soap_instance_url").getAsString() + "service.asmx"; tokenExpirationTime = System.currentTimeMillis() + (expiresIn * 1000); logger.debug("access OAuth2 token expires at " + new Date(tokenExpirationTime)); return accessToken; }</code><technical_language>remove debug logs</technical_language>

Target:
private synchronized String requestOAuth2Token() throws ETSdkException { if (clientId == null || clientSecret == null) { return null; } JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("client_id", clientId); jsonObject.addProperty("client_secret", clientSecret); jsonObject.addProperty("grant_type", "client_credentials"); if(accountId != null && accountId.length() > 0) { jsonObject.addProperty("account_id", accountId); } if(scope != null && scope.length() > 0) { jsonObject.addProperty("scope", scope); } String requestPayload = gson.toJson(jsonObject); ETRestConnection.Response response = null; response = authConnection.post(PATH_OAUTH2TOKEN, requestPayload); if (response.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new ETSdkException("error obtaining OAuth2 access token " + "(" + response.getResponseCode() + " " + response.getResponseMessage() + ")"); } String responsePayload = response.getResponsePayload(); JsonParser jsonParser = new JsonParser(); jsonObject = jsonParser.parse(responsePayload).getAsJsonObject(); this.accessToken = jsonObject.get("access_token").getAsString(); this.expiresIn = jsonObject.get("expires_in").getAsInt(); this.endpoint = jsonObject.get("rest_instance_url").getAsString(); this.soapEndpoint = jsonObject.get("soap_instance_url").getAsString() + "service.asmx"; tokenExpirationTime = System.currentTimeMillis() + (expiresIn * 1000); return accessToken; }
Source:
<code>private void setDefault(XProcOptionInfo info,Element element ){ String select=info.getSelect(); if (Strings.isNullOrEmpty(select)){ return; } char quote=select.charAt(0); if (quote!='"' && quote!='\''){ return; } if (select.charAt(select.length()-1)!=quote){ return; } String def=select.substring(1,select.length()-1); <START> if (def.length()>0){ <END> element.setAttribute("default",def); } }</code><technical_language>this default empty string</technical_language>

Target:
private void setDefault(XProcOptionInfo info,Element element ){ String select=info.getSelect(); if (Strings.isNullOrEmpty(select)){ return; } char quote=select.charAt(0); if (quote!='"' && quote!='\''){ return; } if (select.charAt(select.length()-1)!=quote){ return; } String def=select.substring(1,select.length()-1); element.setAttribute("default",def); }
Source:
<code>public static UNIT getById(final int id) { for (final UNIT e : values()) { <START> if (e.value == id) { <END> return e; } } return MI; }</code><technical_language>e.ordinal() instead of e.value, remove field</technical_language>

Target:
public static DistanceUnit getById(final int id) { for (final DistanceUnit e : values()) { if (e.value == id) { return e; } } return MI; }
Source:
<code><START> protected final IStateHistoryBackend prepareBackend(long startTime, long endTime, <END> List<ITmfStateInterval> intervals) { try { fBackend = getBackendForBuilding(startTime); for (ITmfStateInterval interval : intervals) { fBackend.insertPastState(interval.getStartTime(), interval.getEndTime(), interval.getAttribute(), interval.getStateValue()); } fBackend.finishedBuilding(Math.max(endTime, fBackend.getEndTime())); IStateHistoryBackend backendForBuilding = fBackend; fBackend = null; fBackend = getBackendForQuerying(backendForBuilding); return fBackend; } catch (IOException e) { fail(e.toString()); return null; } }</code><technical_language>This completely fills backend in "build" mode returns a backend for "querying". While this is OK for some test cases, other test cases query while building call this method. extract interval insertion part in a insertIntervals(backend, intervals) method? name this method fillBackend instead</technical_language>

Target:
protected final IStateHistoryBackend prepareBackend(long startTime, long endTime, List<ITmfStateInterval> intervals) { try { fBackend = getBackendForBuilding(startTime); insertIntervals(fBackend, intervals); fBackend.finishedBuilding(Math.max(endTime, fBackend.getEndTime())); IStateHistoryBackend backendForBuilding = fBackend; fBackend = null; fBackend = getBackendForQuerying(backendForBuilding); return fBackend; } catch (IOException e) { fail(e.toString()); return null; } }
Source:
<code>public void filterTextFieldColor_validFilter_validFilterStyleApplied(){ FilterTextField field = getFirstPanelField(); clearField(); type("is:open"); <START> assertTrue(field.getStyle().contains(VALID_FILTER_STYLE)); <END> clearField(); type("-is:open"); assertTrue(field.getStyle().contains(VALID_FILTER_STYLE)); clearField(); type("hello"); assertTrue(field.getStyle().contains(VALID_FILTER_STYLE)); clearField(); type("is:open & has:assignee"); assertTrue(field.getStyle().contains(VALID_FILTER_STYLE)); clearField(); type("(is:closed)"); assertTrue(field.getStyle().contains(VALID_FILTER_STYLE)); }</code><technical_language>factor out clear, type, assert pattern here, a function takes string test</technical_language>

Target:
public void filterTextFieldColor_validFilter_validFilterStyleApplied(){ testValidFilterStyleApplied("is:open"); testValidFilterStyleApplied("-is:open"); testValidFilterStyleApplied("hello"); testValidFilterStyleApplied("is:open & has:assignee"); testValidFilterStyleApplied("(is:closed)"); }
Source:
<code>private boolean possibleToString(Class classExample) { return (classExample.isPrimitive() || classExample.getName().equals("java.lang.Integer") <START> || classExample.getName().equals("java.lang.Boolean") <END> || classExample.getName().equals("java.lang.String") || classExample.getName().equals("java.lang.Double") || classExample.getName().equals("java.lang.Float") || classExample.getName().equals("java.lang.Byte") || classExample.getName().equals("java.lang.Long") || classExample.getName().equals("java.lang.Short") || classExample.getName().equals("java.lang.Character") || classExample.isEnum()); }</code><technical_language>classExample.equals(Boolean.class)</technical_language>

Target:
private boolean possibleToString(Class classExample) { return (classExample.isPrimitive() || classExample.equals(Integer.class) || classExample.equals(Boolean.class) || classExample.equals(String.class) || classExample.equals(Double.class) || classExample.equals(Float.class) || classExample.equals(Byte.class) || classExample.equals(Long.class) || classExample.equals(Short.class) || classExample.equals(Character.class) || classExample.isEnum()); }
Source:
<code>public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongObjectMap<LockResource> localLocks = localShared( resourceType ); for ( long resourceId : resourceIds ) { LockResource resource = localLocks.get( resourceId ); if ( resource.releaseReference() != 0 ) { <START> return; <END> } localLocks.remove( resourceId ); manager.releaseReadLock( new LockResource( resourceType, resourceId ), lockTransaction ); } } finally { stateHolder.decrementActiveClients(); } }</code><technical_language>Do want try releasing remaining resources failure? I know, this terminate transaction release anyway, noting this observation</technical_language>

Target:
public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongObjectMap<LockResource> localLocks = localShared( resourceType ); for ( long resourceId : resourceIds ) { LockResource resource = localLocks.get( resourceId ); if ( resource.releaseReference() == 0 ) { localLocks.remove( resourceId ); manager.releaseReadLock( new LockResource( resourceType, resourceId ), lockTransaction ); } } } finally { stateHolder.decrementActiveClients(); } }
Source:
<code>public void testIgnoreError() throws Exception { <START> XMLParser.Config config = new XMLParser.Config("body", "UTF-8", "title:/book/title,author:/book/author," + <END> "year:/book/year", "title:string,author:string,year:int", "Ignore error and continue"); Transform<StructuredRecord, StructuredRecord> transform = new XMLParser(config); transform.initialize(new MockTransformContext()); List<StructuredRecord> input = ImmutableList.of( StructuredRecord.builder(INPUT) .set("offset", 1) .set("body", "<book category=\"COOKING\"><title lang=\"en\">Everyday Italian</title>" + "<author>Giada De Laurentiis</author><year>null</year><price>30.00</price></book>").build(), StructuredRecord.builder(INPUT) .set("offset", 2) .set("body", "<book category=\"children\"><title lang=\"en\">Harry Potter</title>" + "<author>J K. Rowling</author><year>2005</year><price>49.99</price></book>").build()); MockEmitter<StructuredRecord> emitter = new MockEmitter<>(); for (StructuredRecord record : input) { transform.transform(record, emitter); } Assert.assertEquals(1, emitter.getEmitted().size()); Assert.assertEquals(0, emitter.getErrors().size()); StructuredRecord record = emitter.getEmitted().get(0); Assert.assertEquals("Harry Potter", record.get("title")); Assert.assertEquals("J K. Rowling", record.get("author")); Assert.assertEquals(2005, record.get("year")); }</code><technical_language>a encoding (other UTF-8 - UTF-16) for of test cases? Want other encoding values work</technical_language>

Target:
public void testIgnoreError() throws Exception { XMLParser.Config config = new XMLParser.Config("body", "ISO-8859-1", "title:/book/title,author:/book/author," + "year:/book/year", "title:string,author:string,year:int", "Ignore error and continue"); Transform<StructuredRecord, StructuredRecord> transform = new XMLParser(config); transform.initialize(new MockTransformContext()); List<StructuredRecord> input = ImmutableList.of( StructuredRecord.builder(INPUT) .set("offset", 1) .set("body", "<book category=\"COOKING\"><title lang=\"en\">Everyday Italian</title>" + "<author>Giada De Laurentiis</author><year>null</year><price>30.00</price></book>").build(), StructuredRecord.builder(INPUT) .set("offset", 2) .set("body", "<book category=\"children\"><title lang=\"en\">Harry Potter</title>" + "<author>J K. Rowling</author><year>2005</year><price>49.99</price></book>").build()); MockEmitter<StructuredRecord> emitter = new MockEmitter<>(); for (StructuredRecord record : input) { transform.transform(record, emitter); } Assert.assertEquals(1, emitter.getEmitted().size()); Assert.assertEquals(0, emitter.getErrors().size()); StructuredRecord record = emitter.getEmitted().get(0); Assert.assertEquals("Harry Potter", record.get("title")); Assert.assertEquals("J K. Rowling", record.get("author")); Assert.assertEquals(2005, record.get("year")); }
Source:
<code>public ModulusOffsetCalculator(int numBlocks) { int blocksMinusOne = numBlocks - 1; <START> if (numBlocks <= 0 && (numBlocks & blocksMinusOne) == 0) { <END> throw new IllegalArgumentException("maxOffset " + numBlocks + " must be greater than 0 and a power of 2"); } this.blocksMinusOne = blocksMinusOne; }</code><technical_language>suggestion if (numBlocks <= 0 || (numBlocks & blocksMinusOne) != 0) {</technical_language>

Target:
public ModulusOffsetCalculator(int numBlocks) { int blocksMinusOne = numBlocks - 1; if (numBlocks <= 0 || (numBlocks & blocksMinusOne) != 0) { throw new IllegalArgumentException("maxOffset " + numBlocks + " must be greater than 0 and a power of 2"); } this.blocksMinusOne = blocksMinusOne; }
Source:
<code><START> public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { <END> super.onRequestPermissionsResult(requestCode, permissions, grantResults); RuntimePermissionUtils.onRequestPermissionsResult(this, requestCode, grantResults); }</code><technical_language>line length</technical_language>

Target:
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); RuntimePermissionUtils.onRequestPermissionsResult(this, requestCode, grantResults); }
Source:
<code>private static boolean check4matchingAnyID(Logger logger, String idName, int requestID, int responseID) { logger.trace("check4matchingAnyID() called for request{} and response{} {}.", idName, requestID, idName, responseID); if (requestID != responseID) { logger.warn("Gateway response with unexpected as query asked for {}.", idName, requestID, idName, responseID); return false; <START> } else { <END> logger.trace("check4matchingAnyID() returns {}.", true); return true; } }</code><technical_language>else is redundant</technical_language>

Target:
private static boolean check4matchingAnyID(Logger logger, String idName, int requestID, int responseID) { logger.trace("check4matchingAnyID() called for request{} and response{} {}.", idName, requestID, idName, responseID); if (requestID != responseID) { logger.warn("Gateway response with unexpected as query asked for {}.", idName, requestID, idName, responseID); return false; } logger.trace("check4matchingAnyID() returns {}.", true); return true; }
Source:
<code>public void testNewImportStringLocations() throws Exception { DispoItemData dispoItem = new DispoItemData(); boolean stoppedParsing = false; String name = "sampleTmoStrings.tmo"; URL resource = getClass().getResource(name); InputStream stream = null; try { stream = new BufferedInputStream(resource.openStream()); stoppedParsing = DiscrepancyParser.buildItemFromFile(dispoItem, name, stream, false, new Date(0)); } finally { Lib.close(stream); } int actualLength = dispoItem.getDiscrepanciesList().size(); Assert.assertEquals(6, actualLength); Assert.assertFalse(stoppedParsing); Map<String, Discrepancy> discrepanciesList = dispoItem.getDiscrepanciesList(); Collection<Discrepancy> values = discrepanciesList.values(); Discrepancy discrepancy13 = null; for (Discrepancy discrepancy : values) { String loc = discrepancy.getLocation(); if (loc.equals("Thirteen")) { discrepancy13 = discrepancy; break; } } String actualText = discrepancy13.getText(); <START> <END> Assert.assertEquals("Failure at Test Point Thirteen. Check Point: Boo_READY5. Expected: WT[1]. Actual: WT [0]. ", actualText); Discrepancy discrepancy12 = null; for (Discrepancy discrepancy : values) { String loc = discrepancy.getLocation(); if (loc.equals("Fourteen")) { discrepancy12 = discrepancy; break; } } actualText = discrepancy12.getText(); Assert.assertEquals( "Failure at Test Point Fourteen. Check Group with Checkpoint Failures: " + "Check Point: pokemon. Expected: charmander. Actual: squirtle. " + "Check Point: superman. Expected: unbeatable. Actual: kryptonite. " + "Check Point: Nicest Guy Ever. Expected: Bob Ross. Actual: Bob Ross. " + "Check Point: Things fail. Expected: sometimes. Actual: A lot. ", actualText); }</code><technical_language>common static for duplicated strings</technical_language>

Target:
public void testNewImportStringLocations() throws Exception { DispoItemData dispoItem = new DispoItemData(); boolean stoppedParsing = false; String name = "sampleTmoStrings.tmo"; URL resource = getClass().getResource(name); InputStream stream = null; try { stream = new BufferedInputStream(resource.openStream()); stoppedParsing = DiscrepancyParser.buildItemFromFile(dispoItem, name, stream, false, new Date(0)); } finally { Lib.close(stream); } int actualLength = dispoItem.getDiscrepanciesList().size(); Assert.assertEquals(6, actualLength); Assert.assertFalse(stoppedParsing); Map<String, Discrepancy> discrepanciesList = dispoItem.getDiscrepanciesList(); Collection<Discrepancy> values = discrepanciesList.values(); Discrepancy discrepancy13 = null; for (Discrepancy discrepancy : values) { String loc = discrepancy.getLocation(); if (loc.equals("Thirteen")) { discrepancy13 = discrepancy; break; } } String actualText = discrepancy13.getText(); Assert.assertEquals(String.format(thirtneenFailure, "Thirteen"), actualText); Discrepancy discrepancy12 = null; for (Discrepancy discrepancy : values) { String loc = discrepancy.getLocation(); if (loc.equals("Fourteen")) { discrepancy12 = discrepancy; break; } } actualText = discrepancy12.getText(); Assert.assertEquals(String.format(fourteenFailure, "Fourteen"), actualText); }
Source:
<code>public void log(IStatus status) { log(0, status); if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); for (IStatus <START> children1 : <END> children) { log(1, children1); } } }</code><technical_language>child</technical_language>

Target:
public void log(IStatus status) { log(0, status); if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); for (IStatus child : children) { log(1, child); } } }
Source:
<code>public Map<String, String> buildAndVerifyContext(Function<String, Value> parameterProvider, boolean enforceRequiredParameters, Consumer<HandledException> errorConsumer) { Map<String, String> context = new HashMap<>(); for (Parameter<?, ?> parameter : getParameters()) { try { Value contextValue = parameterProvider.apply(parameter.getName()); <START> if (enforceRequiredParameters && !contextValue.isFilled() && parameter.isRequired()) { <END> errorConsumer.accept(Exceptions.createHandled() .withNLSKey("Parameter.required") .set("name", parameter.getLabel()) .handle()); } else { String value = parameter.checkAndTransform(contextValue); context.put(parameter.getName(), value); } } catch (HandledException e) { errorConsumer.accept(e); } } return context; }</code><technical_language>suggestion if (enforceRequiredParameters && contextValue.isEmptyString() && parameter.isRequired()) {</technical_language>

Target:
public Map<String, String> buildAndVerifyContext(Function<String, Value> parameterProvider, boolean enforceRequiredParameters, Consumer<HandledException> errorConsumer) { Map<String, String> context = new HashMap<>(); for (Parameter<?, ?> parameter : getParameters()) { try { Value contextValue = parameterProvider.apply(parameter.getName()); if (enforceRequiredParameters && contextValue.isEmptyString() && parameter.isRequired()) { errorConsumer.accept(Exceptions.createHandled() .withNLSKey("Parameter.required") .set("name", parameter.getLabel()) .handle()); } else { String value = parameter.checkAndTransform(contextValue); context.put(parameter.getName(), value); } } catch (HandledException e) { errorConsumer.accept(e); } } return context; }
Source:
<code>public void commitAllConnection() { List<DataSource> listOfDataSource = new ArrayList<>(); <START> for (DataSource dataSource : activeConnection.keySet()) { <END> try { Connection connection = activeConnection.get(dataSource); if (connection != null) { listOfDataSource.add(dataSource); connection.commit(); } } catch (SQLException e) { log.error("Error occurred while committing the connection. Connection: " + activeConnection .get(dataSource) + ". We have committed few transaction before error occurs. Committed " + "dataSource are: " + listOfDataSource.toString(), e); } } }</code><technical_language>for (Map.Entry entry : activeConnection.entrySet() ) {</technical_language>

Target:
void commitAllConnection() { StringBuilder commitErrorHandling = null; List<DataSource> listOfCommittedDataSource = null; HashMap<DataSource, Connection> rollBackConnections = null; for (Map.Entry entry : activeConnection.entrySet()) { try { Connection connection = (Connection) entry.getValue(); if (connection != null) { connection.commit(); } } catch (SQLException e) { if (commitErrorHandling.equals(null)) { commitErrorHandling = new StringBuilder(); } if (listOfCommittedDataSource.equals(null)) { listOfCommittedDataSource = new ArrayList<>(); } if (rollBackConnections.equals(null)) { rollBackConnections = new HashMap(); } for (Map.Entry activeEntry : activeConnection.entrySet()) { if (!entry.getKey().equals(activeEntry.getKey())) { listOfCommittedDataSource.add((DataSource) activeEntry.getKey()); } else { break; } } commitErrorHandling.append("Error occurred while committing the connection. Connection: ") .append(entry.getValue()) .append(". We have committed few transaction before error occurred. Committed dataSource : ") .append(listOfCommittedDataSource.toString()).append(". "); for (Map.Entry activeEntry : activeConnection.entrySet()) { if (!listOfCommittedDataSource.contains(activeEntry.getKey())) { rollBackConnections.put((DataSource) activeEntry.getKey(), (Connection) activeEntry.getValue()); } } internalRollbackConnection(rollBackConnections, commitErrorHandling); log.error(commitErrorHandling.toString(), e); } } }
Source:
<code>public void testByte() throws Exception { <START> runTest("test_flat_map/flat_map_byte.orc", <END> TinyintType.TINYINT, getExpectedValues(Integer::byteValue)); }</code><technical_language>I rename files suffixed .dwrf</technical_language>

Target:
public void testByte() throws Exception { runTest("test_flat_map/flat_map_byte.dwrf", TinyintType.TINYINT, ExpectedValuesBuilder.get(Integer::byteValue)); }
Source:
<code>public String toString() { return "OutboundTransferTask{" + "topologyId=" + topologyId + ", destination=" + destination + <START> ", segments=" + new IntSet(segments) + <END> ", chunkSize=" + chunkSize + ", timeout=" + timeout + ", cacheName='" + cacheName + '\'' + '}'; }</code><technical_language>IntSet for toString()</technical_language>

Target:
public String toString() { return "OutboundTransferTask{" + "topologyId=" + topologyId + ", destination=" + destination + ", segments=" + new SmallIntSet(segments) + ", chunkSize=" + chunkSize + ", timeout=" + timeout + ", cacheName='" + cacheName + '\'' + '}'; }
Source:
<code><START> public void selectParentCategory(int catValue) { <END> waitForElementClickableByElement(mainParentCategorySelector); mainParentCategorySelector.click(); WebElement parentSelected = parentCatOption.get(catValue); waitForElementVisibleByElement(parentSelected); parentSelected.click(); }</code><technical_language>i find this method is</technical_language>

Target:
public void selectParentCategory(int catValue) { waitForElementClickableByElement(mainParentCategorySelector); mainParentCategorySelector.click(); WebElement parentSelected = parentCatOption.get(catValue); waitForElementVisibleByElement(parentSelected); parentSelected.click(); PageObjectLogging.log("selectParentCategory", "Parent category selected", true); }
Source:
<code>public Optional<FileReference> getManifest() { <START> Path manifest = componentDirectory.resolve(FILE_NAME_MANIFEST); <END> if (Files.exists(manifest)) { return Optional.of(new ArtifactFileReference(manifest, appReference)); } else { return Optional.empty(); } }</code><technical_language>componentManifest for variable name improve readability</technical_language>

Target:
public Optional<FileReference> getManifest() { Path componentManifest = componentDirectory.resolve(FILE_NAME_MANIFEST); if (Files.exists(componentManifest)) { return Optional.of(new ArtifactFileReference(componentManifest, appReference)); } else { return Optional.empty(); } }
Source:
<code>private boolean hasNewFragment(EList<InteractionFragment> currentList, List<InteractionFragment> newList) { <START> boolean newFragment = false; if (newList.size() > currentList.size()) { newFragment = true; } return newFragment; <END> }</code><technical_language>I return (newList.size() > currentList.size()) is sufficient</technical_language>

Target:
private boolean hasNewFragment(EList<InteractionFragment> currentList, List<InteractionFragment> newList) { return (newList.size() > currentList.size()); }
Source:
<code>public PlanNodeCostEstimate visitJoin(JoinNode node, Void context) { return calculateJoinCost( node.getLeft(), node.getRight(), <START> node.getDistributionType().orElse(JoinNode.DistributionType.PARTITIONED).equals(JoinNode.DistributionType.REPLICATED)); <END> }</code><technical_language>This is easier read: node.getDistributionType().map(JoinNode.DistributionType.REPLICATED::equals).orElse(false) Write</technical_language>

Target:
public PlanNodeCostEstimate visitJoin(JoinNode node, Void context) { return calculateJoinCost( node.getLeft(), node.getRight(), Objects.equals(node.getDistributionType(), Optional.of(JoinNode.DistributionType.REPLICATED))); }
Source:
<code>public void init(Context context) { TranslatorContext translatorContext = ((SamzaSqlApplicationContext) context.getApplicationTaskContext()).getTranslatorContexts().get(queryId); this.msgConverter = translatorContext.getMsgConverter(streamName); ContainerContext containerContext = context.getContainerContext(); metricsRegistry = containerContext.getContainerMetricsRegistry(); processingTime = new SamzaHistogram(metricsRegistry, logicalOpId, TranslatorConstants.PROCESSING_TIME_NAME); <START> inputEvents = metricsRegistry.newCounter(logicalOpId, TranslatorConstants.INPUT_EVENTS_NAME); <END> inputEvents.clear(); queryInputEvents = metricsRegistry.newCounter(queryLogicalId, TranslatorConstants.INPUT_EVENTS_NAME); queryInputEvents.clear(); }</code><technical_language>output, If queryInput events Scan level inputEvents same. I good idea remove scan level input Events</technical_language>

Target:
public void init(Context context) { TranslatorContext translatorContext = ((SamzaSqlApplicationContext) context.getApplicationTaskContext()).getTranslatorContexts().get(queryId); this.msgConverter = translatorContext.getMsgConverter(streamName); ContainerContext containerContext = context.getContainerContext(); metricsRegistry = containerContext.getContainerMetricsRegistry(); processingTime = new SamzaHistogram(metricsRegistry, logicalOpId, TranslatorConstants.PROCESSING_TIME_NAME); queryInputEvents = metricsRegistry.newCounter(queryLogicalId, TranslatorConstants.INPUT_EVENTS_NAME); queryInputEvents.clear(); }
Source:
<code>private ProgressIndicator createTaskIndicator() { ProgressIndicator indicator = new ProgressIndicator(1); indicator.progressProperty().bind(stateManager.tasksProgressBinding); indicator.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { <START> TaskProgressDialog taskProgressDialog = new TaskProgressDialog(); <END> taskProgressDialog.setTitle("Task progress"); Window dialogWindow = taskProgressDialog.getDialogPane().getScene().getWindow(); dialogWindow.setOnCloseRequest(windowEvent -> dialogWindow.hide()); taskProgressDialog.showAndWait(); } }); return indicator; }</code><technical_language>Instead of a real dialog, a collapse overlay similar done in firefox? <LINK_0></technical_language>

Target:
private Group createTaskIndicator() { ProgressIndicator indicator = new ProgressIndicator(); indicator.getStyleClass().add("progress-indicatorToolbar"); indicator.progressProperty().bind(stateManager.getTasksProgress()); Tooltip someTasksRunning = new Tooltip(Localization.lang("Background Tasks are running")); Tooltip noTasksRunning = new Tooltip(Localization.lang("Background Tasks are done")); indicator.setTooltip(noTasksRunning); stateManager.getAnyTaskRunning().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue.booleanValue()) { indicator.setTooltip(someTasksRunning); } else { indicator.setTooltip(noTasksRunning); } } }); indicator.widthProperty().addListener((observable, oldValue, newValue) -> { if (!indicator.isIndeterminate()) { indicator.setPrefWidth(newValue.doubleValue()); } if (newValue.doubleValue() > 0) { Rectangle clip = new Rectangle(newValue.doubleValue(), newValue.doubleValue()); indicator.setClip(clip); } }); indicator.setOnMouseClicked(event -> { TaskProgressView taskProgressView = new TaskProgressView(); EasyBind.listBind(taskProgressView.getTasks(), stateManager.getBackgroundTasks()); taskProgressView.setRetainTasks(true); taskProgressView.setGraphicFactory(BackgroundTask::getIcon); PopOver progressViewPopOver = new PopOver(taskProgressView); progressViewPopOver.setTitle(Localization.lang("Background Tasks")); progressViewPopOver.setArrowLocation(PopOver.ArrowLocation.RIGHT_TOP); progressViewPopOver.show(indicator); }); return new Group(indicator); }
Source:
<code>public void onJailBlockBreak(final BlockBreakEvent event) { final User user = ess.getUser(event.getPlayer()); <START> if (user.isJailed() && !event.getPlayer().hasPermission("essentials.jail.allow-break")) { <END> event.setCancelled(true); } }</code><technical_language>Essentials' user.isAuthorized for permissions lookups - this EssentialsX's perms handling code</technical_language>

Target:
public void onJailBlockBreak(final BlockBreakEvent event) { final User user = ess.getUser(event.getPlayer()); if (user.isJailed() && !user.isAuthorized("essentials.jail.allow-break")) { event.setCancelled(true); } }
Source:
<code>public static Group map(DbGroup entity, Group template) { Group model = template != null ? template : new Group(); model.setName(entity.getName()); model.setId(entity.getId().toString()); if (!StringUtils.isEmpty(entity.getDomain())) { Domain dom = new Domain(); dom.setName(entity.getDomain()); <START> dom.setId(DirectoryEntryIdUtils.encode(dom.getName())); <END> } model.setDomainEntryId(DirectoryEntryIdUtils.encode(entity.getExternalId())); model.setNamespace(entity.getNamespace()); return model; }</code><technical_language>need model.setDomain</technical_language>

Target:
public static Group map(DbGroup entity, Group template) { Group model = template != null ? template : new Group(); model.setName(entity.getName()); model.setId(entity.getId().toString()); if (!StringUtils.isEmpty(entity.getDomain())) { Domain dom = new Domain(); dom.setName(entity.getDomain()); dom.setId(DirectoryEntryIdUtils.encode(dom.getName())); model.setDomain(dom); } model.setDomainEntryId(DirectoryEntryIdUtils.encode(entity.getExternalId())); model.setNamespace(entity.getNamespace()); return model; }
Source:
<code>public String getAbsolutePath() { <START> if (artifactFile == null) { <END> return ""; } return artifactFile.getAbsolutePath(); }</code><technical_language>This 4 lines line</technical_language>

Target:
public String getAbsolutePath() { return (artifactFile == null) ? "" : artifactFile.getAbsolutePath(); }
Source:
<code>public void testProjectNameBehindAFolderDisplayName() throws Exception { final String projectName1 = "job-1"; final String displayName1 = "job-1"; final String projectName2 = "job-2"; final String displayName2 = "job-2"; FreeStyleProject project1 = j.createFreeStyleProject(projectName1); <START> project1.setDisplayName(displayName1); <END> FreeStyleProject project2 = j.createFolder("my-folder-1").createProject(FreeStyleProject.class, projectName2); project2.setDisplayName(displayName2); WebClient wc = j.createWebClient(); Page result = wc.goTo("job/my-folder-1/search/suggest?query=" + projectName1, "application/json"); assertNotNull(result); j.assertGoodStatus(result); String content = result.getWebResponse().getContentAsString(); JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content); assertNotNull(jsonContent); JSONArray jsonArray = jsonContent.getJSONArray("suggestions"); assertNotNull(jsonArray); assertEquals(1, jsonArray.size()); boolean foundProjectName = false; boolean foundDisplayName = false; for(Object suggestion : jsonArray) { JSONObject jsonSuggestion = (JSONObject)suggestion; String name = (String)jsonSuggestion.get("name"); if(projectName1.equals(name)) { foundProjectName = true; } if(displayName1.equals(name)) { foundDisplayName = true; } } assertTrue(foundProjectName); assertTrue(foundDisplayName); }</code><technical_language>is point of setting displayName name? Do test a project a _different_ display name</technical_language>

Target:
public void testProjectNameBehindAFolderDisplayName() throws Exception { final String projectName1 = "job-1"; final String displayName1 = "job-1 display"; final String projectName2 = "job-2"; final String displayName2 = "job-2 display"; FreeStyleProject project1 = j.createFreeStyleProject(projectName1); project1.setDisplayName(displayName1); MockFolder myMockFolder = j.createFolder("my-folder-1"); FreeStyleProject project2 = myMockFolder.createProject(FreeStyleProject.class, projectName2); project2.setDisplayName(displayName2); WebClient wc = j.createWebClient(); Page result = wc.goTo(myMockFolder.getUrl() + "search/suggest?query=" + projectName1, "application/json"); assertNotNull(result); j.assertGoodStatus(result); String content = result.getWebResponse().getContentAsString(); JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content); assertNotNull(jsonContent); JSONArray jsonArray = jsonContent.getJSONArray("suggestions"); assertNotNull(jsonArray); assertEquals(2, jsonArray.size()); boolean foundDisplayName = false; for(Object suggestion : jsonArray) { JSONObject jsonSuggestion = (JSONObject)suggestion; String name = (String)jsonSuggestion.get("name"); if(projectName1.equals(name)) { foundDisplayName = true; } } assertTrue(foundDisplayName); }