auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Map<String, Object> getUsersList(String assetInode, String permission, Map<String, String> params) throws Exception { int start = 0; <START> if (params.containsKey("start")) { <END> start = Integer.parseInt((String) params.get("start")); } int limit = -1; if (params.containsKey("limit")) { limit = Integer.parseInt((String) params.get("limit")); } String query = ""; if (params.containsKey("query")) { query = (String) params.get("query"); } boolean includeAnonymous = false; if (params.containsKey("includeAnonymous")) { includeAnonymous = Boolean.valueOf((String) params.get("includeAnonymous")); } boolean includeDefault = true; if (params.containsKey("includeDefault")) { includeDefault = Boolean.valueOf((String) params.get("includeDefault")); } Map<String, Object> results; if ((InodeUtils.isSet(assetInode) && !assetInode.equals("0")) && (UtilMethods.isSet(permission) && !permission.equals("0"))) { results = processUserListWithPermissionOnInode(assetInode, permission, query, start, limit); } else { results = processUserList(query, start, limit, includeAnonymous, includeDefault); } return results; }</code><technical_language>want include this parsing ConversionUtils handle NumberException, etc. create encapsulate in a method, like: int getParam(final String name, Map<String, String> params) { int result = -1; if(params.containsKey(name)) { result = ConversionUtils.toInteger (params.get(name)); } return result; }</technical_language>

Target:
public Map<String, Object> getUsersList(String assetInode, String permission, Map<String, String> params) throws Exception { final int start = toInt("start", params, 0); final int limit = toInt("limit", params, 100); final String query = getMapValue(params, "query", StringUtils.EMPTY); final boolean includeAnonymous = toBoolean("includeAnonymous", params, false); final boolean includeDefault = toBoolean("includeDefault", params, true); Map<String, Object> results; if ((InodeUtils.isSet(assetInode) && !"0".equals(assetInode)) && (UtilMethods.isSet(permission) && !"0".equals(permission))) { results = processUserListWithPermissionOnInode(assetInode, permission, query, start, limit); } else { results = processUserList(query, start, limit, includeAnonymous, includeDefault); } return results; }
Source:
<code>public void reportError(Throwable error) { <START> Monitor.getMonitor().getEventSender().sendException(new Throwable(delegateClass.getCanonicalName() + " failed to process tuple"), boltService); <END> super.reportError(error); }</code><technical_language>sendException(error)</technical_language>

Target:
public void reportError(Throwable error) { Monitor.getMonitor().getEventSender().sendException(error, boltService); super.reportError(error); }
Source:
<code>public void onTaskFinished(ObaStopsForLocationResponse response) { if (response.getCode() != ObaApi.OBA_OK) { showErrorMessage(getString(UIHelp.getStopErrorString(this, response.getCode()))); return; } Log.d(TAG, "Found stops."); ObaStop closestStop; <START> closestStop = UIHelp.getClosestStop(this, response.getStops(), mLastKnownLocation); <END> if (closestStop != null) { Log.d(TAG, "Closest stop is: " + closestStop.getName()); mDistanceToStopView.setObaStop(closestStop); mArrowView.setObaStop(closestStop); mProgressMessage.setText(getString(R.string.getting_arrival_times)); Intent i = new Builder(this, closestStop).getIntent(); this.setIntent(i); initLoader(i.getExtras()); } else { Log.e(TAG, "No stops returned"); } }</code><technical_language>@barbeau I together: ObaStop closestStop = UIHelp.getClosestStop(this, response.getStops(), mLastKnownLocation);</technical_language>

Target:
public void onTaskFinished(ObaStopsForLocationResponse response) { if (response.getCode() != ObaApi.OBA_OK) { showErrorMessage(getString(UIHelp.getStopErrorString(this, response.getCode()))); return; } Log.d(TAG, "Found stops."); ObaStop closestStop = UIHelp.getClosestStop(this, response.getStops(), mLastKnownLocation); if (closestStop != null) { Log.d(TAG, "Closest stop is: " + closestStop.getName()); mDistanceToStopView.setObaStop(closestStop); mArrowView.setObaStop(closestStop); mProgressMessage.setText(getString(R.string.getting_arrival_times)); Intent i = new Builder(this, closestStop).getIntent(); this.setIntent(i); initLoader(i.getExtras()); } else { Log.e(TAG, "No stops returned"); } }
Source:
<code>public Document createDocument(Iso19115Collection.Document doc) throws GeneratorException { String id = doc.id(); if (doc.contents().trim().isEmpty()) { throw new EmptyDocumentException(); } Document document = new Document(); document.add(new StringField(IndexArgs.ID, id, Field.Store.YES)); document.add(new SortedDocValuesField(IndexArgs.ID, new BytesRef(id))); <START> document.add(new StoredField(IsoField.TITLE.name, doc.getTitle())); <END> document.add(new StoredField(IsoField.ABSTRACT.name, doc.getAbstract())); if (args.storeRaw) { document.add(new StoredField(IndexArgs.RAW, doc.raw())); } FieldType fieldType = new FieldType(); fieldType.setStored(args.storeContents); if (args.storeDocvectors) { fieldType.setStoreTermVectors(true); fieldType.setStoreTermVectorPositions(true); } if (args.storePositions) { fieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); } else { fieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS); } document.add(new Field(IndexArgs.CONTENTS, doc.contents(), fieldType)); return document; }</code><technical_language>I reuse code super class? of this is default generator for title abstract. call superclass method, add in additional fields</technical_language>

Target:
public Document createDocument(Iso19115Collection.Document doc) throws GeneratorException { Document document = super.createDocument(doc); document.add(new StoredField(Iso19115Field.TITLE.name, doc.getTitle())); document.add(new StoredField(Iso19115Field.ABSTRACT.name, doc.getAbstract())); return document; }
Source:
<code><START> private Config(String configPath) { <END> assert configPath != null; assert configPath.endsWith(".properties"); try { config = new PropertiesConfiguration(configPath); } catch (ConfigurationException e) { e.printStackTrace(); } overrideWithEnvironmentVariables(config); assertAllPropertiesPresent(config); }</code><technical_language>nice a configuration file locally, if a ~/bridge-sdk.properties file exists, override default props. environment variables override of (don't if Apache config this here)</technical_language>

Target:
private Config(String configPath) { assert configPath != null; assert configPath.endsWith(".properties"); try { config = new PropertiesConfiguration(configPath); } catch (ConfigurationException e) { e.printStackTrace(); } overrideWithEnvironmentVariables(config); assertAllPropertiesPresent(); assertAllPropertiesValid(); }
Source:
<code>public IConnection createOpenshiftConnection(IServer server, ADBInfo adb) { <START> return createOpenshiftConnection(server, adb, true); <END> }</code><technical_language>return createOpenshiftConnection(server, adb, ConnectionsRegistrySingleton.getInstance());</technical_language>

Target:
public IConnection createOpenshiftConnection(IServer server, ADBInfo adb) { return createOpenshiftConnection(server, adb, ConnectionsRegistrySingleton.getInstance()); }
Source:
<code>public void testSetupDiOpenDevRegKey() throws Exception { HANDLE hDevInfoSet = setupApi.SetupDiGetClassDevs(GUID_DEVINTERFACE_COMPORT, null, null, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); assertTrue("For this test we need a valid HANDLE!",hDevInfoSet != INVALID_HANDLE_VALUE); SP_DEVINFO_DATA devInfo = new SP_DEVINFO_DATA(); boolean succeed = setupApi.SetupDiEnumDeviceInfo(hDevInfoSet, 0, devInfo); <START> assertTrue("For this test we need at least one com-port device",succeed); <END> HKEY hDeviceKey = setupApi.SetupDiOpenDevRegKey(hDevInfoSet, devInfo, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE); if (hDeviceKey != INVALID_HANDLE_VALUE) advapi32.RegCloseKey(hDeviceKey); }</code><technical_language>a space ,</technical_language>

Target:
public void testSetupDiOpenDevRegKey() { HANDLE hDevInfoSet = setupApi.SetupDiGetClassDevs(null, null, null, DIGCF_ALLCLASSES); assertTrue(hDevInfoSet != INVALID_HANDLE_VALUE); assertTrue(setupApi.SetupDiEnumDeviceInfo(hDevInfoSet, FIRST_MEMBER, devInfo)); HKEY hDeviceKey = setupApi.SetupDiOpenDevRegKey(hDevInfoSet, devInfo, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE); assertTrue(hDeviceKey != INVALID_HANDLE_VALUE); advapi32.RegCloseKey(hDeviceKey); }
Source:
<code>public List<DataRecord> getMultipleFullRecordsFromQuery(String catalogId, String field, String value, int rows) { loadOPACConfiguration(catalogId); HashMap<String, String> searchFields = new HashMap<>(); searchFields.put(field, value); if (searchFieldMapping.keySet().containsAll(searchFields.keySet())) { LinkedHashMap<String, String> queryParameters = new LinkedHashMap<>(parameters); LinkedHashMap<String, String> searchFieldMap = getSearchFieldMap(searchFields); try { URI queryURL = createQueryURI(queryParameters); String queryString = queryURL.toString() + "&"; if (Objects.nonNull(interfaceType)) { if (Objects.nonNull(interfaceType.getStartRecordString())) { queryString = queryString + interfaceType.getStartRecordString() + equalsOperand + "0&"; } if (Objects.nonNull(interfaceType.getMaxRecordsString())) { queryString = queryString + interfaceType.getMaxRecordsString() + equalsOperand + rows + "&"; } <START> if (Objects.nonNull(interfaceType.getQueryString())) { queryString = queryString + equalsOperand; } <END> } queryString = queryString + createSearchFieldString(searchFieldMap); return performQueryToMultipleRecords(queryString); } catch (URISyntaxException | IOException | ParserConfigurationException | SAXException | TransformerException e) { logger.error(e.getLocalizedMessage()); } } return Collections.emptyList(); }</code><technical_language>condition effect execution of concatenation</technical_language>

Target:
public List<DataRecord> getMultipleFullRecordsFromQuery(String catalogId, String field, String value, int rows) { loadOPACConfiguration(catalogId); HashMap<String, String> searchFields = new HashMap<>(); searchFields.put(field, value); if (searchFieldMapping.keySet().containsAll(searchFields.keySet())) { LinkedHashMap<String, String> queryParameters = new LinkedHashMap<>(parameters); LinkedHashMap<String, String> searchFieldMap = getSearchFieldMap(searchFields); try { URI queryURL = createQueryURI(queryParameters); String queryString = queryURL.toString() + "&"; if (Objects.nonNull(interfaceType)) { if (Objects.nonNull(interfaceType.getStartRecordString())) { queryString = queryString + interfaceType.getStartRecordString() + equalsOperand + "0&"; } if (Objects.nonNull(interfaceType.getMaxRecordsString())) { queryString = queryString + interfaceType.getMaxRecordsString() + equalsOperand + rows + "&"; } if (Objects.nonNull(interfaceType.getQueryString())) { queryString = queryString + interfaceType.getQueryString() + equalsOperand; } } queryString = queryString + createSearchFieldString(searchFieldMap); return performQueryToMultipleRecords(queryString); } catch (URISyntaxException | IOException | ParserConfigurationException | SAXException | TransformerException e) { logger.error(e.getLocalizedMessage()); } } return Collections.emptyList(); }
Source:
<code>public int getSSLPort() { <START> return 0; <END> }</code><technical_language>this throw, it</technical_language>

Target:
public int getSSLPort() { throw new IllegalStateException("No SSL port exists for localhost"); }
Source:
<code>public List<Item> next() { List<Episode> episodes = episodesIterator.next(); ImmutableList.Builder<Item> items = ImmutableList.builder(); <START> currentEpisodesIterator = episodes.iterator(); <END> ImmutableListMultimap<String, Availability> availabilities = getAvailabilities(episodes); ImmutableListMultimap<String, Broadcast> broadcasts = getBroadcasts(episodes); ImmutableListMultimap<String, Version> versions = getVersions(episodes); while (currentEpisodesIterator.hasNext()) { Episode glycerinEpisode = currentEpisodesIterator.next(); NitroItemSource<Episode> nitroItemSource = NitroItemSource.valueOf( glycerinEpisode, availabilities.get(glycerinEpisode.getPid()), broadcasts.get(glycerinEpisode.getPid()), versions.get(glycerinEpisode.getPid()) ); Item item = itemExtractor.extract(nitroItemSource); List<Clip> clips = getClips(nitroItemSource); item.setClips(clips); items.add(item); } return items.build(); }</code><technical_language>Again, Iterable..</technical_language>

Target:
public List<Item> next() { List<Episode> episodes = episodesIterator.next(); ImmutableList.Builder<Item> items = ImmutableList.builder(); ImmutableListMultimap<String, Availability> availabilities = getAvailabilities(episodes); ImmutableListMultimap<String, Broadcast> broadcasts = getBroadcasts(episodes); ImmutableListMultimap<String, Version> versions = getVersions(episodes); for (Episode glycerinEpisode : episodes) { NitroItemSource<Episode> nitroItemSource = NitroItemSource.valueOf( glycerinEpisode, availabilities.get(glycerinEpisode.getPid()), broadcasts.get(glycerinEpisode.getPid()), versions.get(glycerinEpisode.getPid()) ); Item item = itemExtractor.extract(nitroItemSource); List<Clip> clips = getClips(nitroItemSource); item.setClips(clips); items.add(item); } return items.build(); }
Source:
<code>private void sleepForEnqueue(long maxSleepMillis) { synchronized (localTaskNoticeHelper) { try { localTaskNoticeHelper.wait(maxSleepMillis); } catch (InterruptedException ex) { <START> return; <END> } } }</code><technical_language>call Thread.currentThread().interrupt() restore interrupted status</technical_language>

Target:
private void sleepForEnqueue(long maxSleepMillis) { synchronized (localTaskNoticeHelper) { try { localTaskNoticeHelper.wait(maxSleepMillis); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return; } } }
Source:
<code>public static void createBuckets() throws IOException { <START> rawStorage.createBucket(BUCKET_NAME); <END> }</code><technical_language>I need integration test helper create cleanup shared test bucket</technical_language>

Target:
public static void createBuckets() throws IOException { GoogleCloudStorage rawStorage = createGoogleCloudStorage(); rawStorage.createBucket(BUCKET_NAME); }
Source:
<code>public String getEvaluatorView(String task) { try { Connection conn = getConnection(); <START> String sql = "SELECT evaluatorTask FROM tasks WHERE name = ?;"; <END> PreparedStatement stmt = conn.prepareStatement(sql); ResultSet evaluatorTaskRS = stmt.executeQuery(); evaluatorTaskRS.first(); String evaluatorTask = evaluatorTaskRS.getString(1); conn.close(); return evaluatorTask; } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>evaluatorTask evaluatorView</technical_language>

Target:
public String getEvaluatorView(String task) { try { Connection conn = getConnection(); String sql = "SELECT evaluatorView FROM tasks WHERE name = ?;"; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet evaluatorViewRS = stmt.executeQuery(); evaluatorViewRS.first(); String evaluatorView = evaluatorViewRS.getString(1); conn.close(); return evaluatorView; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>private void importCertificate() { <START> importProviderCertificate(); <END> sourceListModel.setConfirmWindow(null); }</code><technical_language>call this function here. reason do this in locations? I 1st enable remove certificate variable class</technical_language>

Target:
private void importCertificate() { Frontend.getInstance().runAction(VdcActionType.ImportProviderCertificate, importCertificatesParams(), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { testProviderConnectivity(); } }, null, false); sourceListModel.setConfirmWindow(null); }
Source:
<code>StreamsProducer streamsProducerForTask(final TaskId taskId) { if (threadProducer != null) { throw new IllegalStateException("Producer per thread is used"); } <START> return taskProducers.get(taskId); <END> }</code><technical_language>nit: add a check taskId exists in taskProducers do return null</technical_language>

Target:
StreamsProducer streamsProducerForTask(final TaskId taskId) { if (threadProducer != null) { throw new IllegalStateException("Producer per thread is used"); } final StreamsProducer taskProducer = taskProducers.get(taskId); if (taskProducer == null) { throw new IllegalStateException("Unknown TaskId: " + taskId); } return taskProducer; }
Source:
<code>public FloatColumnSelector makeFloatColumnSelector( final IncrementalIndexStorageAdapter.EntryHolder currEntry, final IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerFloatColumnSelector implements FloatColumnSelector { @Override public float get() { final Object[] dims = currEntry.getKey().getDims(); if (dimIndex >= dims.length) { <START> return DimensionHandlerUtils.ZERO_FLOAT; <END> } return (Float) dims[dimIndex]; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { } } return new IndexerFloatColumnSelector(); }</code><technical_language>ask ZERO_ constants makeObjectColumnSelector() methods, return Object. This method returns primitive change is pointless (and in some other places in this commit)</technical_language>

Target:
public FloatColumnSelector makeFloatColumnSelector( final IncrementalIndexStorageAdapter.EntryHolder currEntry, final IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerFloatColumnSelector implements FloatColumnSelector { @Override public float get() { final Object[] dims = currEntry.getKey().getDims(); if (dimIndex >= dims.length) { return 0.0f; } return (Float) dims[dimIndex]; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { } } return new IndexerFloatColumnSelector(); }
Source:
<code>private void getTables() throws SQLException { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery( "SELECT name, sql FROM sqlite_master " + " WHERE type= 'table' " + " ORDER BY name;"); while (resultSet.next()) { String tableName = resultSet.getString("name"); String tableSQL = resultSet.getString("sql"); dbTablesMap.put(tableName, tableSQL); } resultSet.close(); <START> statement.close(); <END> }</code><technical_language>I a finally block is needed ensure record set statement closed</technical_language>

Target:
private void getTables() throws SQLException { Statement statement = null; ResultSet resultSet = null; try { statement = connection.createStatement(); resultSet = statement.executeQuery( "SELECT name, sql FROM sqlite_master " + " WHERE type= 'table' " + " ORDER BY name;"); while (resultSet.next()) { String tableName = resultSet.getString("name"); String tableSQL = resultSet.getString("sql"); dbTablesMap.put(tableName, tableSQL); } } catch(SQLException ex) { throw ex; } finally { if (null != resultSet) { resultSet.close(); } if (null != statement) { statement.close(); } } }
Source:
<code>private ListenableFuture<?> updateDriverBlockedFuture(ListenableFuture<?> sourceBlockedFuture) { checkState(initialized.get(), "Driver is not initialized"); SettableFuture<?> newDriverBlockedFuture = SettableFuture.create(); driverBlockedFuture.set(newDriverBlockedFuture); sourceBlockedFuture.addListener(() -> newDriverBlockedFuture.set(null), newDirectExecutorService()); boolean memoryRevokingRequested = operators.stream() .map(Operator::getOperatorContext) <START> .filter(OperatorContext::isMemoryRevokingRequested) <END> .findAny() .isPresent(); if (memoryRevokingRequested) { newDriverBlockedFuture.set(null); } return newDriverBlockedFuture; }</code><technical_language>Add .filter(op -> !revokingOperators.containsKey(op)). running processFor if operators for startMemoryRevoke called. operators return true OperatorContext::isMemoryRevokingRequested</technical_language>

Target:
private ListenableFuture<?> updateDriverBlockedFuture(ListenableFuture<?> sourceBlockedFuture) { checkState(initialized.get(), "Driver is not initialized"); SettableFuture<?> newDriverBlockedFuture = SettableFuture.create(); driverBlockedFuture.set(newDriverBlockedFuture); sourceBlockedFuture.addListener(() -> newDriverBlockedFuture.set(null), newDirectExecutorService()); boolean memoryRevokingRequested = operators.stream() .filter(operator -> !revokingOperators.containsKey(operator)) .map(Operator::getOperatorContext) .anyMatch(OperatorContext::isMemoryRevokingRequested); if (memoryRevokingRequested) { newDriverBlockedFuture.set(null); } return newDriverBlockedFuture; }
Source:
<code>private void visitKey(Object key, WriteCommand command) { <START> int segment = getSegment(key); <END> if (getOwnership(segment) != Ownership.PRIMARY) { return; } IracMetadata metadata = iracVersionGenerator.generateNewMetadata(segment); if (log.isDebugEnabled()) { log.debugf("[IRAC] New metadata for key '%s' is %s", key, metadata); } IracUtils.updateCommandMetadata(key, command, metadata); if (trace) { log.tracef("[IRAC] Command: %s", command); } }</code><technical_language>SegmentSpecificCommand#extractSegment retrieve segment commands a single key</technical_language>

Target:
private void visitKey(Object key, WriteCommand command) { int segment = getSegment(command, key); if (getOwnership(segment) != Ownership.PRIMARY) { return; } IracMetadata metadata = iracVersionGenerator.generateNewMetadata(segment); updateCommandMetadata(key, command, metadata); if (trace) { log.tracef("[IRAC] New metadata for key '%s' is %s. Command=%s", key, metadata, command); } }
Source:
<code>public MultiTenantRouter(MultiTenantRouterConfiguration routerConfiguration) { this.routerConfiguration = routerConfiguration; routerConfiguration.getHotRodRouterConfiguration().ifPresent(config -> routers.add(new HotRodRouter(config))); <START> routerConfiguration.getRestRouterConfiguration().ifPresent(config -> routers.add(new RestRouter(config))); <END> }</code><technical_language>I simpler store router in a separate field</technical_language>

Target:
public MultiTenantRouter(MultiTenantRouterConfiguration routerConfiguration) { this.routerConfiguration = routerConfiguration; if(routerConfiguration.getHotRodRouterConfiguration() != null) { routers.add(new HotRodRouter(routerConfiguration.getHotRodRouterConfiguration())); } if(routerConfiguration.getRestRouterConfiguration() != null) { routers.add(new RestRouter(routerConfiguration.getRestRouterConfiguration())); } }
Source:
<code>public void testVerifyHttpError() throws Exception { wrapper.setHttpClient(this.stubHttpClient(500, "<?xml version='1.0' encoding='UTF-8' ?>\n" + " <verify_response>\n" + " <request_id>not-really-a-request-id</request_id>\n" + " <status>0</status>\n" + " <error_text>error</error_text>\n" + " </verify_response>")); try { VerifyResult r = client.verify( "447700900999", "TestBrand", "15555215554", 6, Locale.US); <START> fail(); <END> } catch (IOException ioe) { } }</code><technical_language>leave a message test fail if error is caught</technical_language>

Target:
public void testVerifyHttpError() throws Exception { wrapper.setHttpClient(this.stubHttpClient(500, "<?xml version='1.0' encoding='UTF-8' ?>\n" + " <verify_response>\n" + " <request_id>not-really-a-request-id</request_id>\n" + " <status>0</status>\n" + " <error_text>error</error_text>\n" + " </verify_response>")); try { client.verify( "447700900999", "TestBrand", "15555215554", 6, Locale.US); fail("An IOException should be thrown if an HTTP 500 response is received."); } catch (IOException ioe) { } }
Source:
<code>protected Date calculateInvoiceDueDate(ContractsGrantsInvoiceDocument document) { Calendar calendar = dateTimeService.getCurrentCalendar(); Optional<Integer> customerNetTerms = getCustomerNetTerms(document); int netTermsInDays; if (customerNetTerms.isPresent()) { netTermsInDays = customerNetTerms.get(); } else { String defaultNetTerms = parameterService.getParameterValueAsString( ArConstants.AR_NAMESPACE_CODE, ArConstants.CUSTOMER_COMPONENT, CuArParameterKeyConstants.CG_INVOICE_TERMS_DUE_DATE); try { netTermsInDays = Integer.parseInt(defaultNetTerms); } catch (NumberFormatException e) { LOG.error("calculateInvoiceDueDate, Default net terms parameter is malformed; will use zero as the default instead", e); <START> netTermsInDays = 0; <END> } } calendar.add(Calendar.DATE, netTermsInDays); return new Date(calendar.getTimeInMillis()); }</code><technical_language>a good idea check functionals happen if parameter is improperly formatted</technical_language>

Target:
protected Date calculateInvoiceDueDate(ContractsGrantsInvoiceDocument document) { Calendar calendar = dateTimeService.getCurrentCalendar(); Optional<Integer> customerNetTerms = getCustomerNetTerms(document); int netTermsInDays; if (customerNetTerms.isPresent()) { netTermsInDays = customerNetTerms.get(); } else { String defaultNetTerms = parameterService.getParameterValueAsString( ArConstants.AR_NAMESPACE_CODE, ArConstants.CUSTOMER_COMPONENT, CuArParameterKeyConstants.CG_INVOICE_TERMS_DUE_DATE); if (StringUtils.isBlank(defaultNetTerms)) { throw new RuntimeException("Could not find a net terms value for parameter " + CuArParameterKeyConstants.CG_INVOICE_TERMS_DUE_DATE); } try { netTermsInDays = Integer.parseInt(defaultNetTerms); } catch (NumberFormatException e) { LOG.error("calculateInvoiceDueDate, Net terms parameter value is malformed", e); throw new RuntimeException("Net terms value is malformed for parameter " + CuArParameterKeyConstants.CG_INVOICE_TERMS_DUE_DATE); } } calendar.add(Calendar.DATE, netTermsInDays); return new Date(calendar.getTimeInMillis()); }
Source:
<code>public void onCompletion(RecordMetadata md, Exception e) { if ( e != null ) { if ( e instanceof RecordTooLargeException ) { LOGGER.error("RecordTooLargeException @ " + position + " -- " + key); LOGGER.error(e.getLocalizedMessage()); LOGGER.error("Considering raising max.request.size broker-side."); if ( isTXCommit ) <START> inflightMessages.completeMessage(position); <END> } else { throw new RuntimeException(e); } } else { try { if ( LOGGER.isDebugEnabled()) { LOGGER.debug("-> key:" + key + ", partition:" +md.partition() + ", offset:" + md.offset()); LOGGER.debug(" " + this.json); LOGGER.debug(" " + position); LOGGER.debug(""); } if ( isTXCommit ) { BinlogPosition newPosition = inflightMessages.completeMessage(position); if ( newPosition != null ) context.setPosition(newPosition); } } catch (SQLException e1) { e1.printStackTrace(); } } }</code><technical_language>need set new position in context? (similar is done below)</technical_language>

Target:
public void onCompletion(RecordMetadata md, Exception e) { if ( e != null ) { if ( e instanceof RecordTooLargeException ) { LOGGER.error("RecordTooLargeException @ " + position + " -- " + key); LOGGER.error(e.getLocalizedMessage()); LOGGER.error("Considering raising max.request.size broker-side."); markCompleted(); } else { throw new RuntimeException(e); } } else { if ( LOGGER.isDebugEnabled()) { LOGGER.debug("-> key:" + key + ", partition:" +md.partition() + ", offset:" + md.offset()); LOGGER.debug(" " + this.json); LOGGER.debug(" " + position); LOGGER.debug(""); } markCompleted(); } }
Source:
<code>public List<KeyValue> buildBatchFileLookupDirectories() { LOG.debug("Starting BatchFileDirectoryServiceImpl.buildStagingAndReportsDirectories()."); List<KeyValue> directoryKeyValueList = buildDirectoryKeyValuesList(BatchFileUtils.retrieveBatchFileLookupRootDirectories()); <START> LOG.debug("Finished BatchFileDirectoryServiceImpl.buildStagingAndReportsDirectories()."); <END> return directoryKeyValueList; }</code><technical_language>Another area strings name method is another name</technical_language>

Target:
public List<KeyValue> buildBatchFileLookupDirectories() { LOG.debug("Starting BatchFileDirectoryServiceImpl.buildBatchFileLookupDirectories()."); List<KeyValue> directoryKeyValueList = buildDirectoryKeyValuesList(BatchFileUtils.retrieveBatchFileLookupRootDirectories()); LOG.debug("Finished BatchFileDirectoryServiceImpl.buildBatchFileLookupDirectories()."); return directoryKeyValueList; }
Source:
<code>public StreamProperties visitExchange(ExchangeNode node, List<StreamProperties> inputProperties) { if (node.getScope() == REMOTE) { if (node.getOrderingScheme().isPresent()) { return StreamProperties.ordered(); } return StreamProperties.fixedStreams(); } switch (node.getType()) { case GATHER: if (node.getOrderingScheme().isPresent()) { return StreamProperties.ordered(); <START> } <END> return StreamProperties.singleStream(); case REPARTITION: if (node.getPartitioningScheme().getPartitioning().getHandle().equals(FIXED_ARBITRARY_DISTRIBUTION)) { return new StreamProperties(FIXED, Optional.empty(), false); } return new StreamProperties( FIXED, Optional.of(node.getPartitioningScheme().getPartitioning().getArguments().stream() .map(ArgumentBinding::getColumn) .collect(toImmutableList())), false); case REPLICATE: return new StreamProperties(MULTIPLE, Optional.empty(), false); } throw new UnsupportedOperationException("not yet implemented"); }</code><technical_language>This check is repeated twice: (1) for *ALL* remote exchanges (2) for local-gather exchanges. This creates incorrect impression this logic applies differently remote local exchanges. (The problem exists in PropertyDerivations appears if logic applies *ALL* local exchange *GATHER* remote exchanges.) I clearer move this check beginning of this method apply *ALL* exchanges node.getOrderingScheme().isPresent() (which a subset of *GATHER* exchange, this code need *know* that, it?). @Override public StreamProperties visitExchange(ExchangeNode node, List<StreamProperties> inputProperties) { if (node.getOrderingScheme().isPresent()) { return StreamProperties.ordered(); } if (node.getScope() == REMOTE) { // TODO: correctly determine if stream is parallelised // based session properties return StreamProperties.fixedStreams(); } switch (node.getType()) { case GATHER: return StreamProperties.singleStream(); case REPARTITION:</technical_language>

Target:
public StreamProperties visitExchange(ExchangeNode node, List<StreamProperties> inputProperties) { if (node.getOrderingScheme().isPresent()) { return StreamProperties.ordered(); } if (node.getScope() == REMOTE) { return StreamProperties.fixedStreams(); } switch (node.getType()) { case GATHER: return StreamProperties.singleStream(); case REPARTITION: if (node.getPartitioningScheme().getPartitioning().getHandle().equals(FIXED_ARBITRARY_DISTRIBUTION)) { return new StreamProperties(FIXED, Optional.empty(), false); } return new StreamProperties( FIXED, Optional.of(node.getPartitioningScheme().getPartitioning().getArguments().stream() .map(ArgumentBinding::getColumn) .collect(toImmutableList())), false); case REPLICATE: return new StreamProperties(MULTIPLE, Optional.empty(), false); } throw new UnsupportedOperationException("not yet implemented"); }
Source:
<code>public void testCopyVersionMismatch() throws Throwable { ChangeTracker tracker = newTracker( ChangeDetectionPolicy.Mode.Server, ChangeDetectionPolicy.Source.ETag, true, objectAttributes("etag", "versionId")); AmazonServiceException awsException = new AmazonServiceException("aws exception"); <START> awsException.setStatusCode(412); <END> expectChangeException(tracker, awsException, "copy", RemoteFileChangedException.PRECONDITIONS_NOT_MET); tracker.processException(new RuntimeException(), "copy"); }</code><technical_language>Please do magic number - actually, http error codes for this a constant</technical_language>

Target:
public void testCopyVersionMismatch() throws Throwable { ChangeTracker tracker = newTracker( ChangeDetectionPolicy.Mode.Server, ChangeDetectionPolicy.Source.ETag, true, objectAttributes("etag", "versionId")); AmazonServiceException awsException = new AmazonServiceException("aws exception"); awsException.setStatusCode(HttpStatus.SC_PRECONDITION_FAILED); expectChangeException(tracker, awsException, "copy", RemoteFileChangedException.PRECONDITIONS_FAILED); tracker.processException(new RuntimeException(), "copy"); }
Source:
<code>void testDelta(final String[] barcodeRead, final String[] barcodeQuality, final int expectedMismatches, final int expectedSecondMismatches) { Map<String, BarcodeMatch> barcodeMatches = new HashMap<>(); List<String[]> barcodes = Arrays.asList( new String[]{"CTGTGG", "GGCTAG"}, new String[]{"AGGTCG", "AATTGT"}, new String[]{"ACCAAC", "GTATTG"} ); Map<String, ExtractIlluminaBarcodes.BarcodeMetric> barcodeMetrics = barcodes.stream() .collect(Collectors.toMap( s -> s[0] + s[1], <START> s -> new ExtractIlluminaBarcodes.BarcodeMetric(s[0] + s[1], "dummy", "more_dummy", s))); <END> byte[][] reads = new byte[][]{ barcodeRead[0].getBytes(), barcodeRead[1].getBytes() }; byte[][] qualities = new byte[][]{ barcodeQuality[0].getBytes(), barcodeQuality[1].getBytes() }; BarcodeMatch match = ExtractIlluminaBarcodes.PerTileBarcodeExtractor.findBestBarcode(reads, qualities, barcodeMetrics, 2, 2, 2, 20, barcodeMatches, DistanceMetric.HAMMING); Assert.assertFalse(barcodeMatches.isEmpty()); final BarcodeMatch barcodeMatch = barcodeMatches.get(String.join("-",barcodeRead[0], barcodeRead[1])); Assert.assertNotNull(barcodeMatch); Assert.assertEquals(barcodeMatch.mismatches,expectedMismatches); Assert.assertEquals(barcodeMatch.mismatchesToSecondBest,expectedSecondMismatches); }</code><technical_language>I this new ExtractIlluminaBarcodes.BarcodeMetric("dummy", "more_dummy", s[0] + s[1], s). change behavior of test, is more in line parameters of constructor (first parameter is "barcodeName", parameter is "barcodeDisplay", is BarcodeMetric.BARCODE is set from)</technical_language>

Target:
void testDelta(final String[] barcodeRead, final String[] barcodeQuality, final int expectedMismatches, final int expectedSecondMismatches) { final List<String[]> barcodes = Arrays.asList( new String[]{"CTGTGG", "GGCTAG"}, new String[]{"AGGTCG", "AATTGT"}, new String[]{"ACCAAC", "GTATTG"} ); final Map<String, ExtractIlluminaBarcodes.BarcodeMetric> barcodeMetrics = barcodes.stream() .collect(Collectors.toMap( s -> s[0] + s[1], s -> new ExtractIlluminaBarcodes.BarcodeMetric("dummy_name","dummy_library", s[0] + s[1], s))); final byte[][] reads = new byte[][]{barcodeRead[0].getBytes(), barcodeRead[1].getBytes()}; final byte[][] qualities = new byte[][]{barcodeQuality[0].getBytes(), barcodeQuality[1].getBytes()}; final BarcodeMatch match = ExtractIlluminaBarcodes.PerTileBarcodeExtractor.calculateBarcodeMatch(reads, qualities, barcodeMetrics, 2, 2, 2, 20, DistanceMetric.HAMMING); Assert.assertEquals(match.mismatches,expectedMismatches); Assert.assertEquals(match.mismatchesToSecondBest,expectedSecondMismatches); }
Source:
<code>public InputStream lookupFile(String filename, ClassLoader cl) { InputStream is = filename == null || filename.length() == 0 ? null : getAsInputStreamFromClassLoader(filename, cl); if (is == null) { if (log.isDebugEnabled()) log.debugf("Unable to find file %s in classpath; searching for this file on the filesystem instead.", filename); try { is = new FileInputStream(filename); } <START> catch (FileNotFoundException e) { <END> return null; } } return is; }</code><technical_language>reuse lookupFileStrict() handle exception</technical_language>

Target:
public InputStream lookupFile(String filename, ClassLoader cl) { try { return lookupFileStrict( filename, cl ); } catch (FileNotFoundException e) { return null; } }
Source:
<code>public static <T> List<T> readLocalAvroDataStore(String outputDirPath) throws IOException { Path outputPath = new Path(new File(outputDirPath).getAbsolutePath()); FileSystem fs = createLocalFileSystem(); List<T> people = DataStore.read(new FileSystemPath(fs, outputPath)); <START> return people; <END> }</code><technical_language>dataStore variable name instead of people</technical_language>

Target:
public static <T> List<T> readLocalAvroDataStore(String outputDirPath) throws IOException { Path outputPath = new Path(new File(outputDirPath).getAbsolutePath()); FileSystem fs = createLocalFileSystem(); List<T> records = DataStore.read(new FileSystemPath(fs, outputPath)); return records; }
Source:
<code>public void testUploadFindingsNegativeCase() throws Exception { String token = "db975c97-98b1-4988-8d6a-9c3e044dfff2"; String engagementId = ""; MockServerClient testClient = new MockServerClient("localhost", 1080); testClient.when( request() .withMethod("POST") .withHeader(HttpHeaders.AUTHORIZATION, "Token " + token) .withPath("/defectdojo/api/v2/import-scan/") ) .respond( response() .withStatusCode(400) .withHeader(HttpHeaders.CONTENT_TYPE, "application/json") ); DefectDojoUploader uploader = Mockito.mock( DefectDojoUploader.class, Mockito.CALLS_REAL_METHODS ); DefectDojoClient client = new DefectDojoClient(uploader, new URL("https://localhost/defectdojo")); client.uploadDependencyTrackFindings(token, engagementId, new NullInputStream(16)); testClient.verify( request() .withMethod("POST") .withHeader(HttpHeaders.AUTHORIZATION, "Token " + token) <START> .withPath("/defectdojo/api/v2/import-scan/"), <END> VerificationTimes.exactly(1) ); Mockito.verify(uploader, Mockito.times(1)).handleUnexpectedHttpResponse(Mockito.any(), Mockito.eq("https://localhost/defectdojo/api/v2/import-scan/"), Mockito.eq(400), Mockito.any()); testClient.clear( request() .withPath("/defectdojo/api/v2/import-scan/") ); }</code><technical_language>minor judging code style in place 3 lines indented: request() .withMethod("POST") .withHeader(HttpHeaders.AUTHORIZATION, "Token " + token) .withPath("/defectdojo/api/v2/import-scan/"),</technical_language>

Target:
public void testUploadFindingsNegativeCase() throws Exception { String token = "db975c97-98b1-4988-8d6a-9c3e044dfff2"; String engagementId = ""; testClient.when( request() .withMethod("POST") .withHeader(HttpHeaders.AUTHORIZATION, "Token " + token) .withPath("/defectdojo/api/v2/import-scan/") ) .respond( response() .withStatusCode(400) .withHeader(HttpHeaders.CONTENT_TYPE, "application/json") ); DefectDojoUploader uploader = new DefectDojoUploader(); DefectDojoClient client = new DefectDojoClient(uploader, new URL("https://localhost/defectdojo")); client.uploadDependencyTrackFindings(token, engagementId, new NullInputStream(16)); testClient.verify( request() .withMethod("POST") .withHeader(HttpHeaders.AUTHORIZATION, "Token " + token) .withPath("/defectdojo/api/v2/import-scan/"), VerificationTimes.exactly(1) ); }
Source:
<code>public boolean isShowGiverNameToResponseGiver() { <START> return showGiverNameTo.indexOf(FeedbackParticipantType.GIVER) != -1; <END> }</code><technical_language>contains()</technical_language>

Target:
public boolean isShowGiverNameToResponseGiver() { return showGiverNameTo.contains(FeedbackParticipantType.GIVER); }
Source:
<code>public SolrQuery propertyIsNull(String propertyName) { SolrQuery query = new SolrQuery(); List<String> possibleFields = resolver.getAnonymousField(propertyName); StringBuilder solrQuery = new StringBuilder(); for (String possibleField : possibleFields) { String cleanedField = possibleField.substring(0, possibleField.length()); <START> if (solrQuery.length() == 0){ <END> solrQuery.append(" (*:* -" + cleanedField + ":[* TO *]) "); } else { solrQuery.append(" OR (*:* -" + cleanedField + ":[* TO *]) "); } } query.setQuery(solrQuery.toString()); return query; }</code><technical_language>do want call .trim() cleanedField remove whitespace length() check</technical_language>

Target:
public SolrQuery propertyIsNull(String propertyName) { List<String> possibleFields = resolver.getAnonymousField(propertyName); if(possibleFields.isEmpty()){ throw new UnsupportedOperationException("Anonymous Field Property does not exist. " + propertyName); } List<String> solrExpressions = new ArrayList<>(); for (String possibleField : possibleFields) { solrExpressions.add(" (*:* -" + possibleField + ":[* TO *]) "); } String fullExpression = StringUtils.join(solrExpressions, " "); return new SolrQuery(fullExpression); }
Source:
<code><START> public void deleteNodeTestOK() throws NodeExecutionException, CanNotCallChefException, EntityNotFoundException, ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException { <END> when(chefNodeDao.loadNode("testOk", "token")).thenReturn(new ChefNode()); List<ProductInstance> productInstances = new ArrayList<ProductInstance>(); productInstances.add(new ProductInstance()); when(productInstanceDao.findByHostname(anyString())).thenReturn(productInstances); when(httpsClient.doHttpsDelete(Mockito.anyString(), Mockito.anyString(), (Map<String,String>)Mockito.anyObject())).thenReturn(200); when(propertiesProvider.getProperty(anyString())).thenReturn("URL"); nodeManager.nodeDelete("test", "testOk", "token"); verify(httpsClient,times(1)).doHttpsDelete(Mockito.anyString(), Mockito.anyString(), (Map<String,String>)Mockito.anyObject()); }</code><technical_language>gt 120</technical_language>

Target:
public void deleteNodeTestOK() throws NodeExecutionException, CanNotCallChefException, EntityNotFoundException, ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException { when(chefNodeDao.loadNode("testOk", "token")).thenReturn(new ChefNode()); List<ProductInstance> productInstances = new ArrayList<ProductInstance>(); productInstances.add(new ProductInstance()); when(productInstanceDao.findByHostname(anyString())).thenReturn(productInstances); when( httpsClient.doHttps(Mockito.anyString(),Mockito.anyString(), Mockito.anyString(), (Map<String, String>) Mockito.anyObject())).thenReturn(200); when(propertiesProvider.getProperty(anyString())).thenReturn("URL"); nodeManager.nodeDelete("test", "testOk", "token"); verify(httpsClient, times(1)).doHttps(Mockito.anyString(),Mockito.anyString(), Mockito.anyString(), (Map<String, String>) Mockito.anyObject()); }
Source:
<code>public Set<String> getTrashRemovedResources() { if (this._trashRemovedResources == null) { try { this.loadTrashResources(); } catch (Exception e) { logger.error("Error loading trashed resources " + this.getVersionId(), e); <START> throw new RuntimeException("Errore in recupero id risorse rimosse dal cestino (non più ripristinabili) per la versione contenuto corrente " + getVersionId(), e); <END> } } return this._trashRemovedResources; }</code><technical_language>Translate this RuntimeException message in English please</technical_language>

Target:
public Set<String> getTrashRemovedResources() { if (this._trashRemovedResources == null) { try { this.loadTrashResources(); } catch (Exception e) { logger.error("Error loading trashed resources for content with version " + this.getVersionId(), e); throw new RuntimeException("Error loading trashed resources for content with version " + getVersionId(), e); } } return this._trashRemovedResources; }
Source:
<code>public QueryRunner<Result<TopNResultValue>> preMergeQueryDecoration(final QueryRunner<Result<TopNResultValue>> runner) { return intervalChunkingQueryRunnerDecorator.decorate( new QueryRunner<Result<TopNResultValue>>() { @Override public Sequence<Result<TopNResultValue>> run( Query<Result<TopNResultValue>> query, Map<String, Object> responseContext ) { <START> if (!(query instanceof TopNQuery)) { <END> return runner.run(query, responseContext); } else { final TopNQuery topNQuery = (TopNQuery) query; if (TopNQueryEngine.useOptimized(topNQuery)) { final DimensionSpec dimensionSpec = topNQuery.getDimensionSpec(); return runner.run( new TopNQuery( topNQuery.getDataSource(), new DefaultDimensionSpec(dimensionSpec.getDimension(), dimensionSpec.getOutputName()), topNQuery.getTopNMetricSpec(), topNQuery.getThreshold(), topNQuery.getQuerySegmentSpec(), topNQuery.getDimensionsFilter(), topNQuery.getGranularity(), topNQuery.getAggregatorSpecs(), topNQuery.getPostAggregatorSpecs(), topNQuery.getContext() ) , responseContext ); } else { return runner.run(query, responseContext); } } } } , this ); }</code><technical_language>is for a TopNQuery? I imagine a bug if isn't</technical_language>

Target:
public QueryRunner<Result<TopNResultValue>> preMergeQueryDecoration(final QueryRunner<Result<TopNResultValue>> runner) { return intervalChunkingQueryRunnerDecorator.decorate( new QueryRunner<Result<TopNResultValue>>() { @Override public Sequence<Result<TopNResultValue>> run( Query<Result<TopNResultValue>> query, Map<String, Object> responseContext ) { if (!(query instanceof TopNQuery)) { return runner.run(query, responseContext); } else { final TopNQuery topNQuery = (TopNQuery) query; if (TopNQueryEngine.canApplyExtractionInPost(topNQuery)) { final DimensionSpec dimensionSpec = topNQuery.getDimensionSpec(); return runner.run( topNQuery.withDimensionSpec( new DefaultDimensionSpec( dimensionSpec.getDimension(), dimensionSpec.getOutputName() ) ), responseContext ); } else { return runner.run(query, responseContext); } } } } , this ); }
Source:
<code>private RemoteConfig selectDefaultRemoteConfig() { for (final RemoteConfig rc : configuredRemotes) <START> if (getTextForRemoteConfig(rc) == Constants.DEFAULT_REMOTE_NAME) <END> return rc; return configuredRemotes.get(0); }</code><technical_language>equals()</technical_language>

Target:
private RemoteConfig selectDefaultRemoteConfig() { for (final RemoteConfig rc : configuredRemotes) if (Constants.DEFAULT_REMOTE_NAME.equals(getTextForRemoteConfig(rc))) return rc; return configuredRemotes.get(0); }
Source:
<code>private Object invokeMethod(Object interceptor, Method stepMethod, Object... params) { try { Object returnObject = new Mirror().on(interceptor).invoke().method(stepMethod).withArgs(params); return returnObject; } catch (MirrorException e) { if(e.getCause() != null && e.getCause() instanceof ControllerInvocationException) { throw (ControllerInvocationException) e.getCause(); } <START> throw new InterceptionException(e.getCause()); <END> } }</code><technical_language>I meant this throw new InterceptionException(e.getCause()); throw new ControllerInvocationException(e.getCause());</technical_language>

Target:
private Object invokeMethod(Object interceptor, Method stepMethod, Object... params) { try { Object returnObject = new Mirror().on(interceptor).invoke().method(stepMethod).withArgs(params); return returnObject; } catch (MirrorException e) { Throwables.propagateIfInstanceOf(e.getCause(), ControllerInvocationException.class); throw new InterceptionException(e.getCause()); } }