auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private FetchResult fetch(Git git, String label) throws GitAPIException{ FetchCommand fetch = git.fetch(); fetch.setRemote("origin"); fetch.setTagOpt(TagOpt.FETCH_TAGS); setTimeout(fetch); try { setCredentialsProvider(fetch); FetchResult result = fetch.call(); if(result.getTrackingRefUpdates() != null && result.getTrackingRefUpdates().size() > 0) { this.logger.info("Fetched for remote " + label + " and found " + result.getTrackingRefUpdates().size() + " updates"); } return result; } catch (TransportException ex){ <START> if(errorLogOnFailingFetch){ <END> this.logger.error("Could not fetch remote for " + label + " remote: " + git .getRepository().getConfig().getString("remote", "origin", "url")); } else{ this.logger.warn("Could not fetch remote for " + label + " remote: " + git .getRepository().getConfig().getString("remote", "origin", "url")); } throw ex; } catch (Exception ex) { this.logger.warn("Could not fetch remote for " + label + " remote: " + git .getRepository().getConfig().getString("remote", "origin", "url")); return null; } }</code><technical_language>I I a branch here. This is weeds for a configuration item. If log something, pick works done</technical_language>

Target:
private FetchResult fetch(Git git, String label) throws GitAPIException{ FetchCommand fetch = git.fetch(); fetch.setRemote("origin"); fetch.setTagOpt(TagOpt.FETCH_TAGS); setTimeout(fetch); try { setCredentialsProvider(fetch); FetchResult result = fetch.call(); if(result.getTrackingRefUpdates() != null && result.getTrackingRefUpdates().size() > 0) { logger.info("Fetched for remote " + label + " and found " + result.getTrackingRefUpdates().size() + " updates"); } return result; } catch (TransportException ex){ this.logger.error("Could not fetch remote for " + label + " remote: " + git .getRepository().getConfig().getString("remote", "origin", "url")); throw ex; } catch (Exception ex) { String message = "Could not fetch remote for " + label + " remote: " + git .getRepository().getConfig().getString("remote", "origin", "url"); warn(message, ex); return null; } }
Source:
<code>public void migrate() throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(configuration.getConcurrency()); DataStore targetStore = H2MigrateConfiguration.getDataStore(configuration.getTargetStoreConfiguration()); File logDirectory = configuration.getLogDirectory(); try (LogWriter netcdfWriter = new LogWriter(new File(logDirectory, "migrated.txt")); LogWriter h2Writer = new LogWriter(new File(logDirectory, "h2.txt"))) { LinkedHashSet<String> filePaths = new LinkedHashSet<>(); final String[] coverages; if (configuration.getSourceStoreConfiguration() != null) { coverages = getFilesFromStore(filePaths); } else { coverages = getFilesFromReader(filePaths); } List<Future> futures = new ArrayList<>(); for (String path : filePaths) { futures.add( executorService.submit( () -> migrateNetcdf( path, coverages, targetStore, netcdfWriter, h2Writer))); } for (Future future : futures) { try { future.get(); } catch (Exception e) { if (configuration.isFailureIgnored()) { LOGGER.log(Level.WARNING, "Failed to migrate file ", e); } else { <START> throw new MigrationException("Failed to migrate file", e); <END> } } } updateMosaicConfiguration(coverages); } finally { executorService.shutdown(); if (targetStore != null) targetStore.dispose(); } }</code><technical_language>I add emptySpace file: ".. migrate file "</technical_language>

Target:
public void migrate() throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(configuration.getConcurrency()); DataStore targetStore = H2MigrateConfiguration.getDataStore(configuration.getTargetStoreConfiguration()); File logDirectory = configuration.getLogDirectory(); try (LogWriter netcdfWriter = new LogWriter(new File(logDirectory, "migrated.txt")); LogWriter h2Writer = new LogWriter(new File(logDirectory, "h2.txt"))) { targetStore.getTypeNames(); LinkedHashSet<String> filePaths = new LinkedHashSet<>(); final String[] coverages; if (configuration.getSourceStoreConfiguration() != null) { coverages = getFilesFromStore(filePaths); } else { coverages = getFilesFromReader(filePaths); } Map<String, Future> futures = new HashMap<>(); for (String path : filePaths) { futures.put( path, executorService.submit( () -> migrateNetcdf( path, coverages, targetStore, netcdfWriter, h2Writer))); } for (Map.Entry<String, Future> entry : futures.entrySet()) { try { entry.getValue().get(); } catch (Exception e) { if (configuration.isFailureIgnored()) { LOGGER.log(Level.WARNING, "Failed to migrate file: " + entry.getKey(), e); } else { throw new MigrationException( "Failed to migrate file: " + entry.getKey(), e); } } } updateMosaicConfiguration(coverages); LOGGER.info("Migration complete with success!"); } finally { executorService.shutdown(); if (targetStore != null) targetStore.dispose(); } }
Source:
<code>public void flush(boolean force) { if (useOptmizedPartitionedOutputOperator) { if (force) { for (int i = 0; i < partitionData.length; i++) { PartitionData target = partitionData[i]; <START> target.flush(outputBuffer); <END> } return; } } for (int partition = 0; partition < pageBuilders.length; partition++) { PageBuilder partitionPageBuilder = pageBuilders[partition]; if (!partitionPageBuilder.isEmpty() && (force || partitionPageBuilder.isFull())) { Page pagePartition = partitionPageBuilder.build(); partitionPageBuilder.reset(); List<SerializedPage> serializedPages = splitPage(pagePartition, DEFAULT_MAX_PAGE_SIZE_IN_BYTES).stream() .map(serde::serialize) .collect(toImmutableList()); outputBuffer.enqueue(lifespan, partition, serializedPages); pagesAdded.incrementAndGet(); rowsAdded.addAndGet(pagePartition.getPositionCount()); } } }</code><technical_language>inline targe: partitionData[i].flush(outputBuffer);</technical_language>

Target:
public void flush(boolean force) { for (int partition = 0; partition < pageBuilders.length; partition++) { PageBuilder partitionPageBuilder = pageBuilders[partition]; if (!partitionPageBuilder.isEmpty() && (force || partitionPageBuilder.isFull())) { Page pagePartition = partitionPageBuilder.build(); partitionPageBuilder.reset(); List<SerializedPage> serializedPages = splitPage(pagePartition, DEFAULT_MAX_PAGE_SIZE_IN_BYTES).stream() .map(serde::serialize) .collect(toImmutableList()); outputBuffer.enqueue(lifespan, partition, serializedPages); pagesAdded.incrementAndGet(); rowsAdded.addAndGet(pagePartition.getPositionCount()); } } }
Source:
<code>protected <T extends Entity> void populateSpec(EntitySpec<T> spec) { String name, templateId=null, planId=null; if (template.isPresent()) { name = template.get().getName(); templateId = template.get().getId(); } else { name = (String)attrs.getStringKey("name"); } planId = (String)attrs.getStringKey("id"); if (planId==null) planId = (String) attrs.getStringKey(BrooklynCampConstants.PLAN_ID_FLAG); <START> String impl = (String)attrs.getStringKey("impl"); <END> if (!Strings.isBlank(impl)) { try { @SuppressWarnings("unchecked") Class<? extends T> clazz = (Class<? extends T>) mgmt.getCatalog().getRootClassLoader().loadClass(impl); spec.impl(clazz); } catch (ClassNotFoundException e) { throw Exceptions.propagate(e); } } if (!Strings.isBlank(name)) spec.displayName(name); if (templateId != null) spec.configure(BrooklynCampConstants.TEMPLATE_ID, templateId); if (planId != null) spec.configure(BrooklynCampConstants.PLAN_ID, planId); List<Location> childLocations = new BrooklynYamlLocationResolver(mgmt).resolveLocations(attrs.getAllConfig(), true); if (childLocations != null) spec.locations(childLocations); decorateSpec(spec); }</code><technical_language>do need this? support implementation type detect is a concrete class construct instance proxy appropriately (taking interfaces proxy)? feels painful suggesting coming YAML supply type impl</technical_language>

Target:
protected <T extends Entity> void populateSpec(EntitySpec<T> spec) { String name, templateId=null, planId=null; if (template.isPresent()) { name = template.get().getName(); templateId = template.get().getId(); } else { name = (String)attrs.getStringKey("name"); } planId = (String)attrs.getStringKey("id"); if (planId==null) planId = (String) attrs.getStringKey(BrooklynCampConstants.PLAN_ID_FLAG); if (!Strings.isBlank(name)) spec.displayName(name); if (templateId != null) spec.configure(BrooklynCampConstants.TEMPLATE_ID, templateId); if (planId != null) spec.configure(BrooklynCampConstants.PLAN_ID, planId); List<Location> childLocations = new BrooklynYamlLocationResolver(mgmt).resolveLocations(attrs.getAllConfig(), true); if (childLocations != null) spec.locations(childLocations); decorateSpec(spec); }
Source:
<code>private JFreeChart createDebugEventGanttChart() { eventStatistics = new EventStatistics( InitializationManager.getInstance().getDebugEventManager(), selectedDebugInterval); <START> final GanttCategoryDataset dataset = eventStatistics <END> .createDebugEventGanttChartDataset(); final JFreeChart chart = ChartFactory.createGanttChart( "Debug Events During Selected Debug Interval", "Event", "Time", dataset, false, true, false); CategoryPlot plot = chart.getCategoryPlot(); ValueAxis axis = plot.getRangeAxis(); axis.setRangeWithMargins(selectedDebugInterval.getStart().getTime(), selectedDebugInterval.getEnd().getTime()); plot.setRenderer(new WatchDogGanttRenderer()); return chart; }</code><technical_language>final variable? :-)</technical_language>

Target:
private JFreeChart createDebugEventGanttChart() { eventStatistics = new EventStatistics( InitializationManager.getInstance().getDebugEventManager(), selectedDebugInterval); GanttCategoryDataset dataset = eventStatistics .createDebugEventGanttChartDataset(); JFreeChart chart = ChartFactory.createGanttChart( "Debug Events During Selected Debug Interval", "Event", "Time", dataset, false, true, false); CategoryPlot plot = chart.getCategoryPlot(); ValueAxis axis = plot.getRangeAxis(); axis.setRangeWithMargins(selectedDebugInterval.getStart().getTime(), selectedDebugInterval.getEnd().getTime()); plot.setRenderer(new WatchDogGanttRenderer()); return chart; }
Source:
<code>private ArrayList<String> getTestCasesFileNamesWithPaths(String testFileFolder) { ArrayList<String> fileNamesWithPaths = new ArrayList<>(); File folder = new File(testFileFolder); File[] listOfFiles = folder.listFiles(); if (listOfFiles != null) { for (File file : listOfFiles) { String filename = file.getName(); if (filename.endsWith(".xml") || filename.endsWith(".XML")) { <START> fileNamesWithPaths.add(testFileFolder + "/" + filename); <END> } } } return fileNamesWithPaths; }</code><technical_language>hardcoding "/" work in windows environment. File.seperator</technical_language>

Target:
private ArrayList<String> getTestCasesFileNamesWithPaths(String testFileFolder) { ArrayList<String> fileNamesWithPaths = new ArrayList<>(); File folder = new File(testFileFolder); File[] listOfFiles = folder.listFiles(); if (listOfFiles != null) { for (File file : listOfFiles) { String filename = file.getName(); if (filename.endsWith(".xml") || filename.endsWith(".XML")) { fileNamesWithPaths.add(testFileFolder + File.separator + filename); } } } return fileNamesWithPaths; }
Source:
<code>public void setup() { db = dbRule.getGraphDatabaseAPI(); if ( withIndex ) { <START> Neo4jMatchers.createIndex( db, LABEL, keys ); <END> Neo4jMatchers.createIndex( db, LABEL, keys[0] ); } }</code><technical_language><strike>Earth</strike> planet! gonna a method Neo4jMatchers! index creation</technical_language>

Target:
public void setup() { db = dbRule.getGraphDatabaseAPI(); if ( withIndex ) { try ( org.neo4j.graphdb.Transaction tx = db.beginTx() ) { db.schema().indexFor( LABEL ).on( keys[0] ).create(); IndexCreator indexCreator = db.schema().indexFor( LABEL ); for ( String key : keys ) { indexCreator = indexCreator.on( key ); } indexCreator.create(); tx.success(); } try ( org.neo4j.graphdb.Transaction tx = db.beginTx() ) { db.schema().awaitIndexesOnline( 5, TimeUnit.MINUTES ); tx.success(); } } }
Source:
<code><START> public static int nextPowerOf2(int v) { <END> A.ensure(v >= 0, "v must not be negative"); if (v == 0) return 1; v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; }</code><technical_language>Integer.highestOneBit(value) << 1 ? overflowed</technical_language>

Target:
public static int nextPowerOf2(int v) { A.ensure(v >= 0, "v must not be negative"); if (v == 0) return 1; return 1 << (32 - Integer.numberOfLeadingZeros(v - 1)); }
Source:
<code><START> public ResponseEntity<?> deleteStorage(@PathVariable("id") final String id, final NativeWebRequest request) { <END> if (!adminService.isAdmin(AuthorizationService.Operation.WRITE)) { return status(FORBIDDEN).build(); } storageService.deleteStorage(id); return status(NO_CONTENT).build(); }</code><technical_language>declare throws please</technical_language>

Target:
public ResponseEntity<?> deleteStorage(@PathVariable("id") final String id, final NativeWebRequest request) throws PluginException, DbWriteOperationsBlockedException, NoSuchStorageException, StorageIsUsedException, InternalNakadiException{ if (!adminService.isAdmin(AuthorizationService.Operation.WRITE)) { return status(FORBIDDEN).build(); } storageService.deleteStorage(id); return status(NO_CONTENT).build(); }
Source:
<code>public void writeTo(AsyncWritableChannel channel, Callback<Long> callback) { <START> throw new NotImplementedException(); <END> }</code><technical_language>nit: UnsupportedOperationException, NotImplementedException is reflection-specific</technical_language>

Target:
public void writeTo(AsyncWritableChannel channel, Callback<Long> callback) { throw new UnsupportedOperationException(); }
Source:
<code>@Override public boolean tryFinishEviction(GridDhtLocalPartition part) { ctx.database().checkpointReadLock(); try { lock.writeLock().lock(); try { if (stopping) return false; part.finishEviction(); if (part.state() != EVICTED) return false; long seq = this.updateSeq.incrementAndGet(); assert lastTopChangeVer.initialized() : lastTopChangeVer; updateLocal(part.id(), part.state(), seq, lastTopChangeVer); consistencyCheck(); grp.onPartitionEvicted(part.id()); try { grp.offheap().destroyCacheDataStore(part.dataStore()); } catch (IgniteCheckedException e) { log.error("Unable to destroy cache data store on partition eviction [id=" + part.id() + "]", e); } part.clearDeferredDeletes(); List<GridDhtLocalPartition> parts = localPartitions(); int renting = 0; for (GridDhtLocalPartition part0 : parts) { if (part0.state() == RENTING) <START> renting++; <END> } if (renting == 0) ctx.exchange().scheduleResendPartitions(); return true; } finally { lock.writeLock().unlock(); } } finally { ctx.database().checkpointReadUnlock(); } }</code><technical_language>Minor, break loop soon RENTING partition, need iteration</technical_language>

Target:
@Override public boolean tryFinishEviction(GridDhtLocalPartition part) { ctx.database().checkpointReadLock(); try { lock.writeLock().lock(); try { if (stopping) return false; part.finishEviction(); if (part.state() != EVICTED) return false; long seq = this.updateSeq.incrementAndGet(); assert lastTopChangeVer.initialized() : lastTopChangeVer; updateLocal(part.id(), part.state(), seq, lastTopChangeVer); consistencyCheck(); grp.onPartitionEvicted(part.id()); try { grp.offheap().destroyCacheDataStore(part.dataStore()); } catch (IgniteCheckedException e) { log.error("Unable to destroy cache data store on partition eviction [id=" + part.id() + "]", e); } part.clearDeferredDeletes(); List<GridDhtLocalPartition> parts = localPartitions(); boolean renting = false; for (GridDhtLocalPartition part0 : parts) { if (part0.state() == RENTING) { renting = true; break; } } if (!renting) ctx.exchange().scheduleResendPartitions(); return true; } finally { lock.writeLock().unlock(); } } finally { ctx.database().checkpointReadUnlock(); } }
Source:
<code>public Pair<Long,Float> next() { if ( hasNext() ) { <START> return Pair.of( currentIterator().next(), currentIterator().currentScore() ); <END> } else { throw new NoSuchElementException( "The iterator is exhausted" ); } }</code><technical_language>instead of Pair create specific ScoreEntity POJO primitive fields: entity/value score; understand understand represents</technical_language>

Target:
public ScoreEntry next() { if ( hasNext() ) { return new ScoreEntry( iterator.next(), iterator.currentScore() ); } else { throw new NoSuchElementException( "The iterator is exhausted" ); } }
Source:
<code>private boolean isHostHealthy(InetSocketAddress host) { try { CassandraClientPoolingContainer testingContainer = currentPools.get(host); testingContainer.runWithPooledResource(describeRing); testingContainer.runWithPooledResource(validatePartitioner); return true; } catch (Exception e) { log.warn("We tried to add back into the pool, but got an exception" + " that caused us to distrust this host further. Exception message was: : {}", SafeArg.of("host", host), <START> SafeArg.of("exceptionClass", e.getClass().getTypeName()), <END> UnsafeArg.of("exceptionMessage", e.getMessage())); return false; } }</code><technical_language>nit: getTypeName is a new one, fine e.getClass().getName() e.getClass().getCanonicalName() simpler</technical_language>

Target:
private boolean isHostHealthy(InetSocketAddress host) { try { CassandraClientPoolingContainer testingContainer = currentPools.get(host); testingContainer.runWithPooledResource(describeRing); testingContainer.runWithPooledResource(validatePartitioner); return true; } catch (Exception e) { log.warn("We tried to add back into the pool, but got an exception" + " that caused us to distrust this host further. Exception message was: : {}", SafeArg.of("host", host), SafeArg.of("exceptionClass", e.getClass().getCanonicalName()), UnsafeArg.of("exceptionMessage", e.getMessage())); return false; } }
Source:
<code>private void setAttributeOptionsForProduct(TaskAttribute taskAttribute, Product actualProduct) { taskAttribute.clearOptions(); if (taskAttribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().TARGET_MILESTONE.getKey())) { boolean found = false; String actualValue = taskAttribute.getValue(); for (SortableActiveEntry SortableActiveEntry : actualProduct.getMilestones()) { if (SortableActiveEntry.isActive()) { taskAttribute.putOption(SortableActiveEntry.getName(), SortableActiveEntry.getName()); if (!found) { <START> found = actualValue.equals(SortableActiveEntry.getName()); <END> } } } if (!found) { taskAttribute.setValue(""); } } else if (taskAttribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().VERSION.getKey())) { boolean found = false; String actualValue = taskAttribute.getValue(); for (SortableActiveEntry SortableActiveEntry : actualProduct.getVersions()) { if (SortableActiveEntry.isActive()) { taskAttribute.putOption(SortableActiveEntry.getName(), SortableActiveEntry.getName()); if (!found) { found = actualValue.equals(SortableActiveEntry.getName()); } } } if (!found) { taskAttribute.setValue(""); } } else if (taskAttribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().COMPONENT.getKey())) { boolean found = false; String actualValue = taskAttribute.getValue(); for (Component component : actualProduct.getComponents()) { if (component.isActive()) { taskAttribute.putOption(component.getName(), component.getName()); if (!found) { found = actualValue.equals(component.getName()); } } } if (!found) { taskAttribute.setValue(""); } } }</code><technical_language>break if it</technical_language>

Target:
private void setAttributeOptionsForProduct(TaskAttribute taskAttribute, Product actualProduct) { taskAttribute.clearOptions(); if (taskAttribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().TARGET_MILESTONE.getKey())) { internalSetAttributeOptions(taskAttribute, actualProduct.getMilestones()); } else if (taskAttribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().VERSION.getKey())) { internalSetAttributeOptions(taskAttribute, actualProduct.getVersions()); } else if (taskAttribute.getId().equals(BugzillaRestCreateTaskSchema.getDefault().COMPONENT.getKey())) { internalSetAttributeOptions(taskAttribute, actualProduct.getComponents()); } }
Source:
<code>private int index(Iterator<Item> iterator) throws DSpaceSolrIndexerException { try { int i = 0; SolrServer server = solrServerResolver.getServer(); while (iterator.hasNext()) { try { Item item = iterator.next(); <START> System.out.println("indexing item " + item.getID()); <END> server.add(this.index(item)); context.uncacheEntity(item); } catch (SQLException | MetadataBindException | ParseException | XMLStreamException | WritingXmlException ex) { log.error(ex.getMessage(), ex); } i++; if (i % 100 == 0) System.out.println(i + " items imported so far..."); } System.out.println("Total: " + i + " items"); server.commit(); return i; } catch (SolrServerException | IOException ex) { throw new DSpaceSolrIndexerException(ex.getMessage(), ex); } }</code><technical_language>worried this get noisy in production, if 100K items index, this message 100K times</technical_language>

Target:
private int index(Iterator<Item> iterator) throws DSpaceSolrIndexerException { try { int i = 0; SolrServer server = solrServerResolver.getServer(); while (iterator.hasNext()) { try { Item item = iterator.next(); server.add(this.index(item)); context.uncacheEntity(item); } catch (SQLException | MetadataBindException | ParseException | XMLStreamException | WritingXmlException ex) { log.error(ex.getMessage(), ex); } i++; if (i % 100 == 0) System.out.println(i + " items imported so far..."); } System.out.println("Total: " + i + " items"); server.commit(); return i; } catch (SolrServerException | IOException ex) { throw new DSpaceSolrIndexerException(ex.getMessage(), ex); } }
Source:
<code>private PrimitiveLongIterator queryIndexOrEmpty( IndexReader reader, IndexQuery[] query ) { PrimitiveLongIterator indexedNodeIds; try { indexedNodeIds = reader.query( query ); } <START> catch ( IndexNotApplicableKernelException e ) <END> { indexedNodeIds = PrimitiveLongCollections.emptyIterator(); } indexedNodeIds = LookupFilter.exactIndexMatches( propertyReader, indexedNodeIds, query ); return indexedNodeIds; }</code><technical_language>IndexNotApplicableKernelException here? report wrong instead of assuming do matches</technical_language>

Target:
private PrimitiveLongIterator queryIndexOrEmpty( IndexReader reader, IndexQuery[] query ) { PrimitiveLongIterator indexedNodeIds; try { indexedNodeIds = reader.query( query ); } catch ( IndexNotApplicableKernelException e ) { throw new RuntimeException( format( "Consistency checking error: index provider does not support exact query %s", Arrays.toString( query ) ), e ); } indexedNodeIds = LookupFilter.exactIndexMatches( propertyReader, indexedNodeIds, query ); return indexedNodeIds; }
Source:
<code>private String getMonthCharacters(DateGrain dateGrain, String label) { if (label == null) { return null; } int labelCPCount = label.codePointCount(0, label.length()); switch (dateGrain) { case DAY: case WEEK: return label.substring(labelCPCount - 4, labelCPCount - 2); case MONTH: <START> return label.substring(labelCPCount - 2, labelCPCount); <END> default: break; } return null; }</code><technical_language>need change here, is for Date type</technical_language>

Target:
private String getMonthCharacters(DateGrain dateGrain, String label) { switch (dateGrain) { case DAY: case WEEK: return label.substring(label.length() - 4, label.length() - 2); case MONTH: return label.substring(label.length() - 2); default: break; } return null; }
Source:
<code>private static ArrayList<RiakTsPB.TsColumnDescription> parseColumnDescriptions(OtpInputStream is) throws OtpErlangDecodeException { final int colNameCount = is.read_list_head(); final String[] columnNames = new String[colNameCount]; for (int colNameIdx = 0; colNameIdx < colNameCount; colNameIdx++) { final String colName = new String(is.read_binary(), StandardCharsets.UTF_8); columnNames[colNameIdx] = colName; final boolean isLastRow = colNameIdx + 1 == colNameCount; if (isLastRow) { is.read_nil(); } } final int colTypeCount = is.read_list_head(); assert (colNameCount == colTypeCount); final String[] columnTypes = new String[colTypeCount]; for (int colTypeIdx = 0; colTypeIdx < colTypeCount; colTypeIdx++) { final String colType = is.read_atom(); columnTypes[colTypeIdx] = colType; final boolean isLastRow = colTypeIdx + 1 == colNameCount; if (isLastRow) { <START> is.read_nil(); <END> } } final ArrayList<RiakTsPB.TsColumnDescription> columnDescriptions = new ArrayList<>(colNameCount); for (int colDescIdx = 0; colDescIdx < colNameCount; colDescIdx++) { final RiakTsPB.TsColumnDescription desc = RiakTsPB.TsColumnDescription.newBuilder().setName( ByteString.copyFromUtf8(columnNames[colDescIdx])).setType(RiakTsPB.TsColumnType.valueOf( columnTypes[colDescIdx].toUpperCase(Locale.US))).build(); columnDescriptions.add(desc); } return columnDescriptions; }</code><technical_language>this next statement for loop</technical_language>

Target:
private static ArrayList<RiakTsPB.TsColumnDescription> parseColumnDescriptions(OtpInputStream is) throws OtpErlangDecodeException { final int colNameCount = is.read_list_head(); final String[] columnNames = new String[colNameCount]; for (int colNameIdx = 0; colNameIdx < colNameCount; colNameIdx++) { final String colName = new String(is.read_binary(), StandardCharsets.UTF_8); columnNames[colNameIdx] = colName; } if (colNameCount > 0) { is.read_nil(); } final int colTypeCount = is.read_list_head(); assert (colNameCount == colTypeCount); final String[] columnTypes = new String[colTypeCount]; for (int colTypeIdx = 0; colTypeIdx < colTypeCount; colTypeIdx++) { final String colType = is.read_atom(); columnTypes[colTypeIdx] = colType; } if (colTypeCount > 0) { is.read_nil(); } final ArrayList<RiakTsPB.TsColumnDescription> columnDescriptions = new ArrayList<>(colNameCount); for (int colDescIdx = 0; colDescIdx < colNameCount; colDescIdx++) { final RiakTsPB.TsColumnDescription.Builder descBuilder = RiakTsPB.TsColumnDescription.newBuilder(); descBuilder.setName(ByteString.copyFromUtf8(columnNames[colDescIdx])); descBuilder.setType(RiakTsPB.TsColumnType.valueOf(columnTypes[colDescIdx].toUpperCase(Locale.US))); columnDescriptions.add(descBuilder.build()); } return columnDescriptions; }
Source:
<code>public Iterable<String> getColNames() { return Iterables.transform(fields, new Function<Field, String>() { @Override @Nullable <START> public String apply(Field arg0) <END> { return arg0.getSqlName(); } }); }</code><technical_language>@Nullable annotation implies argument null. Correct fix is @Nullable annotation do following: return arg0 != null ? arg0.getSqlName() : null;</technical_language>

Target:
public Iterable<String> getColNames() { return Iterables.transform(fields, new Function<Field, String>() { @Override @Nullable public String apply(@Nullable Field arg0) { return arg0 != null ? arg0.getSqlName() : null; } }); }
Source:
<code>public long getLength() throws IOException { if (size == null) { try { <START> size = getConnection().getContentLengthLong(); <END> } catch (IOException ex) { size = -1L; throw ex; } } return size; }</code><technical_language>log this properly too, I think. Errors in this class bubble inspected easily</technical_language>

Target:
public long getLength() throws IOException { if (size == null) { try { size = getConnection().getContentLengthLong(); } catch (IOException ex) { size = -1L; LOG.error("Exception while getting length for url connection {}",getConnection().getURL().toExternalForm(),ex); throw ex; } } return size; }
Source:
<code>protected final void runLeaf(Statement statement, Description description, RunNotifier notifier) { EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); eachNotifier.fireTestStarted(); try { runLeafIsolated(statement); <START> } catch (AssumptionViolatedException e) { <END> eachNotifier.addFailedAssumption(e); } catch (Throwable e) { eachNotifier.addFailure(e); } finally { eachNotifier.fireTestFinished(); } }</code><technical_language>I if instead of updating runLeaf() update methodBlock() return a Statement calls Thread.interrupted() end of statement chain</technical_language>

Target:
protected final void runLeaf(Statement statement, Description description, RunNotifier notifier) { EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); eachNotifier.fireTestStarted(); try { statement.evaluate(); } catch (AssumptionViolatedException e) { eachNotifier.addFailedAssumption(e); } catch (Throwable e) { eachNotifier.addFailure(e); } finally { eachNotifier.fireTestFinished(); } }
Source:
<code><START> public int appendFromDirectly(byte[] byteArray, int offset, int length) throws IOException { <END> rollOverIfRequired(length); return activeSegment.appendFromDirectly(byteArray, offset, length); }</code><technical_language>this need public right</technical_language>

Target:
int appendFromDirectly(byte[] byteArray, int offset, int length) throws IOException { rollOverIfRequired(length); return activeSegment.appendFromDirectly(byteArray, offset, length); }
Source:
<code>public Model getCREATEModel(Representation rep) { return new ModelImpl() .property("fulfillerComment", new StringProperty()) <START> .property("fulfillerStatus", new EnumProperty(null)); <END> }</code><technical_language>need enum class instead of null</technical_language>

Target:
public Model getCREATEModel(Representation rep) { return new ModelImpl() .property("fulfillerComment", new StringProperty()) .property("fulfillerStatus", new EnumProperty(Order.FulfillerStatus.class)); }
Source:
<code>public void execute(IProgressMonitor m) throws CoreException { SubMonitor progress = SubMonitor.convert(m, CoreText.ConnectProviderOperation_connecting, <START> 100 * projects.size()); <END> MultiStatus ms = new MultiStatus(Activator.getPluginId(), 0, CoreText.ConnectProviderOperation_ConnectErrors, null); for (Entry<IProject, File> entry : projects.entrySet()) { connectProject(entry, ms, progress.newChild(100)); } if (!ms.isOK()) { throw new CoreException(ms); } }</code><technical_language>* 100? simply projects.size() newChild(1) clearer</technical_language>

Target:
public void execute(IProgressMonitor m) throws CoreException { SubMonitor progress = SubMonitor.convert(m, CoreText.ConnectProviderOperation_connecting, projects.size()); MultiStatus ms = new MultiStatus(Activator.getPluginId(), 0, CoreText.ConnectProviderOperation_ConnectErrors, null); for (Entry<IProject, File> entry : projects.entrySet()) { connectProject(entry, ms, progress.newChild(1)); } if (!ms.isOK()) { throw new CoreException(ms); } }
Source:
<code>public void testSetLocationNative() throws IOException { Assume.assumeTrue("Ignore tests for format: " + formatStringPair.get(mOutFormat), shouldRunTest(mOutFormat)); <START> System.loadLibrary("ctsmediav2codec_jni"); <END> Assume.assumeTrue( "mp4 and 3gpp fails this test. Bug: 146925201, delete this once fixed", mOutFormat != MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4 && mOutFormat != MediaMuxer.OutputFormat.MUXER_OUTPUT_3GPP); String inpPath = WorkDir.getMediaDirString() + mSrcFile; String outPath = File.createTempFile("MuxerTestsetLocNat", ".out").getAbsolutePath(); boolean status = nativeTestSetLocation(mOutFormat, inpPath, outPath); new File(outPath).delete(); assertTrue("testSetLocationNative failed for Format: " + mOutFormat, status); }</code><technical_language>I this line 631. this pulled a common routine? a name loadNeededTestLibraries() places do library name</technical_language>

Target:
public void testSetLocationNative() { Assume.assumeTrue(shouldRunTest(mOutFormat)); Assume.assumeTrue("TODO(b/146925201)", mOutFormat != MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4 && mOutFormat != MediaMuxer.OutputFormat.MUXER_OUTPUT_3GPP); System.loadLibrary("ctsmediav2codec_jni"); assertTrue(nativeTestSetLocation(mOutFormat, mInpPath, mOutPath)); }
Source:
<code>public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final pathObject other = (pathObject) obj; if ( node == null ) { return other.node == null; } <START> else return node.equals(other.node); <END> }</code><technical_language>need else clause</technical_language>

Target:
public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final pathObject other = (pathObject) obj; if ( node == null ) { return other.node == null; } return node.equals(other.node); }
Source:
<code>DedupFunctionInfo getFilter() { if (filterField == null) { return null; } List<FunctionInfo> aggregates = parseAggregation(filterField); if (aggregates.size() != 1) { <START> throw new IllegalArgumentException("Only one filter field is allowed!"); <END> } FunctionInfo aggregate = aggregates.get(0); return new DedupFunctionInfo(aggregate.getName(), aggregate.getField(), aggregate.getFunction()); }</code><technical_language>nit: '!' else, lets replace a '.'</technical_language>

Target:
DedupFunctionInfo getFilter() { if (Strings.isNullOrEmpty(filterOperation)) { return null; } List<String> filterParts = new ArrayList<>(); for (String filterPart : Splitter.on(':').trimResults().split(filterOperation)) { filterParts.add(filterPart); } if (filterParts.size() != 2) { throw new IllegalArgumentException(String.format("Invalid filter operation. It should be of format " + "'fieldName:functionName'. But got : %s", filterOperation)); } Function function; String fieldName = filterParts.get(0); String functionStr = filterParts.get(1); try { function = Function.valueOf(functionStr.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("Invalid function '%s'. Must be one of %s.", functionStr, Joiner.on(',').join(Function.values()))); } return new DedupFunctionInfo(fieldName, function); }
Source:
<code>public List<Feature> parseJsonFiles(List<String> jsonFiles) { if (jsonFiles.isEmpty()) { throw new ValidationException("No report file was added!"); } <START> List<Feature> featureResults = new ArrayList<>(jsonFiles.size() * 10); <END> int jsonFileNo = 0; for (String jsonFile : jsonFiles) { Feature[] features = parseForFeature(jsonFile); LOG.info("File '{}' contain features", jsonFile, features.length); collectFeaturesAndSetMetadata(featureResults, features, jsonFile, jsonFileNo++); } if (featureResults.isEmpty()) { throw new ValidationException("Passed files have no features!"); } return featureResults; }</code><technical_language>Remove magic number - impact for performance big worth provide number</technical_language>

Target:
public List<Feature> parseJsonFiles(List<String> jsonFiles) { if (jsonFiles.isEmpty()) { throw new ValidationException("No report file was added!"); } List<Feature> featureResults = new ArrayList<>(); for (int i = 0; i < jsonFiles.size(); i++) { String jsonFile = jsonFiles.get(i); Feature[] features = parseForFeature(jsonFile); LOG.info("File '{}' contain features", jsonFile, features.length); collectFeaturesAndSetMetadata(featureResults, features, jsonFile, i); } if (featureResults.isEmpty()) { throw new ValidationException("Passed files have no features!"); } return featureResults; }
Source:
<code>public static void tearDown () throws Exception { try { HttpUtils.stopSyncServer(); <START> RealmLog.setLevel(LogLevel.WARN); <END> } catch (Exception e) { RealmLog.error("Failed to stop Sync Server", e); } }</code><technical_language>Save log level calling RealmLog.getLevel() restore that</technical_language>

Target:
public static void tearDown () throws Exception { try { HttpUtils.stopSyncServer(); RealmLog.setLevel(originalLogLevel); } catch (Exception e) { RealmLog.error("Failed to stop Sync Server", e); } }
Source:
<code>public InputStream handle(Request request, io.airlift.http.client.Response response) throws RuntimeException { try { <START> if (response.getHeader(CONTENT_TYPE) != null && response.getHeader(CONTENT_TYPE).equals(APPLICATION_JSON)) { <END> return response.getInputStream(); } throw new RuntimeException("Response received was not of type " + APPLICATION_JSON); } catch (IOException e) { throw new RuntimeException("Unable to read response from worker", e); } }</code><technical_language>remove null check java if (APPLICATION_JSON.equals(response.getHeader(CONTENT_TYPE))) ..</technical_language>

Target:
public InputStream handle(Request request, io.airlift.http.client.Response response) { try { if (APPLICATION_JSON.equals(response.getHeader(CONTENT_TYPE))) { return response.getInputStream(); } throw new RuntimeException("Response received was not of type " + APPLICATION_JSON); } catch (IOException e) { throw new RuntimeException("Unable to read response from worker", e); } }
Source:
<code>protected void addProvider(Provider<E> provider) { if (!elementMap.containsKey(provider)) { Collection<E> elementsOfProvider = provider.getAll(); Collection<E> elements = new CopyOnWriteArraySet<E>(); provider.addProviderChangeListener(this); elementMap.put(provider, elements); for (E element : elementsOfProvider) { try { K uid = element.getUID(); if (uid != null && get(uid) != null) { <START> logger.warn(String.format( <END> "%s with Key \"%s\" already exists! Failed to add a second with the same UID!", element.getClass().getName(), uid)); continue; } onAddElement(element); elements.add(element); notifyListenersAboutAddedElement(element); } catch (Exception ex) { logger.warn("Could not add element: " + ex.getMessage(), ex); } } logger.debug("Provider '{}' has been added.", provider.getClass().getName()); } }</code><technical_language>Is a special reason String.format simply parameterized logging</technical_language>

Target:
protected void addProvider(Provider<E> provider) { if (!elementMap.containsKey(provider)) { Collection<E> elementsOfProvider = provider.getAll(); Collection<E> elements = new CopyOnWriteArraySet<E>(); provider.addProviderChangeListener(this); elementMap.put(provider, elements); for (E element : elementsOfProvider) { try { K uid = element.getUID(); if (uid != null && get(uid) != null) { logger.warn("{} with key'{}' already exists! Failed to add a second with the same UID!", element.getClass().getName(), uid); continue; } onAddElement(element); elements.add(element); notifyListenersAboutAddedElement(element); } catch (Exception ex) { logger.warn("Could not add element: {}", ex.getMessage(), ex); } } logger.debug("Provider '{}' has been added.", provider.getClass().getName()); } }
Source:
<code>public JsonObject json() throws IOException { final XML xml = this.storage.xml().nodes(this.xpath()).get(0); <START> final String basebranch = xml.xpath("base/text()").get(0); <END> final String head = xml.xpath("head/text()").get(0); final String[] headparts = head.split(MkPull.USER_BRANCH_SEP, 2); final List<String> patches = xml.xpath("patch/text()"); final String patch; if (patches.isEmpty()) { patch = ""; } else { patch = patches.get(0); } return Json.createObjectBuilder() .add( "number", Integer.parseInt(xml.xpath("number/text()").get(0)) ) .add( "user", Json.createObjectBuilder() .add("login", xml.xpath("user/login/text()").get(0)) .build() ) .add("patch", patch) .add( "head", Json.createObjectBuilder() .add(REF_PROP, headparts[1]) .add(LABEL_PROP, head) .build() ) .add( "base", Json.createObjectBuilder() .add(REF_PROP, basebranch) .add( LABEL_PROP, String.format( "%s:%s", this.coords.user(), basebranch ) ) .build() ) .add( "comments", this.storage.xml().nodes(this.comment()).size() ) .build(); }</code><technical_language>@cvrebert rename this branch</technical_language>

Target:
public JsonObject json() throws IOException { final XML xml = this.storage.xml().nodes(this.xpath()).get(0); final String branch = xml.xpath("base/text()").get(0); final String head = xml.xpath("head/text()").get(0); final String[] parts = head.split(MkPull.USER_BRANCH_SEP, 2); final List<String> patches = xml.xpath("patch/text()"); final String patch; if (patches.isEmpty()) { patch = ""; } else { patch = patches.get(0); } return Json.createObjectBuilder() .add( "number", Integer.parseInt(xml.xpath("number/text()").get(0)) ) .add( "user", Json.createObjectBuilder() .add("login", xml.xpath("user/login/text()").get(0)) .build() ) .add("patch", patch) .add( "head", Json.createObjectBuilder() .add(MkPull.REF_PROP, parts[1]) .add(MkPull.LABEL_PROP, head) .build() ).add( "base", Json.createObjectBuilder() .add(MkPull.REF_PROP, branch) .add( MkPull.LABEL_PROP, String.format( "%s:%s", this.coords.user(), branch ) ).build() ).add( "comments", this.storage.xml().nodes(this.comment()).size() ).build(); }
Source:
<code>public TmfResolvedSymbol getSymbolEntry(long address) { Entry<Long, TmfResolvedSymbol> floorEntry = fSymbolMapping.floorEntry(address); if (floorEntry == null) { return null; } TmfResolvedSymbol symbol = floorEntry.getValue(); long floorValue = symbol.getBaseAddress(); <START> if (symbol.getSymbolName().endsWith(getEndSuffix()) && floorValue != address) { return null; } return symbol; <END> }</code><technical_language>Ternary operator if feeling fancy</technical_language>

Target:
public TmfResolvedSymbol getSymbolEntry(long address) { Entry<Long, TmfResolvedSymbol> floorEntry = fSymbolMapping.floorEntry(address); if (floorEntry == null) { return null; } TmfResolvedSymbol symbol = floorEntry.getValue(); long floorValue = symbol.getBaseAddress(); return (symbol.getSymbolName().endsWith(getEndSuffix()) && floorValue != address) ? null : symbol; }
Source:
<code>public void before() { tester = new WicketTester(application); <START> WebApplication webApplication = tester.getApplication(); <END> webApplication.getWicketFilter().setFilterPath(""); }</code><technical_language>get again? a reference it</technical_language>

Target:
public void before() { tester = new WicketTester(application); application.getWicketFilter().setFilterPath(""); }
Source:
<code>public void check_disable_after_add_three_attempts_and_twenty_seconds() throws InterruptedException { InvalidLoginAttempts invalidLoginAttempts = new InvalidLoginAttempts(0, 0); invalidLoginAttempts.addFailedAttempts(); invalidLoginAttempts.addFailedAttempts(); invalidLoginAttempts.addFailedAttempts(); <START> Thread.sleep(20000); <END> assertThat(invalidLoginAttempts.isLoginEnabled(), is(false)); }</code><technical_language>@manuelplazaspalacio unit test execute in miliseconds, find a for wait 20 30 seconds for test. for example, pass interval parameter</technical_language>

Target:
public void check_disable_after_add_three_attempts_and_twenty_seconds() throws InterruptedException, ActionNotAllowed { InvalidLoginAttempts invalidLoginAttempts = new InvalidLoginAttempts(0, 0); invalidLoginAttempts.setDisableTime(10); invalidLoginAttempts.addFailedAttempts(); invalidLoginAttempts.addFailedAttempts(); invalidLoginAttempts.addFailedAttempts(); Thread.sleep(5); assertThat(invalidLoginAttempts.isLoginEnabled(), is(false)); }
Source:
<code><START> public void sendBatch() { <END> ServiceBusSenderAsyncClient sender = new ServiceBusClientBuilder() .connectionString( "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}") .buildSenderClientBuilder() .entityName("<QUEUE-NAME>") .buildAsyncClient(); sender.createBatch().flatMap(batch -> { batch.tryAdd(new ServiceBusMessage("test-1".getBytes(UTF_8))); batch.tryAdd(new ServiceBusMessage("test-2".getBytes(UTF_8))); return sender.send(batch); }).subscribe(unused -> { }, error -> System.err.println("Error occurred while sending batch:" + error), () -> System.out.println("Send complete.")); END: com.azure.messaging.servicebus.servicebusasyncsenderclient.createBatch sender.close(); }</code><technical_language>Another do #instantiation credentials</technical_language>

Target:
public void sendBatch() { ServiceBusSenderAsyncClient sender = new ServiceBusClientBuilder() .connectionString( "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}") .buildSenderClientBuilder() .entityName("<QUEUE OR TOPIC NAME>") .buildAsyncClient(); sender.createBatch().flatMap(batch -> { batch.tryAdd(new ServiceBusMessage("test-1".getBytes(UTF_8))); batch.tryAdd(new ServiceBusMessage("test-2".getBytes(UTF_8))); return sender.send(batch); }).subscribe(unused -> { }, error -> System.err.println("Error occurred while sending batch:" + error), () -> System.out.println("Send complete.")); END: com.azure.messaging.servicebus.servicebusasyncsenderclient.createBatch sender.close(); }
Source:
<code>protected RegisteredService getRegisteredServiceFromFile(final File file) { val fileName = file.getName(); if (fileName.startsWith(".")) { <START> LOGGER.debug("[{}] starts with ., ignoring", fileName); <END> return null; } if (Arrays.stream(getExtensions()).noneMatch(fileName::endsWith)) { LOGGER.debug("[{}] doesn't end with valid extension, ignoring", fileName); return null; } val matcher = this.serviceFileNamePattern.matcher(fileName); if (matcher.find()) { val serviceId = matcher.group(2); if (NumberUtils.isCreatable(serviceId)) { val id = Long.parseLong(serviceId); return findServiceById(id); } val serviceName = matcher.group(1); return findServiceByExactServiceName(serviceName); } LOGGER.warn("Provided file [{}} does not match the recommended service definition file pattern [{}]", file.getName(), this.serviceFileNamePattern.pattern()); return null; }</code><technical_language>I trace for messages</technical_language>

Target:
protected RegisteredService getRegisteredServiceFromFile(final File file) { val fileName = file.getName(); if (fileName.startsWith(".")) { LOGGER.trace("[{}] starts with ., ignoring", fileName); return null; } if (Arrays.stream(getExtensions()).noneMatch(fileName::endsWith)) { LOGGER.trace("[{}] doesn't end with valid extension, ignoring", fileName); return null; } val matcher = this.serviceFileNamePattern.matcher(fileName); if (matcher.find()) { val serviceId = matcher.group(2); if (NumberUtils.isCreatable(serviceId)) { val id = Long.parseLong(serviceId); return findServiceById(id); } val serviceName = matcher.group(1); return findServiceByExactServiceName(serviceName); } LOGGER.warn("Provided file [{}} does not match the recommended service definition file pattern [{}]", file.getName(), this.serviceFileNamePattern.pattern()); return null; }
Source:
<code>protected Tuple2<MutablePartitionId, PrestoSparkMutableRow> computeNext() { if (currentRow >= rowCount) { return endOfData(); } int rowSize = rowSizes[currentRow]; rowData.limit(currentOffset + rowSize); rowData.position(currentOffset); int partition = rowPartitions[currentRow]; if (partition < 0) { if (replicatePartition < 0) { <START> replicatePartition = -partition; <END> replicatePartition--; } mutablePartitionId.setPartition(replicatePartition); replicatePartition--; if (replicatePartition < 0) { currentRow++; currentOffset += rowSize; } } else { mutablePartitionId.setPartition(partition); currentRow++; currentOffset += rowSize; } return tuple; }</code><technical_language>partition is negative, encodes number of total partitions. pass number of total partitions in constructor encoded in partition</technical_language>

Target:
protected Tuple2<MutablePartitionId, PrestoSparkMutableRow> computeNext() { if (currentRow >= rowCount) { return endOfData(); } int rowSize = rowSizes[currentRow]; rowData.limit(currentOffset + rowSize); rowData.position(currentOffset); int partition = rowPartitions[currentRow]; if (partition == REPLICATED_ROW_PARTITION_ID) { if (remainingReplicasCount == 0) { remainingReplicasCount = partitionCount; } mutablePartitionId.setPartition(remainingReplicasCount - 1); remainingReplicasCount--; if (remainingReplicasCount == 0) { currentRow++; currentOffset += rowSize; } } else { mutablePartitionId.setPartition(partition); currentRow++; currentOffset += rowSize; } return tuple; }