auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor progressMonitor) { final ISourceViewerExtension5 <START> sourceViewer = <END> fSourceViewer; if (sourceViewer != null) { reconciledViewers.add(fSourceViewer); sourceViewer.updateCodeMinings(); } }</code><technical_language>I fSourceViewer itself, assignment. sourceViewer is a reference object fSourceViewer references if null, null</technical_language>

Target:
public void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor progressMonitor) { final ISourceViewerExtension5 sourceViewer= fSourceViewer; if (sourceViewer != null) { reconciledViewers.add(sourceViewer); sourceViewer.updateCodeMinings(); } }
Source:
<code>public GraphQLFieldDefinition(String name, String description, GraphQLOutputType type, DataFetcherFactory dataFetcherFactory, List<GraphQLArgument> arguments, String deprecationReason, FieldDefinition definition) { assertValidName(name); <START> assertNotNull(dataFetcherFactory, "dataFetcherFactory can't be null"); <END> assertNotNull(type, "type can't be null"); assertNotNull(arguments, "arguments can't be null"); this.name = name; this.description = description; this.type = type; this.dataFetcherFactory = dataFetcherFactory; this.arguments = Collections.unmodifiableList(new ArrayList<>(arguments)); this.deprecationReason = deprecationReason; this.definition = definition; }</code><technical_language>this is confusing I think: DataFetcher ... DataFetcherFactory null: 'you provide a DataFetcher (or DataFetcherFactory)'</technical_language>

Target:
public GraphQLFieldDefinition(String name, String description, GraphQLOutputType type, DataFetcherFactory dataFetcherFactory, List<GraphQLArgument> arguments, String deprecationReason, FieldDefinition definition) { assertValidName(name); assertNotNull(dataFetcherFactory, "you have to provide a DataFetcher (or DataFetcherFactory)"); assertNotNull(type, "type can't be null"); assertNotNull(arguments, "arguments can't be null"); this.name = name; this.description = description; this.type = type; this.dataFetcherFactory = dataFetcherFactory; this.arguments = Collections.unmodifiableList(new ArrayList<>(arguments)); this.deprecationReason = deprecationReason; this.definition = definition; }
Source:
<code><START> private void crossfadePreviewViews() { <END> final View topView = isInVisualPreview() ? mViewPager : mVisualPreviewContainer; final View bottomView = isInVisualPreview() ? mVisualPreviewContainer : mViewPager; topView.setAlpha(0f); topView.setVisibility(View.VISIBLE); topView.animate() .alpha(1f) .setDuration(getResources().getInteger(android.R.integer.config_shortAnimTime)) .setListener(null); bottomView.animate() .alpha(0f) .setDuration(getResources().getInteger(android.R.integer.config_shortAnimTime)) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { bottomView.setVisibility(View.GONE); } }); }</code><technical_language>private void crossfadePreviewViews() { final View fadeInView = isInVisualPreview() ? mViewPager : mVisualPreviewContainer; final View fadeOutView = isInVisualPreview() ? mVisualPreviewContainer : mViewPager; AniUtils.fadeIn(fadeInView, Duration.SHORT); AniUtils.fadeOut(fadeOutView, Duration.SHORT); } AniUtils class this animation code simpler</technical_language>

Target:
private void crossfadePreviewViews() { final View fadeInView = isInVisualPreview() ? mViewPager : mVisualPreviewContainer; final View fadeOutView = isInVisualPreview() ? mVisualPreviewContainer : mViewPager; mVisualPreviewContainer.smoothScrollTo(0, 0); mVisualPreviewContainer.post(new Runnable() { @Override public void run() { AniUtils.fadeIn(fadeInView, Duration.SHORT); AniUtils.fadeOut(fadeOutView, Duration.SHORT); } }); }
Source:
<code>public void runVm(VM vm) { try { getKubevirtApi().start(vm.getNamespace(), vm.getName()); } catch (ApiException e) { <START> KubevirtUtils.auditAuthorizationIssues(e, auditLogDirector, provider); throw new EngineException(EngineError.unexpected, "failed to interact with kubevirt start endpoint"); <END> } }</code><technical_language>this is repeat times extracted a method, i.e. handleKubevirtError(e, auditLogDirector, provider, message) throws EngineException</technical_language>

Target:
public void runVm(VM vm) { try { getKubevirtApi().start(vm.getNamespace(), vm.getName()); } catch (ApiException e) { handleException(e, "failed to interact with kubevirt start endpoint"); } }
Source:
<code>public void deleteCloudWatchAlarmsForSystemFailures(CloudStack stack, String regionName, AwsCredentialView credentialView, List<String> instanceIds) { String isCreate = stack.getParameters().get(CLOUDWATCH_CREATE_PARAMETER); <START> if (isCreate != null && isCreate.equals(Boolean.TRUE.toString())) { <END> List<String> instanceIdsFromStack = stack.getGroups().stream() .flatMap(group -> group.getInstances().stream()) .map(CloudInstance::getInstanceId) .collect(Collectors.toList()); List<String> instanceIdsNotInStack = instanceIds.stream() .filter(instanceId -> !instanceIdsFromStack.contains(instanceId)) .collect(Collectors.toList()); if (!instanceIdsNotInStack.isEmpty()) { LOGGER.error("Instance IDs are not part of stack {}", instanceIdsFromStack, stack); throw new CloudConnectorException("Unable to delete cloud watch alarms for system failure because instances ID are not a part of the stack."); } deleteCloudWatchAlarmsForSystemFailures(regionName, credentialView, instanceIds); } }</code><technical_language>this be: Boolean.TRUE.toString().equals(isCreate)</technical_language>

Target:
public void deleteCloudWatchAlarmsForSystemFailures(CloudStack stack, String regionName, AwsCredentialView credentialView, List<String> instanceIds) { if (isCloudwatchEnabled(stack)) { List<String> instanceIdsFromStack = stack.getGroups().stream() .flatMap(group -> group.getInstances().stream()) .map(CloudInstance::getInstanceId) .collect(Collectors.toList()); List<String> instanceIdsNotInStack = instanceIds.stream() .filter(instanceId -> !instanceIdsFromStack.contains(instanceId)) .collect(Collectors.toList()); if (!instanceIdsNotInStack.isEmpty()) { LOGGER.error("Instance IDs are not part of stack {}", instanceIdsFromStack, stack); throw new CloudConnectorException("Unable to delete cloud watch alarms for system failure because instances ID are not a part of the stack."); } deleteCloudWatchAlarmsForSystemFailures(regionName, credentialView, instanceIds); } }
Source:
<code>protected void onLayout(boolean changed, int left, int top, int right, int bottom) { boolean isLtr = isLayoutLtr(); int clientLeft = left + getPaddingLeft(); int clientTop = top + getPaddingTop(); int clientRight = right - getPaddingRight(); int clientBottom = bottom - getPaddingBottom(); <START> int firstRowBottom = layoutFirstRow(clientLeft, clientTop, clientRight, isLtr); <END> int secondRowBottom = layoutSecondRow(clientLeft, clientRight, firstRowBottom); layoutThirdRow(clientLeft, clientRight, clientBottom, secondRowBottom, isLtr); trackLineBounds.set(0f, 0f, (float) getWidth(), trackLineHeightPx * 2); }</code><technical_language>Expressive method name here</technical_language>

Target:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) { boolean isLtr = isLayoutLtr(); int clientLeft = left + getPaddingLeft(); int clientTop = top + getPaddingTop(); int clientRight = right - getPaddingRight(); int clientBottom = bottom - getPaddingBottom(); int firstRowBottom = layoutFirstRow(clientLeft, clientTop, clientRight, isLtr); int secondRowBottom = layoutSecondRow(clientLeft, clientRight, firstRowBottom); layoutThirdRow(clientLeft, clientRight, clientBottom, secondRowBottom, isLtr); updateTrackLineBounds(); }
Source:
<code>public GibbsSampler(final int numSamples, final ParameterizedModel<V, S, T> model) { ParamUtils.isPositive(numSamples, "Number of samples must be positive."); <START> if (model.getUpdateMethod() != ParameterizedModel.UpdateMethod.GIBBS) { <END> throw new IllegalArgumentException("ParameterizedModel must be constructed to update using Gibbs sampling."); } this.numSamples = numSamples; this.model = model; numSamplesPerLogEntry = NUMBER_OF_SAMPLES_PER_LOG_ENTRY; samples = new ArrayList<>(numSamples); samples.add(model.state()); }</code><technical_language>Uitls.validateArg(model.getUpdateMethod() == ParameterizedModel.UpdateMethod.GIBBS. .</technical_language>

Target:
public GibbsSampler(final int numSamples, final ParameterizedModel<V, S, T> model) { ParamUtils.isPositive(numSamples, "Number of samples must be positive."); Utils.validateArg(model.getUpdateMethod() == ParameterizedModel.UpdateMethod.GIBBS, "ParameterizedModel must be constructed to update using Gibbs sampling."); this.numSamples = numSamples; this.model = model; numSamplesPerLogEntry = NUMBER_OF_SAMPLES_PER_LOG_ENTRY; samples = new ArrayList<>(numSamples); samples.add(model.state()); }
Source:
<code>Point resizeCalculationsGTK3(long widget, int width, int height) { Point size = super.resizeCalculationsGTK3(widget, width, height); if (widget == handle && GTK.GTK_VERSION >= OS.VERSION(3, 20, 0)) { GtkRequisition naturalSize = new GtkRequisition(); GtkRequisition minimumSize = new GtkRequisition(); GTK.gtk_widget_get_preferred_size(handle, minimumSize, naturalSize); <START> if ((getStyle() & SWT.VERTICAL) != 0) { <END> size.x = Math.max(size.x, minimumSize.width); } if ((getStyle() & SWT.HORIZONTAL) != 0) { size.y = Math.max(size.y, minimumSize.height); } } return size; }</code><technical_language>Please style instead of getStyle(), this is more consistent rest of code base. I.e.: if ((style & SWT.HORIZONTAL) != 0)</technical_language>

Target:
Point resizeCalculationsGTK3(long widget, int width, int height) { Point size = super.resizeCalculationsGTK3(widget, width, height); if (widget == handle && GTK.GTK_VERSION >= OS.VERSION(3, 20, 0)) { GtkRequisition naturalSize = new GtkRequisition(); GtkRequisition minimumSize = new GtkRequisition(); GTK.gtk_widget_get_preferred_size(handle, minimumSize, naturalSize); if ((style & SWT.VERTICAL) != 0) { size.x = Math.max(size.x, minimumSize.width); } if ((style & SWT.HORIZONTAL) != 0) { size.y = Math.max(size.y, minimumSize.height); } } return size; }
Source:
<code>public void testCaseSensitivity() throws Exception { long timestamp = System.currentTimeMillis(); IncrementalIndex index = indexCreator.createIndex(defaultAggregatorFactories); <START> closer.register(index); <END> populateIndex(timestamp, index); Assert.assertEquals(Arrays.asList("dim1", "dim2"), index.getDimensionNames()); Assert.assertEquals(2, index.size()); final Iterator<Row> rows = index.iterator(); Row row = rows.next(); Assert.assertEquals(timestamp, row.getTimestampFromEpoch()); Assert.assertEquals(Arrays.asList("1"), row.getDimension("dim1")); Assert.assertEquals(Arrays.asList("2"), row.getDimension("dim2")); row = rows.next(); Assert.assertEquals(timestamp, row.getTimestampFromEpoch()); Assert.assertEquals(Arrays.asList("3"), row.getDimension("dim1")); Assert.assertEquals(Arrays.asList("4"), row.getDimension("dim2")); }</code><technical_language>FYI inline registration process, do closer.register(indexCreator.createIndex(defaultAggregatorFactories)) if desired</technical_language>

Target:
public void testCaseSensitivity() throws Exception { long timestamp = System.currentTimeMillis(); IncrementalIndex index = closer.closeLater(indexCreator.createIndex(defaultAggregatorFactories)); populateIndex(timestamp, index); Assert.assertEquals(Arrays.asList("dim1", "dim2"), index.getDimensionNames()); Assert.assertEquals(2, index.size()); final Iterator<Row> rows = index.iterator(); Row row = rows.next(); Assert.assertEquals(timestamp, row.getTimestampFromEpoch()); Assert.assertEquals(Arrays.asList("1"), row.getDimension("dim1")); Assert.assertEquals(Arrays.asList("2"), row.getDimension("dim2")); row = rows.next(); Assert.assertEquals(timestamp, row.getTimestampFromEpoch()); Assert.assertEquals(Arrays.asList("3"), row.getDimension("dim1")); Assert.assertEquals(Arrays.asList("4"), row.getDimension("dim2")); }
Source:
<code><START> public ReleaseRemovalResult removeReleasesFromMavenRepository( final MavenRepository repository, <END> final ReleaseRemovalRequest request, final ReleaseRemovalResult result, final Target repositoryTarget ) { TaskUtil.checkInterruption(); if ( !repository.getLocalStatus().shouldServiceRequest() ) { return result; } getLogger().debug( "Collecting deletable releases on repository '" + repository.getId() + "' from storage directory " + repository.getLocalUrl() ); DefaultWalkerContext ctxMain = new DefaultWalkerContext( repository, new ResourceStoreRequest( "/" ), determineFilter( repositoryTarget ) ); ctxMain.getContext().put( DeleteOperation.DELETE_OPERATION_CTX_KEY, DeleteOperation.MOVE_TO_TRASH ); ctxMain.getProcessors().add( new ReleaseRemovalWalkerProcessor( repository, request, result ) ); walker.walk( ctxMain ); if ( ctxMain.getStopCause() != null ) { result.setSuccessful( false ); } return result; }</code><technical_language>unused return value</technical_language>

Target:
private void removeReleasesFromMavenRepository( final MavenRepository repository, final ReleaseRemovalRequest request, final ReleaseRemovalResult result, final Target repositoryTarget ) { TaskUtil.checkInterruption(); if ( !repository.getLocalStatus().shouldServiceRequest() ) { return; } getLogger().debug( "Collecting deletable releases on repository '" + repository.getId() + "' from storage directory " + repository.getLocalUrl() ); DefaultWalkerContext ctxMain = new DefaultWalkerContext( repository, new ResourceStoreRequest( "/" ), determineFilter( repositoryTarget ) ); ctxMain.getContext().put( DeleteOperation.DELETE_OPERATION_CTX_KEY, DeleteOperation.MOVE_TO_TRASH ); ctxMain.getProcessors().add( new ReleaseRemovalWalkerProcessor( repository, request, result ) ); walker.walk( ctxMain ); if ( ctxMain.getStopCause() != null ) { result.setSuccessful( false ); } }
Source:
<code>private static int findNotEscapedCharacterPosition(String pattern, int currentIndex, char characterToFind) { for (int i = currentIndex; i < pattern.length(); i++) { final char c = pattern.charAt(i); <START> if (c != characterToFind) { <END> continue; } final boolean isEscaped = i > 0 && pattern.charAt(i - 1) == '\\'; if (isEscaped) { continue; } return i; } return -1; }</code><technical_language>style-nit; braces for simple single-statement constrcuts</technical_language>

Target:
private static int findNotEscapedCharacterPosition(String pattern, int currentIndex, char characterToFind) { for (int i = currentIndex; i < pattern.length(); i++) { final char c = pattern.charAt(i); if (c != characterToFind) continue; final boolean isEscaped = i > 0 && pattern.charAt(i - 1) == '\\'; if (isEscaped) continue; return i; } return -1; }
Source:
<code>public static VmPropertiesUtils getInstance() { <START> if (vmPropertiesUtils == null) { <END> synchronized (VmPropertiesUtils.class) { if (vmPropertiesUtils == null) { vmPropertiesUtils = new VmPropertiesUtils(); } } } return vmPropertiesUtils; }</code><technical_language>While it, fix initialization here, singleton for Device Custom Properties</technical_language>

Target:
public static VmPropertiesUtils getInstance() { return vmPropertiesUtils; }
Source:
<code>private void openInNewTab(PageTitle title, HistoryEntry entry) { Tab tab = new Tab(); <START> if (tabList.size() > 0) { <END> tabList.add(tabList.size() - 1, tab); } else { tabList.add(tab); } tab.getBackStack().add(new PageBackStackItem(title, entry)); tabsProvider.showAndHideTabs(); }</code><technical_language>Nice corner case handling. block review: tabList.add(Math.min(0, tabList.size() - 1), tab) instead of a conditional</technical_language>

Target:
private void openInNewTab(PageTitle title, HistoryEntry entry) { Tab tab = new Tab(); tabList.add(Math.max(0, tabList.size() - 1), tab); tab.getBackStack().add(new PageBackStackItem(title, entry)); tabsProvider.showAndHideTabs(); }
Source:
<code>public void run() { while (true) { if (stop) { break; } try { <START> Thread.sleep(100); <END> } catch (InterruptedException e) { log.warn("error refreshing index searchers", e); } openIndex.maybeRefresh(); closedIndex.maybeRefresh(); } }</code><technical_language>Instead say: synchronized (this) { wait(100); } This wait 100ms shutdown</technical_language>

Target:
public void run() { while (true) { if (stop) { break; } openIndex.maybeRefresh(); closedIndex.maybeRefresh(); synchronized (this) { try { wait(100); } catch (InterruptedException e) { log.warn("error refreshing index searchers", e); } } } }
Source:
<code>public void unregisterModelAdapter(Class<?> adapterType) { <START> if (DsfDebugOptions.DEBUG && DsfDebugOptions.DEBUG_SESSION && DsfDebugOptions.DEBUG_SESSION_MODEL_ADAPTERS) { <END> String msg = new Formatter().format( "%s Unregistering model adapter of type %s from session %s (%s)", DsfPlugin.getDebugTime(), adapterType.getName(), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fAdapters.remove(adapterType); }</code><technical_language>DsfDebugOptions... mentioned</technical_language>

Target:
public void unregisterModelAdapter(Class<?> adapterType) { if (DsfDebugOptions.DEBUG_SESSION_MODEL_ADAPTERS) { String msg = new Formatter().format( "%s Unregistering model adapter of type %s from session %s (%s)", DsfPlugin.getDebugTime(), adapterType.getName(), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fAdapters.remove(adapterType); }
Source:
<code>public Compressor borrowCompressor(){ try { return (Compressor) compressorPool.borrowObject(); } catch (Exception e) { throw new ParquetCompressionCodecException(e); <START> } <END> }</code><technical_language>borrow method bellow</technical_language>

Target:
public Compressor borrowCompressor(){ return borrow(compressorPool); }
Source:
<code>public void testOtherFieldsNotValidatedInImport() { ImportVmParameters parameters = createParameters(); String stringOf5000Chars = StringUtils.repeat("A", 5000); <START> assertFalse(BusinessEntitiesDefinitions.GENERAL_MAX_SIZE > stringOf5000Chars.length()); <END> parameters.getVm().setUserDefinedProperties(stringOf5000Chars); parameters.setImportAsNewEntity(true); ImportVmCommand command = new ImportVmCommand(parameters); Set<ConstraintViolation<ImportVmParameters>> validate = ValidationUtils.getValidator().validate(parameters, command.getValidationGroups().toArray(new Class<?>[0])); assertTrue(validate.isEmpty()); parameters.getVm().setUserDefinedProperties(stringOf5000Chars); parameters.setImportAsNewEntity(false); command = new ImportVmCommand(parameters); validate = ValidationUtils.getValidator().validate(parameters, command.getValidationGroups().toArray(new Class<?>[0])); assertTrue(validate.isEmpty()); }</code><technical_language>testing a constant is smaller 5000? why</technical_language>

Target:
public void testOtherFieldsNotValidatedInImport() { ImportVmParameters parameters = createParameters(); String stringOf5000Chars = StringUtils.repeat("A", BusinessEntitiesDefinitions.GENERAL_MAX_SIZE + 1); parameters.getVm().setUserDefinedProperties(stringOf5000Chars); parameters.setImportAsNewEntity(true); ImportVmCommand command = new ImportVmCommand(parameters); Set<ConstraintViolation<ImportVmParameters>> validate = ValidationUtils.getValidator().validate(parameters, command.getValidationGroups().toArray(new Class<?>[0])); assertTrue(validate.isEmpty()); parameters.getVm().setUserDefinedProperties(stringOf5000Chars); parameters.setImportAsNewEntity(false); command = new ImportVmCommand(parameters); validate = ValidationUtils.getValidator().validate(parameters, command.getValidationGroups().toArray(new Class<?>[0])); assertTrue(validate.isEmpty()); }
Source:
<code>public String getStatData() throws IOException { JSONObject o = new JSONObject(); for (UsageStatisticsContributor contributor : UsageStatisticsContributor.all()) { <START> JSONObject contributed = contributor.getStatData(); <END> for (java.util.Iterator<String> it = contributed.keys(); it.hasNext();) { String key = it.next(); if (o.has(key)) { throw new IllegalStateException( contributor.getClass().getName() + " tried to use an already used UsageStatistics key: " + key); } o.put(key, contributed.get(key)); } } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter w = new OutputStreamWriter(new GZIPOutputStream(new CombinedCipherOutputStream(baos,getKey(),"AES")), "UTF-8"); try { o.write(w); } finally { IOUtils.closeQuietly(w); } return new String(Base64.encode(baos.toByteArray())); } catch (GeneralSecurityException e) { throw new Error(e); } }</code><technical_language>Wrap in try/catch for robustness</technical_language>

Target:
public String getStatData() throws IOException { Jenkins j = Jenkins.getInstance(); JSONObject data = new JSONObject(); ExtensionList<UsageStatisticsContributor> contributors = UsageStatisticsContributor.all(); List<JSONObject> nodes = new ArrayList<JSONObject>(); for (Computer computer : j.getComputers()) { JSONObject nodeData = new JSONObject(); for (UsageStatisticsContributor contributor : contributors) { try { contributor.contributeNodeData(computer, nodeData); } catch (Exception e) { LOGGER.log(Level.WARNING, null, e); } } nodes.add(nodeData); } data.put("nodes", nodes); for (UsageStatisticsContributor contributor : contributors) { Class<? extends UsageStatisticsContributor> contributorClass = contributor.getClass(); LOGGER.finest(String.format("Calling '%s' usage stats contributor", contributorClass)); try { contributor.contributeData(data); } catch (Exception e) { LOGGER.log(Level.WARNING, null, e); } } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter w = new OutputStreamWriter(new GZIPOutputStream(new CombinedCipherOutputStream(baos,getKey(),"AES")), "UTF-8"); try { data.write(w); } finally { IOUtils.closeQuietly(w); } return new String(Base64.encode(baos.toByteArray())); } catch (GeneralSecurityException e) { throw new Error(e); } }
Source:
<code>public void showInvalidLoginOrPasswordSnackbar() { Snackbar snackbar = Snackbar .make(mRootView, getResources().getString(R.string.invalid_login_or_password_message), Snackbar.LENGTH_LONG) .setAction("EDIT", view -> { mPassword.requestFocus(); <START> mPassword.selectAll(); <END> }); snackbar.show(); }</code><technical_language>heard DRY ? :nerd_face: introduce a method create snackbar return write code more</technical_language>

Target:
public void showInvalidLoginOrPasswordSnackbar() { String message = getResources().getString(R.string.invalid_login_or_password_message); createSnackbar(message) .setAction(getResources().getString(R.string.snackbar_edit), view -> { mPassword.requestFocus(); mPassword.selectAll(); }) .show(); }
Source:
<code><START> private boolean isSymbolShadowed(Tree tree) { <END> Tree scopedTree = CheckUtils.getFirstAncestor( tree, TreeKinds.FUNCTION_KINDS, Kind.SCRIPT); return getContext().getSymbolModel().getScope(scopedTree).lookupSymbol(SYMBOL) != null; }</code><technical_language>@ivandalbosco undo this change</technical_language>

Target:
private boolean isSymbolShadowed(Tree tree) { Tree scopedTree = CheckUtils.getFirstAncestor(tree, KindSet.FUNCTION_KINDS, Kind.SCRIPT); Symbol symbolSymbol = getContext().getSymbolModel().getScope(scopedTree).lookupSymbol(SYMBOL); return !symbolSymbol.external() || hasWriteUsage(symbolSymbol); }
Source:
<code>public Retrofit build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } okhttp3.Call.Factory callFactory = this.callFactory; if (callFactory == null) { callFactory = new OkHttpClient(); } Executor callbackExecutor = this.callbackExecutor; if (callbackExecutor == null) { callbackExecutor = platform.defaultCallbackExecutor(); } List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories); adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor)); <START> List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories); <END> converterFactories.add(0, new BuiltInConverters()); return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories, callbackExecutor, validateEagerly); }</code><technical_language>nit: if create a new ArrayList, add BuiltInConverters first, addAll(), avoid shifting _N_ converter factories. small performance improvement, type of I a clean house</technical_language>

Target:
public Retrofit build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } okhttp3.Call.Factory callFactory = this.callFactory; if (callFactory == null) { callFactory = new OkHttpClient(); } Executor callbackExecutor = this.callbackExecutor; if (callbackExecutor == null) { callbackExecutor = platform.defaultCallbackExecutor(); } List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories); adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor)); List<Converter.Factory> converterFactories = new ArrayList<>(); converterFactories.add(new BuiltInConverters()); converterFactories.addAll(this.converterFactories); return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories, callbackExecutor, validateEagerly); }
Source:
<code>public boolean storeMessage(MessageContext synCtx) { if (synCtx == null) { <START> return false; <END> } if (connection == null) { log.error(getId() + " cannot proceed. RabbitMQ Connection is null. Ignored MessageId: " + synCtx.getMessageID()); return false; } boolean result = false; try (Channel channel = connection.createChannel()) { channel.confirmSelect(); StorableMessage storableMessage = MessageConverter.toStorableMessage(synCtx); final byte[] message = serializeMessage(storableMessage); final AMQP.BasicProperties basicProperties = getBasicProperties(synCtx, storableMessage); publishMessage(channel, exchangeName, routingKey, basicProperties, message); result = channel.waitForConfirms(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (TimeoutException | IOException e) { String errorMsg = getId() + ". Ignored MessageId: " + synCtx.getMessageID() + ". " + "Could not store message to store [" + store.getName() + "]. " + "Error:" + e.getLocalizedMessage(); log.error(errorMsg, e); } if (log.isDebugEnabled()) { log.debug(getId() + ". Stored MessageId: " + synCtx.getMessageID()); } store.enqueued(); return result; }</code><technical_language>Is this a check need do? situations this null</technical_language>

Target:
public boolean storeMessage(MessageContext synCtx) { if (synCtx == null) { return false; } if (connection == null) { log.error(getId() + " cannot proceed. RabbitMQ Connection is null. Ignored MessageId: " + synCtx.getMessageID()); return false; } boolean result = false; try (Channel channel = connection.createChannel()) { if (publisherConfirmsEnabled) { channel.confirmSelect(); } StorableMessage storableMessage = MessageConverter.toStorableMessage(synCtx); final byte[] message = serializeMessage(storableMessage); final AMQP.BasicProperties basicProperties = getBasicProperties(synCtx, storableMessage); publishMessage(channel, exchangeName, routingKey, basicProperties, message); if (publisherConfirmsEnabled) { result = channel.waitForConfirms(); } else { result = true; } if (log.isDebugEnabled()) { log.debug(getId() + ". Stored MessageId: " + synCtx.getMessageID()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (TimeoutException | IOException e) { String errorMsg = getId() + ". Ignored MessageId: " + synCtx.getMessageID() + ". " + "Could not store message to store [" + store.getName() + "]. " + "Error:" + e.getLocalizedMessage(); log.error(errorMsg, e); } store.enqueued(); return result; }
Source:
<code>public static void createAndWaitForStream(AmazonKinesisClient kinesisClient, String streamName, int shardCount) { StreamStatus streamStatus = getStreamState(kinesisClient, streamName); if (streamStatus != null) { if (streamStatus == StreamStatus.ACTIVE) { return; <START> } else if (streamStatus == StreamStatus.DELETING) { <END> waitForStreamState(kinesisClient, streamName, null); createStream(streamName, shardCount, kinesisClient); } } else { createStream(streamName, shardCount, kinesisClient); } waitForStreamState(kinesisClient, streamName, StreamStatus.ACTIVE); }</code><technical_language>else is needed return</technical_language>

Target:
public static void createAndWaitForStream(AmazonKinesisClient kinesisClient, String streamName, int shardCount) { StreamStatus streamStatus = getStreamState(kinesisClient, streamName); if (streamStatus != null) { if (streamStatus == StreamStatus.ACTIVE) { return; } if (streamStatus == StreamStatus.DELETING) { waitForStreamState(kinesisClient, streamName, null); createStream(streamName, shardCount, kinesisClient); } } else { createStream(streamName, shardCount, kinesisClient); } waitForStreamState(kinesisClient, streamName, StreamStatus.ACTIVE); }
Source:
<code>private Pair<String, String> composeVmNames(VirtualMachineTO vmSpec) { String vmInternalCSName = null; String vmNameOnVcenter = null; <START> if(vmSpec != null) <END> { vmInternalCSName = vmNameOnVcenter = vmSpec.getName(); if (_instanceNameFlag == true) { String[] tokens = vmInternalCSName.split("-"); assert (tokens.length >= 3); vmNameOnVcenter = String.format("%s-%s-%s-%s", tokens[0], tokens[1], tokens[2], vmSpec.getHostName()); } } return new Pair<String, String>(vmInternalCSName, vmNameOnVcenter); }</code><technical_language>Is a case in "vmSpec" null here? is nice avoid a null pointer exception, is, change null pointer else</technical_language>

Target:
protected Pair<String, String> composeVmNames(VirtualMachineTO vmSpec) throws CloudRuntimeException { String vmInternalCSName = ""; String vmNameOnVcenter = ""; if(vmSpec == null) { throw new CloudRuntimeException("vmSpec is null"); } vmInternalCSName = vmNameOnVcenter = vmSpec.getName(); if (_instanceNameFlag && vmSpec.getType() == VirtualMachine.Type.User) { String[] tokens = vmInternalCSName.split("-"); if(tokens.length<3) throw new InvalidParameterValueException("Invalid vmInternalCSName format: "+vmInternalCSName+" expected format : *-*-* (e.g -> i-x-y)"); vmNameOnVcenter = String.format("%s-%s-%s-%s", tokens[0], tokens[1], tokens[2], vmSpec.getHostName()); } return new Pair<String, String>(vmInternalCSName, vmNameOnVcenter); }
Source:
<code>public void onResponse(Object response) { <START> operations.addAndGet(performanceUpdateFrequency); <END> }</code><technical_language>introducing calculation bug again</technical_language>

Target:
public void onResponse(Object response) { operations.addAndGet(1); }
Source:
<code>public static PcapFile getPcapFile(Path filePath) throws IOException, BadPcapFileException { if (Files.notExists(filePath) || !Files.isRegularFile(filePath) || Files.size(filePath) < PcapFileValues.GLOBAL_HEADER_SIZE) { throw new BadPcapFileException("Bad Pcap File."); } if (!Files.isReadable(filePath)) { throw new BadPcapFileException("File is not readable."); } <START> FileChannel fileChannel = (FileChannel) checkNotNull(Files.newByteChannel(filePath)); ByteBuffer header = ByteBuffer.allocate(PcapFileValues.PCAPNG_BLOCK_HEADER_SIZE); fileChannel.read(header); <END> header.flip(); int blockType = header.getInt(); if (blockType == PcapFileValues.PCAPNG_SHB) { return new PcapNgFile(filePath); } return new PcapOldFile(filePath); }</code><technical_language>create FileChannel in a try-with-resource block, is closed</technical_language>

Target:
public static PcapFile getPcapFile(Path filePath) throws IOException, BadPcapFileException { if (Files.notExists(filePath) || !Files.isRegularFile(filePath) || Files.size(filePath) < PcapFileValues.GLOBAL_HEADER_SIZE) { throw new BadPcapFileException("Bad Pcap File."); } if (!Files.isReadable(filePath)) { throw new BadPcapFileException("File is not readable."); } try { FileChannel fileChannel = (FileChannel) checkNotNull(Files.newByteChannel(filePath)); ByteBuffer header = ByteBuffer.allocate(PcapFileValues.PCAPNG_BLOCK_HEADER_SIZE); fileChannel.read(header); header.flip(); int blockType = header.getInt(); if (blockType == PcapFileValues.PCAPNG_SHB) { return new PcapNgFile(filePath); } return new PcapOldFile(filePath); } catch (IOException e) { e.printStackTrace(); return new PcapOldFile(filePath); } }
Source:
<code>private ChannelSftp openChannel() throws JSchException { if (channel == null || !channel.isConnected()) { JSch jsch = new JSch(); int port = uri.getPort() <= 0 ? 22 : uri.getPort(); com.jcraft.jsch.Session session = jsch.getSession(username, uri.getHost(), port); session.setConfig("StrictHostKeyChecking", "no"); session.setTimeout(retryPause); session.setPassword(password); session.connect(); channel = (ChannelSftp) session.openChannel("sftp"); channel.connect(); keepChannelOpen = false; } return channel; <START> } <END></code><technical_language>I timeout is retry pause</technical_language>

Target:
private ChannelSftp openChannel() throws JSchException { if (channel == null || !channel.isConnected()) { JSch jsch = new JSch(); int port = uri.getPort() <= 0 ? 22 : uri.getPort(); com.jcraft.jsch.Session session = jsch.getSession(username, uri.getHost(), port); session.setConfig("StrictHostKeyChecking", "no"); session.setTimeout(timeout); session.setPassword(password); session.connect(); channel = (ChannelSftp) session.openChannel("sftp"); channel.connect(); keepChannelOpen = false; } return channel; }
Source:
<code>Mono<Response<DocumentResultCollection<RecognizeEntitiesResult>>> recognizeBatchEntitiesWithResponse( List<TextDocumentInput> textInputs, TextAnalyticsRequestOptions options, Context context) { Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() .setDocuments(Transforms.toMultiLanguageInput(textInputs)); return service.entitiesRecognitionGeneralWithRestResponseAsync( batchInput, options == null ? null : options.getModelVersion(), options == null ? null : options.showStatistics(), context) .doOnSubscribe(ignoredValue -> logger.info("A batch of named entities input - {}", textInputs.toString())) .doOnSuccess(response -> logger.info("A batch of named entities output - {}", response.getValue())) <START> .doOnError(error -> logger.warning("Failed to named entities - {}", error)) <END> .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); }</code><technical_language>nit: Failed recognize named entities - {}</technical_language>

Target:
Mono<Response<DocumentResultCollection<RecognizeEntitiesResult>>> recognizeBatchEntitiesWithResponse( List<TextDocumentInput> textInputs, TextAnalyticsRequestOptions options, Context context) { Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() .setDocuments(Transforms.toMultiLanguageInput(textInputs)); return service.entitiesRecognitionGeneralWithRestResponseAsync( batchInput, options == null ? null : options.getModelVersion(), options == null ? null : options.showStatistics(), context) .doOnSubscribe(ignoredValue -> logger.info("A batch of named entities input - {}", textInputs.toString())) .doOnSuccess(response -> logger.info("A batch of named entities output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to recognize named entities - {}", error)) .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); }
Source:
<code>private MediaSource buildMediaSource(Uri uri) { return new ExtractorMediaSource.Factory( <START> new DefaultHttpDataSourceFactory(getString(R.string.application_name))) <END> .createMediaSource(uri); }</code><technical_language>Instead of application_name user-agent, Identifier.getUserAgent(context)</technical_language>

Target:
private MediaSource buildMediaSource(Uri uri) { return new ExtractorMediaSource.Factory( new DefaultHttpDataSourceFactory(Identifier.getUserAgent(this))) .createMediaSource(uri); }
Source:
<code>private static String getCustomImage(Label label) { <START> Pattern r = Pattern.compile(CUSTOM_IMAGE_SEPARATOR + "([\\w\\.\\-/:]+[\\w])"); <END> Matcher m = r.matcher(label.toString()); if (m.find()) { return m.group(1); } return null; }</code><technical_language>a constant</technical_language>

Target:
private static String getCustomImage(Label label) { Matcher m = CUSTOM_IMAGE_FROM_LABEL_PATTERN.matcher(label.toString()); if (m.find()) { return m.group(1); } return null; }
Source:
<code>private void renameStatisticsFile() { File defaultFile = new File(getPathToDefaultStatisticsResultsFile()); File lnpStatisticsFile = new File(getPathToTestStatisticsResultsFile()); <START> <END> if (!defaultFile.renameTo(lnpStatisticsFile)) { log.warning("Failed in renaming file."); } }</code><technical_language>I this is needed: java if (lnpStatisticsFile.exists()) { lnpStatisticsFile.delete(); }</technical_language>

Target:
private void renameStatisticsFile() { File defaultFile = new File(TestProperties.LNP_TEST_RESULTS_FOLDER + "/statistics.json"); File lnpStatisticsFile = new File(getPathToTestStatisticsResultsFile()); if (lnpStatisticsFile.exists()) { lnpStatisticsFile.delete(); } if (!defaultFile.renameTo(lnpStatisticsFile)) { log.warning("Failed to rename generated statistics.json file."); } }
Source:
<code>@Override protected void log(int priority, String tag, @NonNull String message, Throwable t) { switch (priority) { case Log.VERBOSE: case Log.DEBUG: break; case Log.INFO: Log.i(AnkiDroidApp.TAG, message, t); break; case Log.WARN: Log.w(AnkiDroidApp.TAG, message, t); break; <START> <END> case Log.ERROR: case Log.ASSERT: Log.e(AnkiDroidApp.TAG, message, t); break; } }</code><technical_language>I idea in current implementation I wanted warnings errors follow style debug logger contains extra stack trace information I believe...? I I copy pasted necessary code upstream debug tree implementation, is here: <LINK_0></technical_language>

Target:
protected void log(int priority, String tag, @NonNull String message, Throwable t) { switch (priority) { case Log.VERBOSE: case Log.DEBUG: break; case Log.INFO: Log.i(AnkiDroidApp.TAG, message, t); break; case Log.WARN: Log.w(AnkiDroidApp.TAG, getTag() + "/ " + message, t); break; case Log.ERROR: case Log.ASSERT: Log.e(AnkiDroidApp.TAG, getTag() + "/ " + message, t); break; } }
Source:
<code>public DatagramWriter(boolean secureClose) { byteStream = secureClose ? new ByteArrayOutputStream() { @Override public void close() throws IOException { Bytes.clear(buf); } } : new ByteArrayOutputStream(); <START> <END> resetCurrentByte(); }</code><technical_language>AFAIK, ByteArrayOutputStream do close if this changes in future, I call super.close()</technical_language>

Target:
public DatagramWriter(boolean secureClose) { byteStream = secureClose ? new ByteArrayOutputStream() { @Override public void close() throws IOException { Bytes.clear(buf); super.close(); } } : new ByteArrayOutputStream(); resetCurrentByte(); }
Source:
<code>private String getClientId() { <START> return ( (ClientMessageBusImpl) clientMessageBus ).getClientId(); <END> }</code><technical_language>cast busimpl needed. getClientId is ClientMessageBus interface, no</technical_language>

Target:
String getClientId() { return clientMessageBus.getClientId(); }
Source:
<code><START> public String decode(byte[] wbxmlBody) { <END> try { int i = 4; if (false == ((wbxmlBody[i] & WBXML_TOKEN_MASK) == 0x05)) { return null; } if (false == ((wbxmlBody[i] & WBXML_TOKEN_WITH_ATTRS) == WBXML_TOKEN_WITH_ATTRS)) { return null; } i++; if ((wbxmlBody[i] & WBXML_TOKEN_MASK) == 0x05) { i += 8; } if (false == ((wbxmlBody[i] & WBXML_TOKEN_MASK) == 0x06 || (wbxmlBody[i] & WBXML_TOKEN_MASK) == 0x07)) { return null; } if (wbxmlBody[i + 1] != WBXML_INLINE_STRING) { return null; } i += 2; int j = i; while (wbxmlBody[j] != 0) { j++; } String value = new String(wbxmlBody, i, j-i); return value; } catch (ArrayIndexOutOfBoundsException e) { if (Email.DEBUG) { Log.d(Email.LOG_TAG, "ArrayIndexOutOfBoundsException while handling " + "CONTENT_MIME_TYPE_B_EMN"); } } catch (Exception e) { if (Email.DEBUG) { Log.d(Email.LOG_TAG, "Exception while handling CONTENT_MIME_TYPE_B_EMN " + e); } } return null; }</code><technical_language>this unit tested, please, following: 1. normal message typical ordering 2. normal message reversed ordering 3. bad message (well formed missing expected data) 4. bad message (malformed somehow, e.g. a string a missing \0)</technical_language>

Target:
public String decode(byte[] wbxmlBody) { try { int i = 4; if ((wbxmlBody[i] & WBXML_TOKEN_MASK) != WBXML_TAG_EMN) { return null; } if ((wbxmlBody[i] & WBXML_TOKEN_WITH_ATTRS) != WBXML_TOKEN_WITH_ATTRS) { return null; } i++; if ((wbxmlBody[i] & WBXML_TOKEN_MASK) == WBXML_ATTR_TIMESTAMP) { i++; if (wbxmlBody[i] == WBXML_ATTR_OPAQUE_DATA) { i++; i+= wbxmlBody[i] + 1; } } if ((wbxmlBody[i] & WBXML_TOKEN_MASK) == WBXML_ATTR_MAILBOX && (wbxmlBody[i] & WBXML_TOKEN_MASK) == WBXML_ATTR_MAILBOX_AT) { return null; } if (wbxmlBody[i + 1] != WBXML_INLINE_STRING) { return null; } i += 2; int j = i; while (wbxmlBody[j] != WBXML_ATTR_NULL ) { j++; } if (i == j) return null; String emailAddress = new String(wbxmlBody, i, j-i); i = j + 1; String extension = ExtensionEncoded(wbxmlBody[i]); if (extension != null) { emailAddress += extension; } return emailAddress; } catch (ArrayIndexOutOfBoundsException e) { if (Email.DEBUG) { Log.d(Email.LOG_TAG, "ArrayIndexOutOfBoundsException while handling " + "CONTENT_MIME_TYPE_B_EMN"); } } catch (Exception e) { if (Email.DEBUG) { Log.d(Email.LOG_TAG, "Exception while handling CONTENT_MIME_TYPE_B_EMN " + e); } } return null; }
Source:
<code>public void fillDigest(MessageDigest digest) throws IOException { final DigestWriter digestWriter = new DigestWriter( digest ); for ( JsonObject bodyPart : bodyParts ) { gson.toJson( bodyPart, digestWriter ); <START> digestWriter.insertNewline(); <END> } this.contentLength = digestWriter.getContentLenght(); }</code><technical_language>reset nextBodyToEncodeIndex, writer here? "repeatable"? a half-consumed entity end producing garbage next consumed..</technical_language>

Target:
public void fillDigest(MessageDigest digest) throws IOException { final DigestWriter digestWriter = new DigestWriter( digest ); for ( JsonObject bodyPart : bodyParts ) { gson.toJson( bodyPart, digestWriter ); digestWriter.insertNewline(); } hintContentLenght( digestWriter.getContentLength() ); }
Source:
<code>public void decorate(Object element, IDecoration decoration) { if (Activator.getDefault() == null) return; if (!PlatformUI.isWorkbenchRunning()) return; final IResource resource = getResource(element); <START> if (resource == null) { <END> decorateResourceMapping(element, decoration); } else { try { decorateResource(resource, decoration); } catch(CoreException e) { handleException(resource, e); } } }</code><technical_language>style-nit: curly brackets single line blocks</technical_language>

Target:
public void decorate(Object element, IDecoration decoration) { if (Activator.getDefault() == null) return; if (!PlatformUI.isWorkbenchRunning()) return; final IResource resource = getResource(element); if (resource == null) decorateResourceMapping(element, decoration); else { try { decorateResource(resource, decoration); } catch(CoreException e) { handleException(resource, e); } } }
Source:
<code><START> Registration register() throws JMException { <END> instance = server.registerMBean(StandbyCommand.this, ObjectNameFactory.getObjectName(StandbyCommand.class.getName())); return this; }</code><technical_language>protected instead of package protected</technical_language>

Target:
protected Registration register() throws JMException { instance = server.registerMBean(StandbyCommand.this, ObjectNameFactory.getObjectName(StandbyCommand.class.getName())); return this; }
Source:
<code>private Map<Text,Text> createSplitDirectoryMap(SortedSet<Text> splits, SortedSet<Text> dirs) { Map<Text,Text> data = new HashMap<>(); <START> Iterator<Text> s = splits.iterator(); <END> Iterator<Text> d = dirs.iterator(); while (s.hasNext() && d.hasNext()) { data.put(s.next(), d.next()); } return data; }</code><technical_language>add Preconditions.checkArgument(splits.size() == dirs.size());</technical_language>

Target:
private Map<Text,Text> createSplitDirectoryMap(SortedSet<Text> splits, SortedSet<Text> dirs) { Preconditions.checkArgument(splits.size() == dirs.size()); Map<Text,Text> data = new HashMap<>(); Iterator<Text> s = splits.iterator(); Iterator<Text> d = dirs.iterator(); while (s.hasNext() && d.hasNext()) { data.put(s.next(), d.next()); } return data; }
Source:
<code>public void tearDown() { File test_scripts_folder = new File(filepathPrefix); if(test_scripts_folder.exists()) { for (String entry : test_scripts_folder.list()) { if(!new File(test_scripts_folder.getPath(), entry).delete()) { fail("Failed to delete file " + entry); } } if(!test_scripts_folder.delete()) { <START> fail("Failed to deleter folder " + test_scripts_folder.getPath()); <END> } } }</code><technical_language>suggestion fail("Failed delete folder " + test_scripts_folder.getPath());</technical_language>

Target:
public void tearDown() { File test_scripts_folder = new File(filepathPrefix); if(test_scripts_folder.exists()) { for (String entry : test_scripts_folder.list()) { if(!new File(test_scripts_folder.getPath(), entry).delete()) { fail("Failed to delete file " + entry); } } if(!test_scripts_folder.delete()) { fail("Failed to delete folder " + test_scripts_folder.getPath()); } } }
Source:
<code>public void addCoreColumn(Term term, String value) { if (coreIdTerm != null && coreIdTerm.equals(term)) { throw new IllegalStateException("You cannot add a term that was specified as coreId term"); } List<Term> coreTerms = terms.get(coreRowType); if (!coreTerms.contains(term)) { if (useHeaders && recordNum>1){ <START> throw new IllegalStateException("You cannot add new terms after the first row when headers are enabled"); <END> } coreTerms.add(term); } try { coreRow.put(term, value); } catch (NullPointerException e) { throw new IllegalStateException("No core record has been created yet. Call newRecord() at least once"); } }</code><technical_language>check for useHeaders relevant. header line, this create a sparse file row lengths file</technical_language>

Target:
public void addCoreColumn(Term term, String value) { if (coreIdTerm != null && coreIdTerm.equals(term)) { throw new IllegalStateException("You cannot add a term that was specified as coreId term"); } List<Term> coreTerms = terms.get(coreRowType); if (!coreTerms.contains(term)) { if (recordNum>1){ throw new IllegalStateException("You cannot add new terms after the first row when headers are enabled"); } coreTerms.add(term); } try { coreRow.put(term, value); } catch (NullPointerException e) { throw new IllegalStateException("No core record has been created yet. Call newRecord() at least once"); } }