auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void saveFactors(final DmsProject measurementDataset, final List<MeasurementVariable> variables) { if (variables != null && !variables.isEmpty()) { for (final MeasurementVariable variable : variables) { <START> switch (variable.getOperation().toString()) { <END> case "ADD": final int rank = this.getNextRank(measurementDataset); this.insertVariable(measurementDataset, variable, rank); break; case "DELETE": this.deleteVariableForFactors(measurementDataset, variable); break; default: break; } } } }</code><technical_language>compare enum</technical_language>

Target:
public void saveFactors(final DmsProject measurementDataset, final List<MeasurementVariable> variables) { if (variables != null && !variables.isEmpty()) { for (final MeasurementVariable variable : variables) { switch (variable.getOperation()) { case ADD: final int rank = this.getNextRank(measurementDataset); this.insertVariable(measurementDataset, variable, rank); break; case DELETE: this.deleteVariableForFactors(measurementDataset, variable); break; default: break; } } } }
Source:
<code>private void addSSLPortToJson(JSONObject jsonObject) throws JSONException { for (PortType portType : ports.keySet()) { <START> if (portType != PortType.PLAINTEXT) { <END> jsonObject.put("sslport", ports.get(portType)); } } }</code><technical_language>checking for portType == PortType.SSL? right check</technical_language>

Target:
private void addSSLPortToJson(JSONObject jsonObject) throws JSONException { for (PortType portType : ports.keySet()) { if (portType == PortType.SSL) { jsonObject.put("sslport", ports.get(portType)); } } }
Source:
<code>private static double averageColumn(double[][] arrayOfArrays, int columnIndex) { double sum = 0; int count = 0; StringBuilder values = new StringBuilder(); for (double[] array : arrayOfArrays) { double value = array[columnIndex]; values.append(value).append(' '); <START> if (value == NA || value == NSU) { <END> continue; } sum += value; count++; } double average = count == 0 ? NA : (double) (sum / count); String logMessage = "Average(" + values.toString().trim() + ") = " + average; log.fine(replaceMagicNumbers(logMessage)); return average; }</code><technical_language>This condition == NA || == NSU extracted out</technical_language>

Target:
private static double averageColumn(double[][] arrayOfArrays, int columnIndex) { double sum = 0; int count = 0; StringBuilder values = new StringBuilder(); for (double[] array : arrayOfArrays) { double value = array[columnIndex]; values.append(value).append(' '); if (isValidSpecialValue(value)) { continue; } sum += value; count++; } double average = count == 0 ? NA : (double) (sum / count); String logMessage = "Average(" + values.toString().trim() + ") = " + average; log.fine(replaceMagicNumbers(logMessage)); return average; }
Source:
<code>public void updateOnMediaChanged(String blogId, String mediaId) { if (mediaId == null) { return; } <START> Cursor cursor = WordPress.wpDB.getMediaFile(blogId, mediaId); <END> if (cursor == null || !cursor.moveToFirst()) { mMediaGridFragment.removeFromMultiSelect(mediaId); mMediaGridFragment.refreshMediaFromDB(); if (mMediaEditFragment != null && mMediaEditFragment.isVisible() && mediaId.equals(mMediaEditFragment.getMediaId())) { if (mMediaEditFragment.isInLayout()) { mMediaEditFragment.loadMedia(null); } else { getFragmentManager().popBackStack(); } } } else { mMediaGridFragment.refreshMediaFromDB(); } if (cursor != null) { cursor.close(); } }</code><technical_language>addition of event(s) this routine called frequently, opening a cursor simply check media file exists. more efficient add a routine this WordPressDB? public boolean mediaFileExists(String blogId, String mediaId) { return SqlUtils.boolForQuery(db, "SELECT 1 " + MEDIA_TABLE + " blogId=? mediaId=?", new String[]{blogId, mediaId}); }</technical_language>

Target:
public void updateOnMediaChanged(String blogId, String mediaId) { if (mediaId == null) { return; } if (!WordPress.wpDB.mediaFileExists(blogId, mediaId)) { mMediaGridFragment.removeFromMultiSelect(mediaId); if (mMediaEditFragment != null && mMediaEditFragment.isVisible() && mediaId.equals(mMediaEditFragment.getMediaId())) { if (mMediaEditFragment.isInLayout()) { mMediaEditFragment.loadMedia(null); } else { getFragmentManager().popBackStack(); } } } mMediaGridFragment.refreshMediaFromDB(); mMediaGridFragment.updateFilterText(); mMediaGridFragment.updateSpinnerAdapter(); }
Source:
<code>void put(SystemStreamPartition ssp, Object key, Object message) { List<IncomingMessageEnvelope> messages = bufferedMessages.get(ssp); String offset = String.valueOf(messages.size()); if (message instanceof EndOfStreamMessage) { offset = IncomingMessageEnvelope.END_OF_STREAM_OFFSET; } IncomingMessageEnvelope messageEnvelope = new IncomingMessageEnvelope(ssp, offset, key, message, <START> 0, 0L, System.nanoTime()); <END> bufferedMessages.get(ssp) .add(messageEnvelope); }</code><technical_language>nanoTime != epoch millis in nanos</technical_language>

Target:
void put(SystemStreamPartition ssp, Object key, Object message) { List<IncomingMessageEnvelope> messages = bufferedMessages.get(ssp); String offset = String.valueOf(messages.size()); if (message instanceof EndOfStreamMessage) { offset = IncomingMessageEnvelope.END_OF_STREAM_OFFSET; } IncomingMessageEnvelope messageEnvelope = new IncomingMessageEnvelope(ssp, offset, key, message, 0, 0L, Instant.now().toEpochMilli()); bufferedMessages.get(ssp) .add(messageEnvelope); }
Source:
<code>public final Timestamp addMillis(long amount) { if (amount == 0 && _precision == Precision.SECOND && _fraction != null && _fraction.scale() >= 3) { return this; } long seconds = amount / 1000; BigDecimal millis = BigDecimal.valueOf(amount % 1000).movePointLeft(3); if (_fraction != null) { millis = _fraction.add(millis); } BigDecimal newFraction; if (BigDecimal.ONE.compareTo(millis) <= 0) { newFraction = millis.subtract(BigDecimal.ONE); seconds += 1; } else if (BigDecimal.ZERO.compareTo(millis) > 0) { newFraction = BigDecimal.ONE.add(millis); seconds -= 1; } else { newFraction = millis; } Timestamp ts = this; <START> do { <END> int incrementalSeconds; if (seconds > Integer.MAX_VALUE) { incrementalSeconds = Integer.MAX_VALUE; } else if (seconds < Integer.MIN_VALUE) { incrementalSeconds = Integer.MIN_VALUE; } else { incrementalSeconds = (int)seconds; } ts = ts.addSecond(incrementalSeconds); seconds -= incrementalSeconds; } while (seconds != 0); ts._fraction = newFraction; return ts; }</code><technical_language>suggest encapsulating this loop a private Timestamp addSecond(long seconds) method</technical_language>

Target:
public final Timestamp addMillis(long amount) { if (amount == 0 && _precision == Precision.SECOND && _fraction != null && _fraction.scale() >= 3) { return this; } long seconds = amount / 1000; BigDecimal millis = BigDecimal.valueOf(amount % 1000).movePointLeft(3); if (_fraction != null) { millis = _fraction.add(millis); } BigDecimal newFraction; if (BigDecimal.ONE.compareTo(millis) <= 0) { newFraction = millis.subtract(BigDecimal.ONE); seconds += 1; } else if (BigDecimal.ZERO.compareTo(millis) > 0) { newFraction = BigDecimal.ONE.add(millis); seconds -= 1; } else { newFraction = millis; } Timestamp ts = addSecond(seconds); ts._fraction = newFraction; return ts; }
Source:
<code>public void doOnTerminateError() { final AtomicBoolean atomicBoolean = new AtomicBoolean(); Single s = Single.error(new TestException()).doOnTerminate(new Action() { @Override public void run() { atomicBoolean.set(true); } }); <START> try { <END> s.blockingGet(); Assert.fail("Did dot throw exception"); } catch (TestException e) { } assertTrue(atomicBoolean.get()); }</code><technical_language>testing style change</technical_language>

Target:
public void doOnTerminateError() { final AtomicBoolean atomicBoolean = new AtomicBoolean(); Single.error(new TestException()).doOnTerminate(new Action() { @Override public void run() { atomicBoolean.set(true); } }) .test() .assertFailure(TestException.class); assertTrue(atomicBoolean.get()); }
Source:
<code>public void authenticate_shouldThrowDisabledExceptionIfUserIsInactive() { final String shogun2UserName = "user"; final String correctPassword = "correctPassword"; final User userToAuth = createUserMock(shogun2UserName, correctPassword); <START> <END> Authentication authRequest = mock(Authentication.class); when(authRequest.getName()).thenReturn(shogun2UserName); when(authRequest.getCredentials()).thenReturn(correctPassword); when(userService.findByAccountName(shogun2UserName)).thenReturn(userToAuth); authProvider.authenticate(authRequest); }</code><technical_language>Please set active flag explicitly false (although is default value). Possibly sense refactor createUserMock method adding additional parameter active...!</technical_language>

Target:
public void authenticate_shouldThrowDisabledExceptionIfUserIsInactive() { final String shogun2UserName = "user"; final String correctPassword = "correctPassword"; final User userToAuth = createUserMock(shogun2UserName, correctPassword); userToAuth.setActive(false); Authentication authRequest = mock(Authentication.class); when(authRequest.getName()).thenReturn(shogun2UserName); when(authRequest.getCredentials()).thenReturn(correctPassword); when(userService.findByAccountName(shogun2UserName)).thenReturn(userToAuth); authProvider.authenticate(authRequest); }
Source:
<code>public void run() { try { while (!Thread.interrupted() && !conn.isClosed()) { try { ResultSet resultSet = conn.createStatement().executeQuery( "SELECT * FROM " + PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME); if (resultSet.next()) { <START> isSysMutexEmpty.getAndSet(false); <END> break; } } catch (SQLException e) { if (conn.isClosed()) { Thread.currentThread().interrupt(); } else { LOGGER.error("Error while scanning , thread: {}", PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME, Thread.currentThread().getName(), e); } } } } catch (SQLException e) { LOGGER.error("Connection access error. Thread: {}", Thread.currentThread().getName(), e); } }</code><technical_language>this a simple set() returned right</technical_language>

Target:
public void run() { try (Connection conn = DriverManager.getConnection(getUrl(), props)) { while (!Thread.interrupted() && !conn.isClosed()) { try { ResultSet resultSet = conn.createStatement().executeQuery( "SELECT * FROM " + PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME + " WHERE TENANT_ID IS NULL AND TABLE_SCHEM='" + schemaName + "' AND TABLE_NAME='" + tableName + "' AND COLUMN_NAME IS NULL AND COLUMN_FAMILY IS NULL"); if (resultSet.next()) { isSysMutexEmpty.set(false); break; } } catch (SQLException e) { if (conn.isClosed()) { Thread.currentThread().interrupt(); } else { LOGGER.error("Error while scanning , thread: {}", PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME, Thread.currentThread().getName(), e); } } } } catch (SQLException e) { LOGGER.error("Connection access error. Thread: {}", Thread.currentThread().getName(), e); } }
Source:
<code><START> public static String cpu() { <END> return Objects.requireNonNull(org.eclipse.tracecompass.tmf.core.event.aspect.Messages.AspectName_CPU); }</code><technical_language>@NonNull, push a fix</technical_language>

Target:
public static @NonNull String cpu() { return Objects.requireNonNull(org.eclipse.tracecompass.tmf.core.event.aspect.Messages.AspectName_CPU); }
Source:
<code>protected void onRequestSuggestions(final Request req, final Callback callback) { RpcStatus.hide(new Runnable() { public void run() { SuggestUtil.SVC.suggestLabel(changeId, new GerritCallback<Set<ChangeLabel.LabelKey>>() { public void onSuccess(final Set<ChangeLabel.LabelKey> result) { <START> final Set<StringSuggestion> r = new HashSet<StringSuggestion>(); <END> for (ChangeLabel.LabelKey p : result) { if (!labelsToExclude.contains(p)) { r.add(new StringSuggestion(p.get())); } } callback.onSuggestionsReady(req, new Response(r)); } }); } }); }</code><technical_language>Seed size result.size</technical_language>

Target:
protected void onRequestSuggestions(final Request req, final Callback callback) { RpcStatus.hide(new Runnable() { public void run() { SuggestUtil.SVC.suggestLabel(changeId, new GerritCallback<Set<ChangeLabel.LabelKey>>() { public void onSuccess(final Set<ChangeLabel.LabelKey> result) { result.removeAll(labelsToExclude); final Set<StringSuggestion> r = new HashSet<StringSuggestion>(result.size()); for (ChangeLabel.LabelKey l : result) { r.add(new StringSuggestion(l.get())); } callback.onSuggestionsReady(req, new Response(r)); } }); } }); }
Source:
<code>protected Collection<Geocache> doImport() throws IOException, ParserException { Log.i("Import LOC from uri: " + uri); importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_READ_FILE, R.string.gpx_import_loading_caches, -1)); final InputStream is = contentResolver.openInputStream(uri); final LocParser parser = new LocParser(listId); try { return parser.parse(is, progressHandler); } finally { if (is != null) { is.close(); <START> } <END> } }</code><technical_language>Please IOUtils.closeQuietly(is); instead then</technical_language>

Target:
protected Collection<Geocache> doImport() throws IOException, ParserException { Log.i("Import LOC from uri: " + uri); importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_READ_FILE, R.string.gpx_import_loading_caches, -1)); final InputStream is = contentResolver.openInputStream(uri); final LocParser parser = new LocParser(listId); try { return parser.parse(is, progressHandler); } finally { IOUtils.closeQuietly(is); } }
Source:
<code><START> protected static BibDatabaseContext createContext(Field field, String value, MetaData metaData) { <END> BibEntry entry = new BibEntry(); entry.setField(field, value); BibDatabase bibDatabase = new BibDatabase(); bibDatabase.insertEntry(entry); return new BibDatabaseContext(bibDatabase, metaData); }</code><technical_language>modifier changed? Is this method of this class? private. Adding static is OK for me</technical_language>

Target:
private BibDatabaseContext createContext(Field field, String value, MetaData metaData) { BibEntry entry = new BibEntry(); entry.setField(field, value); BibDatabase bibDatabase = new BibDatabase(); bibDatabase.insertEntry(entry); return new BibDatabaseContext(bibDatabase, metaData); }
Source:
<code>public Iterable<Tuple> performEvaluation(final Tuple input) { final Object result = evaluateTerm(input); if (result != null) { if (this.isUnwinding) { <START> if (result instanceof Set<?>) { <END> return () -> { final Iterator<?> wrapped = ((Set<?>) result).iterator(); return new Iterator<Tuple>() { @Override public boolean hasNext() { return wrapped.hasNext(); } @Override public Tuple next() { final Object next = wrapped.next(); return Tuples.staticArityLeftInheritanceTupleOf(input, runtimeContext.wrapElement(next)); } }; }; } else { throw new IllegalStateException( "This is an unwinding evaluator, but the evaluation yielded " + result); } } else { return Collections.singleton( Tuples.staticArityLeftInheritanceTupleOf(input, runtimeContext.wrapElement(result))); } } else { return null; } }</code><technical_language>if is a Set Iterable, create a new Set iterate set... this gentler query authors, do do this</technical_language>

Target:
public Iterable<Tuple> performEvaluation(final Tuple input) { final Object result = evaluateTerm(input); if (result != null) { if (this.isUnwinding) { final Set<?> resultAsSet = (result instanceof Set<?>) ? (Set<?>) result : (result instanceof Iterable<?>) ? Sets.newHashSet((Iterable<?>) result) : null; if (resultAsSet != null) { return () -> { final Iterator<?> wrapped = resultAsSet.iterator(); return new Iterator<Tuple>() { @Override public boolean hasNext() { return wrapped.hasNext(); } @Override public Tuple next() { final Object next = wrapped.next(); return Tuples.staticArityLeftInheritanceTupleOf(input, runtimeContext.wrapElement(next)); } }; }; } else { throw new IllegalStateException( "This is an unwinding evaluator, which expects the evaluation result to either be a set or an iterable, but it was " + result); } } else { return Collections.singleton( Tuples.staticArityLeftInheritanceTupleOf(input, runtimeContext.wrapElement(result))); } } else { return null; } }
Source:
<code>protected OperationRequest makeOperationRequest(ReplicaId replicaId) { <START> if(!sslEnabledColos.contains(replicaId.getDataNodeId().getDatacenterName())) { <END> return new GetBlobOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, makeGetRequest(), clusterMap, this, false); } else{ return new GetBlobOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, makeGetRequest(), clusterMap, this, true); } }</code><technical_language>again</technical_language>

Target:
protected OperationRequest makeOperationRequest(ReplicaId replicaId) { return new GetBlobOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, makeGetRequest(), clusterMap, this); }
Source:
<code>private static PRPAMT201306UV02LivingSubjectId createSubjectId(II subjectId) { <START> PRPAMT201306UV02LivingSubjectId id = new PRPAMT201306UV02LivingSubjectId(); <END> if (subjectId != null) { id.getValue().add(subjectId); } return id; }</code><technical_language>If subjectId is null, return a blank PRPAMT201306UV02LivingSubjectId, null</technical_language>

Target:
private static PRPAMT201306UV02LivingSubjectId createSubjectId(II subjectId) { PRPAMT201306UV02LivingSubjectId id = new PRPAMT201306UV02LivingSubjectId(); id.getValue().add(subjectId); return id; }
Source:
<code><START> public RetryPolicy(RetryPolicyOptions retryPolicyOptions) { <END> this.retryPolicyOptions = Objects.requireNonNull(retryPolicyOptions, "'retryPolicyOptions' cannot be null."); }</code><technical_language>This is API breaking change</technical_language>

Target:
public RetryPolicy(RetryPolicyOptions retryPolicyOptions) { this.retryPolicyOptions = Objects.requireNonNull(retryPolicyOptions, "'retryPolicyOptions' cannot be null."); Objects.requireNonNull(retryPolicyOptions.getRetryStrategy(), "'retryPolicyOptions.retryStrategy' cannot be null."); }
Source:
<code>@Override public boolean onCreate() { <START> Picasso.setSingletonInstance(new Picasso.Builder(getContext()).build()); <END> return true; }</code><technical_language>if want override singleton instance, then, need remove ContentProvider manifest, right? is another way</technical_language>

Target:
@Override public boolean onCreate() { context = getContext(); return true; }
Source:
<code>public void onServerStarting(FMLServerStartingEvent event) { event.registerServerCommand(new MiningDimensionTest.DimensionTestCommand()); <START> System.out.println("MiningDimensionTest Registered command /mining <int>"); <END> for (File file : new File(event.getServer().isSinglePlayer() ? "saves" : ".").listFiles()) { if (file.isFile() || !file.getName().startsWith(savefoldername)) continue; String sint = file.getName().replace(savefoldername, ""); if (!sint.isEmpty() && isInteger(sint)) { miningid = Integer.valueOf(sint); DimensionManager.registerDimension(miningid, dimtypetest); System.out.println("Found OFFLINE mining dimension " + miningid); break; } } }</code><technical_language>Please logger get FMLPreInitializationEvent#getModLog instead of System.out</technical_language>

Target:
public void onServerStarting(FMLServerStartingEvent event) { event.registerServerCommand(new MiningDimensionTest.DimensionTestCommand()); logger.info("MiningDimensionTest Registered command /mining <int>"); for (File file : new File(event.getServer().isSinglePlayer() ? "saves" : ".").listFiles()) { if (file.isFile() || !file.getName().startsWith(savefoldername)) continue; String sint = file.getName().replace(savefoldername, ""); if (!sint.isEmpty() && isInteger(sint)) { miningid = Integer.valueOf(sint); DimensionManager.registerDimension(miningid, dimtypetest); logger.info("Found OFFLINE mining dimension " + miningid); break; } } }
Source:
<code>private AuditLogableBase getLoggableQuotaStorageParams(String quotaName, double storageUsagePercentage, double storageRequestedPercentage) { AuditLogableBase logable = new AuditLogableBase(); <START> logable.getUserName(); <END> logable.AddCustomValue("QuotaName", quotaName); logable.AddCustomValue("CurrentStorage", String.valueOf((int)storageUsagePercentage)); logable.AddCustomValue("Requested", String.valueOf((int)storageRequestedPercentage)); return logable; }</code><technical_language>point of ? is assigned variable if assigned, null... I delete line</technical_language>

Target:
private AuditLogableBase getLoggableQuotaStorageParams(String quotaName, double storageUsagePercentage, double storageRequestedPercentage) { AuditLogableBase logable = new AuditLogableBase(); logable.AddCustomValue("QuotaName", quotaName); logable.AddCustomValue("CurrentStorage", percentageFormatter.format(storageUsagePercentage)); logable.AddCustomValue("Requested", percentageFormatter.format(storageRequestedPercentage)); return logable; }
Source:
<code>public Set<UsbSerialDeviceInformation> scan() throws IOException { <START> Set<UsbSerialDeviceInformation> result = Sets.newHashSet(); <END> for (SerialPortInfo serialPortInfo : getSerialPortInfos()) { try { UsbSerialDeviceInformation usbSerialDeviceInfo = tryGetUsbSerialDeviceInformation(serialPortInfo); if (usbSerialDeviceInfo != null) { result.add(usbSerialDeviceInfo); } } catch (IOException e) { logger.warn( "Could not extract usb device information for serial port due to an IOException; message: {}", serialPortInfo, e.getMessage()); } } return result; }</code><technical_language>new HashSet<>();</technical_language>

Target:
public Set<UsbSerialDeviceInformation> scan() throws IOException { Set<UsbSerialDeviceInformation> result = new HashSet<>(); for (SerialPortInfo serialPortInfo : getSerialPortInfos()) { try { UsbSerialDeviceInformation usbSerialDeviceInfo = tryGetUsbSerialDeviceInformation(serialPortInfo); if (usbSerialDeviceInfo != null) { result.add(usbSerialDeviceInfo); } } catch (IOException e) { logger.warn("Could not extract USB device information for serial port {}: {}", serialPortInfo, e.getMessage()); } } return result; }
Source:
<code>public void cantOpenReadOnlyLogFiles() throws Exception { String serviceDir = PARAMETERS.TEST_TEMP_DIR; LogUnitServer s1 = new LogUnitServer(new ServerContextBuilder() .setLogPath(serviceDir) .setMemory(false) .build()); this.router.reset(); this.router.addServer(s1); final long LOW_ADDRESS = 0L; final String low_payload = "0"; final long MID_ADDRESS = 100L; final String mid_payload = "100"; final long HIGH_ADDRESS = 10000000L; final String high_payload = "100000"; final String streamName = "a"; rawWrite(LOW_ADDRESS, low_payload, streamName); rawWrite(MID_ADDRESS, mid_payload, streamName); rawWrite(HIGH_ADDRESS, high_payload, streamName); s1.shutdown(); String[] extension = {"log"}; File serviceDirectory = new File(serviceDir); Collection<File> files = FileUtils.listFiles(serviceDirectory, extension, true); for (File file : files) { try { boolean ok = file.setReadable(false); assertThat(ok).isEqualTo(true); } catch (SecurityException e) { assertThat("Should not hit security exception"+e.toString()); } } boolean readOnlyFailed = false; try { LogUnitServer s2 = new LogUnitServer(new ServerContextBuilder() .setLogPath(serviceDir) .setMemory(false) .build()); } catch (IllegalStateException e) { readOnlyFailed = true; } assertThat(readOnlyFailed).isEqualTo(true); <START> } <END></code><technical_language>fail() instead</technical_language>

Target:
public void cantOpenReadOnlyLogFiles() throws Exception { String serviceDir = PARAMETERS.TEST_TEMP_DIR; LogUnitServer s1 = new LogUnitServer(new ServerContextBuilder() .setLogPath(serviceDir) .setMemory(false) .build()); this.router.reset(); this.router.addServer(s1); final long LOW_ADDRESS = 0L; final String low_payload = "0"; final long MID_ADDRESS = 100L; final String mid_payload = "100"; final long HIGH_ADDRESS = 10000000L; final String high_payload = "100000"; final String streamName = "a"; rawWrite(LOW_ADDRESS, low_payload, streamName); rawWrite(MID_ADDRESS, mid_payload, streamName); rawWrite(HIGH_ADDRESS, high_payload, streamName); s1.shutdown(); try { File serviceDirectory = new File(serviceDir); serviceDirectory.setWritable(false); } catch(SecurityException e) { fail("Should not hit security exception"+e.toString()); } try { LogUnitServer s2 = new LogUnitServer(new ServerContextBuilder() .setLogPath(serviceDir) .setMemory(false) .build()); fail("Should have failed to startup in read-only mode"); } catch (UnrecoverableCorfuError e) { } File serviceDirectory = new File(serviceDir); serviceDirectory.setWritable(true); }
Source:
<code><START> public synchronized void processJavaElementChange(final JavaElementDelta delta, final IProgressMonitor progressMonitor) <END> throws CoreException { try { Logger.debug("Processing {}", delta); final IJavaElement element = delta.getElement(); final CompilationUnit ast = delta.getCompilationUnitAST(); final int deltaKind = delta.getKind(); if (element.getElementType() == IJavaElement.ANNOTATION) { processJavaAnnotationChange((IAnnotation) element, deltaKind, ast, progressMonitor); } else { processJavaElementChange(element, deltaKind, ast, progressMonitor); } } finally { progressMonitor.done(); setBuildStatus(Status.OK_STATUS); Logger.debug("Done processing Java changes."); } }</code><technical_language>this method change - need synchronized</technical_language>

Target:
public void processJavaElementChange(final JavaElementDelta delta, final IProgressMonitor progressMonitor) throws CoreException { try { Logger.debug("Processing {}", delta); readWriteLock.writeLock().lock(); final IJavaElement element = delta.getElement(); final CompilationUnit ast = delta.getCompilationUnitAST(); final int deltaKind = delta.getKind(); if (element.getElementType() == IJavaElement.ANNOTATION) { processJavaAnnotationChange((IAnnotation) element, deltaKind, ast, progressMonitor); } else { processJavaElementChange(element, deltaKind, ast, progressMonitor); } } finally { progressMonitor.done(); readWriteLock.writeLock().unlock(); setBuildStatus(Status.OK_STATUS); Logger.debug("Done processing Java changes."); } }
Source:
<code>public static String stripPathInformation(String osgiBundles) { StringBuilder result = new StringBuilder(); StringTokenizer tokenizer = new StringTokenizer(osgiBundles, ","); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); token = token.replaceAll("\\\\:|/:", ":"); int atIndex = token.indexOf('@'); String bundle = atIndex > 0 ? token.substring(0, atIndex) : token; bundle = bundle.trim(); if (bundle.startsWith(REFERENCE_PREFIX) && bundle.length() > REFERENCE_PREFIX.length()) bundle = bundle.substring(REFERENCE_PREFIX.length()); if (bundle.startsWith(PLATFORM_PREFIX) && bundle.length() > PLATFORM_PREFIX.length()) bundle = bundle.substring(PLATFORM_PREFIX.length()); if (bundle.startsWith(FILE_URL_PREFIX) && bundle.length() > FILE_URL_PREFIX.length()) bundle = bundle.substring(FILE_URL_PREFIX.length()); IPath path = new Path(bundle); String id = null; if (path.isAbsolute()) { id = getSymbolicName(bundle); } if (id == null) { id = path.lastSegment(); } if (id != null) { <START> int underscoreIndex = id.indexOf("_64"); <END> underscoreIndex = id.indexOf('_', underscoreIndex + 1); if (underscoreIndex >= 0) { id = id.substring(0, underscoreIndex); } if (id.endsWith(JAR_EXTENSION)) { id = id.substring(0, id.length() - 4); } } if (result.length() > 0) result.append(","); result.append(id != null ? id : bundle); if (atIndex > -1) result.append(token.substring(atIndex).trim()); } return result.toString(); }</code><technical_language>strings reference\:file\:org.eclipse.core.filesystem.nl_de_4.7.0.v20170819060001.jar ? underscores valid in version qualifiers? If not, switching lastIndexOf solve both</technical_language>

Target:
public static String stripPathInformation(String osgiBundles) { StringBuilder result = new StringBuilder(); StringTokenizer tokenizer = new StringTokenizer(osgiBundles, ","); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); token = token.replaceAll("\\\\:|/:", ":"); int atIndex = token.indexOf('@'); String bundle = atIndex > 0 ? token.substring(0, atIndex) : token; bundle = bundle.trim(); if (bundle.startsWith(REFERENCE_PREFIX) && bundle.length() > REFERENCE_PREFIX.length()) bundle = bundle.substring(REFERENCE_PREFIX.length()); if (bundle.startsWith(PLATFORM_PREFIX) && bundle.length() > PLATFORM_PREFIX.length()) bundle = bundle.substring(PLATFORM_PREFIX.length()); if (bundle.startsWith(FILE_URL_PREFIX) && bundle.length() > FILE_URL_PREFIX.length()) bundle = bundle.substring(FILE_URL_PREFIX.length()); IPath path = new Path(bundle); String id = null; if (path.isAbsolute()) { id = getSymbolicName(bundle); } if (id == null) { id = path.lastSegment(); } if (id != null) { id = PATTERN_BUNDLE_VERSION.matcher(id).replaceFirst(""); if (id.endsWith(JAR_EXTENSION)) { id = id.substring(0, id.length() - 4); } } if (result.length() > 0) result.append(","); result.append(id != null ? id : bundle); if (atIndex > -1) result.append(token.substring(atIndex).trim()); } return result.toString(); }
Source:
<code>public synchronized LeaderAndEpoch currentLeader(TopicPartition topicPartition) { Optional<MetadataResponse.PartitionMetadata> maybeMetadata = partitionMetadataIfCurrent(topicPartition); if (!maybeMetadata.isPresent()) return new LeaderAndEpoch(Optional.empty(), Optional.ofNullable(lastSeenLeaderEpochs.get(topicPartition))); MetadataResponse.PartitionMetadata partitionMetadata = maybeMetadata.get(); <START> Optional<Integer> leaderEpoch = partitionMetadata.leaderEpoch; <END> Optional<Node> leaderNodeOpt = cache.nodeById(partitionMetadata.leaderId); return new LeaderAndEpoch(leaderNodeOpt, leaderEpoch); }</code><technical_language>Nit: this a leaderEpochOpt for consistency leaderNodeOpt</technical_language>

Target:
public synchronized LeaderAndEpoch currentLeader(TopicPartition topicPartition) { Optional<MetadataResponse.PartitionMetadata> maybeMetadata = partitionMetadataIfCurrent(topicPartition); if (!maybeMetadata.isPresent()) return new LeaderAndEpoch(Optional.empty(), Optional.ofNullable(lastSeenLeaderEpochs.get(topicPartition))); MetadataResponse.PartitionMetadata partitionMetadata = maybeMetadata.get(); Optional<Integer> leaderEpochOpt = partitionMetadata.leaderEpoch; Optional<Node> leaderNodeOpt = partitionMetadata.leaderId.flatMap(cache::nodeById); return new LeaderAndEpoch(leaderNodeOpt, leaderEpochOpt); }
Source:
<code>private void populateColumns(TreeItem item, ITmfStateInterval interval) { try { ITmfStateValue state = interval.getStateValue(); String value ; switch (state.getType()) { case INTEGER: value = String.valueOf(state.unboxInt()); item.setText(TYPE_COL, Messages.TypeInteger); break; case LONG: value = String.valueOf(state.unboxLong()); item.setText(TYPE_COL, Messages.TypeLong); break; case STRING: value = state.unboxStr(); item.setText(TYPE_COL, Messages.TypeString); break; case NULL: default: value = emptyString ; item.setText(TYPE_COL, emptyString); break; } TmfTimestamp startTime = new TmfTimestamp(interval.getStartTime(), ITmfTimestamp.NANOSECOND_SCALE); item.setText(START_TIME_COL, startTime.toString()); TmfTimestamp endTime = new TmfTimestamp(interval.getEndTime(), ITmfTimestamp.NANOSECOND_SCALE); item.setText(END_TIME_COL, endTime.toString()); item.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)) ; <START> if ((!filterStatus) && !value.equals(item.getText(VALUE_COL)) || fCurrentTimestamp == startTime.getValue()) { <END> item.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_YELLOW)); } item.setText(VALUE_COL, value) ; } catch (StateValueTypeException e) { throw new RuntimeException(); } }</code><technical_language>modify this lttng class</technical_language>

Target:
private void populateColumns(TreeItem item, ITmfStateInterval interval) { try { ITmfStateValue state = interval.getStateValue(); String value ; switch (state.getType()) { case INTEGER: value = String.valueOf(state.unboxInt()); item.setText(TYPE_COL, Messages.TypeInteger); break; case LONG: value = String.valueOf(state.unboxLong()); item.setText(TYPE_COL, Messages.TypeLong); break; case STRING: value = state.unboxStr(); item.setText(TYPE_COL, Messages.TypeString); break; case NULL: default: value = emptyString ; item.setText(TYPE_COL, emptyString); break; } TmfTimestamp startTime = new TmfTimestamp(interval.getStartTime(), ITmfTimestamp.NANOSECOND_SCALE); item.setText(START_TIME_COL, startTime.toString()); TmfTimestamp endTime = new TmfTimestamp(interval.getEndTime(), ITmfTimestamp.NANOSECOND_SCALE); item.setText(END_TIME_COL, endTime.toString()); item.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)) ; if (!filterStatus && (!value.equals(item.getText(VALUE_COL)) || fCurrentTimestamp == startTime.getValue())) { item.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_YELLOW)); } item.setText(VALUE_COL, value) ; } catch (StateValueTypeException e) { throw new RuntimeException(); } }
Source:
<code>private String getSortValue() { <START> if (account != null) { if (account.email != null) { return account.email; } return Strings.nullToEmpty(account.name); } return Strings.nullToEmpty(group.name); <END> }</code><technical_language>I do this shorter: return account != null ? Objects.firstNonNull(account.email, Strings.nullToEmpty(account.name)) : Strings.nullToEmpty(group.name);</technical_language>

Target:
private String getSortValue() { return account != null ? Objects.firstNonNull(account.email, Strings.nullToEmpty(account.name)) : Strings.nullToEmpty(group.name); }
Source:
<code>private HttpEntity<String> getSampleSheetForRun(Run run, SampleSheet casavaVersion, HttpServletResponse response) throws IOException { if (run == null) { <START> return new ResponseEntity<>(HttpStatus.NOT_FOUND); <END> } User user = securityManager.getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); if (run.getSequencerPartitionContainers().size() != 1) { throw new RestException( "Expected 1 sequencing container for run " + run.getAlias() + ", but found " + run.getSequencerPartitionContainers().size()); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(new MediaType("text", "csv")); response.setHeader("Content-Disposition", "attachment; filename=" + String.format("RUN%d-%s-SampleSheet.csv", run.getId(), casavaVersion.name())); return new HttpEntity<>(casavaVersion.createSampleSheet(run, user), headers); }</code><technical_language>throw RestException instead message run</technical_language>

Target:
private HttpEntity<String> getSampleSheetForRun(Run run, SampleSheet casavaVersion, HttpServletResponse response) throws IOException { if (run == null) { throw new RestException("Run does not exist.", Status.NOT_FOUND); } User user = securityManager.getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); if (run.getSequencerPartitionContainers().size() != 1) { throw new RestException( "Expected 1 sequencing container for run " + run.getAlias() + ", but found " + run.getSequencerPartitionContainers().size()); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(new MediaType("text", "csv")); response.setHeader("Content-Disposition", "attachment; filename=" + String.format("RUN%d-%s-SampleSheet.csv", run.getId(), casavaVersion.name())); return new HttpEntity<>(casavaVersion.createSampleSheet(run, user), headers); }
Source:
<code>public void testNullRequestHeader () throws Exception { final List<String> headers = new ArrayList<>(); <START> doReturn(headers).when(request).getRequestHeader("X-Cloud-Trace-Context"); <END> textFormat.extract(request, textFormatGetter); }</code><technical_language>This test is (testNullSpan). I intention is test a null doReturn(null).when(..</technical_language>

Target:
public void testNullRequestHeader () throws Exception { doReturn(null).when(request).getRequestHeader(Mockito.anyString()); textFormat.extract(request, textFormatGetter); }
Source:
<code><START> private boolean isCompareToDeclaration(MethodTree tree) { <END> Tree returnType = tree.returnType(); return "compareTo".equals(tree.simpleName().name()) && returnType.is(Kind.PRIMITIVE_TYPE) && "int".equals(((PrimitiveTypeTree) returnType).keyword().text()); }</code><technical_language>use/improve AbstractMethodDetection mechanism find compareTo method ( :warning: Generics supported in this class right now)</technical_language>

Target:
private boolean isCompareToDeclaration(MethodTree tree) { return isNamedCompareTo(tree) && hasOneNonPrimitiveParameter(tree) && returnsInt(tree); }
Source:
<code>static TabData getTabData(ApplicationConstants applicationConstants, DetailModelProvider<HostListModel, StorageDeviceListModel> modelProvider) { <START> return new ModelBoundTabData(applicationConstants.disksLabel(), 4, modelProvider); <END> }</code><technical_language>disk</technical_language>

Target:
static TabData getTabData(ApplicationConstants applicationConstants, DetailModelProvider<HostListModel, StorageDeviceListModel> modelProvider) { return new ModelBoundTabData(applicationConstants.logicalVolumes(), 4, modelProvider); }
Source:
<code>public void setHealth(double health) { if (health < 0) health = 0; if (health > getMaxHealth()) health = getMaxHealth(); this.health = health; metadata.set(MetadataIndex.HEALTH, (float) health); for (Objective objective : getServer().getScoreboardManager().getMainScoreboard().getObjectivesByCriteria(Criterias.HEALTH)) { objective.getScore(this.getName()).setScore((int) health); } <START> if (health == 0) { <END> active = false; Sound deathSound = getDeathSound(); if (deathSound != null) { world.playSound(location, deathSound, 1.0f, 1.0f); } playEffect(EntityEffect.DEATH); } }</code><technical_language>equal to. in case</technical_language>

Target:
public void setHealth(double health) { if (health < 0) health = 0; if (health > getMaxHealth()) health = getMaxHealth(); this.health = health; metadata.set(MetadataIndex.HEALTH, (float) health); for (Objective objective : getServer().getScoreboardManager().getMainScoreboard().getObjectivesByCriteria(Criterias.HEALTH)) { objective.getScore(this.getName()).setScore((int) health); } if (health <= 0) { active = false; Sound deathSound = getDeathSound(); if (deathSound != null) { world.playSound(location, deathSound, 1.0f, 1.0f); } playEffect(EntityEffect.DEATH); } }
Source:
<code>public void onDownloadComplete(LoadRequest request, boolean wasCancelled){ Log.d("ImageLoader", "Download complete: " + request.mUrl); if (!wasCancelled && request.mResult != null){ MemoryCache.instance().addBitmapToMemoryCache(request.mUrl, request.mResult); <START> completeLodRequest(request); <END> queueWriteRequest(new WriteRequest(request.mResult, request.mUrl)); } closeRequest(); }</code><technical_language>here... completeLoadRequest(request)</technical_language>

Target:
public void onDownloadComplete(LoadRequest request, boolean wasCancelled){ Log.d("ImageLoader", "Download complete: " + request.mUrl); if (!wasCancelled && request.mResult != null){ MemoryCache.instance().addBitmapToMemoryCache(request.mUrl, request.mResult); completeLoadRequest(request); queueWriteRequest(new WriteRequest(request.mResult, request.mUrl)); } closeRequest(); }
Source:
<code><START> public Account validate(TaskRepository repository, IProgressMonitor monitor) throws CoreException { <END> if (!Boolean.parseBoolean(repository.getProperty(GerritConnector.KEY_REPOSITORY_OPEN_ID_ENABLED))) { monitor = Policy.backgroundMonitorFor(monitor); } try { return ((GerritClient) createReviewClient(repository, false)).getAccountAndRefreshConfig(monitor); } catch (UnsupportedClassVersionError e) { throw toCoreException(repository, e); } catch (GerritException e) { throw toCoreException(repository, "Invalid repository", e); } }</code><technical_language>Account class versions</technical_language>

Target:
public GerritSystemInfo validate(TaskRepository repository, IProgressMonitor monitor) throws CoreException { if (!Boolean.parseBoolean(repository.getProperty(GerritConnector.KEY_REPOSITORY_OPEN_ID_ENABLED))) { monitor = Policy.backgroundMonitorFor(monitor); } try { return ((GerritClient) createReviewClient(repository, false)).getInfo(monitor); } catch (UnsupportedClassVersionError e) { throw toCoreException(repository, e); } catch (GerritException e) { throw toCoreException(repository, "Invalid repository", e); } }
Source:
<code>public String removePlayerFromTeam( HttpSession session, @PathVariable int id) { <START> Member me = (Member) session.getAttribute("member"); <END> if (me == null) { return "redirect:/denied"; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, false, true, false); if (team == null || me.equals(team.getTeamLeader())) { return "redirect:/denied"; } team.removePlayer(me); new MessageDao().notify(me, "You were removed from " + team.getName()); new MessageDao().notify(team.getTeamLeader(), me.getName() + " was removed from " + team.getName()); teamDao.saveTeam(team); return "redirect:/profile"; }</code><technical_language>Change this java Member = (Member) session.getAttribute("member"); MemberDao memberDao = new MemberDao(); = memberDao.getMemberById(member.getId()); if (me == null) { return "redirect:/denied"; }</technical_language>

Target:
public String removePlayerFromTeam( HttpSession session, @PathVariable int id) { Member me = (Member) session.getAttribute("member"); MemberDao memberDao = new MemberDao(); me = memberDao.getMemberById(me.getId()); if (me == null) { return "redirect:/denied"; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, false, true, false); if (team == null || me.equals(team.getTeamLeader())) { return "redirect:/denied"; } team.removePlayer(me); new MessageDao().notify(me, "You were removed from " + team.getName()); new MessageDao().notify(team.getTeamLeader(), me.getName() + " was removed from " + team.getName()); teamDao.saveTeam(team); return "redirect:/profile"; }
Source:
<code>public ResponseEntity<?> getSchemaVersion(@PathVariable("name") final String name, @PathVariable("version") final String version, <START> final NativeWebRequest request) { <END> if (version.equals("latest")) { final EventType eventType = eventTypeService.get(name); return ResponseEntity.status(HttpStatus.OK).body(eventType.getSchema()); } final EventTypeSchema result = schemaService.getSchemaVersion(name, version); return ResponseEntity.status(HttpStatus.OK).body(result); }</code><technical_language>declare throws please</technical_language>

Target:
public ResponseEntity<?> getSchemaVersion(@PathVariable("name") final String name, @PathVariable("version") final String version, final NativeWebRequest request) throws NoSuchEventTypeException, InternalNakadiException, NoSuchSchemaException, InvalidVersionNumberException { if (version.equals("latest")) { final EventType eventType = eventTypeService.get(name); return ResponseEntity.status(HttpStatus.OK).body(eventType.getSchema()); } final EventTypeSchema result = schemaService.getSchemaVersion(name, version); return ResponseEntity.status(HttpStatus.OK).body(result); }
Source:
<code>public boolean updateLiveInAndOut(ControlFlowGraph cfg, Map<CfgBlock, BlockLiveness> livenessPerBlock) { liveOut.clear(); for (CfgBlock successor : block.successors()) { <START> if (successor != cfg.end()) { <END> liveOut.addAll(livenessPerBlock.get(successor).liveIn); } } Set<Symbol> oldIn = liveIn; liveIn = new HashSet<>(liveOut); for (Tree element : Lists.reverse(block.elements())) { Usage usage = usageByElement.get(element); if (isWrite(usage)) { liveIn.remove(symbol(usage)); } else if (isRead(usage)) { liveIn.add(symbol(usage)); } } return !oldIn.equals(liveIn); }</code><technical_language>@pynicolas discussed want end block blocks returned ControlFlowGraph#blocks(). ruins unit tests. do this improvement</technical_language>

Target:
public boolean updateLiveInAndOut(ControlFlowGraph cfg, Map<CfgBlock, BlockLiveness> livenessPerBlock) { liveOut.clear(); for (CfgBlock successor : block.successors()) { liveOut.addAll(livenessPerBlock.get(successor).liveIn); } Set<Symbol> oldIn = liveIn; liveIn = new HashSet<>(liveOut); for (Tree element : Lists.reverse(block.elements())) { Usage usage = usageByElement.get(element); if (isWrite(usage)) { liveIn.remove(symbol(usage)); } else if (isRead(usage)) { liveIn.add(symbol(usage)); } } return !oldIn.equals(liveIn); }
Source:
<code>private static Object getAvroValue(Object input, Schema schema) { if (input instanceof byte[]) { return new GenericData.Fixed(schema, (byte[]) input); } else if (input instanceof Map && !((Map) input).isEmpty()) { return getAvroGenericRecord((StreamlineEvent) input, schema.toString()); <START> } else if (input instanceof List && !((List) input).isEmpty()) { <END> return new GenericData.Array<Object>(schema, (Collection<Object>) input); } else { return input; } }</code><technical_language>check done Collection instead of List</technical_language>

Target:
private static Object getAvroValue(Object input, Schema schema) { if (input instanceof byte[] && Schema.Type.FIXED.equals(schema.getType())) { return new GenericData.Fixed(schema, (byte[]) input); } else if (input instanceof Map && !((Map) input).isEmpty()) { GenericRecord result; result = new GenericData.Record(schema); for (Map.Entry<String, Object> entry: ((Map<String, Object>) input).entrySet()) { result.put(entry.getKey(), getAvroValue(entry.getValue(), schema.getField(entry.getKey()).schema())); } return result; } else if (input instanceof Collection && !((Collection) input).isEmpty()) { List<Object> values = new ArrayList<>(((Collection) input).size()); for (Object value: (Collection) input) { values.add(getAvroValue(value, schema.getElementType())); } return new GenericData.Array<Object>(schema, values); } else { return input; } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } setTitle(getString(R.string.navdrawer_item_send_feedback)); setContentView(R.layout.report); if (savedInstanceState == null) { ObaRegion currentRegion = Application.get().getCurrentRegion(); if (showValidateRegionDialog(currentRegion)) { <START> mRegionId = currentRegion.getId(); <END> RegionValidateDialog rvd = new RegionValidateDialog(); rvd.show(getSupportFragmentManager(), ReportConstants.TAG_REGION_VALIDATE_DIALOG); } else { createIssueTypeListFragment(); } } setUpProgressBar(); }</code><technical_language>@azizmb9494 please Bundle pass data RegionValidateDialog fragment? like: Bundle bundle = new Bundle(); bundle.putLong(key, regionId); rvd.setArguments(bundle); I think, try avoid creating unnecessary members</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } setTitle(getString(R.string.navdrawer_item_send_feedback)); setContentView(R.layout.report); if (savedInstanceState == null) { ObaRegion currentRegion = Application.get().getCurrentRegion(); if (showValidateRegionDialog(currentRegion)) { RegionValidateDialog rvd = new RegionValidateDialog(); rvd.show(getSupportFragmentManager(), ReportConstants.TAG_REGION_VALIDATE_DIALOG); } else { createIssueTypeListFragment(); } } setUpProgressBar(); }