auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public URI apply(Object from) { if (!(from instanceof String)) { throw new AssertionError("you must specify a region, as a String argument"); } Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); }

Target:
I would take this out. This is a distraction and we could better solve this with a tool like error-prone than divert someone to wondering.. hmm what if that is not a String? Instead of focusing on the real code, there's a distraction. I'd just note this potential snafu here: https://issues.apache.org/jira/browse/JCLOUDS-752 (ps take out @Nullable too).
Source:
public static boolean isJava6() { System.out.println(System.getProperty("java.version", "None??")); return System.getProperty("java.version", "").contains("1.6."); }

Target:
> Happy to take that out if you like. That would be nice, thanks. Or I can remove in a follow-up if you prefer.
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; AvailabilityZone that = AvailabilityZone.class.cast(obj); return Objects.equal(this.name, that.name) && this.state.equals(that.state); }

Target:
``` java return Objects.equal(this.name, that.name) && Objects.equal(this.state, that.state); ```
Source:
private void addGrantsToACL(AccessControlList acl) { String ownerId = acl.getOwner().getId(); acl.addPermission(GroupGranteeURI.ALL_USERS, Permission.READ); acl.addPermission(new EmailAddressGrantee(TEST_ACL_EMAIL), Permission.READ_ACP); acl.addPermission(new CanonicalUserGrantee(ownerId), Permission.WRITE_ACP); }

Target:
static import `Permission.READ_ACP` to follow style of `TEST_ACL_EMAIL`?
Source:
public static NovaTemplateOptions availabilityZone(String availabilityZone) { return new NovaTemplateOptions().availabilityZone(availabilityZone); }

Target:
@demobox SGTM!
Source:
public NodeAndNovaTemplateOptions(AtomicReference<NodeMetadata> nodeMetadata, AtomicReference<NovaTemplateOptions> novaTemplateOptions){ this.nodeMetadata = nodeMetadata; this.novaTemplateOptions = novaTemplateOptions; }

Target:
[minor] Are we ever going to create these directly, rather than with the static helpers? Can we reduce this to one private or protected constructor, and two static builders ``` public static NodeAndNovaTemplateOptions newNodeAndNovaTemplateOptions(AtomicReference<NodeMetadata> node, AtomicReference<NovaTemplateOptions> options) { return new NodeAndNovaTemplateOptions(node, options); } public static NodeAndNovaTemplateOptions newNodeAndNovaTemplateOptions(NodeMetadata node, NovaTemplateOptions options) { return newNodeAndNovaTemplateOptions(Atomics.newReference(node), Atomics.newReference(options)); // or return new NodeAndNovaTemplateOptions(Atomics.newReference(node), Atomics.newReference(options)); // if we prefer that } ``` ?
Source:
public void testReboot() throws Exception { Set<? extends NodeMetadata> rebootNodes = client.rebootNodesMatching(inGroup(group)); for (ComputeMetadata node : rebootNodes) { assert node.getProviderId() != null : node; assert node.getLocation() != null : node; assertEquals(node.getType(), ComputeType.NODE); } // validation testGet(); }

Target:
Please use `assertNotNull` from TestNG and fix indents here
Source:
private Image findImageWithId(Set<? extends Image> images) { // Try to find the image in the cache and fallback to the GetImageStrategy // see https://issues.apache.org/jira/browse/JCLOUDS-570 Optional<? extends Image> image = tryFind(images, idPredicate); if (image.isPresent()) { return image.get(); } logger.warn("Image %s not found in the image cache. Trying to get it from the provider...", imageId); // Note that this will generate make a call to the provider instead of using a cache, but // this will be executed rarely, only when an image is not present in the image list but // it actually exists in the provider. It shouldn't be an expensive call so using a cache just for // this corner case is overkill. Image imageFromProvider = getImageStrategy.getImage(imageId); if (imageFromProvider == null) { throwNoSuchElementExceptionAfterLoggingImageIds(format("%s not found", idPredicate), images); } // Register the just found image in the image cache, so subsequent uses of the TemplateBuilder and // the ComptueService find it. this.images.registerImage(imageFromProvider); return imageFromProvider; }

Target:
> Regarding the log level, I'd rather use warning, as using this "hidden" images is something we might want to notify How about INFO, then? I'd agree that this is something users might want to know about (i.e. level > DEBUG), but it's not a _problem_ as such - you wouldn't expect to trigger an alert based on this, for example (i.e. level < WARN)?
Source:
protected String imageIdForZone(String zoneId) { ImageApi imageApi = api.getImageApiForZone(zoneId); return Iterables.getFirst(imageApi.list().concat(), null).getId(); }

Target:
Intended change in functionality here? And wouldn't the default value `null` that's being passed here immediately cause an NPE?
Source:
private Server createServer(String zoneId, String availabilityZoneId) { ServerApi serverApi = api.getServerApiForZone(zoneId); CreateServerOptions options = new CreateServerOptions(); if (availabilityZoneId != null) options = options.availabilityZone(availabilityZoneId); ServerCreated server = serverApi.create(hostName, imageIdForZone(zoneId), flavorRefForZone(zoneId), options); awaitActive(serverApi).apply(server); return serverApi.get(server.getId()); }

Target:
[minor] Formatting? ``` if (availabilityZoneId != null) { options = options.availabilityZone(availabilityZoneId); } ```
Source:
public void testToString() { LoginCredentials toTest = LoginCredentials.builder().user("myuser").password("password").privateKey("key").build(); String str = toTest.toString(); assertTrue(str.contains("myuser"), "str="+toTest); assertTrue(str.contains("passwordPresent=true"), "str="+toTest); assertTrue(str.contains("privateKeyPresent=true"), "str="+toTest); }

Target:
I'm not against this test, but I don't think we test the sanity/composition of `toString` anywhere else. My personal vote would be to omit this test, and in the previous test simply to verify something like `assertNotNull(toTest.toString());`. But curious to hear what others have to say. @nacx @abayer @andrewgaul?
Source:
public OperatingSystem getImage(final String id) { return find(listImages(), new Predicate<OperatingSystem>() { @Override public boolean apply(OperatingSystem input) { return input.equals(id); } }, null); }

Target:
`OperatingSystem.equals(String)`?
Source:
protected void configure() { bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class); }

Target:
Any reason for the import change?
Source:
public Set<Integer> getCpusOfProcessors() { if(processors.isEmpty()) return ImmutableSet.of(); return Sets.newHashSet(Iterables.transform(processors, new Function<ContainerVirtualGuestConfigurationOption, Integer>() { @Override public Integer apply(ContainerVirtualGuestConfigurationOption input) { return input.getTemplate().getStartCpus(); } })); }

Target:
By doing this you are returning an immutable set if there are no processors, but a mutable one if there is some. Why that different behavior? I'd just remove this line, as the `transform` below will already do nothing if the processors set is empty.
Source:
public ProductItem(int id, @Nullable String description, @Nullable String softwareDescriptionId, @Nullable SoftwareDescription softwareDescription) { this.id = checkNotNull(id, "id"); this.description = description; this.softwareDescriptionId = softwareDescriptionId; this.softwareDescription = softwareDescription; }

Target:
A primitive `int` will never be null, you could remove this check.
Source:
public Tag(int accountId, int id, int internal, String name) { this.accountId = checkNotNull(accountId, "accountId"); this.id = checkNotNull(id, "id"); this.internal = checkNotNull(internal, "internal"); this.name = checkNotNull(name, "name"); }

Target:
Remove null check for primitives.
Source:
public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) { // both security groups and networks are optional, and CloudStack will // use the zone/user's default network/security group if none given if (templateOptions.getSecurityGroupIds().size() > 0) { options.securityGroupIds(templateOptions.getSecurityGroupIds()); } if (templateOptions.getNetworks().size() > 0) { options.networkIds(templateOptions.getNetworks()); } return options; }

Target:
`if (!templateOptions.getNetworks().isEmpty())`?
Source:
protected void setupSSL() { try { sslContext = new SslContextBuilder(InetAddress.getLocalHost().getHostName()).build(); } catch (GeneralSecurityException ex) { throw Throwables.propagate(ex); } catch (UnknownHostException ex) { throw Throwables.propagate(ex); } }

Target:
nit. faster to write `throw new RuntimeException(e);` :)
Source:
public ListProjectsOptions id(String id) { this.queryParameters.replaceValues("id", ImmutableSet.of(id + "")); return this; }

Target:
Just curious...why the `id + ""` here?
Source:
void testDescribeSnapshotsWithFilterInvalid() { String region = defaultRegion; SortedSet<Snapshot> allResults = Sets.newTreeSet(client.describeSnapshotsInRegion(region)); assertNotNull(allResults); if (allResults.size() >= 1) { Snapshot snapshot = allResults.last(); Snapshot result = Iterables.getOnlyElement(client.describeSnapshotsInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("invalid-filter", snapshot.getId()).build())); } }

Target:
[minor] "WithInvalidFilter"?
Source:
private Iterable<Payload> doSlice(InputStream rawContent, ContentMetadata meta) { return new PayloadIterator(rawContent, meta); }

Target:
Could all the doSlice methods be static? Also, make them `protected` so they can be overridden?
Source:
public void containerExists() throws InterruptedException { if(System.getProperty("os.name").contains("indows")) throw new SkipException("not yet implemented"); else super.containerExists(); }

Target:
Could you call a helper method: ``` java private static void skipIfWindows() { if (System.getProperty("os.name").contains("indows")) { throw new SkipException("not yet implemented"); } } ```
Source:
protected void tearDownContext() { if (nodes != null) { client.destroyNodesMatching(inGroup(group)); } super.tearDownContext(); }

Target:
`try...catch` needed here?
Source:
protected Builder() { id("softlayer") .name("SoftLayer") .apiMetadata(new SoftLayerApiMetadata()) .homepage(URI.create("http://www.softlayer.com")) .console(URI.create("https://manage.softlayer.com")) .iso3166Codes("SG","US-CA","US-TX","US-VA","US-WA","US-TX", "NL") .endpoint("https://api.softlayer.com/rest") .defaultProperties(SoftLayerProviderMetadata.defaultProperties()); }

Target:
"NL-NH" is probably most accurate for Amsterdam.
Source:
public SecurityGroup createSecurityGroup(String name, Location location) { String zone = location.getId(); if (zone != null) { return createSecurityGroup(name, zone); } else { return null; } }

Target:
As in places above, use ``` if (zone == null) { return null; } return createSecurityGroup(name, zone); ``` ?
Source:
public void testIdMissingPrices() { ProductItem item = ProductItem.builder().build(); assertEquals(item.getId() + "", imageId().apply(item)); }

Target:
Since we know what `item.getId()` is, could we just have ``` assertEquals("", imageId().apply(item)); ``` here?
Source:
public void testId() { ProductItemPrice price = ProductItemPrice.builder().id(1234).build(); ProductItem item = ProductItem.builder().id(5678).prices(price).build(); assertEquals("Expected the ID of the ProductItemPrice to be returned", "1234",imageId().apply(item)); }

Target:
Message should be [last](http://testng.org/javadoc/org/testng/Assert.html#assertEquals(boolean, boolean, java.lang.String))?
Source:
public static Function<ProductItem, String> imageId() { return new Function<ProductItem, String>() { @Override public String apply(ProductItem productItem) { checkNotNull(productItem, "productItem"); ProductItemPrice price = ProductItems.price().apply(productItem); checkNotNull(price, "price"); return String.valueOf(price.getId()); } }; }

Target:
Combine into `return String.valueOf(checkNotNull(price, "price").getId());`? But why the change in the first place, by the way?
Source:
public boolean deleteImage(String id) { try { AsyncCreateResponse deleteJob = client.getTemplateClient().deleteTemplate(id); boolean deleteComplete = jobComplete.apply(deleteJob.getJobId()); } catch (Exception e) { return false; } return true; }

Target:
Move into the `try` block?
Source:
public Set<SecurityGroup> listSecurityGroupsInLocation(final Location location) { String region = AWSUtils.getRegionFromLocationOrNull(location); if (region != null) { return listSecurityGroupsInLocation(region); } else { return ImmutableSet.of(); } }

Target:
Quick style question (also applies below): what do you feel about making the "exceptional case" (`region == null`, I'm guessing?) the bit you handle in the `if...` clause, e.g. ``` if (region == null) { return ImmutableSet.of(); // handle special case } return listSecurityGroupsInLocation(region); ``` ?
Source:
protected Supplier<URI> provideStorageUrl(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion, @Named(LocationConstants.PROPERTY_REGION) String region) { //Get the URI's keyed by their region name Supplier<Map<String, Supplier<URI>>> endpointsSupplier = factory.createForApiTypeAndVersion(ServiceType.OBJECT_STORE, apiVersion); //Pick the matching region name (if any) otherwise just return an arbitrary URL if no region name is set //NOTE: The region string should never be null (it can be empty) if this object was instantiated via guice // as it pulls these named strings from a Properties object. That being said, there's no real reason we // should treat a null string differently to an empty string. if (!Strings.isNullOrEmpty(region)) { return getValueInMapOrNull(endpointsSupplier, region); } else { return getLastValueInMap(endpointsSupplier); } }

Target:
If `region` cannot be `null`, how about just `if (!region.equals("")...`..?
Source:
public void handle(Exception exception) { if (exception instanceof IllegalArgumentException || exception instanceof IllegalStateException) { throw new InterceptionException(exception); } if (exception instanceof ReflectionProviderException) { throwIfNotValidationException(exception, exception.getCause()); } throwIfNotValidationException(exception, exception); }

Target:
I'm almost tending to use VRaptor specific exceptions for this case, instead of reusing IllegalArg and IllegalState... We're doing this only because of validations, right? We could create a ValidationFailedException.
Source:
protected boolean replay(Exception e) { ExceptionRecorder<Result> exresult = exceptions.findByException(e); if (exresult == null) { return false; } reportException(e); logger.debug("handling exception {}", e); exresult.replay(result); return true; }

Target:
maybe you should do `logger.debug("handling exception {}", e.getClass(), e);`, which would print the stacktrace after "Handling exception BazingaException".
Source:
public static ControllerMethod instanceFor(Class<?> type, Method method) { CDIProxies.extractRawTypeIfPossible(type); return new DefaultControllerMethod(new DefaultBeanClass(type), method); }

Target:
Use `tabs` instead of `spaces`.
Source:
public void setup() throws Exception { contexts.startRequestScope(); contexts.startSessionScope(); contexts.startApplicationScope(); initEvent.fire(new VRaptorInitialized(null)); super.setup(); }

Target:
shouldn't it be started from largest scope to smallest?
Source:
public <T extends View> T onErrorUse(Class<T> view) { if (!hasErrors()) { return new MockResult(proxifier).use(view); //ignore anything, no errors occurred } result.include("errors", getErrors()); outjector.outjectRequestMap(); logger.debug("there are errors on result: {}", messages.handleErrors()); return viewsFactory.instanceFor(view, messages.handleErrors()); }

Target:
it includes `getErrors()` to the view, but now we're logging `messages.handleErrors()`. Is it right?
Source:
public void shouldDelegateToStatusOnPermanentlyRedirectToControllerInstance() throws Exception { Status status = mockResult(Status.class); result.permanentlyRedirectTo(new RandomController()); verify(status).movedPermanentlyTo(RandomController.class); verify(messages).assertAbsenceOfErrors(); }

Target:
leave this verify only for the method which is checking this behavior. No need to repeat it on all.
Source:
public XMLSerialization indented() { indented = environment.get(ENVIRONMENT_INDENTED_KEY, "true").equalsIgnoreCase("true"); return this; }

Target:
although it will throw an exception if the key is not found. I guess we could change the supports method to return false if the key doesn't exist.
Source:
public void shouldReturnEmptyList() { when(dao.searchSimilarTitle(music.getTitle())).thenReturn(new ArrayList<Music>()); controller.search(music); List<Music> musics = (List<Music>) result.included().get("musics"); Assert.assertTrue(musics.isEmpty()); }

Target:
`assertThat(musics, empty())`
Source:
public void shouldAddUser() { controller.add(user); verify(userDao).add(user); assertEquals("User " + user.getName() + " successfully added", result.included().get("notice")); }

Target:
`assertThat(result.included().get("notice"), "User " + user.getName() + " successfully added")` Yes, `assertThat` have inverted parameters unlike another JUnit methods.
Source:
private Predicate<String> currentOrSubpackage(final String controllerPackageName) { return new Predicate<String>() { @Override public boolean apply(String input) { return controllerPackageName.contains(input); } }; }

Target:
I'd write a simple test case to make sure (if not already there), but makes sence to use `startsWith`
Source:
public String get(InjectionPoint ip) { Annotated annotated = ip.getAnnotated(); Property property = annotated.getAnnotation(Property.class); String key = property.value(); if (isNullOrEmpty(key)) key = ip.getMember().getName(); return environment.get(key); }

Target:
:sadpanda:
Source:
public <T> T instanceFor(Class<T> type) { type = (Class<T>) Proxies.extractRawType(type); logger.debug("asking cdi to get instance for {}", type); Bean<?> bean = getBeanFrom(type); CreationalContext<?> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, type, ctx); }

Target:
you could _extract method_ here, to avoid duplicated code on `instanceFor` and `canProvide` methods (just like `type = extractRawType(type)`) or just add this 2 lines on `getBeanFrom`
Source:
public void setControllerMethod(ControllerMethod controllerMethod) { createValuedParameter(controllerMethod); this.controllerMethod = controllerMethod; }

Target:
I think this method should be called on `getValuedParameters` because even if i'll never use, it always create valued parameters when VRaptor sets ControllerMethod (and to create this, we use `parameterNameProvider`, etc... it is kind of expensive). Maybe a simple lazy strategy: ``` Java if (valuedParameters != null) createValuedParameter(controllerMethod); ```
Source:
public LocaleBasedPrimitiveDoubleConverter() { }

Target:
protected
Source:
private void addRedirectListener() { response.addRedirectListener(new MutableResponse.RedirectListener() { @Override public void beforeRedirect() { if (!validator.hasErrors() && entityManager.getTransaction().isActive()) { entityManager.getTransaction().commit(); } } }); }

Target:
Change to commit();
Source:
public void intercept(SimpleInterceptorStack stack) { addRedirectListener(); EntityTransaction transaction = null; try { transaction = entityManager.getTransaction(); transaction.begin(); stack.next(); if (!validator.hasErrors() && transaction.isActive()) { transaction.commit(); } } finally { if (transaction != null && transaction.isActive()) { transaction.rollback(); } } }

Target:
Change to commit();
Source:
@Override void apply(RequestBuilder builder, @Nullable Object value) { try { checkNotNull(value, "@Url parameter is null."); } catch (NullPointerException npe) { throw Utils.parameterError(method, npe, p, "@Url parameter is null."); } builder.setRelativeUrl(value); }

Target:
There's no need to do this. We can just check for null locally and pass null as the cause to the `Utils` method.
Source:
Part(Method method, int p, Headers headers, Converter<T, RequestBody> converter) { this.headers = headers; this.converter = converter; this.method = method; this.p = p; }

Target:
Can we make the field order and statement order match the constructor argument order?
Source:
Path(Method method, int p, String name, Converter<T, String> valueConverter, boolean encoded) { this.name = checkNotNull(name, "name == null"); this.valueConverter = valueConverter; this.encoded = encoded; this.method = method; this.p = p; }

Target:
If they're impossible we actually usually prefer `AssertionError`. I would leave them as-is because they should never be observable by users.
Source:
static Type getParameterLowerBound(int index, ParameterizedType type) { Type[] types = type.getActualTypeArguments(); if (index < 0 || index >= types.length) { throw new IllegalArgumentException( "Index " + index + " not in range [0," + types.length + ") for " + type); } Type paramType = types[index]; if (paramType instanceof WildcardType) { return ((WildcardType) paramType).getLowerBounds()[0]; } return paramType; }

Target:
Just let the regular array bounds checking do this?
Source:
public static <T> Response<T> success(int code, @Nullable T body) { if (code < 200 || code >= 300) throw new IllegalArgumentException("code < 200 or >= 300: " + code); return success(body, new okhttp3.Response.Builder() // .code(code) .message("Response.success()") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://localhost/").build()) .build()); }

Target:
Line too long. Please add `{` and `}` when wrapping.
Source:
@Test public void builtInConvertersAbsentInCloneBuilder() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .build(); assertEquals(retrofit.converterFactories().size() - 1, retrofit.newBuilder().converterFactories().size()); }

Target:
should this just assert that it’s empty? Otherwise if we split the built in ones across two factories then this test is wrong
Source:
void emitError(Throwable t) { set(STATE_TERMINATED); if (!isUnsubscribed()) { try { if (!isUnsubscribed()) { subscriber.onError(t); } } catch (Throwable inner) { Exceptions.throwIfFatal(inner); CompositeException composite = new CompositeException(t, inner); RxJavaPlugins.getInstance().getErrorHandler().handleError(composite); } } }

Target:
This seems redundant? It's checked two lines above
Source:
private void checkPercentageValidity(int percentage, String message) { if (percentage < 0 || percentage > 100) { throw new IllegalArgumentException(message); } }

Target:
+`static`
Source:
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { JsonAdapter<?> adapter = moshi.adapter(type, jsonAnnotations(annotations)); if (lenient) { adapter = adapter.lenient(); } if (failOnUnknown) { adapter.failOnUnknown(); } return new MoshiResponseBodyConverter<>(adapter); }

Target:
this would need to be `adapter = adapter.failOnUnknown()`
Source:
public Builder(Retrofit retrofit) { this.platform = retrofit.platform; this.callFactory = retrofit.callFactory; this.baseUrl = retrofit.baseUrl; this.converterFactories = retrofit.converterFactories; this.adapterFactories = retrofit.adapterFactories; this.callbackExecutor = retrofit.callbackExecutor; this.validateEagerly = retrofit.validateEagerly; }

Target:
All lists should use `addAll` and not retain these unmodifiable references.
Source:
public MoshiConverterFactory asLenient() { if (lenient) { return this; } return create(moshi, true); }

Target:
I would just delete this `if`. It'll never happen and even if it does it's not that big of a deal to create a new instance.
Source:
@Test public void completableSuccess200() { server.enqueue(new MockResponse().setBody("Hi")); try { service.completable().await(); assertThat(true); } catch (RuntimeException e) { fail(); } }

Target:
You can delete the try/catch and `assertThat`, they don't add value
Source:
private CompletableCallOnSubscribe(Call originalCall) { this.originalCall = originalCall; }

Target:
nit: remove `private` to avoid the need for a synthetic accessor method to be generated
Source:
@Override public T convert(ResponseBody value) throws IOException { BufferedSource source = value.source(); try { return adapter.decode(source); } finally { if (source != null) { try { source.close(); } catch (IOException ignored) { } } } }

Target:
calling `value.source()` can throw, so this will need split into two lines, variable initialization and retrieving the source–the latter of which is inside the `try` block
Source:
@Override public <R> Observable<Result<R>> adapt(Call<R> call, Retrofit retrofit) { return Observable.create(new CallOnSubscribe<>(call, retrofit)) // .onErrorReturn(new Func1<Throwable, Result<R>>() { @Override public Result<R> call(Throwable throwable) { return Result.error(throwable); } }); }

Target:
This can be removed now.
Source:
public static ObservableBehaviorAdapter create() { return INSTANCE; }

Target:
Is this an pattern? Weird for create to not create.
Source:
public static <T> Call<T> response(final Response<T> response) { return new Call<T>() { @Override public Response<T> execute() throws IOException { return response; } @Override public void enqueue(Callback<T> callback) { callback.onResponse(response); } @Override public void cancel() { } @SuppressWarnings("CloneDoesntCallSuperClone") // Immutable object. @Override public Call<T> clone() { return response(response); } }; }

Target:
return this ?
Source:
public synchronized void cancel() { canceled = true; com.squareup.okhttp.Call rawCall = this.rawCall; if (rawCall != null) { rawCall.cancel(); } }

Target:
I hate that the use of this ends up in the docs.
Source:
@FromJson public AnInterface read(JsonReader jsonReader) throws IOException { jsonReader.beginObject(); String name = null; while (jsonReader.peek() != JsonReader.Token.END_OBJECT) { switch (jsonReader.nextName()) { case "name": name = jsonReader.nextString(); break; } } jsonReader.endObject(); return new AnImplementation(name); }

Target:
`while (jsonReader.hasNext())` ... Unless you're going for symmetry with the other libraries!
Source:
static <T> T checkNotNull(T object, String message, Object... args) { if (args.length > 0) message = String.format(message, args); if (object == null) throw new NullPointerException(message); return object; }

Target:
Don't need to format the message unless `object` is null.
Source:
private static TypedInput createResponseBody(final ResponseBody body) { if (body == null) { return null; } return new TypedInput() { @Override public String mimeType() { return body.contentType().toString(); } @Override public long length() { return body.contentLength(); } @Override public InputStream in() throws IOException { return body.byteStream(); } }; }

Target:
I don't think this is reachable
Source:
public String toString() { try { return "TypedString[" + new String(getBytes(), "UTF-8") + "]"; } catch (UnsupportedEncodingException e) { throw new AssertionError("Must be able to decode UTF-8"); } }

Target:
`@Override`
Source:
void addFieldListParams(String name, Iterable<?> values) { if (name == null) { throw new IllegalArgumentException("Field name must not be null."); } if (values == null) { throw new IllegalArgumentException("Field param values must not be null."); } for (Object value : values) { formBody.addField(name, value.toString()); } }

Target:
This will NPE if someone passes a list with `null`. Do we ignore or throw an exception?
Source:
public List<byte[]> getParts() throws Exception { List<byte[]> parts = new ArrayList<byte[]>(); for (MimePart part : mimeParts) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { part.writeTo(bos); parts.add(bos.toByteArray()); } finally { bos.close(); } } return parts; }

Target:
Pass `mimeParts.size()` to constructor.
Source:
public String fileName() { return null; }

Target:
The `@Override` should be on this line.
Source:
public String mimeType() { return "multipart/form-data; boundary=" + boundary; }

Target:
The `@Override` should be on this line.
Source:
public long length() { return length; }

Target:
The `@Override` should be on this line.
Source:
public void writeTo(OutputStream out) throws IOException { for (MimePart part : mimeParts) { part.writeTo(out); } out.write(footer); }

Target:
The `@Override` should be on this line.
Source:
@Test public void arrayIterable() throws Exception { FormUrlEncodedTypedOutput fe = new FormUrlEncodedTypedOutput(); fe.addField("ping", Arrays.asList(new String[]{"pong", "pong-too"})); ByteArrayOutputStream out = new ByteArrayOutputStream(); fe.writeTo(out); String actual = new String(out.toByteArray(), "UTF-8"); assertThat(actual).isEqualTo("ping=pong&ping=pong-too"); }

Target:
Drop `new String[]` as above.
Source:
@Override public void addPathParam(String name, String value) { boolean disableUrlEncoding = false; addPathParam(name, value, disableUrlEncoding); }

Target:
While I appreciate the explicit-ness, I'd rather this value just be inlined into the method call. If you want to be specific you can do: ``` java addPathParam(name, value, false /* do not URL encode */); ```
Source:
public ApacheClient() { this(new DefaultHttpClient()); DefaultHttpClient client = (DefaultHttpClient) this.client; this.redirectHandler = new RedirectHandler(); client.setRedirectHandler(this.redirectHandler); }

Target:
Drop the `this` on this and the next line.
Source:
void addPart(String name, TypedOutput body) { if (name == null) { throw new NullPointerException("Part name must not be null."); } if (body == null) { throw new NullPointerException("Part body must not be null."); } boolean first = (parts.size() == 0); byte[] part = buildPart(name, body, first); parts.add(part); length += part.length; }

Target:
Replace `first` with `parts.isEmpty()`
Source:
public static Method getMethod(Class c, String name) { Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(name)) { return method; } } throw new IllegalArgumentException("Unknown method '" + name + "' on " + c); }

Target:
inline?
Source:
public static boolean isBeginningOfEntity(String label) { return StringUtils.startsWith(label, TaggingLabels.GROBID_START_ENTITY_LABEL_PREFIX) || StringUtil.startsWith(label, TaggingLabels.IOB_START_ENTITY_LABEL_PREFIX) || StringUtil.startsWith(label, TaggingLabels.ENAMEX_START_ENTITY_LABEL_PREFIX); }

Target:
This method will fail with `IOB_INSIDE_LABEL_PREFIX` returning `true` for `isBeginningOfEntity()` while it is not the beginning of an entity. Problem `IOB_INSIDE_LABEL_PREFIX` == `GROBID_START_ENTITY_LABEL_PREFIX` == "I-". Normally this method should not be called with IOB labels... but not 100% sure.
Source:
public void processingReferenceSection() throws Exception { String text = "(1) Ahrens, M. Home fires that began with upholstered furniture; National Fire Protection Association: Quincy, Massachusetts, 2011.\n" + "(2) Evarts, B. Home fires that began with matresses and bedding; National Fire Protection Association: Quincy, Massachusetts, 2011.\n" + "(3) Kramer, R. H.; Zammarano, M.; Linteris, G. T.; Gedde, U. W.; Gilman, J. W. Polym. Degrad. Stab. 2010, 95, 1115−1122.\n" + "(4) Underwriter Laboratories, UL test: Legacy home contents and new content fires, YouTube online video clip, 2011.\n" + "(5) Gallagher, S.; Campbell, J. In Siloxane-Phosphonate Finishes on Cellulose: Thermal Characterization and Flammability Data; Proceed-ings of the Beltwide Cotton Conference, San Antonio, TX, 2004; pp 2443-2847.\n" + "(6) Watanabe, I.; Sakai, S. Environ. Int. 2003, 29, 665−682. (7) Babrauskas, V.; Blum,\n"; List<BibDataSet> res = engine.getParsers().getCitationParser().processingReferenceSection(text, engine.getParsers().getReferenceSegmenterParser()); assertNotNull(res); System.out.println(res); assertTrue(res.size() > 2); }

Target:
remove this println please ;-)
Source:
public static void main(String[] args) throws Exception { GrobidProperties.getInstance(); AcknowledgmentTrainer trainer = new AcknowledgmentTrainer(); AbstractTrainer.runTraining(trainer); AbstractTrainer.runEvaluation(trainer); System.exit(0); }

Target:
yes, the first link in AbstractTrainer there is a method called `evaluateNFold` or something like that (I'm trying to remember)
Source:
public static <T> ZooKeeperNode<T> create(ZooKeeperClient zkClient, String nodePath, Function<byte[], T> deserializer, Closure<T> dataUpdateListener) throws InterruptedException, KeeperException, ZooKeeperConnectionException { ZooKeeperNode<T> zkNode = new ZooKeeperNode<T>(zkClient, nodePath, new FunctionWrapper<T>(deserializer), dataUpdateListener); zkNode.init(); return zkNode; }

Target:
this should chain to once of the creates below
Source:
public void onAttach(Activity activity) { super.onAttach(activity); // Initialize Baidu Map library com.baidu.mapapi.SDKInitializer.initialize(getActivity().getApplicationContext()); mDpApp = (DroidPlannerApp) activity.getApplication(); }

Target:
@droneboost use the `activity` parameter instead of calling the `getActivity()` method.
Source:
private void setAutoPanMode(AutoPanMode current, AutoPanMode update) { if (mPanMode.compareAndSet(current, update)) { switch (current) { case DRONE: LocalBroadcastManager.getInstance(getActivity().getApplicationContext()) .unregisterReceiver(eventReceiver); break; case DISABLED: default: break; } switch (update) { case DRONE: LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).registerReceiver (eventReceiver, mEventFilter); break; case DISABLED: default: break; } } }

Target:
@droneboost here you can just call `mPanMode.compareAndSet(current, update)` to accomplish the intended functionality. You especially don't want to unregister the event receiver since it's filtering over events besides the drone gps updates.
Source:
public void search(View view) { ArrayList<MKOLSearchRecord> records = mOffline.searchCity(mCityNameView .getText().toString()); if (records == null || records.size() != 1) { return; } mCidView.setText(String.valueOf(records.get(0).cityID)); }

Target:
@droneboost any reason the size of `records` is restricted to `1`? If there are more than one results, we can just still grab the first one as you're doing below.
Source:
public void finishedLoadingLogs() { FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_geotag_layout); if (fragment == null || !(fragment instanceof GeoTagImagesFragment)) { fragment = new GeoTagImagesFragment(); fm.beginTransaction().replace(R.id.fragment_geotag_layout, fragment).commit(); } }

Target:
@chaviw you can skip the check for `null`. If `fragment` is `null` then the `instanceof` check will also fail.
Source:
public void updateTitle(@StringRes int title) { final int toolbarId = getToolbarId(); final FragmentManager fm = getSupportFragmentManager(); Fragment actionBarGeoTag = fm.findFragmentById(toolbarId); if (actionBarGeoTag != null && actionBarGeoTag instanceof ActionBarGeoTagFragment) { ((ActionBarGeoTagFragment) actionBarGeoTag).updateTitle(title); } }

Target:
@chaviw same here. you can skip the check for null.
Source:
private void finishedGeotagging(Intent intent) { boolean success = intent.getBooleanExtra(GeoTagImagesService.EXTRA_SUCCESS, false); if (success) { ArrayList<File> files = (ArrayList<File>) intent.getSerializableExtra(GeoTagImagesService.EXTRA_GEOTAGGED_FILES); activity.finishedGeotagging(files); } else { String failure = intent.getStringExtra(GeoTagImagesService.EXTRA_FAILURE_MESSAGE); failedLoading(failure); } }

Target:
@chaviw check for `activity` being null.
Source:
private void startGeoTagging() { File folder = getApplicationContext().getExternalFilesDir(null); File tlogFile = new File(folder.getPath() + "/camera_msgs.tlog"); Timber.d("path: " + tlogFile.getPath()); geoTagImages(getApplicationContext(), tlogFile); }

Target:
@chaviw you should be able to call `getExternalFilesDir(null)` directly.
Source:
private static String findRootPath(File extFile) { File currPath = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { currPath = extFile; try { while (Environment.isExternalStorageRemovable(currPath.getParentFile())) { currPath = currPath.getParentFile(); } } catch (IllegalArgumentException e) { //swallow return currPath.getAbsolutePath(); } } return currPath.getAbsolutePath(); }

Target:
@chaviw check for `extFile` being `null`.
Source:
public static UVCDialog newInstance() { final UVCDialog dialog = new UVCDialog(); final Bundle args = new Bundle(); dialog.setArguments(args); return dialog; }

Target:
@guiseco what's the `Bundle args` for here, since no arguments is being added to it?
Source:
public UsbDevice getItem(final int position) { if ((position >= 0) && (position < mList.size())) return mList.get(position); else return null; }

Target:
@guiseco you don't need to check the validity of the `position` argument here, since it's based on the `getCount()` that you overrode above.
Source:
public CharSequence[][] getHelpItems() { return new CharSequence[][] { { getResources().getString(R.string.help_item_description) }, { "https://www.youtube.com/watch?v=btsk7bzn-9Q" } }; }

Target:
@metalnow not a bug, but in an `Activity`, you can call `getString(...)` directly.
Source:
public void onDroneEvent(DroneInterfaces.DroneEventsType event, Drone drone) { if(event.equals(DroneInterfaces.DroneEventsType.STATE)){ if(drone.getState().isCollisionImminent()){ mPool.play(beepBeep,1f,1f,1,1,1f); }else{ mPool.stop(beepBeep); } } }

Target:
@TShapinsky DroneEventsType is an enum, so you can use `event == DroneEventsType.STATE` instead of using the `equals()` method.
Source:
private static String getCustomClassName(Class<? extends ObjCObject> type) { CustomClass customClassAnno = type.getAnnotation(CustomClass.class); String name = type.getName(); if (customClassAnno != null && customClassAnno.value().length() > 0) { name = customClassAnno.value(); } name = CUSTOM_CLASS_NAME_PREFIX + name.replace('.', '_'); return name; }

Target:
This should only be done if there is no `@CustomClass` annotation. If there is the name it specifies should be used as is and the user will have to make sure there are no collisions.
Source:
private void generateIBClassesFile(File installDir) throws IOException { List<String> customClasses = config.getCustomIBClasses(); if (!customClasses.isEmpty()) { FileWriter fw = new FileWriter(new File(installDir, "ib.classes")); String array = StringUtils.toString(customClasses.toArray(new String[customClasses.size()]), ","); fw.write(array); fw.close(); } }

Target:
Again, use try-with-resources.
Source:
private static void release(@Pointer long self, @Pointer long sel) { if (ObjCRuntime.int_objc_msgSend(self, retainCount) == 1) { synchronized (CUSTOM_OBJECTS) { CUSTOM_OBJECTS.remove(self); } } long cls = ObjCRuntime.object_getClass(self); long nativeSuper = customClassToNativeSuper.get(cls); Super sup = new Super(self, nativeSuper); ObjCRuntime.void_objc_msgSendSuper(sup.getHandle(), sel); }

Target:
Should the `customClassToNativeSuper.get()` call be in a synchronized block?
Source:
private static @Pointer long retain (ObjCObject self, @Pointer long sel) { if (ObjCRuntime.int_objc_msgSend(self.getHandle(), retainCount) == 1) { synchronized (CUSTOM_OBJECTS) { CUSTOM_OBJECTS.put(self.getHandle(), self); } } return ObjCRuntime.ptr_objc_msgSendSuper(new Super(self.getHandle(), NS_OBJECT_CLASS).getHandle(), sel); }

Target:
Not sure whether it should be `== 0` instead here?
Source:
public static ConversionResult getResult(int error) { switch (error) { case 0: return CONVERSION_OK; case 1: return ILLEGAL_SEQUENCE; case 2: return OUTPUT_BUFFER_TOO_SMALL; case 3: return INCOMPLETE_SEQUENCE; case 4: return ERROR_METHOD_ID; case 5: return ERROR_ARRAY_FUNCTION_CALL; case 6: return ERROR_DESCRIPTOR; default: return WEIRD_ERROR; } }

Target:
If this should never happen throw an `IllegalArgumentException` instead.
Source:
public IconvEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar) { super(cs, averageBytesPerChar, maxBytesPerChar); this.iconv_tPointer = IconvProvider.initConversion("UTF-16LE", ((IconvCharset) cs).getIconvName()); }

Target:
I believe we talked about doing this lazily?
Source:
private boolean containsAll(final NullnessAnnotation... search) { Boolean result = null; if (this.annotations.isEmpty()) { // an empty list of annotations can never contain all result = false; } else { for (final NullnessAnnotation obj : search) { if (!this.annotations.contains(obj)) { result = false; break; } } } if (result == null) { result = true; } return result; }

Target:
This could just default to `true` and be primitive and remove the `if` statement below.
Source:
private boolean containsAny(final NullnessAnnotation... search) { Boolean result = null; if (this.annotations.isEmpty()) { result = false; } else { for (final NullnessAnnotation obj : search) { if (this.annotations.contains(obj)) { result = true; break; } } } if (result == null) { result = false; } return result; }

Target:
Same but this would default to `false`.
Source:
public boolean contains(int num) { final boolean lowerLimitCheckPassed = lowerLimit == null || num >= lowerLimit; final boolean upperLimitCheckPassed = upperLimit == null || num <= upperLimit; return lowerLimitCheckPassed && upperLimitCheckPassed; }

Target:
you should not have null in code, you can use 0 or MAX .
Source:
protected boolean isClassEnumeration(DetailAST aAST) { return hasMembers(aAST, mExcludes); }

Target:
For this method the { bracket is on the same line, while for other methods it is on the other lines. Normally you should not think about such thing at all and use IDE-autoformatting, but checkstyle is somewhat special. I have not found usages of this method outside this class - should it be private?
Source:
public TorrentStatistic getStatistics(String dotTorrentFilePath) throws IOException { FileMetadataProvider metadataProvider = new FileMetadataProvider(dotTorrentFilePath); TorrentMetadata metadata = metadataProvider.getTorrentMetadata(); LoadedTorrent loadedTorrent = communicationManager.getTorrentsStorage().getLoadedTorrent(metadata.getHexInfoHash()); if (loadedTorrent != null) { return loadedTorrent.getTorrentStatistic(); } throw new IllegalStateException("Torrent has not been loaded yet"); }

Target:
let's return here a copy of `TorrentStatistic ` instance because this class is mutable
Source:
public static byte[] hash(byte[] data) throws NoSuchAlgorithmException { MessageDigest crypt; crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(data); return crypt.digest(); }

Target:
Can you call the other version of `hash()` from here instead? ``` java public static byte[] hash(byte[] data) throws NoSuchAlgorithmException { return hash(data, 0, data.length); } ```
Source:
static Pair<TextSelection, Boolean> getSelection(@NotNull Editor editor) { SelectionModel selectionModel = editor.getSelectionModel(); int selectionStart = selectionModel.getSelectionStart(); int selectionEnd = selectionModel.getSelectionEnd(); TextSelection selection = calculateSelectionPosition(editor, selectionStart, selectionEnd); boolean isBackwardsSelection = isBackwardsSelection(editor, selectionStart, selectionEnd); return new Pair<>(selection, isBackwardsSelection); }

Target:
As already written in a previous PR: I would expect that isBackwardsSelection could be moved in TextSelection.
Source:
protected int getSize() { return queue.size(); }

Target:
Make package private? ```suggestion int getSize() { ```
Source:
public void testInsertWhileNotEnable() { store.setValue(EclipsePreferenceConstants.SHOW_CONTRIBUTION_ANNOTATIONS, false); final User ALICE_TEST_USER = new User(new JID("ALICE_TEST_USER@test"), false, false, null); manager.insertAnnotation(model, 5, 7, ALICE_TEST_USER); assertEquals(0, getAnnotationCount(model)); }

Target:
Remove and use static variable instead?
Source:
public void asyncExec(Runnable runnable) { try { EDTExecutor.invokeLater(runnable); } catch (ProcessCanceledException e) { log.error("Synchronous execution on EDT interrupted - " + runnable, e); } }

Target:
```suggestion log.error("Asynchronous execution on EDT interrupted - " + runnable, e); ```
Source:
public boolean hasPrivilege(UserPrivilege.Keys privilege) { //System.out.println("3 - hasPrivilege() " + privilege + " : " + this.privileges.containsKey(privilege)); if (this.privileges.containsKey(privilege)) { return this.privileges.get(privilege).getValue(); } return false; }

Target:
NPE
Source:
static String getRequireBundleValue(File manifestFile) { String bundleValue; try (FileInputStream manifestStream = new FileInputStream(manifestFile)) { Manifest manifest = new Manifest(manifestStream); bundleValue = manifest.getMainAttributes().getValue(REQUIRE_BUNDLE_KEY); } catch (IOException e) { throw new GradleException( "Unable to determine the bundle dependencies defined in manifest: " + manifestFile.getAbsolutePath(), e); } return bundleValue; }

Target:
Can be private according to IntelliJ code inspection.
Source:
static String[] parseRequireBundleValue(String value, List<String> bundlesToExclude) { return Arrays.stream(value.split(",")) .map( (it) -> { return it.split(";")[0]; }) .filter( (it) -> { return !bundlesToExclude.contains(it); }) .toArray(String[]::new); }

Target:
Can be private according to IntelliJ code inspection.
Source:
private Project getProjectFromSession() { ISarosSession currentSession = sarosSession; if (currentSession == null) { return null; } SharedIDEContext sharedIDEContext = currentSession.getComponent(SharedIDEContext.class); if (!sharedIDEContext.isInitialized()) { return null; } return sharedIDEContext.getProject(); }

Target:
Nullcheck missing.
Source:
public boolean isOnline() { if (status == Type.AVAILABLE || status == Type.AWAY) return true; return false; }

Target:
why not `return status == Type.AVAILABLE || status == Type.AWAY`
Source:
public void dispose() { sessionManager.removeSessionLifecycleListener(sessionLifecycleListener); ISarosSession currentSession = session; if (currentSession != null) { currentSession.removeListener(sessionListener); removeSessionNode(currentSession); } sessionNodeList.clear(); userNodeList.clear(); }

Target:
The job of a dispose method is either to free unmanaged resources / memory and to deregister stuff properly so that the object can be garbage collected. Of course you can set all references to null / clear datastructures etc. to help the garbage collector but this is just boiler plate code with little benefits.
Source:
private XStream createXStream() { XStream xStream = new XStream(new DomDriver(CHARSET)); xStream.alias("colorIDSet", ColorIDSet.class); return xStream; }

Target:
Is this the same behavior as before ? To be more specific, is there any need for a charset at all ? Because you are producing already a string.
Source:
public void setSize(final int width, final int height) { this.syncExec(() -> browser.setSize(width, height)); }

Target:
Isn't the coding convention like: omit "this" when it is not needed ?
Source:
private void syncExec(final Runnable runnable) { final AtomicReference<RuntimeException> exception = new AtomicReference<RuntimeException>(); browser .getDisplay() .syncExec( () -> { try { runnable.run(); } catch (RuntimeException e) { exception.set(e); } }); if (exception.get() != null) { throw exception.get(); } }

Target:
syncExec( () -> {runnable.run(); return null;});
Source:
public boolean selectionExists(ISelector selector) { return (Boolean) this.browser.syncRun(String.format("return %s.length > 0;", selector.getStatement())); }

Target:
Can the value returned by ```Java this.browser.syncRun(String.format("return %s.length > 0;", selector.getStatement())) ``` be `null`? If this is the case, you need a nullcheck before returning the value as the implicit unboxing needed to convert the returned `Boolean` into a `boolean` (which is the actual return type of the method) will throw a NPE if the value is `null`.