auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (isThreadDisplay && data.getCount() == 0) { handler.goBack(); return; } swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setEnabled(isPullToRefreshAllowed()); final int loaderId = loader.getId(); cursors[loaderId] = data; cursorValid[loaderId] = true; Cursor cursor; if (cursors.length > 1) { cursor = new MergeCursorWithUniqueId(cursors, getComparator()); uniqueIdColumn = cursor.getColumnIndex("_id"); } else { cursor = data; uniqueIdColumn = ID_COLUMN; } <START> if (adapter != null) adapter.setUniqueIdColumn(uniqueIdColumn); <END> if (isThreadDisplay) { if (cursor.moveToFirst()) { title = cursor.getString(SUBJECT_COLUMN); if (!TextUtils.isEmpty(title)) { title = Utility.stripSubject(title); } if (TextUtils.isEmpty(title)) { title = getString(R.string.general_no_subject); } updateTitle(); } else { } } cleanupSelected(cursor); updateContextMenu(cursor); adapter.swapCursor(cursor); resetActionMode(); computeBatchDirection(); if (isLoadFinished()) { if (savedListState != null) { handler.restoreListPosition(); } fragmentListener.updateMenu(); } }</code><technical_language>A method adapter is called a null check down. this necessary either</technical_language>

Target:
public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (isThreadDisplay && data.getCount() == 0) { handler.goBack(); return; } swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setEnabled(isPullToRefreshAllowed()); final int loaderId = loader.getId(); cursors[loaderId] = data; cursorValid[loaderId] = true; Cursor cursor; if (cursors.length > 1) { cursor = new MergeCursorWithUniqueId(cursors, getComparator()); uniqueIdColumn = cursor.getColumnIndex("_id"); } else { cursor = data; uniqueIdColumn = ID_COLUMN; } adapter.setUniqueIdColumn(uniqueIdColumn); if (isThreadDisplay) { if (cursor.moveToFirst()) { title = cursor.getString(SUBJECT_COLUMN); if (!TextUtils.isEmpty(title)) { title = Utility.stripSubject(title); } if (TextUtils.isEmpty(title)) { title = getString(R.string.general_no_subject); } updateTitle(); } else { } } cleanupSelected(cursor); updateContextMenu(cursor); adapter.swapCursor(cursor); resetActionMode(); computeBatchDirection(); if (isLoadFinished()) { if (savedListState != null) { handler.restoreListPosition(); } fragmentListener.updateMenu(); } }
Source:
<code>@Override public void initialize(InputSplit spl, TaskAttemptContext ctx) throws IOException { if(isInitialized) close(); isInitialized = true; final Configuration conf = ContextUtil.getConfiguration(ctx); final FileVirtualSplit split = (FileVirtualSplit)spl; final Path file = split.getPath(); final FileSystem fs = file.getFileSystem(conf); this.stringency = SAMHeaderReader.getValidationStringency(conf); final FSDataInputStream in = fs.open(file); final SAMFileHeader header = SAMHeaderReader.readSAMHeaderFrom(in, conf); codec = new BAMRecordCodec(header); in.seek(0); bci = new BlockCompressedInputStream( new WrapSeekable<FSDataInputStream>( in, fs.getFileStatus(file).getLen(), file)); virtualStart = split.getStartVirtualOffset(); fileStart = virtualStart >>> 16; virtualEnd = split.getEndVirtualOffset(); bci.seek(virtualStart); codec.setInputStream(bci); if(BAMInputFormat.DEBUG_BAM_SPLITTER) { final long recordStart = virtualStart & 0xffff; System.err.println("XXX inizialized BAMRecordReader byte offset: " + fileStart + " record offset: " + recordStart); } keepReadPairsTogether = SortOrder.queryname.equals(header.getSortOrder()) && conf.getBoolean(BAMInputFormat.KEEP_PAIRED_READS_TOGETHER_PROPERTY, false); readPair = false; lastOfPair = false; intervals = BAMInputFormat.getIntervals(conf); if (intervals != null) { overlapDetector = new OverlapDetector<>(0, 0); <START> overlapDetector.addAll(intervals, intervals); <END> } }</code><technical_language>worth [optimizing](<LINK_0> intervals handing overlap detector</technical_language>

Target:
@Override public void initialize(InputSplit spl, TaskAttemptContext ctx) throws IOException { if(isInitialized) close(); isInitialized = true; final Configuration conf = ctx.getConfiguration(); final FileVirtualSplit split = (FileVirtualSplit)spl; final Path file = split.getPath(); final FileSystem fs = file.getFileSystem(conf); this.stringency = SAMHeaderReader.getValidationStringency(conf); final FSDataInputStream in = fs.open(file); final SAMFileHeader header = SAMHeaderReader.readSAMHeaderFrom(in, conf); codec = new BAMRecordCodec(header); in.seek(0); bci = new BlockCompressedInputStream( new WrapSeekable<FSDataInputStream>( in, fs.getFileStatus(file).getLen(), file)); virtualStart = split.getStartVirtualOffset(); fileStart = virtualStart >>> 16; virtualEnd = split.getEndVirtualOffset(); bci.seek(virtualStart); codec.setInputStream(bci); if(BAMInputFormat.DEBUG_BAM_SPLITTER) { final long recordStart = virtualStart & 0xffff; System.err.println("XXX inizialized BAMRecordReader byte offset: " + fileStart + " record offset: " + recordStart); } keepReadPairsTogether = SortOrder.queryname.equals(header.getSortOrder()) && conf.getBoolean(BAMInputFormat.KEEP_PAIRED_READS_TOGETHER_PROPERTY, false); readPair = false; lastOfPair = false; intervals = BAMInputFormat.getIntervals(conf); if (intervals != null) { overlapDetector = new OverlapDetector<>(0, 0); overlapDetector.addAll(intervals, intervals); } }
Source:
<code>public GetVmConfigurationBySnapshotQueryParams(Guid snapshotSourceId) { <START> super(); <END> this.snapshotSourceId = snapshotSourceId; }</code><technical_language>super call redundant</technical_language>

Target:
public GetVmConfigurationBySnapshotQueryParams(Guid snapshotSourceId) { this.snapshotSourceId = snapshotSourceId; }
Source:
<code>protected File getTargetFile(String suffix) { <START> String filename = String.format("test%s.properties", suffix == null ? "" : suffix); <END> return new File(Environment.getDefault().getConfig(), filename); }</code><technical_language>case suffix == null used, this simplified</technical_language>

Target:
protected File getTargetFile(String suffix) { String filename = String.format("test%s.properties", suffix); return new File(Environment.getDefault().getConfig(), filename); }
Source:
<code>public void testCreateTableWithArrayColumn() throws Exception { String tableName = generateUniqueName(); String schemaName = generateUniqueName(); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName); String query = "create table " + pTableFullName + "(a_char CHAR(15) NOT NULL, " + "b_char CHAR(10) NOT NULL, " + "c_var_array VARCHAR ARRAY, " + <START> "d_char_array CHAR(15) ARRAY[3] CONSTRAINT PK PRIMARY KEY (a_char, b_char)) " + <END> "TTL=2592000, IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN, DISABLE_TABLE_SOR=true, REPLICATION_SCOPE=1"; conn.createStatement().execute(query); conn.commit(); String[] args = {"-tb", tableName, "-s", schemaName}; SchemaExtractionTool set = new SchemaExtractionTool(); set.setConf(conn.unwrap(PhoenixConnection.class).getQueryServices().getConfiguration()); set.run(args); Assert.assertEquals(query.toUpperCase(), set.getOutput().toUpperCase()); } }</code><technical_language>Good edge case check</technical_language>

Target:
public void testCreateTableWithArrayColumn() throws Exception { String tableName = generateUniqueName(); String schemaName = generateUniqueName(); String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName); String query = "create table " + pTableFullName + "(a_char CHAR(15) NOT NULL, " + "b_char CHAR(10) NOT NULL, " + "c_var_array VARCHAR ARRAY, " + "d_char_array CHAR(15) ARRAY[3] CONSTRAINT PK PRIMARY KEY (a_char, b_char)) " + "TTL=2592000, IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN, REPLICATION_SCOPE=1"; List<String> queries = new ArrayList<String>(){}; queries.add(query); String result = runSchemaExtractionTool(schemaName, tableName, null, queries); Assert.assertEquals(query.toUpperCase(), result.toUpperCase()); }
Source:
<code>public void testMigrationTranslator() throws Exception { ResearchProject researchProject = new ResearchProject(); String id = "101"; researchProject.setId(id); Submission submission = new Submission(); submission.setResearchProjectSnapshot(researchProject); DBOSubmission backup = new DBOSubmission(); backup.setAccessRequirementId(1L); backup.setCreatedBy(2L); backup.setCreatedOn(3L); backup.setDataAccessRequestId(4L); backup.setEtag("etag"); backup.setId(5L); backup.setSubmissionSerialized(JDOSecondaryPropertyUtils.compressObject(X_STREAM, submission)); assertNull(backup.getResearchProjectId()); <START> DBOSubmission dbo = backup.getTranslator().createDatabaseObjectFromBackup(backup); <END> assertEquals(Long.parseLong(id), dbo.getResearchProjectId().longValue()); assertEquals(dbo, backup); }</code><technical_language>Replace backup new DBOSubmission() catch bug</technical_language>

Target:
public void testMigrationTranslator() throws Exception { ResearchProject researchProject = new ResearchProject(); String id = "101"; researchProject.setId(id); Submission submission = new Submission(); submission.setResearchProjectSnapshot(researchProject); DBOSubmission backup = new DBOSubmission(); backup.setAccessRequirementId(1L); backup.setCreatedBy(2L); backup.setCreatedOn(3L); backup.setDataAccessRequestId(4L); backup.setEtag("etag"); backup.setId(5L); backup.setSubmissionSerialized(JDOSecondaryPropertyUtils.compressObject(X_STREAM, submission)); assertNull(backup.getResearchProjectId()); DBOSubmission dbo = (new DBOSubmission()).getTranslator().createDatabaseObjectFromBackup(backup); assertEquals(Long.parseLong(id), dbo.getResearchProjectId().longValue()); assertEquals(dbo, backup); }
Source:
<code>@Test public void shouldOpenCompareEditorInWorkspaceModel() throws Exception { resetRepository(PROJ1); createTag(PROJ1, "compare2"); changeFilesInProject(); showDialog(PROJ1, "Team", "Synchronize..."); bot.shell("Synchronize repository: " + REPO1 + File.separator + ".git") .activate(); bot.comboBox(2) .setSelection(UIText.SynchronizeWithAction_tagsName); bot.comboBox(3).setSelection("compare2"); bot.button(IDialogConstants.OK_LABEL).click(); SWTBotView syncView = bot.viewByTitle("Synchronize"); syncView.toolbarDropDownButton("Show File System Resources").click() .menuItem("Workspace").click(); SWTBotTree syncViewTree = syncView.bot().tree(); <START> TestUtil.waitUntilTreeHasNodeWithText(bot, syncViewTree, "> GeneralProject", 10000); <END> syncViewTree.getAllItems()[0].expand().getItems()[0].expand() .getItems()[0].doubleClick(); SWTBot compare = bot.editorByTitle(FILE1).bot(); assertNotNull(compare); }</code><technical_language>"> " + PROJ1 instead of hardcoding project name</technical_language>

Target:
@Test public void shouldOpenCompareEditorInWorkspaceModel() throws Exception { resetRepository(PROJ1); createTag(PROJ1, "compare2"); changeFilesInProject(); showDialog(PROJ1, "Team", "Synchronize..."); bot.shell("Synchronize repository: " + REPO1 + File.separator + ".git") .activate(); bot.comboBox(2) .setSelection(UIText.SynchronizeWithAction_tagsName); bot.comboBox(3).setSelection("compare2"); bot.button(IDialogConstants.OK_LABEL).click(); SWTBotView syncView = bot.viewByTitle("Synchronize"); syncView.toolbarDropDownButton("Show File System Resources").click() .menuItem("Workspace").click(); SWTBotTree syncViewTree = syncView.bot().tree(); TestUtil.waitUntilTreeHasNodeWithText(bot, syncViewTree, "> " + PROJ1, 10000); syncViewTree.getAllItems()[0].expand().getItems()[0].expand() .getItems()[0].doubleClick(); SWTBot compare = bot.editorByTitle(FILE1).bot(); assertNotNull(compare); }
Source:
<code>String getAttributeValue(int idx) { final QName attribute = getAttribute(idx); switch (attribute.getLocalPart()) { case XJConstants.TYPE_HINT_NAME: return this.name; case XJConstants.TYPE_HINT_TYPE: return XJConstants.JSONTYPE_TYPE_MAP.get(this.jsonToken); default: <START> throw new IllegalArgumentException("Unknown attribute"); <END> } }</code><technical_language>Please add localPart exception message</technical_language>

Target:
String getAttributeValue(int idx) { final QName attribute = getAttribute(idx); switch (attribute.getLocalPart()) { case XJConstants.TYPE_HINT_NAME: return this.name; case XJConstants.TYPE_HINT_TYPE: return XJConstants.JSONTYPE_TYPE_MAP.get(this.jsonToken); default: throw new IllegalArgumentException("Unknown attribute " + attribute.getLocalPart()); } }
Source:
<code>public InputStream openInput(String arg) throws IOException { <START> if (arg.equals(STDIN_MARKER)) <END> return new BufferedInputStream(System.in, IN_BUF_SZ); InputStream infile = new BufferedInputStream(new FileInputStream(arg), IN_BUF_SZ); if (arg.endsWith(".gz")) return new GZIPInputStream(infile); else if (arg.endsWith(".bz2")) return new BZip2CompressorInputStream(infile); else return infile; }</code><technical_language>Objects.requireNonNull(arg)</technical_language>

Target:
public InputStream openInput(String arg) throws IOException { arg = Objects.requireNonNull(arg); if (arg.equals(STDIN_MARKER)) { return new BufferedInputStream(System.in, IN_BUF_SZ); } InputStream infile = new BufferedInputStream(new FileInputStream(arg), IN_BUF_SZ); if (arg.endsWith(".gz")) { return new GZIPInputStream(infile); } else if (arg.endsWith(".bz2")) { return new BZip2CompressorInputStream(infile); } else { return infile; } }
Source:
<code>private BufferCachingGrpcDataReader(WorkerNetAddress address, CloseableResource<BlockWorkerClient> client, long dataTimeoutMs, ReadRequest readRequest, GrpcBlockingStream<ReadRequest, ReadResponse> stream) { mAddress = address; mClient = client; mDataTimeoutMs = dataTimeoutMs; mMarshaller = new ReadResponseMarshaller(); mPosToRead = readRequest.getOffset(); mReadRequest = readRequest; mStream = stream; <START> <END> mCloser = Closer.create(); mCloser.register(mClient); mCloser.register(() -> { mStream.close(); mStream.waitForComplete(mDataTimeoutMs); }); long blockSize = mReadRequest.getLength() + mReadRequest.getOffset(); long chunkSize = mReadRequest.getChunkSize(); int buffCount = (int) (blockSize / chunkSize); if ((blockSize % chunkSize) != 0) { buffCount += 1; } mDataBuffers = new DataBuffer[buffCount]; }</code><technical_language>nit: unnecessary empty lines line 88 95. code base compact for readability in general</technical_language>

Target:
private BufferCachingGrpcDataReader(WorkerNetAddress address, CloseableResource<BlockWorkerClient> client, long dataTimeoutMs, ReadRequest readRequest, GrpcBlockingStream<ReadRequest, ReadResponse> stream) { mAddress = address; mClient = client; mDataTimeoutMs = dataTimeoutMs; mPosToRead = readRequest.getOffset(); mReadRequest = readRequest; mStream = stream; long blockSize = mReadRequest.getLength() + mReadRequest.getOffset(); long chunkSize = mReadRequest.getChunkSize(); int buffCount = (int) (blockSize / chunkSize); if ((blockSize % chunkSize) != 0) { buffCount += 1; } mDataBuffers = new DataBuffer[buffCount]; }
Source:
<code>public DataSource get() { final BoneCPDataSource src = new BoneCPDataSource(); src.setDriverClass("org.postgresql.Driver"); src.setJdbcUrl(this.jdbc); <START> if (this.user != null) { <END> src.setUser("postgres"); } src.setPassword(this.password); src.setPartitionCount(Tv.THREE); src.setMaxConnectionsPerPartition(1); src.setMinConnectionsPerPartition(1); src.setAcquireIncrement(1); src.setDisableConnectionTracking(true); return src; }</code><technical_language>set postgres in ctor</technical_language>

Target:
public DataSource get() { final BoneCPDataSource src = new BoneCPDataSource(); src.setDriverClass("org.postgresql.Driver"); src.setJdbcUrl(this.jdbc); if (this.user != null) { src.setUser(this.user); } src.setPassword(this.password); src.setPartitionCount(Tv.THREE); src.setMaxConnectionsPerPartition(1); src.setMinConnectionsPerPartition(1); src.setAcquireIncrement(1); src.setDisableConnectionTracking(true); return src; }
Source:
<code>public Segment decodeNext(ParsingProgress progress) { StringBuilder currentId = new StringBuilder(); String currentTypeString = null; int state = 0; loop: while (!progress.isFinished()) { char c = progress.getNextChar(); switch (state) { case 0: switch (c) { case TYPE_DELIM: if (currentId.length() == 0) { throw new IllegalArgumentException("Unspecified entity type id at pos " + progress.getPos() + " in '" + progress.getSource() + "'."); } currentTypeString = currentId.toString(); currentId.delete(0, currentId.length()); state = 1; break; case PATH_DELIM: currentTypeString = currentId.toString(); currentId.delete(0, currentId.length()); break loop; default: currentId.append(c); } break; case 1: switch (c) { case PATH_DELIM: break loop; default: currentId.append(c); } break; } } String currentIdString = currentId.toString(); if (currentIdString.isEmpty()) { currentIdString = currentTypeString; currentTypeString = null; if (state == 1) { currentIdString += TYPE_DELIM; } } currentIdString = PathSegmentCodec.decode(currentIdString); Segment ret = typeProvider.deduceSegment(currentTypeString, currentIdString, progress.isFinished()); if (ret == null) { throw new IllegalArgumentException("Unrecognized entity type '" + currentTypeString + "' for segment" <START> + " with id: '" + currentIdString + "' in source '" + progress.getSource() <END> + "'. The following types are recognized: " + typeProvider.getValidTypeName()); } typeProvider.segmentParsed(ret); return ret; }</code><technical_language>s/in source/in path/ parsing a path here</technical_language>

Target:
public Segment decodeNext(ParsingProgress progress) { StringBuilder currentId = new StringBuilder(); String currentTypeString = null; int state = 0; loop: while (!progress.isFinished()) { char c = progress.getNextChar(); switch (state) { case 0: switch (c) { case TYPE_DELIM: if (currentId.length() == 0) { throw new IllegalArgumentException("Unspecified entity type id at pos " + progress.getPos() + " in '" + progress.getSource() + "'."); } currentTypeString = currentId.toString(); currentId.delete(0, currentId.length()); state = 1; break; case PATH_DELIM: currentTypeString = currentId.toString(); currentId.delete(0, currentId.length()); break loop; default: currentId.append(c); } break; case 1: switch (c) { case PATH_DELIM: break loop; default: currentId.append(c); } break; } } String currentIdString = currentId.toString(); if (currentIdString.isEmpty()) { currentIdString = currentTypeString; currentTypeString = null; if (state == 1) { currentIdString += TYPE_DELIM; } } currentIdString = PathSegmentCodec.decode(currentIdString); Segment ret = typeProvider.deduceSegment(currentTypeString, currentIdString, progress.isFinished()); if (ret == null) { throw new IllegalArgumentException("Unrecognized entity type '" + currentTypeString + "' for segment" + " with id: '" + currentIdString + "' in path '" + progress.getSource() + "'. The following types are recognized: " + typeProvider.getValidTypeName()); } typeProvider.segmentParsed(ret); return ret; }
Source:
<code>private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException { if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) { throw new NumberFormatException(value); } int i = beginIndex; int result = 0; int digit; if (i < endIndex) { digit = Character.digit(value.charAt(i++), 10); if (digit < 0) { <START> throw new NumberFormatException("Invalid number: " + value); <END> } result = -digit; } while (i < endIndex) { digit = Character.digit(value.charAt(i++), 10); if (digit < 0) { throw new NumberFormatException("Invalid number: " + value); } result *= 10; result -= digit; } return -result; }</code><technical_language>This value.substring(beginIndex, endIndex)</technical_language>

Target:
private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException { if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) { throw new NumberFormatException(value); } int i = beginIndex; int result = 0; int digit; if (i < endIndex) { digit = Character.digit(value.charAt(i++), 10); if (digit < 0) { throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex)); } result = -digit; } while (i < endIndex) { digit = Character.digit(value.charAt(i++), 10); if (digit < 0) { throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex)); } result *= 10; result -= digit; } return -result; }
Source:
<code>private boolean hasMoreActivationsThisTurn(Game game) { <START> ActivationInfo activationInfo = getActivationInfo(game); <END> return activationInfo == null || activationInfo.turnNum != game.getTurnNum() || activationInfo.activationCounter < maxActivationsPerTurn; }</code><technical_language>returning true if == Integer.MAX_VALUE;</technical_language>

Target:
protected boolean hasMoreActivationsThisTurn(Game game) { if (maxActivationsPerTurn == Integer.MAX_VALUE) { return true; } ActivationInfo activationInfo = getActivationInfo(game); return activationInfo == null || activationInfo.turnNum != game.getTurnNum() || activationInfo.activationCounter < maxActivationsPerTurn; }
Source:
<code>final public void run() { int sleepMillis = config.getIntegerProperty(CoreConfig.EXCESS_ENUM_READER_SLEEP); while (true) { try { Set<Locator> excess = IOContainer.fromConfig().getExcessEnumIO().getExcessEnumMetrics(); synchronized (this) { excessEnumMetrics = excess; <START> } <END> readMeter.mark(); Thread.sleep(sleepMillis); } catch (Exception e) { log.error("ExcessEnumReader failed with exception " + e); readErrMeter.mark(); } } }</code><technical_language>is this necessary? I thought assignments atomic operations</technical_language>

Target:
final public void run() { int sleepMillis = config.getIntegerProperty(CoreConfig.EXCESS_ENUM_READER_SLEEP); while (true) { try { Set<Locator> excess = IOContainer.fromConfig().getExcessEnumIO().getExcessEnumMetrics(); excessEnumMetrics = excess; readMeter.mark(); Thread.sleep(sleepMillis); } catch (Exception e) { log.error("ExcessEnumReader failed with exception " + e); readErrMeter.mark(); } } }
Source:
<code>public Iterable<VirtualMachine> listNodes() { Closer closer = Closer.create(); VSphereServiceInstance instance = serviceInstance.get(); closer.register(instance); try { try { return listNodes(instance); } catch (Throwable e) { logger.error("Can't find vm", e); throw closer.rethrow(e); } finally { closer.close(); } <START> } catch (Throwable t) { <END> return ImmutableSet.of(); } }</code><technical_language>Is this catch needed? exceptions caught</technical_language>

Target:
public Iterable<VirtualMachine> listNodes() { try (VSphereServiceInstance instance = serviceInstance.get();) { return listNodes(instance); } catch (Throwable e) { logger.error("Can't find vm", e); Throwables.propagateIfPossible(e); return ImmutableSet.of(); } }
Source:
<code>private List<Iterable<Range>> divideRangesByGroup( Granularity g, long from, long to ) { List<Iterable<Range>> listRange = new ArrayList<Iterable<Range>>(); long rangeSize = ROLLUP_ON_READ_REPAIR_SIZE_PER_THREAD * g.milliseconds(); for ( long start = g.snapMillis( from ); start < to ; ) { <START> long end = (start + rangeSize) < to ? (start + rangeSize ) : to; <END> listRange.add( Range.rangesForInterval( g, start, end ) ); start = end; } return listRange; }</code><technical_language>If I understanding this correctly, If convert "from" "to" snapMillis, dont do this logic right? dont do it. wondering</technical_language>

Target:
private List<Iterable<Range>> divideRangesByGroup( Granularity g, long from, long to ) { List<Iterable<Range>> listRange = new ArrayList<Iterable<Range>>(); long rangeSize = ROLLUP_ON_READ_REPAIR_SIZE_PER_THREAD * g.milliseconds(); for ( long start = from; start < to ; ) { long end = (start + rangeSize) < to ? (start + rangeSize ) : to; listRange.add( Range.rangesForInterval( g, start, end ) ); start = end; } return listRange; }
Source:
<code>public Object processInvocation(final InterceptorContext context) throws Exception { if (MDC.getMap() != null) { <START> for (String str : MDC.getMap().keySet()) { <END> MDC.remove(str); } } final StoredLogDiagnosticContext data = (StoredLogDiagnosticContext) context.getPrivateData(KEY); context.putPrivateData(KEY, null); if (data != null && data.getMdc() != null) { for (Map.Entry<String, Object> entry : data.getMdc().entrySet()) { MDC.put(entry.getKey(), entry.getValue()); } final int depth = NDC.getDepth(); NDC.push(data.getNdc()); try { return context.proceed(); } finally { NDC.setMaxDepth(depth); for (String str : MDC.getMap().keySet()) { MDC.remove(str); } } } return context.proceed(); }</code><technical_language>This is critical perf request path, impl of MDC.getMap() pretty expensive, involving a map copy. result getMap() call L67 cached reused in L68</technical_language>

Target:
public Object processInvocation(final InterceptorContext context) throws Exception { final Map<String, Object> mdc = MDC.getMap(); if (mdc != null) { for (String str : mdc.keySet()) { MDC.remove(str); } } final StoredLogDiagnosticContext data = (StoredLogDiagnosticContext) context.getPrivateData(KEY); context.putPrivateData(KEY, null); if (data != null && data.getMdc() != null) { for (Map.Entry<String, Object> entry : data.getMdc().entrySet()) { MDC.put(entry.getKey(), entry.getValue()); } final int depth = NDC.getDepth(); NDC.push(data.getNdc()); try { return context.proceed(); } finally { NDC.setMaxDepth(depth); for (String str : MDC.getMap().keySet()) { MDC.remove(str); } } } return context.proceed(); }
Source:
<code>public void setConfiguration(Configuration configuration, List<String> subFileList, boolean interactive) { this.configuration = configuration; register(); HistoryGuru histGuru = HistoryGuru.getInstance(); try { generateProjectRepositoriesMap(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, "Cannot generate project - repository map", ex); } populateGroups(getGroups(), new TreeSet<>(getProjects().values())); if (subFileList != null) { histGuru.invalidateRepositories( configuration.getRepositories(), subFileList, interactive); } else { histGuru.invalidateRepositories(configuration.getRepositories(), interactive); } configuration.setRepositories(new ArrayList<>(histGuru.getRepositories())); <START> configuration.getBodyIncludeFileContent(true); <END> configuration.getHeaderIncludeFileContent(true); configuration.getFooterIncludeFileContent(true); configuration.getForbiddenIncludeFileContent(true); }</code><technical_language>I, personally, get rid of force param add method resetIncludeFiles similar. I intent more clear</technical_language>

Target:
public void setConfiguration(Configuration configuration, List<String> subFileList, boolean interactive) { this.configuration = configuration; register(); HistoryGuru histGuru = HistoryGuru.getInstance(); try { generateProjectRepositoriesMap(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, "Cannot generate project - repository map", ex); } populateGroups(getGroups(), new TreeSet<>(getProjects().values())); if (subFileList != null) { histGuru.invalidateRepositories( configuration.getRepositories(), subFileList, interactive); } else { histGuru.invalidateRepositories(configuration.getRepositories(), interactive); } configuration.setRepositories(new ArrayList<>(histGuru.getRepositories())); reloadIncludeFiles(configuration); }
Source:
<code>public boolean configure(StaplerRequest request, JSONObject object) throws FormException { nativeLibraryPath = object.getString("nativeLibraryPath"); master = object.getString("master"); description = object.getString("description"); frameworkName = object.getString("frameworkName"); slaveAttributes = object.getString("slaveAttributes"); checkpoint = object.getBoolean("checkpoint"); slaveInfos = new ArrayList<MesosSlaveInfo>(); JSONArray labels = object.getJSONArray("slaveInfos"); if (labels != null) { for (int i = 0; i < labels.size(); i++) { JSONObject label = labels.getJSONObject(i); if (label != null) { MesosSlaveInfo slaveInfo = new MesosSlaveInfo( object.getString("labelString"), object.getString("slaveCpus"), object.getString("slaveMem"), object.getString("maxExecutors"), object.getString("executorCpus"), object.getString("executorMem"), <START> object.getJSONObject("hasCustomRemoteFSRoot"), <END> object.getString("idleTerminationMinutes"), object.getString("slaveAttributes"), object.getString("jvmArgs")); slaveInfos.add(slaveInfo); } } } save(); return super.configure(request, object); }</code><technical_language>is this JSON instead of a string</technical_language>

Target:
public boolean configure(StaplerRequest request, JSONObject object) throws FormException { nativeLibraryPath = object.getString("nativeLibraryPath"); master = object.getString("master"); description = object.getString("description"); frameworkName = object.getString("frameworkName"); slaveAttributes = object.getString("slaveAttributes"); checkpoint = object.getBoolean("checkpoint"); slaveInfos = new ArrayList<MesosSlaveInfo>(); JSONArray labels = object.getJSONArray("slaveInfos"); if (labels != null) { for (int i = 0; i < labels.size(); i++) { JSONObject label = labels.getJSONObject(i); if (label != null) { MesosSlaveInfo slaveInfo = new MesosSlaveInfo( object.getString("labelString"), object.getString("slaveCpus"), object.getString("slaveMem"), object.getString("maxExecutors"), object.getString("executorCpus"), object.getString("executorMem"), object.getString("remoteFSRoot"), object.getString("idleTerminationMinutes"), object.getString("slaveAttributes"), object.getString("jvmArgs"), object.getString("containerImage"), object.getString("containerOptions")); slaveInfos.add(slaveInfo); } } } save(); return super.configure(request, object); }
Source:
<code>public void onPostValidation(boolean valid) { FormViewUtil.setupBackground(getContext(), valid, textEditText); boolean isRepeatableField = getParent() instanceof DDMFieldRepeatableItemView; if (!isRepeatableField) { View errorView = findViewById(R.id.error_view); if (errorView != null) { errorView.setVisibility(valid ? GONE : VISIBLE); <START> } <END> } }</code><technical_language>View errorView = findViewById(R.id.error_view); if (errorView != null) { errorView.setVisibility(valid ? : VISIBLE); } This code extracted a function called in places</technical_language>

Target:
public void onPostValidation(boolean valid) { FormViewUtil.setupBackground(getContext(), valid, textEditText); boolean isRepeatableField = getParent() instanceof DDMFieldRepeatableItemView; if (!isRepeatableField) { FormViewUtil.setupErrorView(valid, findViewById(R.id.error_view)); } }
Source:
<code>public void setExtractPayload(boolean extractPayload) { if (this.payloadExpression == null) { setPayloadExpression(extractPayload ? EXPRESSION_PARSER.parseExpression("payload") : EXPRESSION_PARSER.parseExpression("#this")); <START> } <END> }</code><technical_language>time port FunctionExpression DSL</technical_language>

Target:
public void setExtractPayload(boolean extractPayload) { if (this.payloadExpression == null) { setPayloadExpression(extractPayload ? null : EXPRESSION_PARSER.parseExpression("#this")); } }
Source:
<code>private void loadWindowsContent(RequestBuilder.Method method) { String host = com.google.gwt.user.client.Window.Location.getHostName(); String user = LoginModel.getInstance().getLogin(); String requestUrl = null; if ("http".equals(SchedulerConfig.get().getCalendarServerProtocol())) { requestUrl = "http://" + host + ":" + SchedulerConfig.get().getCalendarServerPort() + "/calendar-service/private-urls/" + user + "/"; } else { <START> requestUrl = "https://" + host + "/calendar-service/private-urls/" + user + "/"; <END> } RequestBuilder rb = new RequestBuilder(method, requestUrl); rb.setCallback(new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { text.setContents(contentBuilder.buildContentString(response.getText())); } else { text.setContents("Error : status code " + response.getStatusCode()); } refreshWindow(text); } private void refreshWindow(HTMLPane text) { pane.clear(); root.clear(); window.clear(); pane.addMember(img); pane.addMember(text); root.addMember(pane); root.addMember(buttons); window.addItem(root); window.show(); } @Override public void onError(Request request, Throwable exception) { text.setContents("Exception : " + exception.getMessage()); refreshWindow(text); } }); try { rb.send(); } catch (RequestException e) { com.google.gwt.user.client.Window.alert("error = " + e.getMessage()); } }</code><technical_language>part put if : requestUrl += "/calendar-service/private-urls/" + user + "/";</technical_language>

Target:
private void loadWindowsContent(RequestBuilder.Method method) { String host = com.google.gwt.user.client.Window.Location.getHostName(); String user = LoginModel.getInstance().getLogin(); StringBuilder requestUrl = new StringBuilder(); if ("http".equals(SchedulerConfig.get().getCalendarServerProtocol())) { requestUrl.append("http://" + host + ":" + SchedulerConfig.get().getCalendarServerPort()); } else { requestUrl.append("https://" + host); } requestUrl.append("/calendar-service/private-urls/" + user + "/"); RequestBuilder rb = new RequestBuilder(method, requestUrl.toString()); rb.setCallback(new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { text.setContents(contentBuilder.buildContentString(response.getText())); } else { text.setContents("Error : status code " + response.getStatusCode()); } refreshWindow(text); } private void refreshWindow(HTMLPane text) { pane.clear(); root.clear(); window.clear(); pane.addMember(img); pane.addMember(text); root.addMember(pane); root.addMember(buttons); window.addItem(root); window.show(); } @Override public void onError(Request request, Throwable exception) { text.setContents("Exception : " + exception.getMessage()); refreshWindow(text); } }); try { rb.send(); } catch (RequestException e) { com.google.gwt.user.client.Window.alert("error = " + e.getMessage()); } }
Source:
<code>protected void onDemotion() { managementContext.getRebindManager().stop(); for (Application app: managementContext.getApplications()) Entities.unmanage(app); Collection<Exception> exceptions = MutableSet.of(); int tasks = 0; LOG.debug("Cancelling tasks on demotion"); try { for (Entity entity: managementContext.getEntityManager().getEntities()) { for (Task<?> t: managementContext.getExecutionContext(entity).getTasks()) { if (!t.isDone()) { tasks++; try { LOG.debug("Cancelling "+t+" on "+entity); t.cancel(true); <START> } catch (Exception e) { <END> Exceptions.propagateIfFatal(e); exceptions.add(e); } } } } } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.warn("Error inspecting tasks to cancel on demotion: "+e, e); } if (!exceptions.isEmpty()) LOG.warn("Error when cancelling tasks on demotion: "+Exceptions.create(exceptions)); if (tasks>0) LOG.info("Cancelled "+tasks+" tasks on demotion"); }</code><technical_language>exception t.cancel(true) throw - is cautious? harm try-catch I guess</technical_language>

Target:
protected void onDemotion() { managementContext.getRebindManager().stop(); for (Application app: managementContext.getApplications()) Entities.unmanage(app); Collection<Exception> exceptions = MutableSet.of(); int tasks = 0; LOG.debug("Cancelling tasks on demotion"); try { for (Entity entity: managementContext.getEntityManager().getEntities()) { for (Task<?> t: managementContext.getExecutionContext(entity).getTasks()) { if (!t.isDone()) { tasks++; try { LOG.debug("Cancelling "+t+" on "+entity); t.cancel(true); } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.debug("Error cancelling "+t+" on "+entity+" (will warn when all tasks are cancelled): "+e, e); exceptions.add(e); } } } } } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.warn("Error inspecting tasks to cancel on demotion: "+e, e); } if (!exceptions.isEmpty()) LOG.warn("Error when cancelling tasks on demotion: "+Exceptions.create(exceptions)); if (tasks>0) LOG.info("Cancelled "+tasks+" tasks on demotion"); }
Source:
<code><START> public void testGetModulesByClass() { <END> Iterable<IAnalysisModule> modules = fTrace.getAnalysisModules(); assertFalse(modules.iterator().hasNext()); fTrace.traceOpened(new TmfTraceOpenedSignal(this, fTrace, null)); modules = fTrace.getAnalysisModules(); Iterable<TestAnalysis> testModules = TmfTraceUtils.getAnalysisModulesOfClass(fTrace, TestAnalysis.class); assertTrue(modules.iterator().hasNext()); assertTrue(testModules.iterator().hasNext()); for (IAnalysisModule module : modules) { if (module instanceof TestAnalysis) { IAnalysisModule otherModule = fTrace.getAnalysisModule(module.getId()); assertNotNull(otherModule); assertTrue(otherModule.equals(module)); } } }</code><technical_language>Actually, part of this test method stayed in test trace tests (wrongly) getAnalysisModules trace. correct push again</technical_language>

Target:
public void testGetModulesByClass() { fTrace.traceOpened(new TmfTraceOpenedSignal(this, fTrace, null)); Iterable<TestAnalysis> testModules = TmfTraceUtils.getAnalysisModulesOfClass(fTrace, TestAnalysis.class); assertTrue(testModules.iterator().hasNext()); int count = 0; for (TestAnalysis module : testModules) { assertNotNull(module); count++; } assertEquals(2, count); TestAnalysis module = TmfTraceUtils.getAnalysisModuleOfClass(fTrace, TestAnalysis.class, AnalysisManagerTest.MODULE_PARAM); assertNotNull(module); IAnalysisModule traceModule = fTrace.getAnalysisModule(AnalysisManagerTest.MODULE_PARAM); assertNotNull(traceModule); assertEquals(module, traceModule); }
Source:
<code>public void arrow_function_expression_scope() throws Exception { Scope scope = getScopeFor(Kind.ARROW_FUNCTION_EXPRESSION); assertThat(scope.getSymbols(Symbol.Kind.PARAMETER)).extracting(Symbol::name).containsExactly("$a"); <START> assertThat(scope.getSymbols(Symbol.Kind.VARIABLE)).isEmpty(); <END> assertThat(scope.getSymbol("$c", Symbol.Kind.VARIABLE)).isNotNull(); }</code><technical_language>discussed captured variables symbols modified independently. This case here</technical_language>

Target:
public void arrow_function_expression_scope() throws Exception { Scope scope = getScopeFor(Kind.ARROW_FUNCTION_EXPRESSION); assertThat(scope.getSymbols(Symbol.Kind.PARAMETER)).extracting(Symbol::name).containsExactlyInAnyOrder("$a", "$d"); assertThat(scope.getSymbols(Symbol.Kind.VARIABLE)).isEmpty(); Symbol symbolC = scope.getSymbol("$c"); Symbol symbolD = scope.getSymbol("$d"); assertThat(symbolC).isNotNull(); assertThat(symbolC.kind()).isEqualTo(Symbol.Kind.VARIABLE); assertThat(symbolD).isNotNull(); assertThat(scope.getSymbol("$d", Symbol.Kind.PARAMETER)).isEqualTo(symbolD); assertThat(scope.getSymbol("$d", Symbol.Kind.VARIABLE)).isNull(); Scope functionScope = getScopeFor(Kind.FUNCTION_DECLARATION); assertThat(symbolC).isEqualTo(functionScope.getSymbol("$c")); assertThat(symbolD).isNotEqualTo(functionScope.getSymbol("$d")); }
Source:
<code>public CompletableFuture<Optional<InetAddress>> lookup(String hostname) { <START> if (lookupEnabled) { <END> return circuitBreaker.executeCompletionStage(() -> { final NettyResolverContext resolverContext = iterator.next(); final Timer.Context timerContext = lookupTimer.time(); return resolverContext.lookup(hostname).whenComplete((res, ex) -> { timerContext.stop(); }); }).toCompletableFuture(); } else { return CompletableFuture.completedFuture(Optional.empty()); } }</code><technical_language>DnsResolver is designed a shared service solely for flows (even right now.) If want disable lookups avoiding calls DnsResolver altogether in specific components disabling service globally</technical_language>

Target:
public CompletableFuture<Optional<InetAddress>> lookup(String hostname) { return circuitBreaker.executeCompletionStage(() -> { final NettyResolverContext resolverContext = iterator.next(); final Timer.Context timerContext = lookupTimer.time(); return resolverContext.lookup(hostname).whenComplete((res, ex) -> { timerContext.stop(); }); }).toCompletableFuture(); }
Source:
<code>public int hashCode() { int result = dataStoreName != null ? dataStoreName.hashCode() : 0; <START> result = 31 * result + (ascending ? 1 : 0); <END> return result; }</code><technical_language>suggestion result = 31 * result + (ascending ? 1 : 0); result = ~~result;</technical_language>

Target:
public int hashCode() { int result = dataStoreName != null ? dataStoreName.hashCode() : 0; result = 31 * result + (ascending ? 1 : 0); result = ~~result; return result; }
Source:
<code>public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<RowExpression> context) { RowExpression inheritedPredicate = context.get(); <START> if (!extractConjuncts(inheritedPredicate).contains(new SymbolReference(node.getSemiJoinOutput().getName()))) { <END> return visitNonFilteringSemiJoin(node, context); } return visitFilteringSemiJoin(node, context); }</code><technical_language>SymbolReference is issue</technical_language>

Target:
public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<RowExpression> context) { RowExpression inheritedPredicate = context.get(); if (!extractConjuncts(inheritedPredicate).contains(node.getSemiJoinOutput())) { return visitNonFilteringSemiJoin(node, context); } return visitFilteringSemiJoin(node, context); }
Source:
<code>public void testSuccess() throws Exception { Parameter param = new Parameter(); param.setName("param1"); param.setValue("abs"); param.setSessionKey("*"); session1.put("param1","yarr"); pipe.addParameter(param); pipe.setLookupAtRuntime(true); pipe.setFileName(sourceFolderPath); pipe.setReplaceFrom("param1"); pipe.setReplaceTo("kar"); pipe.setReturnString("${param1}andandandparam2"); pipe.configure(); PipeRunResult res = doPipe(pipe, "whatisthis", session1); <START> assertEquals(res.getResult().toString(), "String: inside the file"); <END> }</code><technical_language>toString appends type of object used. In this case a String. String: prefix. If asString() convert object in getResult() a string</technical_language>

Target:
public void testSuccess() throws Exception { Parameter param = setUp(session1); pipe.addParameter(param); pipe.setLookupAtRuntime(true); pipe.setFileName(sourceFolderPath); pipe.setReplaceFrom("param1"); pipe.setReplaceTo("kar"); pipe.setReturnString("${param1}andandandparam2"); pipe.configure(); PipeRunResult res = doPipe(pipe, "whatisthis", session1); assertEquals(res.getResult().asString(), "inside the file"); }
Source:
<code>public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); out.writeInt(backupCount); out.writeInt(asyncBackupCount); out.writeInt(timeToLiveSeconds); out.writeInt(maxIdleSeconds); out.writeObject(maxSizeConfig); out.writeUTF(evictionPolicy.name()); out.writeObject(mapEvictionPolicy); out.writeObject(mapStoreConfig); out.writeObject(nearCacheConfig); out.writeBoolean(readBackupData); out.writeUTF(cacheDeserializedValues.name()); out.writeObject(mergePolicyConfig); out.writeUTF(inMemoryFormat.name()); out.writeObject(wanReplicationRef); writeNullableList(entryListenerConfigs, out); writeNullableList(partitionLostListenerConfigs, out); writeNullableList(mapIndexConfigs, out); writeNullableList(mapAttributeConfigs, out); writeNullableList(queryCacheConfigs, out); out.writeBoolean(statisticsEnabled); out.writeObject(partitioningStrategyConfig); out.writeUTF(quorumName); out.writeObject(hotRestartConfig); <START> out.writeShort(preprocessingPolicy.getId()); <END> }</code><technical_language>Missing RU support</technical_language>

Target:
public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); out.writeInt(backupCount); out.writeInt(asyncBackupCount); out.writeInt(timeToLiveSeconds); out.writeInt(maxIdleSeconds); out.writeObject(maxSizeConfig); out.writeUTF(evictionPolicy.name()); out.writeObject(mapEvictionPolicy); out.writeObject(mapStoreConfig); out.writeObject(nearCacheConfig); out.writeBoolean(readBackupData); out.writeUTF(cacheDeserializedValues.name()); out.writeObject(mergePolicyConfig); out.writeUTF(inMemoryFormat.name()); out.writeObject(wanReplicationRef); writeNullableList(entryListenerConfigs, out); writeNullableList(partitionLostListenerConfigs, out); writeNullableList(mapIndexConfigs, out); writeNullableList(mapAttributeConfigs, out); writeNullableList(queryCacheConfigs, out); out.writeBoolean(statisticsEnabled); out.writeObject(partitioningStrategyConfig); out.writeUTF(quorumName); out.writeObject(hotRestartConfig); if (out.getVersion().isGreaterOrEqual(Versions.V3_12)) { out.writeShort(metadataPolicy.getId()); } }
Source:
<code>public void close() { if (enabled.compareAndSet(true, false)) { List<Runnable> pendingTasks = scheduler.shutdownNow(); for (Runnable task : pendingTasks) { if (task instanceof CryptoJob) { ((CryptoJob) task).closeJob(CLOSED_EXCEPTION); } else { logger.error("Unknown type of job seen : " + task.getClass()); } } try { <START> scheduler.awaitTermination(10000, TimeUnit.MILLISECONDS); <END> } catch (Exception e) { logger.error("Unexpected exception while waiting for crypto jobs to terminate", e); } } }</code><technical_language>reason increase it</technical_language>

Target:
public void close() { if (enabled.compareAndSet(true, false)) { List<Runnable> pendingTasks = scheduler.shutdownNow(); for (Runnable task : pendingTasks) { if (task instanceof CryptoJob) { ((CryptoJob) task).closeJob(CLOSED_EXCEPTION); } else { logger.error("Unknown type of job seen : " + task.getClass()); } } try { scheduler.awaitTermination(1000, TimeUnit.MILLISECONDS); } catch (Exception e) { logger.error("Unexpected exception while waiting for crypto jobs to terminate", e); } } }
Source:
<code>public void start() { synchronized (stateLock) { Preconditions.checkState(!started, "already started"); DataSourceMetadata metadata = metadataStorageCoordinator.getDataSourceMetadata(dataSource); if (null == metadata) { metadataStorageCoordinator.insertDataSourceMetadata( dataSource, new DerivativeDataSourceMetadata(spec.getBaseDataSource(), spec.getDimensions(), spec.getMetrics()) ); } exec = MoreExecutors.listeningDecorator(Execs.scheduledSingleThreaded(supervisorId)); final Duration delay = config.getTaskCheckDuration().toStandardDuration(); future = exec.scheduleWithFixedDelay( new Runnable() { @Override public void run() { try { <START> DataSourceMetadata metadata = metadataStorageCoordinator.getDataSourceMetadata(dataSource); <END> if (metadata != null && metadata instanceof DerivativeDataSourceMetadata && spec.getBaseDataSource().equals(((DerivativeDataSourceMetadata) metadata).getBaseDataSource()) && spec.getDimensions().equals(((DerivativeDataSourceMetadata) metadata).getDimensions()) && spec.getMetrics().equals(((DerivativeDataSourceMetadata) metadata).getMetrics())) { checkSegmentsAndSubmitTasks(); } else { log.error("Failed to start %s. Metadata in database(%s) is different from new dataSource metadata(%s)", supervisorId, metadata, spec); } } catch (Exception e) { log.makeAlert(e, StringUtils.format("uncaught exception in %s.", supervisorId)).emit(); } } }, 0, delay.getMillis(), TimeUnit.MILLISECONDS ); started = true; } }</code><technical_language>is metadata null? I feel a bug exception thrown</technical_language>

Target:
public void start() { synchronized (stateLock) { Preconditions.checkState(!started, "already started"); DataSourceMetadata metadata = metadataStorageCoordinator.getDataSourceMetadata(dataSource); if (null == metadata) { metadataStorageCoordinator.insertDataSourceMetadata( dataSource, new DerivativeDataSourceMetadata(spec.getBaseDataSource(), spec.getDimensions(), spec.getMetrics()) ); } exec = MoreExecutors.listeningDecorator(Execs.scheduledSingleThreaded(supervisorId)); final Duration delay = config.getTaskCheckDuration().toStandardDuration(); future = exec.scheduleWithFixedDelay( new Runnable() { @Override public void run() { try { DataSourceMetadata metadata = metadataStorageCoordinator.getDataSourceMetadata(dataSource); if (metadata instanceof DerivativeDataSourceMetadata && spec.getBaseDataSource().equals(((DerivativeDataSourceMetadata) metadata).getBaseDataSource()) && spec.getDimensions().equals(((DerivativeDataSourceMetadata) metadata).getDimensions()) && spec.getMetrics().equals(((DerivativeDataSourceMetadata) metadata).getMetrics())) { checkSegmentsAndSubmitTasks(); } else { log.error( "Failed to start %s. Metadata in database(%s) is different from new dataSource metadata(%s)", supervisorId, metadata, spec ); } } catch (Exception e) { log.makeAlert(e, StringUtils.format("uncaught exception in %s.", supervisorId)).emit(); } } }, 0, delay.getMillis(), TimeUnit.MILLISECONDS ); started = true; } }