auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Map<Integer, List<Name>> getNamesByGidsAndNTypeIdsInMap(final List<Integer> gids, final List<Integer> ntypeIds) { final Map<Integer, List<Name>> map = new HashMap<Integer, List<Name>>(); if (gids == null || gids.isEmpty()) { return map; } try { final Criteria criteria = this.getSession().createCriteria(Name.class); criteria.add(Restrictions.in("germplasmId", gids)); criteria.add(Restrictions.in("typeId", ntypeIds)); final List<Name> list = criteria.list(); if (list == null) { return map; } for (final Name name : list) { List<Name> names = map.get(name.getGermplasmId()); if (names == null) { <START> names = new ArrayList<Name>(); <END> map.put(name.getGermplasmId(), names); } names.add(name); } } catch (final HibernateException e) { this.logAndThrowException("Error with getNamesByGidsInMap(gids=" + gids + ") query from Name " + e.getMessage(), e); } return map; }</code><technical_language>prevent adding of duplicates a Collection is a Set. I this code prevent addition of duplicate names. Please review - I misunderstood issue. If I wrong place for actual fix this issue please know</technical_language>

Target:
public Map<Integer, List<Name>> getNamesByGidsAndNTypeIdsInMap(final List<Integer> gids, final List<Integer> ntypeIds) { final Map<Integer, List<Name>> map = new HashMap<Integer, List<Name>>(); if (gids == null || gids.isEmpty()) { return map; } try { final Criteria criteria = this.getSession().createCriteria(Name.class); criteria.add(Restrictions.in("germplasmId", gids)); criteria.add(Restrictions.in("typeId", ntypeIds)); final List<Name> list = criteria.list(); if (list == null) { return map; } for (final Name name : list) { List<Name> names = map.get(name.getGermplasmId()); if (names == null) { names = new ArrayList<Name>(); map.put(name.getGermplasmId(), names); } names.add(name); } } catch (final HibernateException e) { String message = "Error with getNamesByGidsInMap(gids=" + gids + ") query from Name " + e.getMessage(); NameDAO.LOG.error(message); throw new MiddlewareQueryException(message, e); } return map; }
Source:
<code>public void testUnhandledExceptionNotStoredOnPreviousExceptionStored() { assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); exception = new RuntimeException("Error 1"); CrashReporter.storeUnhandledException(exception); <START> assertTrue(!sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); <END> String error1Data = sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, ""); exception = new RuntimeException("Error 2"); CrashReporter.storeUnhandledException(exception); assertTrue(!sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").equals(error1Data)); }</code><technical_language>assertFalse(...);</technical_language>

Target:
public void testUnhandledExceptionNotStoredOnPreviousExceptionStored() { assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); exception = new RuntimeException("Error 1"); CrashReporter.storeUnhandledException(exception); assertFalse(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); String error1Data = sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, ""); exception = new RuntimeException("Error 2"); CrashReporter.storeUnhandledException(exception); assertFalse(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").equals(error1Data)); }
Source:
<code><START> public static FeedRangeInternal fromJsonString(String json) { <END> FeedRangeInternal parsedRange; try { parsedRange = FeedRangeInternal.tryParse(json); } catch (IOException e) { throw new IllegalArgumentException( String.format("Unable to parse JSON %s", json), e); } if (parsedRange == null) { throw new IllegalArgumentException( String.format( "The provided string '%s' does not represent any known format.", json)); } return parsedRange; }</code><technical_language>optimization; public methods in parent class (fromJsonString toJsonString). fromJsonString is instantiate, cache json return in toJsonString</technical_language>

Target:
public static FeedRangeInternal fromJsonString(String json) { FeedRangeInternal parsedRange = FeedRangeInternal.tryParse(json); if (parsedRange == null) { throw new IllegalArgumentException( String.format( "The provided string '%s' does not represent any known format.", json)); } return parsedRange; }
Source:
<code><START> private RowFilter createSingleRowFilter(byte[] first, byte[] second) throws IOException { <END> ByteArrayOutputStream baos = new ByteArrayOutputStream(first.length * 2); QuoteMetaOutputStream quotingStream = new QuoteMetaOutputStream(baos); for (int i = 0; i < first.length; i++) { if (first[i] == 0) { quotingStream.write(second[i]); } else { baos.write(ReaderExpressionHelper.ANY_BYTE_BYTES); } } ByteString quotedValue = ByteString.copyFrom(baos.toByteArray()); return RowFilter.newBuilder().setRowKeyRegexFilter(quotedValue).build(); }</code><technical_language>static method</technical_language>

Target:
private static RowFilter createSingleRowFilter(byte[] first, byte[] second) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(first.length * 2); QuoteMetaOutputStream quotingStream = new QuoteMetaOutputStream(baos); for (int i = 0; i < first.length; i++) { if (first[i] == 0) { quotingStream.write(second[i]); } else { baos.write(ReaderExpressionHelper.ANY_BYTE_BYTES); } } ByteString quotedValue = ByteString.copyFrom(baos.toByteArray()); return RowFilter.newBuilder().setRowKeyRegexFilter(quotedValue).build(); }
Source:
<code><START> public void buildNonconformityTypeStatistics() { <END> SecurityContextHolder.getContext().setAuthentication(adminUser); List<NonconformityTypeStatisticsDTO> dtos = statisticsDAO.getAllNonconformitiesByCriterion(null); assertNotNull(dtos); assertEquals(6, dtos.size()); for(NonconformityTypeStatisticsDTO dto : dtos){ nonconformStatDAO.create(dto); } List<NonconformityTypeStatisticsDTO> created = nonconformStatDAO.getAllNonconformityStatistics(null); assertNotNull(created); assertEquals(6, created.size()); }</code><technical_language>This testing in chartdata app, right? DAO methods? If so, in a test file</technical_language>

Target:
public void buildNonconformityTypeStatistics() { NonconformityTypeChartCalculator calc = new NonconformityTypeChartCalculator(statisticsDAO, nonconformStatDAO, txnManager); List<NonconformityTypeStatisticsDTO> dtos = calc.getCounts(); assertNotNull(dtos); assertEquals(1, dtos.size()); }
Source:
<code>public int hashCode() { int result1 = this.result.hashCode(); <START> long temp = Double.doubleToLongBits(this.experience); <END> result1 = 31 * result1 + (int) (temp ^ (temp >>> 32)); return result1; }</code><technical_language>Double.hashCode(experience)</technical_language>

Target:
public int hashCode() { return Objects.hash(this.result, this.experience); }
Source:
<code>protected String getExpiryKey(Object event) { if (getterExpiry == null) { Class<?> fqcn = event.getClass(); <START> Getter<Object, Object> getterObj = PojoUtils.createGetter(fqcn, expiryExpression, Object.class); <END> getterExpiry = getterObj; } return getterExpiry.get(event).toString(); }</code><technical_language>create getter start processing</technical_language>

Target:
protected String getExpiryKey(Object event) { return getterExpiry.get(event).toString(); }
Source:
<code>public void setMigrationMode(MigrationSupport value) { <START> for (Object migrationModeEntityModel : getMigrationMode().getItems()) { <END> if (((EntityModel)migrationModeEntityModel).getEntity() == value) { getMigrationMode().setSelectedItem(migrationModeEntityModel); break; } } }</code><technical_language>needed Enum..</technical_language>

Target:
public void setMigrationMode(MigrationSupport value) { getMigrationMode().setSelectedItem(value); }
Source:
<code>void setSucceeded() { <START> this.succeeded = true; <END> this.done = true; }</code><technical_language>minor: this required anywhere</technical_language>

Target:
void setSucceeded() { succeeded = true; done = true; }
Source:
<code>protected String getTaskUsageName() { <START> return "rt_upload"; <END> }</code><technical_language>I suggest a naming conversion easier figure out tasks used. For example, for *ArtifactoryGenericDeployTask* *generic_deploy*</technical_language>

Target:
protected String getTaskUsageName() { return "generic_deploy"; }
Source:
<code><START> protected final void sessionEstablished() throws HandshakeException { <END> amendPeerPrincipal(); if (!sessionEstablished) { sessionEstablished = true; for (SessionListener sessionListener : sessionListeners) { sessionListener.sessionEstablished(this, this.getSession()); } } }</code><technical_language>I kown if amendPeerPrincipal shoud in out if block :thinking:</technical_language>

Target:
protected final void sessionEstablished() throws HandshakeException { if (!sessionEstablished) { amendPeerPrincipal(); sessionEstablished = true; for (SessionListener sessionListener : sessionListeners) { sessionListener.sessionEstablished(this, this.getSession()); } } }
Source:
<code>public String getFunctionName() { <START> return "jiraFindIssuesAtCommitLogs"; <END> }</code><technical_language>jiraFindInChangeSets? Juts a bit shorter</technical_language>

Target:
public String getFunctionName() { return "jiraFindInChangeSets"; }
Source:
<code>public void sortingShouldWorkForEasyStrings() { <START> assertSortedLike(new String(""), new String("")); <END> assertSortedLike("", "a"); assertSortedLike("a", "asdf"); assertSortedLike("aaa", "bbb"); assertSortedLike("1", "2"); }</code><technical_language>this</technical_language>

Target:
public void sortingShouldWorkForEasyStrings() { assertSortedLike("", ""); assertSortedLike("", "a"); assertSortedLike("a", "asdf"); assertSortedLike("aaa", "bbb"); assertSortedLike("1", "2"); }
Source:
<code>public static CsvReader create(AlluxioURI uri) throws IOException { Path inputPath = new Path(uri.getScheme(), uri.getAuthority().toString(), uri.getPath()); Configuration conf = ReadWriterUtils.readNoCacheConf(); FileSystem fs = inputPath.getFileSystem(conf); <START> return new CsvReader(fs, inputPath); <END> }</code><technical_language>do new CsvReader(inputPath) do conf/fs creation in constructor</technical_language>

Target:
public static CsvReader create(AlluxioURI uri) throws IOException { return new CsvReader(new Path(uri.getScheme(), uri.getAuthority().toString(), uri.getPath())); }
Source:
<code>public void initSelectedMacPool() { Collection<MacPool> allMacPools = getMacPoolListModel().getItems(); StoragePool dc = getEntity(); if (allMacPools != null && dc != null) { Guid macPoolId = dc.getMacPoolId(); <START> if (macPoolId != null) { <END> for (MacPool macPool : allMacPools) { if (macPoolId.equals(macPool.getId())) { getMacPoolListModel().setSelectedItem(macPool); break; } } } } }</code><technical_language>1. if is null? choose default pool? 2. part of previous patch</technical_language>

Target:
public void initSelectedMacPool() { Collection<MacPool> allMacPools = getMacPoolListModel().getItems(); StoragePool dc = getEntity(); if (allMacPools != null && dc != null) { Guid macPoolId = dc.getMacPoolId(); for (MacPool macPool : allMacPools) { if (macPool.getId().equals(macPoolId)) { getMacPoolListModel().setSelectedItem(macPool); break; } } } }
Source:
<code>public void canNotMatchBinaryBody() { final byte[] body = new byte[]{0}; final MkAnswer query = Mockito.mock(MkAnswer.class); <START> Mockito.doReturn(body).when(query).content(); <END> final byte[] mismatch = new byte[]{1}; MatcherAssert.assertThat( query, Matchers.not( MkAnswerMatchers.hasContent( Matchers.is(mismatch) ) ) ); }</code><technical_language>@westonized standard when/thenReturn syntax here</technical_language>

Target:
public void canNotMatchBinaryBody() { final MkAnswer query = Mockito.mock(MkAnswer.class); Mockito.doReturn(new byte[]{0}).when(query).content(); MatcherAssert.assertThat( query, Matchers.not( MkAnswerMatchers.hasContent( Matchers.is(new byte[]{1}) ) ) ); }
Source:
<code>public WsManAssetAdapterConfig getInstance() { <START> m_config.getReadLock().lock(); <END> try { return m_config; } finally { m_config.getReadLock().unlock(); } }</code><technical_language>I suspect this locking code is needed. of m_config change safe unconditionally return here. Delete 108 113 replace with: return m_config;</technical_language>

Target:
public WsManAssetAdapterConfig getInstance() { return m_config; }
Source:
<code>public ScoredCandidates<T> generate( T content, ResultDescription desc, EquivToTelescopeResult equivToTelescopeResult ) { EquivToTelescopeComponent generatorComponent = EquivToTelescopeComponent.create(); <START> generatorComponent.setComponentName(prependIfDeerInstance("Title Search Generator")); <END> if (Strings.isNullOrEmpty(content.getTitle())) { desc.appendText("subject has no title"); return DefaultScoredCandidates.<T>fromSource(name).build(); } Iterable<? extends T> candidates = searchForCandidates(content, desc); return titleScorer.scoreCandidates(content, candidates, desc, generatorComponent); }</code><technical_language>pass in name variable this</technical_language>

Target:
public ScoredCandidates<T> generate( T content, ResultDescription desc, EquivToTelescopeResult equivToTelescopeResult ) { EquivToTelescopeComponent generatorComponent = EquivToTelescopeComponent.create(); generatorComponent.setComponentName(name); if (Strings.isNullOrEmpty(content.getTitle())) { desc.appendText("subject has no title"); return DefaultScoredCandidates.<T>fromSource(name).build(); } Iterable<? extends T> candidates = searchForCandidates(content, desc); return titleScorer.scoreCandidates(content, candidates, desc, generatorComponent); }
Source:
<code>public void writePoint( CoordinateReferenceSystem crs, double[] coordinate ) throws RuntimeException { append( "{geometry: {type: \"Point\", coordinates: [" ); <START> for ( int i = 0; i < coordinate.length; i++ ) <END> { append( Double.toString( coordinate[i] ) ); if ( i != coordinate.length - 1 ) { append( ", " ); } } append( "], crs: {type: link, properties: {href: \"" ); append( crs.href ); append( "\", code: " ); append( Integer.toString( crs.code ) ); append( "}}}}" ); }</code><technical_language>Arrays.toString( coordinate ) array [a, b, c] need put commas careful</technical_language>

Target:
public void writePoint( CoordinateReferenceSystem crs, double[] coordinate ) throws RuntimeException { append( "{geometry: {type: \"Point\", coordinates: " ); append( Arrays.toString(coordinate) ); append( ", crs: {type: link, properties: {href: \"" ); append( crs.getHref() ); append( "\", code: " ); append( Integer.toString( crs.getCode() ) ); append( "}}}}" ); }
Source:
<code><START> public void deleteById() throws Exception { <END> Object id1 = roamingRepository.create(new NewRoamingGroup("name1", "description1", RoamingGroupType.REGIONAL)); Object id2 = roamingRepository.create(new NewRoamingGroup("name2", "description2", RoamingGroupType.REGIONAL)); roamingRepository.delete(new ID(id1)); List<RoamingGroup> got = roamingRepository.findAll(); List<RoamingGroup> want = Lists.newArrayList(new RoamingGroup(new ID(id2), "name2", "description2", RoamingGroupType.REGIONAL, Lists.<Operator>newArrayList())); assertThat(got, deepEquals(want)); }</code><technical_language>I discussed test stay in previous variant</technical_language>

Target:
public void deleteById() throws Exception { Object id = roamingRepository.create(new NewRoamingGroup("name", "description", RoamingGroupType.REGIONAL)); roamingRepository.delete(new ID(id)); List<RoamingGroup> found = roamingRepository.findAll(); assertTrue(found.isEmpty()); }
Source:
<code>public void setOp(boolean value) { <START> throw new UnsupportedOperationException("Cannot change operator status of server console"); <END> }</code><technical_language>Please fix copy/pasta</technical_language>

Target:
public void setOp(boolean value) { throw new UnsupportedOperationException("Cannot change operator status of RCon command sender"); }
Source:
<code>public void validate(DrugOrder order, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "dosingInstructions", <START> "DrugOrder.error.dosingInstructionsIsNullForDosingTypeOther"); <END> }</code><technical_language>I looked messages.properties, this odd message code. (Other?)</technical_language>

Target:
public void validate(DrugOrder order, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "dosingInstructions", "DrugOrder.error.dosingInstructionsIsNullForDosingTypeFreeText"); }
Source:
<code>public int readData(byte[] buffer, int numBytes) throws IOException { <START> int readBytes = 0; <END> if (getInputStream() != null) readBytes = getInputStream().read(buffer, 0, numBytes); return readBytes; }</code><technical_language>Check if buffer null</technical_language>

Target:
public int readData(byte[] buffer, int numBytes) throws IOException { if (buffer == null) throw new NullPointerException("Buffer cannot be null."); if (numBytes < 1) throw new IllegalArgumentException("Bytes to read cannot be less than 1."); int readBytes = 0; if (getInputStream() != null) readBytes = getInputStream().read(buffer, 0, numBytes); return readBytes; }
Source:
<code>public static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph) { return StreamSupport.stream(graph.nodes().spliterator(), false) .filter(n -> n.getContent().getDefinition() instanceof DMNDiagram) .findFirst() <START> .orElseThrow(() -> new UnsupportedOperationException("TODO")); <END> }</code><technical_language>Is this TODO</technical_language>

Target:
public static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph) { return StreamSupport.stream(graph.nodes().spliterator(), false) .filter(n -> n.getContent().getDefinition() instanceof DMNDiagram) .findFirst() .orElseThrow(() -> new IllegalStateException("DMNDiagram root not found.")); }
Source:
<code>if (migrationStatus.status() == MigrationStatus.Status.COMPLETE) { <START> File databasePath = getDatabasePath("downloads.db"); <END> if (databasePath.exists()) { SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(databasePath.getAbsolutePath(), null, 0); SqlDatabaseWrapper database = new SqlDatabaseWrapper(sqLiteDatabase); database.deleteDatabase(); } liteDownloadManagerCommands.submitAllStoredDownloads(() -> Log.d(TAG, "Migration completed, submitting all downloads")); }</code><technical_language>Extract this a constant,</technical_language>

Target:
if (migrationStatus.status() == MigrationStatus.Status.COMPLETE) { File databasePath = getDatabasePath(V1_DB_PATH); if (databasePath.exists()) { SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(databasePath.getAbsolutePath(), null, 0); SqlDatabaseWrapper database = new SqlDatabaseWrapper(sqLiteDatabase); database.deleteDatabase(); } liteDownloadManagerCommands.submitAllStoredDownloads(() -> Log.d(TAG, "Migration completed, submitting all downloads")); }
Source:
<code>private MapSqlParameterSource getDbUserParameterSource(DbUser user) { return getCustomMapSqlParameterSource() .addValue("department", user.getDepartment()) .addValue("domain", user.getDomain()) .addValue("email", user.getEmail()) .addValue("name", user.getFirstName()) .addValue("note", user.getNote()) .addValue("surname", user.getLastName()) .addValue("user_id", user.getId()) .addValue("username", user.getLoginName()) .addValue("last_admin_check_status", user.isAdmin()) .addValue("external_id", user.getExternalId()) .addValue("namespace", user.getNamespace()) .addValue("options", <START> userOptionsToString(user)); <END> }</code><technical_language>I 'SerializationFactory.getSerializer().serialize(user.getUserOptions())</technical_language>

Target:
private MapSqlParameterSource getDbUserParameterSource(DbUser user) { return getCustomMapSqlParameterSource() .addValue("department", user.getDepartment()) .addValue("domain", user.getDomain()) .addValue("email", user.getEmail()) .addValue("name", user.getFirstName()) .addValue("note", user.getNote()) .addValue("surname", user.getLastName()) .addValue("user_id", user.getId()) .addValue("username", user.getLoginName()) .addValue("last_admin_check_status", user.isAdmin()) .addValue("external_id", user.getExternalId()) .addValue("namespace", user.getNamespace()) .addValue("options", SerializationFactory.getSerializer().serialize(user.getUserOptions())); }
Source:
<code>public boolean execute(String jobName, Date jobRunDate) throws InterruptedException { boolean routed = false; List<PaymentWorksVendorUpdatesDTO> pendingACHUpdates = getPaymentWorksWebService().getPendingAchUpdatesFromPaymentWorks(); LOG.info("execute, number of ACH Updates retrieved: " + pendingACHUpdates.size()); boolean hasErrors = false; routed = getPaymentWorksAchService().processACHUpdates(pendingACHUpdates, hasErrors); <START> if (hasErrors) { <END> throw new RuntimeException("processACHUpdates, there was at least one error processing ACH Updates."); } LOG.debug("execute, were all the changes routed: " + routed); return routed; }</code><technical_language>"hasErrors" is a primitive boolean initialized false above, passed service reference, variable stay false this "if" block executed. want rework this part (along other areas expecting "hasErrors" passed reference)</technical_language>

Target:
public boolean execute(String jobName, Date jobRunDate) throws InterruptedException { boolean routed = false; List<PaymentWorksVendorUpdatesDTO> pendingACHUpdates = getPaymentWorksWebService().getPendingAchUpdatesFromPaymentWorks(); LOG.info("execute, number of ACH Updates retrieved: " + pendingACHUpdates.size()); PaymentWorksVendorUpdateResults resultsDTO = new PaymentWorksVendorUpdateResults(); routed = getPaymentWorksAchService().processACHUpdates(pendingACHUpdates, resultsDTO); if (resultsDTO.isHasErrors()) { throw new RuntimeException("processACHUpdates, there was at least one error processing ACH Updates."); } LOG.debug("execute, were all the changes routed: " + routed); return routed; }
Source:
<code>public boolean isHoliday(LocalDate dateToCheck, HolidayType holidayType, ExternalIdBundle regionOrExchangeIds) { <START> Collection<Holiday> holidays = get(holidayType, regionOrExchangeIds); <END> for (Holiday holiday : holidays) { if (holiday.getHolidayDates().contains(dateToCheck)) { return true; } } return false; }</code><technical_language>This implementation is create a new HashSet references date in calendar time isHoliday() is called. This pretty expensive isHoliday() is called times analytics. structure internal state of this class this is a simple contains()-type lookup</technical_language>

Target:
public boolean isHoliday(LocalDate dateToCheck, HolidayType holidayType, ExternalIdBundle regionOrExchangeIds) { if (isWeekend(dateToCheck)) { return true; } for (ExternalId id : regionOrExchangeIds.getExternalIds()) { if (isHoliday(dateToCheck, holidayType, id)) { return true; } } return false; }
Source:
<code>public void put(Collection<SinkRecord> records) throws CopycatException { String topic; int partition; for (SinkRecord record : records) { topic = record.topic(); partition = record.kafkaPartition(); TopicPartition topicPart = new TopicPartition(topic, partition); if (assignment.contains(topicPart)) { hdfsWriter.writeRecord(topicPart, record); } else { <START> log.warn("Seen record from not assigned TopicPartition {}", record, topicPart); <END> } } }</code><technical_language>> Saw. log this a higher level, error? This is a pretty critical error. proceed if hit this means losing data this method ignores data moves on. a serious problem underlying consumer messed in this HdfsSinkTask code</technical_language>

Target:
public void put(Collection<SinkRecord> records) throws CopycatException { try { hdfsWriter.write(records); } catch (IOException e) { throw new CopycatException(e); } }
Source:
<code><START> public static synchronized VoltDBInterface instance() { <END> if (singleton == null) { singleton = new RealVoltDB(); } return singleton; }</code><technical_language>... synchronized access VoltDB instance cool. transaction performance impact if want initialize invoking full do resource this</technical_language>

Target:
public static VoltDBInterface instance() { return singleton; }
Source:
<code>public void set(Position newPosition) throws SQLException { if ( newPosition == null ) return; lastHeartbeatRead = newPosition.getLastHeartbeatRead(); String sql = "INSERT INTO `positions` set " + "server_id = ?, " + "gtid_set = ?, " + "binlog_file = ?, " + "binlog_position = ?, " + "last_heartbeat_read = ?, " + "client_id = ? " + "ON DUPLICATE KEY UPDATE " + "last_heartbeat_read = ?, " + "gtid_set = ?, binlog_file = ?, binlog_position=?"; BinlogPosition binlogPosition = newPosition.getBinlogPosition(); try( Connection c = connectionPool.getConnection() ){ PreparedStatement s = c.prepareStatement(sql); <START> LOGGER.debug("Writing binlog position to " + c.getCatalog() + ".positions: " + newPosition + ", last lastHeartbeatRead read: " + lastHeartbeatRead); <END> s.setLong(1, serverID); s.setString(2, binlogPosition.getGtidSetStr()); s.setString(3, binlogPosition.getFile()); s.setLong(4, binlogPosition.getOffset()); s.setLong(5, lastHeartbeatRead); s.setString(6, clientID); s.setLong(7, lastHeartbeatRead); s.setString(8, binlogPosition.getGtidSetStr()); s.setString(9, binlogPosition.getFile()); s.setLong(10, binlogPosition.getOffset()); s.execute(); } }</code><technical_language>lastHeartbeatRead read -> heartbeat read a big deal..</technical_language>

Target:
public void set(Position newPosition) throws SQLException { if ( newPosition == null ) return; lastHeartbeatRead = newPosition.getLastHeartbeatRead(); String sql = "INSERT INTO `positions` set " + "server_id = ?, " + "gtid_set = ?, " + "binlog_file = ?, " + "binlog_position = ?, " + "last_heartbeat_read = ?, " + "client_id = ? " + "ON DUPLICATE KEY UPDATE " + "last_heartbeat_read = ?, " + "gtid_set = ?, binlog_file = ?, binlog_position=?"; BinlogPosition binlogPosition = newPosition.getBinlogPosition(); try( Connection c = connectionPool.getConnection() ){ PreparedStatement s = c.prepareStatement(sql); LOGGER.debug("Writing binlog position to " + c.getCatalog() + ".positions: " + newPosition + ", last heartbeat read: " + lastHeartbeatRead); s.setLong(1, serverID); s.setString(2, binlogPosition.getGtidSetStr()); s.setString(3, binlogPosition.getFile()); s.setLong(4, binlogPosition.getOffset()); s.setLong(5, lastHeartbeatRead); s.setString(6, clientID); s.setLong(7, lastHeartbeatRead); s.setString(8, binlogPosition.getGtidSetStr()); s.setString(9, binlogPosition.getFile()); s.setLong(10, binlogPosition.getOffset()); s.execute(); } }
Source:
<code>public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (!isAdded() || getPageActivity().isSearching()) { return; } MenuItem savePageMenu = menu.findItem(R.id.menu_save_page); if (savePageMenu == null) { return; } if (getTitle() != null) { <START> updateSavePageMenuItem(savePageMenu); <END> } MenuItem shareMenu = menu.findItem(R.id.menu_share_page); MenuItem otherLangMenu = menu.findItem(R.id.menu_other_languages); MenuItem findInPageMenu = menu.findItem(R.id.menu_find_in_page); MenuItem themeChooserMenu = menu.findItem(R.id.menu_themechooser); if (pageLoadStrategy.isLoading()) { savePageMenu.setEnabled(false); shareMenu.setEnabled(false); otherLangMenu.setEnabled(false); findInPageMenu.setEnabled(false); themeChooserMenu.setEnabled(false); } else { shareMenu.setEnabled(true); otherLangMenu.setVisible(model.getPage() != null && model.getPage().getPageProperties().getLanguageCount() != 0); otherLangMenu.setEnabled(true); findInPageMenu.setEnabled(true); themeChooserMenu.setEnabled(true); } }</code><technical_language>Need run this another thread. spawn (AsyncTask, etc.) another method onPrepareOptionsMenu. (Something page is loaded). fine if a bit later</technical_language>

Target:
public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (!isAdded() || getPageActivity().isSearching()) { return; } MenuItem savePageItem = menu.findItem(R.id.menu_page_save); if (savePageItem == null) { return; } if (getTitle() != null) { updateSavePageMenuItem(savePageItem); } MenuItem shareItem = menu.findItem(R.id.menu_page_share); MenuItem otherLangItem = menu.findItem(R.id.menu_page_other_languages); MenuItem findInPageItem = menu.findItem(R.id.menu_page_find_in_page); MenuItem themeChooserItem = menu.findItem(R.id.menu_page_font_and_theme); if (pageLoadStrategy.isLoading()) { savePageItem.setEnabled(false); shareItem.setEnabled(false); otherLangItem.setEnabled(false); findInPageItem.setEnabled(false); themeChooserItem.setEnabled(false); } else { shareItem.setEnabled(true); otherLangItem.setVisible(model.getPage() != null && model.getPage().getPageProperties().getLanguageCount() != 0); otherLangItem.setEnabled(true); findInPageItem.setEnabled(true); themeChooserItem.setEnabled(true); } }
Source:
<code>public void getRepo() throws IOException { final Repo repo = this.repo(); MatcherAssert.assertThat(new MkRepoCommit( repo, SHA <START> ).repo(), Matchers.equalTo(repo) <END> ); }</code><technical_language>indentation is wrong. Please run $ mvn clean install -Pqulice is wrong</technical_language>

Target:
public void getRepo() throws IOException { final Repo repo = this.repo(); MatcherAssert.assertThat( new MkRepoCommit( repo, "6dcb09b5b57875f334f61aebed695e2e4193db5e" ).repo(), Matchers.equalTo(repo) ); }
Source:
<code>static String resolveArgValueFromStrContainingArgKey(String argString, Map<String, String> args) { <START> Pattern argPattern = Pattern.compile("\\$(?:\\{(.*)\\}|(.*))"); <END> Matcher matcher = argPattern.matcher(argString); if (matcher.find()) { if (matcher.group(1) != null) { return args.get(matcher.group(1)); } else if (matcher.group(2) != null) { return args.get(matcher.group(2)); } } return null; }</code><technical_language>suggestion Pattern argPattern = Pattern.compile("^\\$(?:\\{(.*)\\}|(.*))$"); Align start end of string. match bla$ad ${foo}bar</technical_language>

Target:
static String resolveArgValueFromStrContainingArgKey(String argString, Map<String, String> args) { Pattern argPattern = Pattern.compile(ARG_PATTERN_REGEX); Matcher matcher = argPattern.matcher(argString); if (matcher.matches()) { if (matcher.group(1) != null) { return args.get(matcher.group(1)); } else if (matcher.group(2) != null) { return args.get(matcher.group(2)); } } return null; }
Source:
<code>public void visit(LwM2mResource resource) { if (resource.isMultiInstances()) { throw new CodecException("Multiple instances resource %s cannot be encoded in text format", path); } LOG.trace("Encoding resource into text", resource); ResourceModel rSpec = model.getResourceModel(path.getObjectId(), resource.getId()); Type expectedType = rSpec != null ? rSpec.type : resource.getType(); Object val = converter.convertValue(resource.getValue(), resource.getType(), expectedType, path); String strValue; switch (expectedType) { case INTEGER: case FLOAT: case STRING: strValue = String.valueOf(val); break; case BOOLEAN: strValue = ((Boolean) val) ? "1" : "0"; break; case TIME: strValue = String.valueOf(((Date) val).getTime() / 1000L); break; case OBJLNK: ObjectLink objlnk = (ObjectLink) val; strValue = String.valueOf(objlnk.getObjectId() + ":" + objlnk.getObjectInstanceId()); break; case OPAQUE: <START> byte[] binaryValue = ((byte[])val); <END> strValue = Base64.encodeBase64String(binaryValue); break; default: throw new CodecException("Cannot encode %s in text format for %s", val, path); } encoded = strValue.getBytes(StandardCharsets.UTF_8); }</code><technical_language>formatting issue : space (byte[]) val I fix this myself, If plan contribute is [an eclipse formatter file](<LINK_0> I if Visual Studio Code is able handle ? If don't, I easily fix this integrate commit,</technical_language>

Target:
public void visit(LwM2mResource resource) { if (resource.isMultiInstances()) { throw new CodecException("Multiple instances resource %s cannot be encoded in text format", path); } LOG.trace("Encoding resource into text", resource); ResourceModel rSpec = model.getResourceModel(path.getObjectId(), resource.getId()); Type expectedType = rSpec != null ? rSpec.type : resource.getType(); Object val = converter.convertValue(resource.getValue(), resource.getType(), expectedType, path); String strValue; switch (expectedType) { case INTEGER: case FLOAT: case STRING: strValue = String.valueOf(val); break; case BOOLEAN: strValue = ((Boolean) val) ? "1" : "0"; break; case TIME: strValue = String.valueOf(((Date) val).getTime() / 1000L); break; case OBJLNK: ObjectLink objlnk = (ObjectLink) val; strValue = String.valueOf(objlnk.getObjectId() + ":" + objlnk.getObjectInstanceId()); break; case OPAQUE: byte[] binaryValue = (byte[]) val; strValue = Base64.encodeBase64String(binaryValue); break; default: throw new CodecException("Cannot encode %s in text format for %s", val, path); } encoded = strValue.getBytes(StandardCharsets.UTF_8); }
Source:
<code>public boolean isUpgrade(PullRequest pullRequest) { <START> Objects.requireNonNull(pullRequest, "url cannot be null"); <END> checkIssueTrackerExists(); final String body = pullRequest.getBody(); final Matcher m = UPGRADE.matcher(body); return m.find(); }</code><technical_language>incorrect message "url null"</technical_language>

Target:
public boolean isUpgrade(PullRequest pullRequest) { Objects.requireNonNull(pullRequest, "pull request cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final Matcher m = UPGRADE.matcher(body); return m.find(); }
Source:
<code>public EntityRef createEntityWithId(long id, Iterable<Component> components) { if (!entityManager.registerId(id)) { <START> return EntityRef.NULL; <END> } for (Component c : components) { componentStore.put(id, c); } EntityRef entity = createEntityRef(id); if (entityManager.getEventSystem() != null) { entityManager.getEventSystem().send(entity, OnActivatedComponent.newInstance()); } for (Component component: components) { entityManager.notifyComponentAdded(entity, component.getClass()); } return entity; }</code><technical_language>This "silently" fails creating entity specific id. Is a chance for consumer id taken? this happen often? log a warning in this case</technical_language>

Target:
public EntityRef createEntityWithId(long id, Iterable<Component> components) { if (!entityManager.registerId(id)) { return EntityRef.NULL; } components = (components == null) ? Collections.EMPTY_LIST : components; for (Component c : components) { componentStore.put(id, c); } EntityRef entity = createEntityRef(id); EventSystem eventSystem = entityManager.getEventSystem(); if (eventSystem != null) { eventSystem.send(entity, OnActivatedComponent.newInstance()); } for (Component component : components) { entityManager.notifyComponentAdded(entity, component.getClass()); } return entity; }
Source:
<code>public static List<GACallSet> create(List<String> variantSetNames, List<List<String>> callSets) { List<GACallSet> sets = new ArrayList<>(); Iterator<String> variantSetNamesIterator = variantSetNames.iterator(); Iterator<List<String>> callSetsIterator = callSets.iterator(); while (variantSetNamesIterator.hasNext() && callSetsIterator.hasNext()) { String fileName = variantSetNamesIterator.next(); List<String> callsInFile = callSetsIterator.next(); for (String callName : callsInFile) { <START> GACallSet callset = new GACallSet(callName, callName, callName, new ArrayList<>(Arrays.asList(fileName)), <END> System.currentTimeMillis(), System.currentTimeMillis(), null); sets.add(callset); } } return sets; }</code><technical_language>Collections.singletonList(fileName) more clear new ArrayList<>(Arrays.asList(fileName))</technical_language>

Target:
public static List<GACallSet> create(List<String> variantSetNames, List<List<String>> callSets) { List<GACallSet> sets = new ArrayList<>(); Iterator<String> variantSetNamesIterator = variantSetNames.iterator(); Iterator<List<String>> callSetsIterator = callSets.iterator(); while (variantSetNamesIterator.hasNext() && callSetsIterator.hasNext()) { String fileName = variantSetNamesIterator.next(); List<String> callsInFile = callSetsIterator.next(); for (String callName : callsInFile) { GACallSet callset = new GACallSet(callName, callName, callName, Collections.singletonList(fileName), System.currentTimeMillis(), System.currentTimeMillis(), null); sets.add(callset); } } return sets; }
Source:
<code>public void testAddDilutions() { PoolPage page1 = PoolPage.getForEdit(getDriver(), getBaseUrl(), 701L); DataTable includedTable = page1.getTable(PoolTableWrapperId.INCLUDED_DILUTIONS); assertEquals(0, includedTable.countRows()); DataTable available = page1.getTable(PoolTableWrapperId.AVAILABLE_DILUTIONS); available.searchFor("LDI701"); available.checkBoxForRow(0); <START> page1.clickLinkButtonAndGetUrl("Add"); <END> PoolPage page2 = PoolPage.getForEdit(getDriver(), getBaseUrl(), 701L); DataTable includedTable2 = page2.getTable(PoolTableWrapperId.INCLUDED_DILUTIONS); assertEquals(1, includedTable2.countRows()); }</code><technical_language>This page refresh, PoolPage method add selected dilutions return a new (post-refresh) page object. for remove</technical_language>

Target:
public void testAddDilutions() { PoolPage page1 = PoolPage.getForEdit(getDriver(), getBaseUrl(), 701L); DataTable includedTable = page1.getTable(PoolTableWrapperId.INCLUDED_DILUTIONS); assertEquals(0, includedTable.countRows()); DataTable available = page1.getTable(PoolTableWrapperId.AVAILABLE_DILUTIONS); available.searchFor("LDI701"); available.checkBoxForRow(0); PoolPage page2 = page1.addSelectedDilutions(); DataTable includedTable2 = page2.getTable(PoolTableWrapperId.INCLUDED_DILUTIONS); assertEquals(1, includedTable2.countRows()); }
Source:
<code>public int compareTo(TimestampedInputSplit o) { TimestampedHiveInputSplit split = (TimestampedHiveInputSplit) o; int modTimeComp = Long.compare(this.modificationTime, split.modificationTime); if (modTimeComp != 0L) { return modTimeComp; } <START> int pathComp = this.hiveTablePartition.getStorageDescriptor().compareTo( <END> split.hiveTablePartition.getStorageDescriptor()); return pathComp != 0 ? pathComp : this.getSplitNumber() - o.getSplitNumber(); }</code><technical_language>I this compares more paths</technical_language>

Target:
public int compareTo(TimestampedInputSplit o) { TimestampedHiveInputSplit split = (TimestampedHiveInputSplit) o; int modTimeComp = Long.compare(this.modificationTime, split.modificationTime); if (modTimeComp != 0L) { return modTimeComp; } int sdComp = this.hiveTablePartition.getStorageDescriptor().compareTo( split.hiveTablePartition.getStorageDescriptor()); return sdComp != 0 ? sdComp : this.getSplitNumber() - o.getSplitNumber(); }
Source:
<code>public void init() throws SchematronInitializationException { if (transformerFactory == null) { transformerFactory = <START> XMLUtils.getInstance() <END> .getSecureXmlTransformerFactory( TransformerFactoryImpl.class.getName(), SchematronValidationService.class.getClassLoader()); } Configuration config = ((TransformerFactoryImpl) transformerFactory).getConfiguration(); config.setErrorListener(new SaxonErrorListener(schematronFileNames)); updateValidators(); }</code><technical_language>XML_UTILS = XMLUtils.getInstance() is defined statically</technical_language>

Target:
public void init() throws SchematronInitializationException { if (transformerFactory == null) { transformerFactory = XML_UTILS.getSecureXmlTransformerFactory( TransformerFactoryImpl.class.getName(), SchematronValidationService.class.getClassLoader()); } Configuration config = ((TransformerFactoryImpl) transformerFactory).getConfiguration(); config.setErrorListener(new SaxonErrorListener(schematronFileNames)); updateValidators(); }
Source:
<code>public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { try { MediaType mediaType = ContentNegotiationResolver.INSTANCE.getContentType(request, response, supportedMediaTypes); if (MediaType.APPLICATION_JSON.equals(mediaType)) { request.getRequestDispatcher(meUri).forward(request, response); } else { request.getSession().setAttribute(FormController.SPRING_SECURITY_AUTHENTICATION_FAILED_KEY, errorModelFactory.toError(request, exception)); String redirectUrl = defaultFailureUrl; <START> String next = request.getParameter("next"); <END> if (redirectUrl.contains("?")) { redirectUrl += "&next=" + URLEncoder.encode(next, "UTF-8"); } else { redirectUrl += "?next=" + URLEncoder.encode(next, "UTF-8"); } redirectStrategy.sendRedirect(request, response, redirectUrl); } } catch (UnresolvedMediaTypeException ex) { log.error("Couldn't resolve media type: {}", ex.getMessage(), ex); } finally { FailedAuthenticationRequestEvent event = createFailureEvent(request, response, exception); publisher.publish(event); } }</code><technical_language>this is important a test validates lose next param if present</technical_language>

Target:
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { try { MediaType mediaType = contentNegotiationResolver.getContentType(request, response, supportedMediaTypes); if (MediaType.APPLICATION_JSON.equals(mediaType)) { request.getRequestDispatcher(meUri).forward(request, response); } else { request.getSession().setAttribute(FormController.SPRING_SECURITY_AUTHENTICATION_FAILED_KEY, errorModelFactory.toError(request, exception)); String redirectUrl = defaultFailureUrl; String next = request.getParameter(NEXT_QUERY_PARAM); if (Strings.hasText(next)) { if (redirectUrl.contains("?")) { redirectUrl += "&" + NEXT_QUERY_PARAM + "=" + URLEncoder.encode(next, "UTF-8"); } else { redirectUrl += "?" + NEXT_QUERY_PARAM + "=" + URLEncoder.encode(next, "UTF-8"); } } redirectStrategy.sendRedirect(request, response, redirectUrl); } } catch (UnresolvedMediaTypeException ex) { log.error("Couldn't resolve media type: {}", ex.getMessage(), ex); } finally { FailedAuthenticationRequestEvent event = createFailureEvent(request, response, exception); publisher.publish(event); } }
Source:
<code>private static void connect( SocketChannel soChannel, BoltServerAddress address, int timeoutMillis ) throws IOException { Socket socket = soChannel.socket(); try { socket.connect( address.toSocketAddress(), timeoutMillis ); } catch ( SocketTimeoutException e ) { <START> throw new ConnectException( "Timeout " + timeoutMillis + "ms expired" + e.getMessage() ); <END> } }</code><technical_language>I is e argument, e.getMessage()</technical_language>

Target:
private static void connect( SocketChannel soChannel, BoltServerAddress address, int timeoutMillis ) throws IOException { Socket socket = soChannel.socket(); try { socket.connect( address.toSocketAddress(), timeoutMillis ); } catch ( SocketTimeoutException e ) { throw new ConnectException( "Timeout " + timeoutMillis + "ms expired" + e ); } }
Source:
<code>private WikiObjectComponentBuilder getAssociatedComponentBuilder(DocumentReference xClassReference) { try { String serializedXClassReference = this.defaultEntityReferenceSerializer.serialize(xClassReference); if (this.componentManager.hasComponent(WikiObjectComponentBuilder.class, serializedXClassReference)) { return this.componentManager.getInstance(WikiObjectComponentBuilder.class, serializedXClassReference); } else { serializedXClassReference = this.localEntityReferenceSerializer.serialize(xClassReference); if (this.componentManager.hasComponent(WikiObjectComponentBuilder.class, serializedXClassReference)) { return this.componentManager.getInstance( WikiObjectComponentBuilder.class, serializedXClassReference); } else { return null; } } } catch (ComponentLookupException e) { <START> this.logger.warn(String.format( <END> "Unable to find a WikiObjectComponentBuilder associated to the helper [%s]: %s", xClassReference, e.getMessage())); return null; } }</code><technical_language>If end is means component exist failed initialize is a serious issue logged error actual exception IMO</technical_language>

Target:
private WikiObjectComponentBuilder getAssociatedComponentBuilder(DocumentReference xClassReference) { try { String serializedXClassReference = this.defaultEntityReferenceSerializer.serialize(xClassReference); if (this.componentManager.hasComponent(WikiObjectComponentBuilder.class, serializedXClassReference)) { return this.componentManager.getInstance(WikiObjectComponentBuilder.class, serializedXClassReference); } else { serializedXClassReference = this.localEntityReferenceSerializer.serialize(xClassReference); if (this.componentManager.hasComponent(WikiObjectComponentBuilder.class, serializedXClassReference)) { return this.componentManager.getInstance( WikiObjectComponentBuilder.class, serializedXClassReference); } else { return null; } } } catch (ComponentLookupException e) { this.logger.error(String.format( "Unable to find a WikiObjectComponentBuilder associated to the helper [%s]: %s", xClassReference, e)); return null; } }
Source:
<code>public E createInstance() { checkConverterInitialized(); <START> I instance = internalSerializer.createInstance(); <END> try { return converter.toExternal(instance); } catch (Throwable t) { return null; } }</code><technical_language>nit: move this try-catch section well</technical_language>

Target:
public E createInstance() { checkConverterInitialized(); try { I instance = internalSerializer.createInstance(); return converter.toExternal(instance); } catch (Throwable t) { return null; } }
Source:
<code>public OkapiError(@Nullable JSONObject data) { String localmessage = StringUtils.EMPTY; assert localmessage != null; if (data == null) { state = OkapiErrors.UNSPECIFIED; message = localmessage; return; } if (data.has("error")) { OkapiErrors localstate; try { JSONObject error = data.getJSONObject("error"); if (error.has("reason_stack")) { String reason = error.getString("reason_stack"); if (StringUtils.contains(reason, "invalid_oauth_request")) { if (StringUtils.contains(reason, "invalid_timestamp")) { localstate = OkapiErrors.INVALID_TIMESTAMP; } else if (StringUtils.contains(reason, "invalid_token")) { localstate = OkapiErrors.INVALID_TOKEN; } else { localstate = OkapiErrors.UNSPECIFIED; } } else { localstate = OkapiErrors.UNSPECIFIED; } } else { <START> localstate = OkapiErrors.UNSPECIFIED; <END> } if (error.has("developer_message")) { localmessage = StringUtils.defaultString(error.getString("developer_message")); assert localmessage != null; } } catch (JSONException ex) { Log.d("OkapiError: Failed to parse JSON", ex); localstate = OkapiErrors.UNSPECIFIED; } this.state = localstate; this.message = localmessage; return; } state = OkapiErrors.NO_ERROR; message = localmessage; }</code><technical_language>Do repeat UNSPECIFIED 3 times. This is a sign done otherwise, in default initialization of variable</technical_language>

Target:
public OkapiError(@Nullable JSONObject data) { if (data == null) { state = OkapiErrors.UNSPECIFIED; message = StringUtils.EMPTY; return; } if (data.has("error")) { String localmessage = null; OkapiErrors localstate = OkapiErrors.UNSPECIFIED; try { JSONObject error = data.getJSONObject("error"); if (error.has("reason_stack")) { String reason = error.getString("reason_stack"); if (StringUtils.contains(reason, "invalid_oauth_request")) { if (StringUtils.contains(reason, "invalid_timestamp")) { localstate = OkapiErrors.INVALID_TIMESTAMP; } else if (StringUtils.contains(reason, "invalid_token")) { localstate = OkapiErrors.INVALID_TOKEN; } } } if (error.has("developer_message")) { localmessage = error.getString("developer_message"); assert localmessage != null; } } catch (JSONException ex) { Log.d("OkapiError: Failed to parse JSON", ex); localstate = OkapiErrors.UNSPECIFIED; } state = localstate; message = StringUtils.defaultString(localmessage); return; } state = OkapiErrors.NO_ERROR; message = StringUtils.EMPTY; }