auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void close() { ExecutorService maybeNull = maybeNull(); if (maybeNull != null) { maybeNull.shutdownNow(); try { START maybeNull.awaitTermination(5, TimeUnit.SECONDS); END } catch (InterruptedException e) { // at least we tried } } } I think we usually wait 1 second by default now.. though it is arbitrary anyway

Target:
public void close() { ExecutorService maybeNull = maybeNull(); if (maybeNull != null) { maybeNull.shutdownNow(); try { maybeNull.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException e) { // at least we tried } } }
Source:
ElasticsearchHttpSpanConsumer(ElasticsearchHttpStorage es) { this.es = es; this.indexNameFormatter = es.indexNameFormatter(); START this.indexToServiceSpansCache = Collections.synchronizedMap(new LinkedHashMap<String, Set<Pair<String>>>() { END @Override protected boolean removeEldestEntry(Map.Entry<String, Set<Pair<String>>> eldest) { return size() > MAX_CACHE_DAYS; } }); } if static, should be initialized outside the ctor.. maybe make it final static.

Target:
ElasticsearchHttpSpanConsumer(ElasticsearchHttpStorage es) { this.es = es; this.indexNameFormatter = es.indexNameFormatter(); }
Source:
START public void setLogsUrl(String logsUrl) { END this.logsUrl = logsUrl; } set if not null or empty

Target:
public void setLogsUrl(String logsUrl) { if (!StringUtils.isEmpty(logsUrl)) { this.logsUrl = logsUrl; } }
Source:
public void annotationKeys() { assertThat(CassandraUtil.annotationKeys(QueryRequest.builder() .lookback(86400000L) .serviceName("service") .addAnnotation(Constants.ERROR) .addBinaryAnnotation(TraceKeys.HTTP_METHOD, "GET").build())) START .containsExactly("service", "error", "http.method:GET"); END } interesting.. surprised this works, but maybe I shouldn't be

Target:
public void annotationKeys() { assertThat(CassandraUtil.annotationKeys(QueryRequest.builder() .lookback(86400000L) .serviceName("service") .addAnnotation(Constants.ERROR) .addBinaryAnnotation(TraceKeys.HTTP_METHOD, "GET").build())) .containsExactly("error", "http.method:GET", "service"); }
Source:
public void correctHttpResponse() throws Exception { START final PublicMetrics publicMetrics = () -> Collections.singleton(new Metric<Number>("mem.free", 1024)); END final ResponseEntity<String> response = responseForMetrics(publicMetrics); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); assertThat(response.getHeaders().getContentType().toString(), equalTo("text/plain;version=0.0.4;charset=utf-8")); } no big deal, but we don't put final on variables even if it is explicit and there are good reasons why some folks make conventions like that. leaving them out keeps line shorter and focuses more attention on the test code (at risk of someone doing the shell-game with references)

Target:
public void correctHttpResponse() throws Exception { PublicMetrics publicMetrics = () -> Collections.singleton(new Metric<Number>("mem.free", 1024)); ResponseEntity<String> response = responseForMetrics(publicMetrics); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); assertThat(response.getHeaders().getContentType().toString(), equalTo("text/plain;version=0.0.4;charset=utf-8")); }
Source:
private boolean isJodaTimeInClasspath() { if ( jodaTimeInClassPath != null ) { return jodaTimeInClassPath.booleanValue(); } START jodaTimeInClassPath = isClassPresent( JODA_TIME_CLASS_NAME ); END return jodaTimeInClassPath.booleanValue(); } Some nitpicking (for a change!); I usually see this pattern written that way: ``` if ( jodaTimeInClassPath == null ) { jodaTimeInClassPath = isClassPresent( JODA_TIME_CLASS_NAME ); } return jodaTimeInClassPath.booleanValue(); ```

Target:
private boolean isJodaTimeInClasspath() { if ( jodaTimeInClassPath == null ) { jodaTimeInClassPath = isClassPresent( JODA_TIME_CLASS_NAME ); } return jodaTimeInClassPath.booleanValue(); }
Source:
default S locales(Locale... locales) { locales( new HashSet<>( Arrays.asList( locales ) ) ); START return (S) this; END } You could do this instead, and avoid the unchecked cast: ``` return locales( new HashSet<>( Arrays.asList( locales ) ) ); ```

Target:
default S locales(Locale... locales) { return locales( new HashSet<>( Arrays.asList( locales ) ) ); }
Source:
protected int compare(Number number) { // At this point number can be a floating point number and it should be treated differently in such case: if ( number instanceof Double ) { return NumberComparatorHelper.compare( (Double) number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); } if ( number instanceof Float ) { return NumberComparatorHelper.compare( (Float) number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); START } END return NumberComparatorHelper.compare( number, maxValue ); } Is there a reason why you split this logic in two? I would have put everything in `NumberComparatorHelper#compare(Number, long)`.

Target:
protected int compare(Number number) { return NumberComparatorHelper.compare( number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); }
Source:
public Optional<JavaBeanField> findDeclaredField(Class<?> declaringClass, String property) { Contracts.assertNotNull( declaringClass, MESSAGES.classCannotBeNull() ); Field field = run( GetDeclaredField.action( declaringClass, property ) ); START String resolvedName = propertyNodeNameProvider.getName( javaBeanPropertyFrom( declaringClass, property ) ); END return Optional.ofNullable( field ).map( f -> new JavaBeanField( f, resolvedName ) ); } if `field` at this point is `null` - there's not need to do any additional work we should just return `Optional.empty()`. Otherwise we can find the resolved name and use `Optional.of()`. Something like: ```java Field field = run( GetDeclaredField.action( declaringClass, property ) ); if ( field == null ) { return Optional.empty(); } else { String resolvedName = propertyNodeNameProvider.getName( new JavaBeanPropertyImpl( declaringClass, property ) ); return Optional.of( new JavaBeanField( field, resolvedName ) ); } ```

Target:
public Optional<JavaBeanField> findDeclaredField(Class<?> declaringClass, String property) { Contracts.assertNotNull( declaringClass, MESSAGES.classCannotBeNull() ); Field field = run( GetDeclaredField.action( declaringClass, property ) ); return Optional.ofNullable( field ).map( this::field ); }
Source:
START @Override public Type[] getParameterTypes() { END return method.getParameterTypes(); } The `@Override` annotations should be on their own line.

Target:
public Class<?>[] getParameterTypes() { return method.getParameterTypes(); }
Source:
public JavaBeanExecutable<?> executable(Executable executable) { if ( executable instanceof Constructor ) { return new JavaBeanConstructor( (Constructor<?>) executable ); } START return executable( executable.getDeclaringClass(), ( (Method) executable ) ); END } Can't you just call `executable(Class<?> declaringClass, Executable executable)` and remove the `if()`?

Target:
public JavaBeanExecutable<?> executable(Executable executable) { return executable( executable.getDeclaringClass(), executable ); }
Source:
@Override public Class<?> getDeclaringClass() { START return declaringClass; END } Fixed.

Target:
public Class<?> getDeclaringClass() { return declaringClass; }
Source:
private boolean isAnnotationAllowed(Annotation annotationToCheck, Set<Annotation> processedAnnotations) { // need to have this to prevent infinite loops for example on annotations like @Target if ( !processedAnnotations.add( annotationToCheck ) ) { return false; } Class<? extends Annotation> annotationType = annotationToCheck.annotationType(); return ALLOWED_ANNOTATIONS.contains( annotationType ) || Arrays.stream( annotationType.getDeclaredAnnotations() ) START .anyMatch( annotation -> isAnnotationAllowed( annotation, processedAnnotations ) ); END } Same here, not sure this construct buys us much.

Target:
private boolean isAnnotationAllowed(Annotation annotationToCheck, Set<Annotation> processedAnnotations) { // Need to have this to prevent infinite loops, for example on annotations like @Target if ( !processedAnnotations.add( annotationToCheck ) ) { return false; } Class<? extends Annotation> annotationType = annotationToCheck.annotationType(); if ( ALLOWED_ANNOTATIONS.contains( annotationType ) ) { return true; } for ( Annotation annotation : annotationType.getDeclaredAnnotations() ) { if ( isAnnotationAllowed( annotation, processedAnnotations ) ) { return true; } } return false; }
Source:
ReturnValueExecutableValidationContext( ConstraintValidatorManager constraintValidatorManager, ConstraintValidatorFactory constraintValidatorFactory, ValidatorScopedContext validatorScopedContext, TraversableResolver traversableResolver, HibernateConstraintValidatorInitializationContext constraintValidatorInitializationContext, T rootBean, Class<T> rootBeanClass, BeanMetaData<T> rootBeanMetaData, Executable executable, Optional<ExecutableMetaData> executableMetaData, Object executableReturnValue ) { super( constraintValidatorManager, constraintValidatorFactory, validatorScopedContext, traversableResolver, constraintValidatorInitializationContext, rootBean, rootBeanClass, rootBeanMetaData, buildDisableAlreadyValidatedBeanTracking( executableMetaData ) ); this.executable = executable; this.executableReturnValue = executableReturnValue; START this.executableMetaData = executableMetaData; END } Very minor but let's try to be consistent with the order of the method parameters.

Target:
ReturnValueExecutableValidationContext( ConstraintValidatorManager constraintValidatorManager, ConstraintValidatorFactory constraintValidatorFactory, ValidatorScopedContext validatorScopedContext, TraversableResolver traversableResolver, HibernateConstraintValidatorInitializationContext constraintValidatorInitializationContext, T rootBean, Class<T> rootBeanClass, BeanMetaData<T> rootBeanMetaData, Executable executable, Optional<ExecutableMetaData> executableMetaData, Object executableReturnValue ) { super( constraintValidatorManager, constraintValidatorFactory, validatorScopedContext, traversableResolver, constraintValidatorInitializationContext, rootBean, rootBeanClass, rootBeanMetaData, buildDisableAlreadyValidatedBeanTracking( executableMetaData ) ); this.executable = executable; this.executableMetaData = executableMetaData; this.executableReturnValue = executableReturnValue; }
Source:
public boolean equals(Object o) { if ( this == o ) { return true; } START if ( o == null || o.getClass() != BeanGroupProcessedUnit.class ) { END return false; } BeanGroupProcessedUnit that = (BeanGroupProcessedUnit) o; if ( bean != that.bean ) { // instance equality return false; } if ( !group.equals( that.group ) ) { return false; } return true; } Annoying one... Please make it a separate JIRA and commit.

Target:
public boolean equals(Object o) { if ( this == o ) { return true; } // No need to check if the class matches because of how this class is used in the set. BeanGroupProcessedUnit that = (BeanGroupProcessedUnit) o; if ( bean != that.bean ) { // instance equality return false; } if ( !group.equals( that.group ) ) { return false; } return true; }
Source:
public boolean equals(Object o) { // no need to check for instance equality or if the calss match because of // how this class is used in the set. BeanPathMetaConstraintProcessedUnit that = (BeanPathMetaConstraintProcessedUnit) o; if ( bean != that.bean ) { // instance equality return false; } if ( metaConstraint != that.metaConstraint ) { return false; } if ( !path.equals( that.path ) ) { return false; } START END return true; } Can't you keep that one at the top? Let's avoid the cast if we can.

Target:
public boolean equals(Object o) { if ( this == o ) { return true; } // No need to check if the class matches because of how this class is used in the set. BeanPathMetaConstraintProcessedUnit that = (BeanPathMetaConstraintProcessedUnit) o; if ( bean != that.bean ) { // instance equality return false; } if ( metaConstraint != that.metaConstraint ) { return false; } if ( !path.equals( that.path ) ) { return false; } return true; }
Source:
public void initialize(ConstraintDescriptor<ParameterScriptAssert> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) { ParameterScriptAssert constraintAnnotation = constraintDescriptor.getAnnotation(); validateParameters( constraintAnnotation ); this.languageName = constraintAnnotation.lang(); this.script = constraintAnnotation.script(); START this.escapedScript = InterpolationHelper.escapeMessageParameter( constraintAnnotation.script() ); END initializeScriptContext( initializationContext ); } As mentioned above, let's move these 3 to the super `initialize()` method.

Target:
public void initialize(ConstraintDescriptor<ParameterScriptAssert> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) { ParameterScriptAssert constraintAnnotation = constraintDescriptor.getAnnotation(); validateParameters( constraintAnnotation ); initialize( constraintAnnotation.lang(), constraintAnnotation.script(), initializationContext ); }
Source:
public <T> T getMandatoryParameter(String parameterName, Class<T> type) { START if ( !parameters.containsKey( parameterName ) ) { END throw LOG.getUnableToFindAnnotationParameterException( parameterName, null ); } Object parameter = parameters.get( parameterName ); if ( !type.isAssignableFrom( parameter.getClass() ) ) { throw LOG.getWrongParameterTypeException( type, parameter.getClass() ); } return (T) parameter; } We could avoid the `containsKey()` + `get()` cascade by just checking the result of the latter on being null.

Target:
public <T> T getMandatoryParameter(String parameterName, Class<T> type) { Object parameter = parameters.get( parameterName ); if ( parameter == null ) { throw LOG.getUnableToFindAnnotationParameterException( parameterName, null ); } if ( !type.isAssignableFrom( parameter.getClass() ) ) { throw LOG.getWrongParameterTypeException( type, parameter.getClass() ); } return (T) parameter; }
Source:
private static int buildHashCode(ConstraintLocation delegate, TypeVariable<?> typeParameter) { START int result = delegate != null ? delegate.hashCode() : 0; END result = 31 * result + typeParameter.hashCode(); return result; } Didn't we agree that the null check on delegate isn't needed (sambe above)?

Target:
private static int buildHashCode(ConstraintLocation delegate, TypeVariable<?> typeParameter) { int result = delegate.hashCode(); result = 31 * result + typeParameter.hashCode(); return result; }
Source:
public BeanMetaData<T> getRootBeanMetaData() { START if ( rootBeanClass != null && rootBeanMetaData == null ) { END rootBeanMetaData = beanMetaDataManager.getBeanMetaData( rootBeanClass ); } return rootBeanMetaData; } What's the reasoning for initializing it lazily instead of doing it in the constructor and making the field truly final? Btw. can `rootBeanClass()` ever be null?

Target:
public BeanMetaData<T> getRootBeanMetaData() { return rootBeanMetaData; }
Source:
private static int buildHashCode(ConstraintDescriptorImpl<?> constraintDescriptor, ConstraintLocation location, List<ValueExtractorDescriptor> valueExtractorDescriptors) { final int prime = 31; int result = 1; START result = prime * result + ( constraintDescriptor != null ? constraintDescriptor.hashCode() : 0 ); END result = prime * result + ( location != null ? location.hashCode() : 0 ); return result; } Are the null checks really needed?

Target:
private static int buildHashCode(ConstraintDescriptorImpl<?> constraintDescriptor, ConstraintLocation location, List<ValueExtractorDescriptor> valueExtractorDescriptors) { final int prime = 31; int result = 1; result = prime * result + constraintDescriptor.hashCode(); result = prime * result + location.hashCode(); return result; }
Source:
public static <T> ArrayList<T> newArrayList(int size) { START return new ArrayList<T>( getInitialCapacityFromExpectedSize( size ) ); END } Why are you doing it for a list type?

Target:
public static <T> ArrayList<T> newArrayList(int size) { return new ArrayList<T>( size ); }
Source:
Type getExtractedType() { return extractedType; START } END Missing new line.

Target:
public Type getExtractedType() { return extractedType; }
Source:
private ClockProvider createClockProvider(Configuration<?> config) { BootstrapConfiguration bootstrapConfiguration = config.getBootstrapConfiguration(); String clockProviderFqcn = bootstrapConfiguration.getClockProviderClassName(); if ( clockProviderFqcn == null ) { return config.getDefaultClockProvider(); } @SuppressWarnings("unchecked") START Class<ClockProvider> clockProviderClass = (Class<ClockProvider>) run( END LoadClass.action( clockProviderFqcn, null ) ); return createInstance( clockProviderClass ); } Technically, wouldn't it be `Class<? extends ClockProvider>`?

Target:
private ClockProvider createClockProvider(Configuration<?> config) { BootstrapConfiguration bootstrapConfiguration = config.getBootstrapConfiguration(); String clockProviderFqcn = bootstrapConfiguration.getClockProviderClassName(); if ( clockProviderFqcn == null ) { return config.getDefaultClockProvider(); } @SuppressWarnings("unchecked") Class<? extends ClockProvider> clockProviderClass = (Class<? extends ClockProvider>) run( LoadClass.action( clockProviderFqcn, null ) ); return createInstance( clockProviderClass ); }
Source:
public void testValidatePropertyWithNestedPathAndNullPropertyInTheWay() { Validator validator = getValidator(); X someX = new X(); Set<ConstraintViolation<X>> constraintViolationsX = validator.validateProperty( someX, "list[0].foo" ); START assertNumberOfViolations( constraintViolationsX, 1 ); END assertCorrectPropertyPaths( constraintViolationsX, "list[0].foo" ); } Seems these assertions are never reached due to the (expected) exception before?

Target:
public void testValidatePropertyWithNestedPathAndNullPropertyInTheWay() { Validator validator = getValidator(); X someX = new X(); validator.validateProperty( someX, "list[0].foo" ); }
Source:
public void reportErrors(Collection<ConstraintCheckIssue> errors) { START errors.forEach( this::reportError ); END } Looks like there is a Java 8 construct left.

Target:
public void reportErrors(Collection<ConstraintCheckIssue> errors) { for ( ConstraintCheckIssue error : errors ) { reportError( error ); } }
Source:
START protected boolean canCheckThisAnnotation(AnnotationMirror annotation) { END return annotationClasses.contains( annotation.getAnnotationType().asElement().toString() ); } Seems that's never overridden. Should it be private then?

Target:
private boolean canCheckThisAnnotation(AnnotationMirror annotation) { return annotationClasses.contains( annotation.getAnnotationType().asElement().toString() ); }
Source:
protected ConstraintViolationSetAssert(Set<? extends ConstraintViolation<?>> actualViolations) { START super( new ArrayList(actualViolations) ); END this.actualViolations = actualViolations; } Have you checked if IterableAssert could be sufficient as a base class? It would avoid this conversion.

Target:
protected ConstraintViolationSetAssert(Set<? extends ConstraintViolation<?>> actualViolations) { super( actualViolations ); this.actualViolations = actualViolations; }
Source:
protected GroupConversionDescriptorSetAssert(Set<GroupConversionDescriptor> actual) { START super( new ArrayList( actual ) ); END this.actual = actual; } Same question here.

Target:
protected GroupConversionDescriptorSetAssert(Set<GroupConversionDescriptor> actual) { super( actual ); this.actual = actual; }
Source:
private ExecutableElement getValidationAppliesToMethod(Element annotation) { for ( Element e : annotation.getEnclosedElements() ) { ExecutableElement method = e.accept( new ElementKindVisitor6<ExecutableElement, Void>() { @Override public ExecutableElement visitExecutableAsMethod(ExecutableElement e, Void p) { if ( e.getSimpleName().contentEquals( "validationAppliesTo" ) ) { return e; } START return super.visitExecutableAsMethod( e, p ); END } }, null ); if ( method != null ) { return method; } } return null; } I don't think the call to the super method is needed?

Target:
private ExecutableElement getValidationAppliesToMethod(Element annotation) { for ( Element e : annotation.getEnclosedElements() ) { ExecutableElement method = e.accept( new ElementKindVisitor6<ExecutableElement, Void>() { @Override public ExecutableElement visitExecutableAsMethod(ExecutableElement e, Void p) { if ( e.getSimpleName().contentEquals( "validationAppliesTo" ) ) { return e; } return null; } }, null ); if ( method != null ) { return method; } } return null; }
Source:
public static String join(Iterable<?> iterable, String separator) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( Object object : iterable ) { if ( !isFirst ) { sb.append( separator ); } else { isFirst = false; } START sb.append( object ); END } return sb.toString(); } Does that handle 'null' properly?

Target:
public static String join(Iterable<?> iterable, String separator) { if ( iterable == null ) { return null; } StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( Object object : iterable ) { if ( !isFirst ) { sb.append( separator ); } else { isFirst = false; } sb.append( object ); } return sb.toString(); }
Source:
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if ( resolve( context, base, method ) ) { throw new ValidationException( "Invalid property" ); } Object returnValue = null; // due to bugs in most EL implementations when it comes to evaluating varargs we take care of the formatter call // ourselves. START if ( base instanceof FormatterWrapper ) { END returnValue = evaluateFormatExpression( context, base, method, paramTypes, params ); } return returnValue; } Couldn't also other methods be invoked, e.g. `${'FooBar'.subString(3)}`? I guess it doesn't make awfully lots of sense, but I think it is legal. WDYT?

Target:
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if ( resolve( context, base, method ) ) { throw new ValidationException( "Invalid property" ); } Object returnValue = null; // due to bugs in most EL implementations when it comes to evaluating varargs we take care of the formatter call // ourselves. if ( base instanceof FormatterWrapper ) { returnValue = evaluateFormatExpression( context, method, params ); } return returnValue; }
Source:
START public void EdgeReached(Direction edge) { END postEvent(this, "EdgeReached", edge); } Note that one of the reasons I chose to use the `@EnumeratedBy` annotation was due to the fact that we don't know if there are extensions out there that are calling the `int` version of this method. Using the annotation allows us to keep the signature of the function the same at runtime. By outright changing this, if such an extension exists it would result in a NoSuchMethodError after this change is published. I would recommend we also have an `int` version to maintain backward compatibility.

Target:
public void EdgeReached(Direction edge) { // We will have to use getValue() to send an int for backwards-compat. But I decided to use this // function as the base because I think converting the enum is a better check than the one from // before. // But if you think using the old func as the base is less confusing, we can do that. postEvent(this, "EdgeReached", edge.getValue()); }
Source:
public void updateMenuState(int numSelectedProjects, int numProjects) { boolean allowDelete = !isReadOnly && numSelectedProjects > 0; boolean allowExport = numSelectedProjects > 0; boolean allowExportAll = numProjects > 0; String exportProjectLabel = numSelectedProjects > 1 ? START MESSAGES.exportSelectedProjectsMenuItem() : MESSAGES.exportProjectMenuItem(); END fileDropDown.setItemHtmlById(WIDGET_NAME_EXPORTPROJECT, exportProjectLabel); fileDropDown.setItemEnabled(MESSAGES.deleteProjectMenuItem(), allowDelete); fileDropDown.setItemEnabledById(WIDGET_NAME_EXPORTPROJECT, allowExport); fileDropDown.setItemEnabled(MESSAGES.exportAllProjectsMenuItem(), allowExportAll); } It'd be nice if we change the message so that it takes the numeric argument so the string is something like "Export N selected projects"

Target:
public void updateMenuState(int numSelectedProjects, int numProjects) { boolean allowDelete = !isReadOnly && numSelectedProjects > 0; boolean allowExport = numSelectedProjects > 0; boolean allowExportAll = numProjects > 0; String exportProjectLabel = numSelectedProjects > 1 ? MESSAGES.exportSelectedProjectsMenuItem(numSelectedProjects) : MESSAGES.exportProjectMenuItem(); fileDropDown.setItemHtmlById(WIDGET_NAME_EXPORTPROJECT, exportProjectLabel); fileDropDown.setItemEnabled(MESSAGES.deleteProjectMenuItem(), allowDelete); fileDropDown.setItemEnabledById(WIDGET_NAME_EXPORTPROJECT, allowExport); fileDropDown.setItemEnabled(MESSAGES.exportAllProjectsMenuItem(), allowExportAll); }
Source:
public final boolean IsConnected() { if (sdkLevel >= SdkLevel.LEVEL_ICE_CREAM_SANDWICH) { return (connectedBluetoothSocket != null && BluetoothReflection.isBluetoothSocketConnected(connectedBluetoothSocket)); } START else END return (connectedBluetoothSocket != null); } `else` case should still have curly braces even for a single statement ([Google Java Style Guide](https://google.github.io/styleguide/javaguide.html#s4.1.1-braces-always-used)).

Target:
public final boolean IsConnected() { if (sdkLevel >= SdkLevel.LEVEL_ICE_CREAM_SANDWICH) { return (connectedBluetoothSocket != null && BluetoothReflection.isBluetoothSocketConnected(connectedBluetoothSocket)); } else { return (connectedBluetoothSocket != null); } }
Source:
public int getLeftX() { try { START return (int) Math.round(Double.parseDouble(getPropertyValue(PROPERTY_NAME_X))); END } catch (NumberFormatException e) { // Ignore this. If we throw an exception here, the project is unrecoverable. return 0; } } Shouldn't this return `x` rather than re-parsing the property?

Target:
public int getLeftX() { return x; }
Source:
public int getTopY() { try { START return (int) Math.round(Double.parseDouble(getPropertyValue(PROPERTY_NAME_Y))); END } catch (NumberFormatException e) { // Ignore this. If we throw an exception here, the project is unrecoverable. return 0; } } Return `y` instead of re-parsing?

Target:
public int getTopY() { return y; }
Source:
START public void OriginAtCenter(boolean b) { END originAtCenter = b; } I'm thinking that we should make this `protected` so that it can't be inadvertently called unless the subclass explicitly makes it `public` and provides the right Simple annotations.

Target:
protected void OriginAtCenter(boolean b) { originAtCenter = b; }
Source:
public MockBarChartDataModel(MockBarChartView view) { super(view.getChartWidget().getData()); // Set local view variable (needed to invoke the updateLabels method) START this.view = view; END // Create the Data Series object dataSeries = new BarDataset(); // Set the default style properties for the Data Series setDefaultStylingProperties(); // Adds the Data Series to the Chart. addDataSeriesToChart(); } Something to think about: if all of the DataModel types have a specific view type, then you could add an additional generic parameter to MockChartDataModel for the view type in addition to the dataset. This would allow you to move the view field up to the superclass.

Target:
public MockBarChartDataModel(MockBarChartView view) { super(view); // Create the Data Series object dataSeries = new BarDataset(); // Set the default style properties for the Data Series setDefaultStylingProperties(); // Adds the Data Series to the Chart. addDataSeriesToChart(); }
Source:
public void addDataFile(MockDataFile dataFileSource) { List<String> columnNames = dataFileSource.getColumnNames(); for (String column : columnNames) { // Create a new MockChartData2D component and attach it to the Chart // TODO: More data component support MockChartData2D data = new MockChartData2D(editor); addComponent(data); START data.addToChart(MockChart.this); END // Change the properties of the instantiated data component data.changeProperty("DataFileYColumn", column); data.changeProperty("Label", column); data.changeProperty("Source", dataFileSource.getName()); } } Is qualifying `this` here necessary? The context looks to be `MockChart` already.

Target:
public void addDataFile(MockDataFile dataFileSource) { List<String> columnNames = dataFileSource.getColumnNames(); for (String column : columnNames) { // Create a new MockChartData2D component and attach it to the Chart // TODO: More data component support MockChartData2D data = new MockChartData2D(editor); addComponent(data); data.addToChart(this); // Change the properties of the instantiated data component data.changeProperty("DataFileYColumn", column); data.changeProperty("Label", column); data.changeProperty("Source", dataFileSource.getName()); } }
Source:
public List<List<String>> getColumns(List<String> columns) { START ArrayList<List<String>> dataColumns = new ArrayList<List<String>>(); END for (String column : columns) { // Get the index of the column and get the column itself int index = columnNames.indexOf(column); List<String> dataColumn = getColumn(index); // Add the column to the result dataColumns.add(dataColumn); } return dataColumns; } Local variable could be declared List instead of ArrayList. Is this worth caching?

Target:
public List<List<String>> getColumns(List<String> columns) { List<List<String>> dataColumns = new ArrayList<List<String>>(); for (String column : columns) { // Get the index of the column and get the column itself int index = columnNames.indexOf(column); List<String> dataColumn = getColumn(index); // Add the column to the result dataColumns.add(dataColumn); } return dataColumns; }
Source:
public void onColumnsChange(MockDataFile dataFile) { // Edge case: Event originates from the wrong MockDataFile source START if (!this.dataFile.equals(dataFile)) { END return; } // Update the column entries updateColumns(); } It seems like `==` would be sufficient and faster than `.equals()` here since we'd be testing identity of the component rather than equality?

Target:
public void onColumnsChange(MockDataFile dataFile) { // Edge case: Event originates from the wrong MockDataFile source if (this.dataFile != dataFile) { return; } // Update the column entries updateColumns(); }
Source:
public void removeDataObserver(ChartDataBase dataComponent) { START dataSourceObservers.remove(dataComponent); END // No more Data Source observers exist; // Shut down polling service and null it // (the reason for nulling is so that a new // service could be created upon adding a new // observer) if (dataSourceObservers.isEmpty()) { dataPollService.shutdown(); dataPollService = null; } } Have add and remove synchronized on dataSourceObservers just on the off chance an extension tries to do something on a separate thread introducing a race condition.

Target:
public synchronized void removeDataObserver(ChartDataBase dataComponent) { dataSourceObservers.remove(dataComponent); // No more Data Source observers exist; // Shut down polling service and null it // (the reason for nulling is so that a new // service could be created upon adding a new // observer) if (dataSourceObservers.isEmpty()) { dataPollService.shutdown(); dataPollService = null; } }
Source:
public void Namespace(String namespace) { this.namespace = namespace; sharedPreferences = context.getSharedPreferences(namespace, Context.MODE_PRIVATE); // SharedPreferences listener currently exists; Unregister it START if (sharedPreferenceChangeListener != null) { END sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); } // Create a new SharedPreferences change listener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // Upon value change, notify the observers with the key and the value notifyDataObservers(key, GetValue(key, null)); } }; // Register the SharedPreferences change listener sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); } You will need to unregister before line 94, otherwise you're calling unregister on a different sharedPreferences object than the register call was made on.

Target:
public void Namespace(String namespace) { this.namespace = namespace; // SharedPreferences previously defined; Unregister the change listener. if (sharedPreferences != null) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); } sharedPreferences = context.getSharedPreferences(namespace, Context.MODE_PRIVATE); // Register the SharedPreferences change listener sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); }
Source:
START public List getDataValue(String key) { END // Get the value from the TinyDB data with the specified key Object value = GetValue(key, new ArrayList()); // Check if value is of type List, and return it if that is the case. if (value instanceof List) { return (List)value; } // Default option (could not parse data): return empty ArrayList return new ArrayList(); } Consider switching this to `List<Object>` instead of the unspecified `List` type.

Target:
public List<Object> getDataValue(String key) { // Get the value from the TinyDB data with the specified key Object value = GetValue(key, new ArrayList()); // Check if value is of type List, and return it if that is the case. if (value instanceof List) { return (List<Object>) value; } // Default option (could not parse data): return empty ArrayList return new ArrayList<Object>(); }
Source:
public synchronized T getDataset() { START return dataset; END } It's not clear that dataset is updated other than being set in the constructors of subclasses. I don't see what synchronizing this method actually gains for the performance loss.

Target:
public T getDataset() { return dataset; }
Source:
private YailList getYailListPropertyHelper(Callable<YailList> propertyCallable) { // Since reading might be in progress, the task of // getting a DataFile property should be queued so that the // thread is blocked until the reading is finished. try { return threadRunner .submit(propertyCallable) // Run the callable async (and queued) START .get(); // Get the property (blocks thread until previous threads finish) END } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return new YailList(); // Return empty list (default option) } This could potentially block the UI thread for long enough time that an ANR appears, depending on the size of the file being read.

Target:
private YailList getYailListPropertyHelper(Callable<YailList> propertyCallable) { // Since reading might be in progress, the task of // getting a DataFile property should be queued so that the // thread is blocked until the reading is finished. try { return threadRunner .submit(propertyCallable) // Run the callable async (and queued) .get(); // Get the property (blocks thread until previous threads finish) } catch (InterruptedException e) { Log.e(this.getClass().getName(), e.getMessage()); } catch (ExecutionException e) { Log.e(this.getClass().getName(), e.getMessage()); } return new YailList(); // Return empty list (default option) }
Source:
public void changePreviewSize(int width, int height, int idx) { // It will definitely be modified in the future to add more options. PORTRAIT_WIDTH = width; PORTRAIT_HEIGHT = height; LANDSCAPE_WIDTH = height; LANDSCAPE_HEIGHT = width; idxPhoneSize = idx; setPhoneStyle(); START if (landscape) END resizePanel(LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT); else resizePanel(width, height); } Code style: Curly braces after if and around else statements.

Target:
public void changePreviewSize(int width, int height, int idx) { // It will definitely be modified in the future to add more options. PORTRAIT_WIDTH = width; PORTRAIT_HEIGHT = height; LANDSCAPE_WIDTH = height; LANDSCAPE_HEIGHT = width; idxPhoneSize = idx; setPhoneStyle(); if (landscape) { resizePanel(LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT); } else { resizePanel(width, height); } }
Source:
private void updateLayoutType(String value) { layout = value; YoungAndroidListViewAddDataPropertyEditor editor = (YoungAndroidListViewAddDataPropertyEditor) properties.getProperty(PROPERTY_NAME_LISTVIEW_ADD_DATA).getEditor(); editor.setLayout(layout); START if(!currentItems.isEmpty()) { END createLabelItem(currentItems); } } Code style: space after `if`

Target:
private void updateLayoutType(String value) { layout = Integer.parseInt(value); YoungAndroidListViewAddDataPropertyEditor editor = (YoungAndroidListViewAddDataPropertyEditor) properties.getProperty(PROPERTY_NAME_LISTVIEW_ADD_DATA).getEditor(); editor.setLayout(layout); if (!currentItems.isEmpty()) { createLabelItem(currentItems); } }
Source:
public void TextSize(int fontSize) { START if(fontSize>1000) END textSize = 999; else textSize = fontSize; setAdapterData(); } See earlier notes about code style with if statements.

Target:
public void TextSize(int fontSize) { if (fontSize > 1000 || fontSize < 1) textSize = 999; else textSize = fontSize; setAdapterData(); }
Source:
public void resultReturned(int requestCode, int resultCode, Intent data) { if (requestCode == this.requestCode && resultCode == Activity.RESULT_OK) { if (data.hasExtra(RecognizerIntent.EXTRA_RESULTS)) { ArrayList<String> results = data.getExtras().getStringArrayList(RecognizerIntent.EXTRA_RESULTS); result = results.get(0); speechListener.onResult(result); } else { result = ""; START } END } } In the current version of the code, the result is reported regardless of which branch is taken here. I recommend you keep the semantics consistent and move the call to `onResult` here rather than in the if branch.

Target:
public void resultReturned(int requestCode, int resultCode, Intent data) { if (requestCode == this.requestCode && resultCode == Activity.RESULT_OK) { if (data.hasExtra(RecognizerIntent.EXTRA_RESULTS)) { ArrayList<String> results = data.getExtras().getStringArrayList(RecognizerIntent.EXTRA_RESULTS); result = results.get(0); } else { result = ""; } speechListener.onResult(result); } }
Source:
public void onPartialResult(String text) { result = text; START AfterGettingText(result); END } While I thought this was pretty cool to see having my label updated as I spoke, I'm a bit concerned that apps might not be programmed correctly for the logic of `AfterGettingText` being called multiple times per call to `GetText`. I conferred with the team here and the consensus is that we should continue to use `AfterGettingText`, but add a new parameter called `partial` that should be `true` if the call is in response to `onPartialResult` and `false` if it is called from `onResult`. This would allow developers to determine whether the app user has finished speaking.

Target:
public void onPartialResult(String text) { result = text; AfterGettingText(result, true); }
Source:
public void onResult(String text) { result = text; AfterGettingText(result, false); START onDelete(); END } Is it necessary to do this here? The semantics of onDelete are supposed to be such that it's only called when the component is being removed from the screen in the companion app.

Target:
public void onResult(String text) { result = text; AfterGettingText(result, false); }
Source:
public DialogBox createNoProjectsDialog(boolean showDialog) { final NoProjectDialogBox dialogBox = new NoProjectDialogBox(); START dialogBox.show(); END return dialogBox; } At the moment this results in the dialog showing unconditionally. You should wrap this in a check against `showDialog` like the old code.

Target:
public DialogBox createNoProjectsDialog(boolean showDialog) { final NoProjectDialogBox dialogBox = new NoProjectDialogBox(); if (showDialog) { dialogBox.show(); } return dialogBox; }
Source:
private Integer generateHashCode(AndroidViewComponent component, PercentStorageRecord.Dim dim) { if (dim == PercentStorageRecord.Dim.HEIGHT) { START return (component.hashCode() + dim.hashCode()) * 2 + 1; END } else { return (component.hashCode() + dim.hashCode()) * 2; } } You don't need to add `dim.hashCode()` here (or the next line). By virtue of adding 0 or 1 we are encoding the dimension information perfectly.

Target:
private Integer generateHashCode(AndroidViewComponent component, PercentStorageRecord.Dim dim) { if (dim == PercentStorageRecord.Dim.HEIGHT) { return component.hashCode() * 2 + 1; } else { return component.hashCode() * 2; } }
Source:
public void unregisterPercentLength(AndroidViewComponent component, PercentStorageRecord.Dim dim) { // iterate map, remove all entry match this START for (Integer key : dimChanges.keySet()) { END dimChanges.remove(generateHashCode(component, dim)); } } You don't need the for loop here any more. The call to `remove` on line 716 either will remove the entry if it exists or do nothing if it doesn't exist. Because it changes the map, it will result in a `ConcurrentModificationException` as written since you're modifying the loop while iterating over it.

Target:
public void unregisterPercentLength(AndroidViewComponent component, PercentStorageRecord.Dim dim) { // iterate map, remove all entry match this dimChanges.remove(generateHashCode(component, dim)); }
Source:
private ServerPing getPingInfo( String motd, int protocol ) { START new ServerPing( END new ServerPing.Protocol( bungee.getName() + " " + bungee.getGameVersion(), protocol ), new ServerPing.Players( listener.getMaxPlayers(), bungee.getOnlineCount(), null ), motd, BungeeCord.getInstance().config.getFaviconObject() ); } You're kind of missing a return here...................

Target:
private ServerPing getPingInfo(String motd, int protocol) { return new ServerPing( new ServerPing.Protocol( bungee.getName() + " " + bungee.getGameVersion(), protocol ), new ServerPing.Players( listener.getMaxPlayers(), bungee.getOnlineCount(), null ), motd, BungeeCord.getInstance().config.getFaviconObject() ); }
Source:
public ComponentBuilder append(BaseComponent component, FormatRetention retention) { START BaseComponent previous = parts.get( parts.size() - 1 ); END if ( previous == null ) { previous = dummy; dummy = null; } if ( previous != null ) { component.copyFormatting( previous, retention, false ); } parts.add( component ); resetCursor(); return this; } Can throw exception when created with no args constructor

Target:
public ComponentBuilder append(BaseComponent component, FormatRetention retention) { BaseComponent previous = ( parts.isEmpty() ) ? null : parts.get( parts.size() - 1 ); if ( previous == null ) { previous = dummy; dummy = null; } if ( previous != null ) { component.copyFormatting( previous, retention, false ); } parts.add( component ); resetCursor(); return this; }
Source:
START Configuration(Configuration defaults) END { this(); setDefaults(defaults); } Why remove public?

Target:
public Configuration(Configuration defaults) { this(); setDefaults( defaults ); }
Source:
public void handle(LegacyHandshake legacyHandshake) throws Exception { this.legacy = true; START ch.close( bungee.getTranslation( "outdated_client", BungeeCord.getInstance().getGameVersion() ) ); END } Use bungee field

Target:
public void handle(LegacyHandshake legacyHandshake) throws Exception { this.legacy = true; ch.close( bungee.getTranslation( "outdated_client", bungee.getGameVersion() ) ); }
Source:
public void copyFormatting(BaseComponent component) { START copyFormatting( component, FormatRetention.ALL, false ); END } I think old behaviour was to replace?

Target:
public void copyFormatting(BaseComponent component) { copyFormatting( component, FormatRetention.ALL, true ); }
Source:
public void setTabHeader(BaseComponent header, BaseComponent footer) { START header = ChatComponentTransformer.getInstance().transform( getServerSentScoreboard(), this, header )[0]; END footer = ChatComponentTransformer.getInstance().transform( getServerSentScoreboard(), this, footer )[0]; unsafe().sendPacket( new PlayerListHeaderFooter( ComponentSerializer.toString( header ), ComponentSerializer.toString( footer ) ) ); } Same thing with mutation

Target:
public void setTabHeader(BaseComponent header, BaseComponent footer) { header = ChatComponentTransformer.getInstance().transform( this, header )[0]; footer = ChatComponentTransformer.getInstance().transform( this, footer )[0]; unsafe().sendPacket( new PlayerListHeaderFooter( ComponentSerializer.toString( header ), ComponentSerializer.toString( footer ) ) ); }
Source:
public ComponentBuilder append(String text, FormatRetention retention) { parts.add( current ); START END TextComponent component = new TextComponent( current ); component.setText( text ); current = component; retain( retention ); return this; } Fair enough, my bad

Target:
public ComponentBuilder append(String text, FormatRetention retention) { parts.add( current ); current = new TextComponent( (TextComponent) current ); ((TextComponent) current).setText( text ); retain( retention ); return this; }
Source:
public boolean hasChatColors() { START return ( settings != null ) ? settings.isChatColours() : true; END } `return settings == null || settings.isChatColours()`?

Target:
public boolean hasChatColors() { return settings == null || settings.isChatColours(); }
Source:
public TooltipImpl(Element element, TooltipOptions options) { this.$element = $(element); this.options = getOptions(options); //Is GWT optimization works here ? if (options.getResources() != null){ this.style = options.getResources().css(); } else{ this.style = getDefaultResources().css(); } START END init(); } That's a good question that I don't know the answer, this pattern is commonly used by gwt widgets. You would maybe remove the If if you have more than one ctor and I think that in that case, it would prune what isn't used.

Target:
public TooltipImpl(Element element, TooltipOptions options) { this(element, options, getDefaultResources()); }
Source:
public Integer convert(String s) { START try{ END return Integer.parseInt(s); }catch(NumberFormatException e){ GWT.log("Impossible to convert the string'"+s+"' to an integer."); return null; } } missing spaces in format

Target:
public Integer convert(String s) { try{ return Integer.parseInt(s); }catch(NumberFormatException e){ return null; } }
Source:
START public static XmlHighlighting highlight(SensorContext context, XmlFile xmlFile) { END XmlHighlighting highlighting = new XmlHighlighting(xmlFile); highlighting.highlight(context); return highlighting; } Why returning XmlHighlighting instead of void? I haven't seen it used anywhere

Target:
public static void highlight(SensorContext context, XmlFile xmlFile) { new XmlHighlighting(xmlFile).highlight(context); }
Source:
private static OutermostChildElements getOutermostChildElements(List<Node> children) { Element firstChildElement = null; Element lastChildElement = null; for (Node child : children) { if (child.getNodeType() == Node.ELEMENT_NODE) { if (firstChildElement == null) { firstChildElement = (Element) child; } lastChildElement = (Element) child; } } START return new OutermostChildElements(firstChildElement, lastChildElement); END } It seems to me that the only cases where first and last will be null is when there is no children being ELEMENT. In such case, we are not reporting anything through `checkChildrenLine`. Instead of having `@Nullable` first/last I would simply not create the object if both are null, and return null.

Target:
private static Optional<OutermostChildElements> getOutermostChildElements(List<Node> children) { Element firstChildElement = null; Element lastChildElement = null; for (Node child : children) { if (child.getNodeType() == Node.ELEMENT_NODE) { if (firstChildElement == null) { firstChildElement = (Element) child; } lastChildElement = (Element) child; } } if (firstChildElement != null) { return Optional.of(new OutermostChildElements(firstChildElement, lastChildElement)); } return Optional.empty(); }
Source:
private static void processException(Exception e, SensorContext context, InputFile inputFile) { reportAnalysisError(e, context, inputFile); START throw new IllegalStateException("Unable to analyse file " + inputFile.uri(), e); END } Ok as you need to rework the PR, i would go for a log instead of throwing the ISE here.

Target:
private static void processException(Exception e, SensorContext context, InputFile inputFile) { reportAnalysisError(e, context, inputFile); LOG.error("Unable to analyse file " + inputFile.uri(), e); }