auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static QueryResult convertPbListKeysResp(List<RiakTsPB.TsListKeysResp> responseChunks) { if (responseChunks == null) { return QueryResult.EMPTY; } int size = 0; for (RiakTsPB.TsListKeysResp resp : responseChunks) { size += resp.getKeysCount(); } <START> final ArrayList<RiakTsPB.TsRow> pbRows = new ArrayList<RiakTsPB.TsRow>(size); <END> for (RiakTsPB.TsListKeysResp resp : responseChunks) { pbRows.addAll(resp.getKeysList()); } return new QueryResult(pbRows); }</code><technical_language>refactor this logic Convertible one</technical_language>

Target:
public static QueryResult convertPbListKeysResp(List<RiakTsPB.TsListKeysResp> responseChunks) { if (responseChunks == null) { return QueryResult.EMPTY; } int totalKeyCount = 0; for (RiakTsPB.TsListKeysResp responseChunk : responseChunks) { totalKeyCount += responseChunk.getKeysCount(); } FlatteningIterable<RiakTsPB.TsListKeysResp, RiakTsPB.TsRow> flatIterable = new FlatteningIterable<RiakTsPB.TsListKeysResp, RiakTsPB.TsRow>(responseChunks, new FlatteningIterable.InnerIterableProvider<RiakTsPB.TsListKeysResp, RiakTsPB.TsRow>() { @Override public Iterator<RiakTsPB.TsRow> getInnerIterator(RiakTsPB.TsListKeysResp provider) { return provider.getKeysList().iterator(); } }); return new QueryResult(flatIterable, totalKeyCount); }
Source:
<code>public void dataCenterWithClusterSelectedItemChanged() { super.dataCenterWithClusterSelectedItemChanged(); if (snapshotId != null) { AsyncDataProvider.getInstance().getVmConfigurationBySnapshot(asyncQuery( vm -> { <START> List<Disk> snapshotDisks = vm.getStaticData() <END> .getDiskList() .stream() .map(diskImage -> (Disk) diskImage) .collect(Collectors.toList()); InitDisksAndStorageDomains(snapshotDisks); }), snapshotId); } else { AsyncDataProvider.getInstance().getVmDiskList(asyncQuery( vmDisks -> InitDisksAndStorageDomains(vmDisks)), vm.getId(), true); } }</code><technical_language>vm.getDiskList()</technical_language>

Target:
public void dataCenterWithClusterSelectedItemChanged() { super.dataCenterWithClusterSelectedItemChanged(); if (snapshotId != null) { AsyncDataProvider.getInstance().getVmConfigurationBySnapshot(asyncQuery( vm -> initDisksAndStorageDomains(new ArrayList<>(vm.getDiskMap().values()))), snapshotId); } else { AsyncDataProvider.getInstance().getVmDiskList(asyncQuery( this::initDisksAndStorageDomains), vm.getId(), true); } }
Source:
<code>public HtmlMetacardUtility(List<HtmlExportCategory> categoryList) { this(HTML_TEMPLATE); this.categoryList = categoryList; <START> sortCategoryList(); <END> }</code><technical_language>do this.categoryList = sortCategoryList(categoryList) change sortCategoryList in a parameter</technical_language>

Target:
public HtmlMetacardUtility(List<HtmlExportCategory> categoryList) { this(HTML_TEMPLATE); this.categoryList = categoryList; }
Source:
<code><START> public List<DSpaceObject> getdSpaceObjectsFromRequest(HttpServletRequest request) throws IOException { <END> return constructDSpaceObjectList(ContextUtil.obtainContext(request), request); }</code><technical_language>@benbosman : encourage start minimal/basic unit tests waiting for "perfection". above, I concerns UUID parsing is fragile. So, unit tests prove is working a basic level helpful here, especially client REST API literally send *anything* in a text/uri-list...so need ensure parsing works expect</technical_language>

Target:
public List<DSpaceObject> getdSpaceObjectsFromRequest(HttpServletRequest request) { return constructDSpaceObjectList(ContextUtil.obtainContext(request), request); }
Source:
<code>public void assignOperators() throws Exception { final List<Object> dto = Lists.<Object>newArrayList(1, 2); final List<ID> ids = Lists.newArrayList(new ID(1), new ID(2)); context.checking(new Expectations() {{ <START> oneOf(repository).assignOperators(with(matching(new ID("roamingGroupID"))), with(matching(ids))); <END> }}); Request request = makeRequestThatContains(dto); Reply<?> reply = service.assignOperators("roamingGroupID", request); assertThat(reply, isOk()); }</code><technical_language>export ID in var</technical_language>

Target:
public void assignOperators() throws Exception { final List<Object> dto = Lists.<Object>newArrayList(1, 2); final List<ID> ids = Lists.newArrayList(new ID(1), new ID(2)); final ID groupID = new ID("groupID"); context.checking(new Expectations() {{ oneOf(repository).assignOperators(with(matching(groupID)), with(matching(ids))); }}); Request request = makeRequestThatContains(dto); Reply<?> reply = service.assignOperators("groupID", request); assertThat(reply, isOk()); }
Source:
<code>private FileIndex(boolean fake, final IOnResult<FileIndex> callback) { EncryptedPreferences.get( fake ? PREFERENCES_KEY_FAKE : PREFERENCES_KEY_REAL, new IOnResult<EncryptedPreferences>() { @Override public void onResult(EncryptedPreferences result) { Utils.toast("Created the EncryptedPreferences"); mPreferences = result; mIndex = result.getJson(); try { if (mIndex.has(JSON_FILES) && mIndex.has(JSON_FOLDERS)) { Utils.toast("Index exists.. let's read and parse"); mFilesArray = new JSONArrayUnsorted(mIndex.getJSONArray(JSON_FILES)); mFoldersArray = new JSONArrayUnsorted(mIndex.getJSONArray(JSON_FOLDERS)); parseJSON(); } else { Utils.toast("Index does not exist.. let's create, parse and make the root"); mFilesArray = new JSONArrayUnsorted(new JSONArray()); mFoldersArray = new JSONArrayUnsorted(new JSONArray()); mIndex.put(JSON_FILES, mFilesArray.getManagedArray()); mIndex.put(JSON_FOLDERS, mFoldersArray.getManagedArray()); parseJSON(); mRoot = new IndexedFolder(null, "root"); addFolder(mRoot); } } catch (JSONException e) { Log.e(Utils.tag(), "Oh hey, not workin something", e); } callback.onResult(FileIndex.this); <START> } <END> }); }</code><technical_language>create IOnResult object of method call, for readability</technical_language>

Target:
private FileIndex(boolean fake, final IOnResult<FileIndex> callback) { IOnResult<EncryptedPreferences> onResult = new IOnResult<EncryptedPreferences>() { @Override public void onResult(EncryptedPreferences result) { Utils.d("Created the EncryptedPreferences"); mPreferences = result; mIndex = result.getJson(); try { if (mIndex.has(JSON_FILES) && mIndex.has(JSON_FOLDERS)) { Utils.d("Index exists.. let's read and parse"); mFilesArray = new JSONArrayUnsorted(mIndex.getJSONArray(JSON_FILES)); mFoldersArray = new JSONArrayUnsorted(mIndex.getJSONArray(JSON_FOLDERS)); parseJSON(); } else { Utils.d("Index does not exist.. let's create, parse and make the root"); mFilesArray = new JSONArrayUnsorted(new JSONArray()); mFoldersArray = new JSONArrayUnsorted(new JSONArray()); mIndex.put(JSON_FILES, mFilesArray.getManagedArray()); mIndex.put(JSON_FOLDERS, mFoldersArray.getManagedArray()); parseJSON(); mRoot = new IndexedFolder(null, "root"); addFolder(mRoot); } } catch (JSONException e) { Log.e(Utils.tag(this), "Oh hey, not workin something", e); } callback.onResult(FileIndex.this); } }; EncryptedPreferences.get(fake ? PREFERENCES_KEY_FAKE : PREFERENCES_KEY_REAL, onResult); }
Source:
<code>public ResponseEntity<ResourceSupport> startProcess(@PathVariable(name = "name") String scriptName) throws Exception { if (log.isTraceEnabled()) { log.trace("Starting Process for Script with name: " + scriptName); } <START> Context context = ContextUtil.obtainContext(requestService.getCurrentRequest().getServletRequest()); <END> ProcessRest processRest = scriptRestRepository.startProcess(context, scriptName); ProcessResource processResource = converter.toResource(processRest); context.complete(); return ControllerUtils.toResponseEntity(HttpStatus.ACCEPTED, new HttpHeaders(), processResource); }</code><technical_language>I guess this change is related this PR unable get more information commits description... explain purpose? if is a bug fix, point a test verify change made</technical_language>

Target:
public ResponseEntity<RepresentationModel<?>> startProcess(@PathVariable(name = "name") String scriptName) throws Exception { if (log.isTraceEnabled()) { log.trace("Starting Process for Script with name: " + scriptName); } Context context = ContextUtil.obtainContext(requestService.getCurrentRequest().getServletRequest()); ProcessRest processRest = scriptRestRepository.startProcess(context, scriptName); ProcessResource processResource = converter.toResource(processRest); context.complete(); return ControllerUtils.toResponseEntity(HttpStatus.ACCEPTED, new HttpHeaders(), processResource); }
Source:
<code>public void success() { boolean success = false; while (!success) { <START> RetryState rs = state.get(); <END> success = state.compareAndSet(rs, new RetryState(rs.count + 1, true)); } }</code><technical_language>RetryState rs = null; while(!success) { rs = state.get(); ...</technical_language>

Target:
public void success() { boolean success = false; RetryState rs; while (!success) { rs = state.get(); success = state.compareAndSet(rs, new RetryState(rs.count + 1, true)); } }
Source:
<code>public Object adapt(Object object) { if (object instanceof CDOID) { CDOID id = (CDOID)object; if (id instanceof CDOIDExternal) { CDOIDExternal idExternal = (CDOIDExternal)id; Resource resource = notifier.eResource(); if (resource != null) { String uriString = idExternal.getURI(); URI uri = URI.createURI(uriString); object = resource.getResourceSet().getEObject(uri, false); } } else { try { InternalCDOView view = getCDOObject().cdoView(); object = view.getObject(id, true); } catch (ObjectNotFoundException ex) { object = null; } } } if (object instanceof CDOObject) { object = CDOUtil.getEObject((EObject)object); } if (feature instanceof EAttribute) { if (object == null) { object = feature.getDefaultValue(); } else { EDataType eAttributeType = ((EAttribute)feature).getEAttributeType(); String <START> literalValue; <END> if (eAttributeType instanceof EEnum && object instanceof Integer) { EEnumLiteral literal = ((EEnum)eAttributeType).getEEnumLiteral((Integer)object); literalValue = literal.getLiteral(); } else { literalValue = String.valueOf(object); } if (eAttributeType != null) { object = eAttributeType.getEPackage().getEFactoryInstance().createFromString(eAttributeType, literalValue); } } } return object; }</code><technical_language>call stringValue is meaning calling createFromString</technical_language>

Target:
public Object adapt(Object object) { if (object instanceof CDOID) { CDOID id = (CDOID)object; if (id instanceof CDOIDExternal) { CDOIDExternal idExternal = (CDOIDExternal)id; Resource resource = notifier.eResource(); if (resource != null) { String uriString = idExternal.getURI(); URI uri = URI.createURI(uriString); object = resource.getResourceSet().getEObject(uri, false); } } else { try { InternalCDOView view = getCDOObject().cdoView(); object = view.getObject(id, true); } catch (ObjectNotFoundException ex) { object = null; } } } if (object instanceof CDOObject) { object = CDOUtil.getEObject((EObject)object); } if (feature instanceof EAttribute) { if (object == null) { object = feature.getDefaultValue(); } else { EDataType eAttributeType = ((EAttribute)feature).getEAttributeType(); if (eAttributeType != null) { String stringValue; if (eAttributeType instanceof EEnum && object instanceof Integer) { EEnumLiteral literal = ((EEnum)eAttributeType).getEEnumLiteral((Integer)object); stringValue = literal.getLiteral(); } else { stringValue = String.valueOf(object); } object = eAttributeType.getEPackage().getEFactoryInstance().createFromString(eAttributeType, stringValue); } } } return object; }
Source:
<code>public void setResponseAddress(String defaultReplyTo) { <START> if (defaultReplyTo.startsWith("SpEL:")) { <END> this.responseExpression = PARSER.parseExpression(defaultReplyTo.substring(5)); } else { this.responseAddress = new Address(defaultReplyTo); } }</code><technical_language>smells a bit. use: PARSER.parseExpression(defaultReplyTo, new TemplateParserContext()); instead? rely standard SpEL syntax: #{myBean.foo} etc</technical_language>

Target:
public void setResponseAddress(String defaultReplyTo) { if (defaultReplyTo.startsWith(PARSER_CONTEXT.getExpressionPrefix())) { this.responseExpression = PARSER.parseExpression(defaultReplyTo, PARSER_CONTEXT); } else { this.responseAddress = new Address(defaultReplyTo); } }
Source:
<code>public BasicKeyChain toEncrypted(KeyCrypter keyCrypter, KeyParameter aesKey) { lock.lock(); try { checkNotNull(keyCrypter); checkState(this.keyCrypter == null, "Key chain is already encrypted"); BasicKeyChain encrypted = new BasicKeyChain(keyCrypter); for (ECKey key : hashToKeys.values()) { ECKey encryptedKey = key.encrypt(keyCrypter, aesKey); if (!ECKey.encryptionIsReversible(key, encryptedKey, keyCrypter, aesKey)) throw new KeyCrypterException("The key " + key.toString() + " cannot be successfully decrypted after encryption so aborting wallet encryption."); encrypted.importKeyLocked(encryptedKey); } for (ListenerRegistration<KeyChainEventListener> listener : listeners) { <START> encrypted.listeners.add(listener); <END> } return encrypted; } finally { lock.unlock(); } }</code><technical_language>newly added addEventListener(ListenerRegistration) here, no</technical_language>

Target:
public BasicKeyChain toEncrypted(KeyCrypter keyCrypter, KeyParameter aesKey) { lock.lock(); try { checkNotNull(keyCrypter); checkState(this.keyCrypter == null, "Key chain is already encrypted"); BasicKeyChain encrypted = new BasicKeyChain(keyCrypter); for (ECKey key : hashToKeys.values()) { ECKey encryptedKey = key.encrypt(keyCrypter, aesKey); if (!ECKey.encryptionIsReversible(key, encryptedKey, keyCrypter, aesKey)) throw new KeyCrypterException("The key " + key.toString() + " cannot be successfully decrypted after encryption so aborting wallet encryption."); encrypted.importKeyLocked(encryptedKey); } for (ListenerRegistration<KeyChainEventListener> listener : listeners) { encrypted.addEventListener(listener); } return encrypted; } finally { lock.unlock(); } }
Source:
<code>private void updateList() { <START> log.error("updateList"); <END> List<StatefulAsset> statefulAssets = assetService.getStatefulAssets(); ObservableList<StatefulAsset> nonRemovedStatefulAssets = FXCollections.observableArrayList(statefulAssets.stream() .filter(e -> !e.wasRemovedByVoting()) .collect(Collectors.toList())); assetComboBox.setItems(nonRemovedStatefulAssets); observableList.setAll(statefulAssets.stream() .map(statefulAsset -> new AssetListItem(statefulAsset, bsqFormatter)) .collect(Collectors.toList())); GUIUtil.setFitToRowsForTableView(tableView, 41, 28, 2, 100); }</code><technical_language>suggestion</technical_language>

Target:
private void updateList() { List<StatefulAsset> statefulAssets = assetService.getStatefulAssets(); ObservableList<StatefulAsset> nonRemovedStatefulAssets = FXCollections.observableArrayList(statefulAssets.stream() .filter(e -> !e.wasRemovedByVoting()) .collect(Collectors.toList())); assetComboBox.setItems(nonRemovedStatefulAssets); observableList.setAll(statefulAssets.stream() .map(statefulAsset -> new AssetListItem(statefulAsset, bsqFormatter)) .collect(Collectors.toList())); GUIUtil.setFitToRowsForTableView(tableView, 41, 28, 2, 100); }
Source:
<code>private String getJarsFromClasspath() { StringBuilder jars = new StringBuilder(); ClassLoader cl = ClassLoader.getSystemClassLoader(); URL[] urls = ((URLClassLoader) cl).getURLs(); for (URL url : urls) { String jarName = new File(url.getFile()).getName(); <START> if (jarName.startsWith("fluo-api-") || jarName.startsWith("fluo-accumulo-")) { <END> if (jars.length() != 0) { jars.append(","); } jars.append(url.getFile()); } } return jars.toString(); }</code><technical_language>possibly this a configurable regex, configurable impl property</technical_language>

Target:
private String getJarsFromClasspath() { StringBuilder jars = new StringBuilder(); ClassLoader cl = FluoAdminImpl.class.getClassLoader(); URL[] urls = ((URLClassLoader) cl).getURLs(); String regex = config.getString(FluoConfigurationImpl.ACCUMULO_JARS_REGEX_PROP, FluoConfigurationImpl.ACCUMULO_JARS_REGEX_DEFAULT); Pattern pattern = Pattern.compile(regex); for (URL url : urls) { String jarName = new File(url.getFile()).getName(); if (pattern.matcher(jarName).matches()) { if (jars.length() != 0) { jars.append(","); } jars.append(url.getFile()); } } return jars.toString(); }
Source:
<code>protected double getSpeed(ReaderWay way) { String highwayValue = way.getTag("highway"); <START> if (way.hasTag("motorroad", "yes")) { <END> highwayValue = "motorroad"; } Integer speed = defaultSpeedMap.get(highwayValue); if (speed == null) throw new IllegalStateException(toString() + ", no speed found for: " + highwayValue + ", tags: " + way); if (highwayValue.equals("track")) { String tt = way.getTag("tracktype"); if (!Helper.isEmpty(tt)) { Integer tInt = trackTypeSpeedMap.get(tt); if (tInt != null) speed = tInt; } } return speed; }</code><technical_language>override highway? For example a motorway motorroad (not if this combination is valid)</technical_language>

Target:
protected double getSpeed(ReaderWay way) { String highwayValue = way.getTag("highway"); if (!Helper.isEmpty(highwayValue) && way.hasTag("motorroad", "yes") && highwayValue != "motorway" && highwayValue != "motorway_link") { highwayValue = "motorroad"; } Integer speed = defaultSpeedMap.get(highwayValue); if (speed == null) throw new IllegalStateException(toString() + ", no speed found for: " + highwayValue + ", tags: " + way); if (highwayValue.equals("track")) { String tt = way.getTag("tracktype"); if (!Helper.isEmpty(tt)) { Integer tInt = trackTypeSpeedMap.get(tt); if (tInt != null) speed = tInt; } } return speed; }
Source:
<code>public void onMessageBatch(List<org.springframework.amqp.core.Message> messages, Channel channel) { Message<?> converted; if (this.converterAdapter.isAmqpMessageList()) { converted = new GenericMessage<>(messages); } else { <START> List<Message<?>> messagingMessages = messages.stream() <END> .map(message -> toMessagingMessage(message)) .collect(Collectors.toList()); if (this.converterAdapter.isMessageList()) { converted = new GenericMessage<>(messagingMessages); } else { converted = new GenericMessage<>(messagingMessages .stream() .map(msg -> msg.getPayload()) .collect(Collectors.toList())); } } try { invokeHandlerAndProcessResult(null, channel, converted); } catch (Exception e) { throw RabbitExceptionTranslator.convertRabbitAccessException(e); } }</code><technical_language>avoid Java Streams critical Framework paths</technical_language>

Target:
public void onMessageBatch(List<org.springframework.amqp.core.Message> messages, Channel channel) { Message<?> converted; if (this.converterAdapter.isAmqpMessageList()) { converted = new GenericMessage<>(messages); } else { List<Message<?>> messagingMessages = new ArrayList<>(); for (org.springframework.amqp.core.Message message : messages) { messagingMessages.add(toMessagingMessage(message)); } if (this.converterAdapter.isMessageList()) { converted = new GenericMessage<>(messagingMessages); } else { List<Object> payloads = new ArrayList<>(); for (Message<?> message : messagingMessages) { payloads.add(message.getPayload()); } converted = new GenericMessage<>(payloads); } } try { invokeHandlerAndProcessResult(null, channel, converted); } catch (Exception e) { throw RabbitExceptionTranslator.convertRabbitAccessException(e); } }
Source:
<code>private static boolean test_setup() { boolean setupOk = false; try { <START> System.out.println("Here"); <END> InetAddress localHost = InetAddress.getLocalHost(); System.out.println("Here2"); String host = localHost.getHostAddress(); System.out.println("Here3" + host); _test_service_socket = new ServerSocket(_port); _test_socket = new Socket(host, _port); _from_test_service = new BufferedReader(new InputStreamReader (_test_socket.getInputStream())); _to_test_service = new PrintWriter(new OutputStreamWriter (_test_socket.getOutputStream())); _to_test_service.write(Utility.getProcessUid().stringForm()+"\n"); _to_test_service.write(Utility.intToHexString(Utility.getpid())+"\n"); for (int i = 0; i < _number; i++) { _tx[i] = new AtomicAction(); _tx[i].begin(); AtomicAction.suspend(); _to_test_service.write(_tx[i].type()+"\n"); _to_test_service.write(_tx[i].get_uid().stringForm()+"\n"); } terminateTx(_tx[0], false); terminateTx(_tx[2], true); terminateTx(_tx[3], false); terminateTx(_tx[5], false); terminateTx(_tx[6], false); terminateTx(_tx[8], false); _to_test_service.flush(); setupOk = true; } catch (Exception ex) { System.err.println("test_setup: Failed " + ex); ex.printStackTrace(); } return setupOk; }</code><technical_language>stack trace provides information output statements safe remove them</technical_language>

Target:
private static boolean test_setup() { boolean setupOk = false; try { String host = InetAddress.getLocalHost().getHostAddress(); _test_service_socket = new ServerSocket(_port); _test_socket = new Socket(host, _port); _from_test_service = new BufferedReader(new InputStreamReader (_test_socket.getInputStream())); _to_test_service = new PrintWriter(new OutputStreamWriter (_test_socket.getOutputStream())); _to_test_service.write(Utility.getProcessUid().stringForm()+"\n"); _to_test_service.write(Utility.intToHexString(Utility.getpid())+"\n"); for (int i = 0; i < _number; i++) { _tx[i] = new AtomicAction(); _tx[i].begin(); AtomicAction.suspend(); _to_test_service.write(_tx[i].type()+"\n"); _to_test_service.write(_tx[i].get_uid().stringForm()+"\n"); } terminateTx(_tx[0], false); terminateTx(_tx[2], true); terminateTx(_tx[3], false); terminateTx(_tx[5], false); terminateTx(_tx[6], false); terminateTx(_tx[8], false); _to_test_service.flush(); setupOk = true; } catch (Exception ex) { System.err.println("test_setup: Failed " + ex); ex.printStackTrace(); } return setupOk; }
Source:
<code>public ITopic[] getSubtopics() { <START> return subTopics.toArray(new ITopic[subTopics.size()]); <END> }</code><technical_language>do 'return subTopics.toArray(new ITopic[0]);'</technical_language>

Target:
public ITopic[] getSubtopics() { return subTopics.toArray(new ITopic[0]); }
Source:
<code>public void testParseHandlesMultipleSheets() throws IOException, InvalidFormatException, DataParserException { InputStream file = getFile("/TestFileMultipleSheets.xlsx"); Workbook workbook = WorkbookFactory.create(file); WorkbookParserSettings settings = WorkbookParserSettings.builder() .withHeader(ExcelHeader.WITH_HEADER) .build(); WorkbookParser parser = new WorkbookParser(settings, getContext(), workbook, "Sheet1::1"); Record firstSheetFirstRow = parser.parse(); Record firstSheetSecondRow = parser.parse(); Record secondSheetFirstRow = parser.parse(); Record secondSheetSecondRow = parser.parse(); LinkedHashMap<String, Field> firstContentMap = new LinkedHashMap<>(); for (int i = 1; i <= 5; i++) { firstContentMap.put("column" + i, Field.create((double) i)); } Field expectedFirstRow = Field.createListMap(firstContentMap); LinkedHashMap<String, Field> secondContentMap = new LinkedHashMap<>(); for (int i = 1; i <= 5; i++) { secondContentMap.put("column" + i, Field.create((double) i)); } Field expectedSecondRow = Field.createListMap(secondContentMap); LinkedHashMap<String, Field> thirdContentMap = new LinkedHashMap<>(); for (int i = 1; i <= 5; i++) { thirdContentMap.put("header" + i, Field.create((double) i*10)); } Field expectedThirdRow = Field.createListMap(thirdContentMap); LinkedHashMap<String, Field> fourthContentMap = new LinkedHashMap<>(); for (int i = 1; i <= 5; i++) { fourthContentMap.put("header" + i, Field.create((double) i*10)); } <START> Field expectedFourthRow = Field.createListMap(fourthContentMap); <END> assertEquals(expectedFirstRow, firstSheetFirstRow.get()); assertEquals(expectedSecondRow, firstSheetSecondRow.get()); assertEquals(expectedThirdRow, secondSheetFirstRow.get()); assertEquals(expectedFourthRow, secondSheetSecondRow.get()); }</code><technical_language>lines repeated 4x in this test case. create a helper method construct Field call instead? a single parameter select cases two</technical_language>

Target:
public void testParseHandlesMultipleSheets() throws IOException, InvalidFormatException, DataParserException { Workbook workbook = createWorkbook("/excel/TestMultipleSheets.xlsx"); WorkbookParser parser = new WorkbookParser(settingsWithHeader, getContext(), workbook, "Sheet1::1"); List<Pair<String, Integer>> sheetParameters = Arrays.asList( Pair.of("column", 1), Pair.of("header", 10) ); for (int sheet = 1; sheet <= sheetParameters.size(); sheet++) { for (int row = 1; row <= 2; row++) { Record parsedRow = parser.parse(); LinkedHashMap<String, Field> contentMap = new LinkedHashMap<>(); String columnPrefix = sheetParameters.get(sheet - 1).getLeft(); Integer valueMultiplier = sheetParameters.get(sheet - 1).getRight(); for (int column = 1; column <= 5; column++) { contentMap.put(columnPrefix + column, Field.create(BigDecimal.valueOf(column * valueMultiplier))); } Field expectedRow = Field.createListMap(contentMap); assertEquals(String.format("Parsed value for sheet %1d, row %2d did not match expected value", sheet, row), expectedRow, parsedRow.get()); } } }
Source:
<code>public Collection<Binding<MessageChannel>> bindConsumer(MessageChannel inputChannel, String inputChannelName) { String channelBindingTarget = this.channelBindingServiceProperties.getBindingDestination(inputChannelName); String[] channelBindingTargets = StringUtils.commaDelimitedListToStringArray(channelBindingTarget); List<Binding<MessageChannel>> bindings = new ArrayList<>(); for (String target : channelBindingTargets) { <START> Binder<MessageChannel> binder = getBinderForChannel(inputChannelName); <END> Binding<MessageChannel> binding = binder.bindConsumer(target, consumerGroup(inputChannelName), inputChannel, this.channelBindingServiceProperties.getConsumerProperties(inputChannelName)); bindings.add(binding); } this.consumerBindings.put(inputChannelName, bindings); return bindings; }</code><technical_language>getBinderForChannel(inputChannelName) done iteration</technical_language>

Target:
public Collection<Binding<MessageChannel>> bindConsumer(MessageChannel inputChannel, String inputChannelName) { String channelBindingTarget = this.channelBindingServiceProperties.getBindingDestination(inputChannelName); String[] channelBindingTargets = StringUtils.commaDelimitedListToStringArray(channelBindingTarget); List<Binding<MessageChannel>> bindings = new ArrayList<>(); Binder<MessageChannel> binder = getBinderForChannel(inputChannelName); String consumerGroup = consumerGroup(inputChannelName); Properties consumerProperties = this.channelBindingServiceProperties.getConsumerProperties(inputChannelName); for (String target : channelBindingTargets) { Binding<MessageChannel> binding = binder.bindConsumer(target, consumerGroup, inputChannel, consumerProperties); bindings.add(binding); } this.consumerBindings.put(inputChannelName, bindings); return bindings; }
Source:
<code>public ServerVariables getServerVariable(ObjectNode obj, String location, ParseResult result){ if(obj == null){ return null; } final ServerVariables serverVariables = new ServerVariables(); ServerVariable serverVariable = null; Set<String> variableKeys = getKeys(obj); for (String variableName : variableKeys) { JsonNode variableValue = obj.get(variableName); if (!variableValue.getNodeType().equals(JsonNodeType.OBJECT)) { result.invalidType(location, variableName, "object", variableValue); } else { serverVariable = new ServerVariable(); ObjectNode objNode = getObject(variableName, obj, false, location, result); ArrayNode an = getArray("enum",objNode,false,location,result); if (an != null) { List<String> _enum = new ArrayList<>(); for(JsonNode n : an) { if(n.isValueNode()) { _enum.add(n.asText()); serverVariable.setEnum(_enum); } else { result.invalidType(location, "enum", "value", n); } } } String value = getString("default", objNode, true, String.format("%s.%s'", location, variableName), result); serverVariable.setDefault(value); value = getString("description", objNode, false, String.format("%s.%s'", location, variableName), result); serverVariable.setDescription(value); <START> serverVariable.setExtensions(new LinkedHashMap<>()); <END> Set<String> keys = getKeys(objNode); for(String key : keys) { if(key.startsWith("x-")) { serverVariable.getExtensions().put(key, Json.mapper().convertValue(objNode.get(key), Object.class)); } } serverVariables.addServerVariable(variableName,serverVariable); } } return serverVariables; }</code><technical_language>set a LinkedHashMap values</technical_language>

Target:
public ServerVariables getServerVariable(ObjectNode obj, String location, ParseResult result){ if(obj == null){ return null; } final ServerVariables serverVariables = new ServerVariables(); ServerVariable serverVariable = null; Set<String> variableKeys = getKeys(obj); for (String variableName : variableKeys) { JsonNode variableValue = obj.get(variableName); if (!variableValue.getNodeType().equals(JsonNodeType.OBJECT)) { result.invalidType(location, variableName, "object", variableValue); } else { serverVariable = new ServerVariable(); ObjectNode objNode = getObject(variableName, obj, false, location, result); ArrayNode arrayNode = getArray("enum",objNode,false,location,result); if (arrayNode != null) { List<String> _enum = new ArrayList<>(); for(JsonNode n : arrayNode) { if(n.isValueNode()) { _enum.add(n.asText()); serverVariable.setEnum(_enum); } else { result.invalidType(location, "enum", "value", n); } } } String value = getString("default", objNode, true, String.format("%s.%s'", location, variableName), result); if(StringUtils.isNotBlank(value)) { serverVariable.setDefault(value); } value = getString("description", objNode, false, String.format("%s.%s'", location, variableName), result); if(StringUtils.isNotBlank(value)) { serverVariable.setDescription(value); } Map <String,Object> extensions = getExtensions(objNode,location,result); if(extensions != null && extensions.size() > 0) { serverVariable.setExtensions(extensions); } serverVariables.addServerVariable(variableName,serverVariable); } } return serverVariables; }
Source:
<code><START> void createSSBonds() { <END> List<SSBond> bonds = structure.getSSBonds(); if (bonds == null) bonds = new ArrayList<SSBond>(); int internalId = 0; for (StructConn conn : structConn) { String ptnr1_chainId = conn.getPtnr1_auth_asym_id(); String ptnr1_seqId = conn.getPtnr1_auth_seq_id(); String ptnr2_chainId = conn.getPtnr2_auth_asym_id(); String ptnr2_seqId = conn.getPtnr2_auth_seq_id(); Group s1 = lookupResidue(ptnr1_chainId, ptnr1_seqId); Group s2 = lookupResidue(ptnr2_chainId, ptnr2_seqId); if (null != s1 && null != s2) { if ("CYS".equals(s1.getPDBName()) && "CYS".equals(s2.getPDBName())) { SSBondImpl bond = new SSBondImpl(); bond.setSerNum(internalId++); bond.setChainID1(ptnr1_chainId); bond.setResnum1(ptnr1_seqId); if ("?".equals(conn.getPdbx_ptnr1_PDB_ins_code())) { conn.setPdbx_ptnr1_PDB_ins_code(null); } bond.setInsCode1(conn.getPdbx_ptnr1_PDB_ins_code()); bond.setChainID2(ptnr2_chainId); bond.setResnum2(ptnr2_seqId); if ("?".equals(conn.getPdbx_ptnr2_PDB_ins_code())) { conn.setPdbx_ptnr2_PDB_ins_code(null); } bond.setInsCode2(conn.getPdbx_ptnr2_PDB_ins_code()); bonds.add(bond); } } } structure.setSSBonds(bonds); }</code><technical_language>is good practice explicitly set visibility of method, helps others understanding code helps readability in general. do BioJava could. set private needed</technical_language>

Target:
private void createSSBonds() { List<SSBond> bonds = structure.getSSBonds(); if (bonds == null) bonds = new ArrayList<SSBond>(); final String symop = "1_555"; int internalId = 0; for (StructConn conn : structConn) { String ptnr1_chainId = conn.getPtnr1_auth_asym_id(); String ptnr1_seqId = conn.getPtnr1_auth_seq_id(); String ptnr2_chainId = conn.getPtnr2_auth_asym_id(); String ptnr2_seqId = conn.getPtnr2_auth_seq_id(); Group s1 = lookupResidue(ptnr1_chainId, ptnr1_seqId); Group s2 = lookupResidue(ptnr2_chainId, ptnr2_seqId); if (null != s1 && null != s2) { if ("CYS".equals(s1.getPDBName()) && symop.equals(conn.getPtnr1_symmetry()) && "CYS".equals(s2.getPDBName()) && symop.equals(conn.getPtnr2_symmetry())) { SSBondImpl bond = new SSBondImpl(); bond.setSerNum(internalId++); bond.setChainID1(ptnr1_chainId); bond.setResnum1(ptnr1_seqId); if ("?".equals(conn.getPdbx_ptnr1_PDB_ins_code())) { conn.setPdbx_ptnr1_PDB_ins_code(null); } bond.setInsCode1(conn.getPdbx_ptnr1_PDB_ins_code()); bond.setChainID2(ptnr2_chainId); bond.setResnum2(ptnr2_seqId); if ("?".equals(conn.getPdbx_ptnr2_PDB_ins_code())) { conn.setPdbx_ptnr2_PDB_ins_code(null); } bond.setInsCode2(conn.getPdbx_ptnr2_PDB_ins_code()); bonds.add(bond); } } } structure.setSSBonds(bonds); }
Source:
<code><START> public void update(StyleRange[] ranges) { <END> updateStyles = true; int oldRise = rise; int oldFontHeight = fontHeight; int oldMetricsWidth = metricsWidth; rise = 0; metricsWidth = 0; fontHeight = 0; if (ranges != null) { for (int i = 0; i < ranges.length; i++) { StyleRange style = ranges[i]; if (style.isVariableHeight()) { if (style.font != null) { Integer height = getMaxFontHeight(style.font); if (height != null && height > fontHeight) { fontHeight = height; } } if (style.metrics != null) { int width = style.metrics.width; if (width > metricsWidth) { metricsWidth = width; } } if (style.rise > rise) { rise = style.rise; } } } } if (oldRise != rise || oldFontHeight != fontHeight) { height = -1; } if (oldMetricsWidth != metricsWidth) { width = -1; } }</code><technical_language>I this method a bug. If a line (1st line) 3 characters 2 style ranges, applying 1st character, other 2nd character, need consider default font of styledtext find is biggest</technical_language>

Target:
public void update(StyleRange[] ranges) { updateStyles = true; int oldMaxRise = maxRise; int oldMaxFontHeight = maxFontHeight; int oldMaxMetricsWidth = maxMetricsWidth; maxRise = 0; maxMetricsWidth = 0; maxFontHeight = defaultFontHeight; if (ranges != null) { for (int i = 0; i < ranges.length; i++) { StyleRange style = ranges[i]; if (style.isVariableHeight()) { if (style.font != null) { Integer height = getMaxFontHeight(style.font); if (height != null && height > maxFontHeight) { maxFontHeight = height; } } if (style.metrics != null) { int width = style.metrics.width; if (width > maxMetricsWidth) { maxMetricsWidth = width; } } if (style.rise > maxRise) { maxRise = style.rise; } } } } if (oldMaxRise != maxRise || (oldMaxFontHeight != maxFontHeight)) { height = -1; } if (oldMaxMetricsWidth != maxMetricsWidth) { width = -1; } }
Source:
<code>public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final Bundle args = getArguments(); final WhatsNewModel model = args.getParcelable(ARG_MODEL); binding.title.setText(escapePlatformName(model.getTitle())); binding.message.setText(escapePlatformName(model.getMessage())); @DrawableRes <START> int imageDrawable = getResources().getIdentifier(model.getImage(), "drawable", <END> getContext().getPackageName()); binding.image.setImageResource(imageDrawable); }</code><technical_language>define util function for in Util class</technical_language>

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final Bundle args = getArguments(); final WhatsNewModel model = args.getParcelable(ARG_MODEL); binding.title.setText(escapePlatformName(model.getTitle())); binding.message.setText(escapePlatformName(model.getMessage())); @DrawableRes final int imageRes = UiUtil.getDrawable(getContext(), model.getImage()); binding.image.setImageResource(imageRes); final Drawable drawable = UiUtil.getDrawable(getContext(), imageRes); if (drawable != null) { if (drawable.getIntrinsicHeight() > drawable.getIntrinsicWidth()) { binding.image.setScaleType(ImageView.ScaleType.FIT_END); } else { binding.image.setScaleType(ImageView.ScaleType.FIT_CENTER); } } }
Source:
<code>private Provider getDeletedProvider() { if (deletedProvider == null) { <START> deletedProvider = getDbFacade().getProviderDao().get(getParameters().getProvider().getId()); <END> } return deletedProvider; }</code><technical_language>encapsulate getProviderDao() getDbFacade().getProviderDao()</technical_language>

Target:
private Provider getDeletedProvider() { if (deletedProvider == null) { deletedProvider = getProviderDao().get(getParameters().getProvider().getId()); } return deletedProvider; }
Source:
<code>private boolean upgradeTwentyFiveTwentySix(SQLiteDatabase db) { db.beginTransaction(); try { db.execSQL(DbUtil.addColumnToTable( INDEXED_FIXTURE_PATHS_TABLE, INDEXED_FIXTURE_PATHS_COL_ATTRIBUTES, <START> "TEXT")); <END> db.setTransactionSuccessful(); return true; } finally { db.endTransaction(); } }</code><technical_language>this a BLOB</technical_language>

Target:
private boolean upgradeTwentyFiveTwentySix(SQLiteDatabase db) { db.beginTransaction(); try { db.execSQL(DbUtil.addColumnToTable( INDEXED_FIXTURE_PATHS_TABLE, INDEXED_FIXTURE_PATHS_COL_ATTRIBUTES, "BLOB")); db.setTransactionSuccessful(); return true; } finally { db.endTransaction(); } }
Source:
<code>private String resolveUserPropertiesFilePath() { <START> String userPropertiesPath = System.getProperty("connectionProperties"); <END> if (userPropertiesPath == null) { return DEFAULT_USER_PROPERTIES_PATH; } return userPropertiesPath; }</code><technical_language>I if "connectionProperties" name is generic. iisHadoopConnectionProperties</technical_language>

Target:
private String resolveUserPropertiesFilePath() { String userPropertiesPath = System.getProperty("iisConnectionProperties"); if (userPropertiesPath == null) { return DEFAULT_USER_PROPERTIES_PATH; } return userPropertiesPath; }
Source:
<code>public LeaderElectionHealthReport leaderElectionRateHealthReport() { double leaderElectionRateForAllClients = getLeaderElectionRateForAllClients(); return isHealthy(leaderElectionRateForAllClients) <START> ? LeaderElectionHealthReport.builder() .status(LeaderElectionHealthStatus.HEALTHY) .leaderElectionRate(leaderElectionRateForAllClients) .build() : LeaderElectionHealthReport.builder() .status(LeaderElectionHealthStatus.UNHEALTHY) .leaderElectionRate(leaderElectionRateForAllClients) .build(); <END> }</code><technical_language>interesting of it. some of builder is same, I suggest do either: java LeaderElectionHealthStatus status = isHealthy(...) ? LeaderElectionHealthStatus.HEALTHY : LeaderElectionHealthStatus.UNHEALTHY; return LeaderElectionReport.builder().status(status).leaderElectionRate(...).build(); inline status builder</technical_language>

Target:
public LeaderElectionHealthReport leaderElectionRateHealthReport() { double leaderElectionRateForAllClients = getLeaderElectionRateForAllClients(); LeaderElectionHealthStatus status = isHealthy(leaderElectionRateForAllClients) ? LeaderElectionHealthStatus.HEALTHY : LeaderElectionHealthStatus.UNHEALTHY; return LeaderElectionHealthReport.builder() .status(status) .leaderElectionRate(leaderElectionRateForAllClients) .build(); }
Source:
<code>private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse) throws IOException { ResponseBody rawBody = rawResponse.body(); rawResponse = rawResponse.newBuilder() .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())) .build(); int code = rawResponse.code(); if (code < 200 || code >= 300) { try { ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody); return Response.error(bufferedBody, rawResponse); } finally { closeQuietly(rawBody); } } if (code == 204 || code == 205) { return Response.success(null, rawResponse); } ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody); try { T body = responseConverter.convert(catchingBody); return Response.success(body, rawResponse); } catch (RuntimeException e) { catchingBody.throwIfCaught(); <START> throw new RuntimeException("Problem has occurred during conversion of response for " <END> + infoForException, e); } }</code><technical_language>a fan of wrapping here. hides underlying error creates RetrofitError-like semantics again</technical_language>

Target:
private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse) throws IOException { ResponseBody rawBody = rawResponse.body(); rawResponse = rawResponse.newBuilder() .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())) .build(); int code = rawResponse.code(); if (code < 200 || code >= 300) { try { ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody); return Response.error(bufferedBody, rawResponse); } finally { closeQuietly(rawBody); } } if (code == 204 || code == 205) { return Response.success(null, rawResponse); } ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody); try { T body = responseConverter.convert(catchingBody); return Response.success(body, rawResponse); } catch (RuntimeException e) { catchingBody.throwIfCaught(); throw new RuntimeException("Problem has occurred during conversion of response for " + toString(), e); } }
Source:
<code>public void setScrollView(@Nullable ObservableWebView webView) { webview = webView; <START> if (webview != null) { <END> webview.addOnScrollChangeListener(this); webview.addOnDownMotionEventListener(this); webview.addOnUpOrCancelMotionEventListener(this); } }</code><technical_language>null out listeners a previous WebView</technical_language>

Target:
public void setScrollView(@Nullable ObservableWebView webView) { this.webView = webView; if (this.webView != null) { this.webView.clearAllListeners(); this.webView.addOnScrollChangeListener(this); this.webView.addOnDownMotionEventListener(this); this.webView.addOnUpOrCancelMotionEventListener(this); } }
Source:
<code>private static <T extends RpcScheduler> T createScheduler( Class<T> theClass, int priorityLevels, String ns, Configuration conf) { try { Constructor<T> ctor = theClass.getDeclaredConstructor(int.class, String.class, Configuration.class); return ctor.newInstance(priorityLevels, ns, conf); <START> } catch (RuntimeException e) { <END> throw e; } catch (Exception e) { } try { Constructor<T> ctor = theClass.getDeclaredConstructor(int.class); return ctor.newInstance(priorityLevels); } catch (RuntimeException e) { throw e; } catch (Exception e) { } try { Constructor<T> ctor = theClass.getDeclaredConstructor(); return ctor.newInstance(); } catch (RuntimeException e) { throw e; } catch (Exception e) { } throw new RuntimeException(theClass.getName() + " could not be constructed."); }</code><technical_language>HDFS-9478 is fixing exception handling constructing callqueue instances. a similar fix for createScheduler</technical_language>

Target:
private static <T extends RpcScheduler> T createScheduler( Class<T> theClass, int priorityLevels, String ns, Configuration conf) { try { Constructor<T> ctor = theClass.getDeclaredConstructor(int.class, String.class, Configuration.class); return ctor.newInstance(priorityLevels, ns, conf); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { throw new RuntimeException(theClass.getName() + " could not be constructed.", e.getCause()); } catch (Exception e) { } try { Constructor<T> ctor = theClass.getDeclaredConstructor(int.class); return ctor.newInstance(priorityLevels); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { throw new RuntimeException(theClass.getName() + " could not be constructed.", e.getCause()); } catch (Exception e) { } try { Constructor<T> ctor = theClass.getDeclaredConstructor(); return ctor.newInstance(); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { throw new RuntimeException(theClass.getName() + " could not be constructed.", e.getCause()); } catch (Exception e) { } throw new RuntimeException(theClass.getName() + " could not be constructed."); }
Source:
<code>public InputStream getMapContent() throws IOException { URL requestWorkspacesURL = new URL(getMapContextUrl()); HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(cParams.getConnectionTimeOut()); <START> if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { <END> throw new IOException(I18N.tr("HTTP Error {0} message : {1} while downloading from {2}",connection.getResponseCode(),connection.getResponseMessage(),getMapContextUrl())); } return connection.getInputStream(); }</code><technical_language>copy-pasted "if" blocks preceeded tabs..</technical_language>

Target:
public InputStream getMapContent() throws IOException { String url = RemoteCommons.getUrlContext(cParams, workspaceName, id); URL requestWorkspacesURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(cParams.getConnectionTimeOut()); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(I18N.tr("HTTP Error {0} message : {1} while downloading from {2}", connection.getResponseCode(), connection.getResponseMessage(), url)); } return connection.getInputStream(); }
Source:
<code>public TupleBatch[] partition(@Nonnull final TupleBatch tb) { BitSet[] partitions = new BitSet[numPartition()]; for (int i = 0; i < tb.numTuples(); i++) { <START> partitions[tb.getInt(index, i) - 1].set(i); <END> } TupleBatch[] tbs = new TupleBatch[numPartition()]; for (int i = 0; i < tbs.length; ++i) { tbs[i] = tb.filter(partitions[i]); } return tbs; }</code><technical_language>do a schema check catch non-integer columns early? Also, out-of-bounds in "partition" column trigger exception, BitSet grow automatically? If latter, add explicit check fail out-of-bounds value</technical_language>

Target:
public TupleBatch[] partition(@Nonnull final TupleBatch tb) { BitSet[] partitions = new BitSet[numPartitions()]; for (int i = 0; i < partitions.length; ++i) { partitions[i] = new BitSet(); } for (int i = 0; i < tb.numTuples(); i++) { partitions[tb.getInt(index, i) - 1].set(i); } TupleBatch[] tbs = new TupleBatch[numPartitions()]; for (int i = 0; i < tbs.length; ++i) { tbs[i] = tb.filter(partitions[i]); } return tbs; }