auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public DeveloperProducts(String expectedSku, Map<String, Product> products) { this.sku = products.remove(expectedSku); this.provided = products; log.debug("Test?? {}", this.sku); }

Target:
If this isn't left in by accident, can you change the message to be a little more informative?
Source:
protected Object getOutputValueForAccessor(String field, Object input) { // Since we're returning primitives for two methods, we need to convert them as necessary if (field != null && (field.equals("Result") || field.equals("Standalone")) && input == null) { return false; } return input; }

Target:
leftovers from `StatusDTOTest`. just `return input;` is enough here since this DTO has no primitives.
Source:
public StatusDTO setManagerCapabilities(Collection<String> capabilities) { if (capabilities != null) { if (this.capabilities == null) { this.capabilities = new HashSet<String>(); } this.capabilities.clear(); this.capabilities.addAll(capabilities); } else { this.capabilities = null; } return this; }

Target:
Something else that I missed. I know it's not that important, but we don't have to set the type when creating new objects any more. We can just use the diamond operator `new HashSet<>`.
Source:
protected X509Certificate loadCACertificate(String path) { try ( InputStream inStream = new FileInputStream(path); ) { X509Certificate cert = (X509Certificate) this.certFactory.generateCertificate(inStream); inStream.close(); return cert; } catch (Exception e) { throw new RuntimeException(e); } }

Target:
This line unnecessary since we're using try-with-resources syntax...
Source:
public void initModelTranslator(ModelTranslator modelTranslator) { modelTranslator.registerTranslator(this.capabilityTranslator, ConsumerCapability.class, CapabilityDTO.class); }

Target:
What's driving the change to increase visibility here? These are intended to be used only by subclasses.
Source:
public EventDTO clone() { EventDTO copy = super.clone(); copy.timestamp = timestamp != null ? new Date(timestamp.getTime()) : null; return copy; }

Target:
Use the clone method here rather than new date.
Source:
public java.util.Collection<Consumer> getConsumers() { return this.virtUuidToConsumerMap.values(); }

Target:
A bit more PoC code that's left over. We should do a proper import and not fully qualify this on the fly.
Source:
private void clearContentAccessCerts(Environment env) { ownerEnvContentAccessCurator.removeAllForEnvironment(env.getId()); ownerEnvContentAccessCurator.refresh(); }

Target:
How does this work? I don't see a specific `refresh()` method in OwnerEnvContentAccessCurator, so I'm supposing it goes to `refresh(E... entities)` in the superclass. But since you're not passing in any entities, that looks like it would just be a no-op.
Source:
public GuestIdDTO clone() { GuestIdDTO copy = super.clone(); Map<String, String> attributes = this.getAttributes(); if (attributes != null) { copy.setAttributes(new HashMap<String, String>(attributes)); } return copy; }

Target:
This is unnecessary once the encapsulation issue is resolved
Source:
public boolean equals(Object other) { if (!(other instanceof GuestId)) { return false; } GuestId that = (GuestId) other; if (this.getGuestId().equalsIgnoreCase(that.getGuestId())) { EqualsBuilder builder = new EqualsBuilder() .append(this.getAttributes(), that.getAttributes()); return builder.isEquals(); } return false; }

Target:
This is just a map of strings, and the EqualsBuilder is just calling into .equals as the replaced code was doing. We're not gaining anything with this change.
Source:
public String getHref() { return this.id != null ? String.format("/pools/%s", this.id) : null; }

Target:
For methods like this which pull from other bits of data, since we're making it extensible, try to use the methods instead: ``` return this.getId() != null ? String.format(...) : null;``` That way subclasses need not override both methods should the source of the ID change.
Source:
private boolean changedProductsInSet(Set<Product> products, Map<String, Product> changedProducts) { if (products != null && changedProducts != null) { for (Product product: products) { if (product != null && product.getId() != null && changedProducts.get(product.getId()) != null) { return true; } } } return false; }

Target:
Checkstyle failure here: need a space between product and the colon. Should also pull the method declaration into one line as well.
Source:
public int hashCode() { HashCodeBuilder hcBuilder = new HashCodeBuilder(); hcBuilder.append(releaseVer); return hcBuilder.toHashCode(); }

Target:
Nice, but unnecessary -- HashCodeBuilder in this case is just doing exactly what the original code you replaced does (especially since you're not seeing the builder with a prime value). Just leave this as-is for now.
Source:
public void deleteSubscription(@PathParam("subscription_id") String subscriptionId) { // Look up master pool by subscription Id Pool master = this.poolManager.getMasterPoolBySubscriptionId(subscriptionId); if (master == null) { throw new NotFoundException( i18n.tr("A subscription with the ID \"{0}\" could not be found.", subscriptionId)); } this.poolManager.deletePools(Collections.singletonList(master), null); }

Target:
This is very minor, but would you mind switching this to ``` this.poolManager.deletePools(Collections.singletonList(master)) ``` so we don't have that superfluous `null` hanging around. I think the functionality should be the same since the one parameter method just delegates to the two parameter method but provides the `null` as the second parameter.
Source:
public boolean preProcess(BindContext context) { for (BindOperation operation : operations) { log.debug("Starting preprocess of {}", operation.getClass().getSimpleName()); if (operation.preProcess(context)) { log.debug("Finished preprocess of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain in preprocess of operation {}", operation.getClass().getSimpleName()); return false; } } return true; }

Target:
method can be protected now (private if not isolated in tests).
Source:
public boolean execute(BindContext context) { for (BindOperation operation : operations) { log.debug("Starting execute of {}", operation.getClass().getSimpleName()); if (operation.execute(context)) { log.debug("Finished execute of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain execute in operation {}", operation.getClass().getSimpleName()); return false; } } return true; }

Target:
method can be protected now (private if not isolated in tests).
Source:
public void lock(BindContext context) { log.debug("Requesting locks"); context.lockPools(); log.debug("Successfully achieved locks"); }

Target:
method can be protected now (private if not isolated in tests).
Source:
public void regenerateCertificatesOf(String productId, boolean lazy) { if (lazy) { poolCurator.markCertificatesDirtyForProductId(productId); } else { List<Pool> poolsForProduct = this.listAvailableEntitlementPools(null, null, null, productId, new Date(), false, false, new PoolFilterBuilder(), null, false, false) .getPageData(); for (Pool pool : poolsForProduct) { regenerateCertificatesOf(pool.getEntitlements(), lazy); } } }

Target:
We don't need to pass lazy through here, since we already know it's false at this point.
Source:
public boolean deleteForOwner(Owner owner) { String deleteForOwner = "delete from UeberCertificate uc where uc.owner = :owner"; Query query = getEntityManager().createQuery(deleteForOwner); query.setParameter("owner", owner); return query.executeUpdate() > 0 ? true : false; }

Target:
You can just return ```query.executeUpdate() > 0``` here.
Source:
public boolean isUeberPool() { return product.getName().equals(Product.ueberProductNameForOwner(owner)); }

Target:
It's unlikely, but product could be null here.
Source:
public Map<String, Object> getQueueInfo(String queueName) throws JMSException { log.debug("Getting info about queue {}", queueName); List<Map<String, Object>> mm = runQuery("_object_id", singularMap("_object_name", queueName)); if (mm.size() == 0) { throw new RuntimeException("Couldn't find a queue in Qpid: " + queueName); } if (mm.size() > 1) { throw new RuntimeException("Found unexpected amount of information about queue: " + queueName); } return mm.get(0); }

Target:
This should be private unless there are plans to use it outside the class.
Source:
public static Map<Object, Object> singularMap(Object key, Object value) { Map<Object, Object> query = new HashMap<Object, Object>(); query.put(key, value); return query; }

Target:
This should be private unless there are plans to use it outside the class.
Source:
public void remove(@PathParam("owner_key") String ownerKey, @PathParam("content_id") String contentId) { Owner owner = this.getOwnerByKey(ownerKey); Content content = this.getContent(ownerKey, contentId); if (content.isLocked()) { throw new ForbiddenException(i18n.tr("content \"{1}\" is locked", content.getId())); } List<Product> affectedProducts = this.contentManager.removeContent(content, owner, true); }

Target:
unused collection affectedProducts
Source:
public Content setOwners(Collection<Owner> owners) { this.owners.clear(); if (owners != null) { this.owners.addAll(owners); } return this; }

Target:
Shouldn't we perform the null check before trying to call `clear()`?
Source:
public int revokeAllEntitlements(Consumer consumer) { List<Entitlement> entsToDelete = entitlementCurator.listByConsumer(consumer); revokeEntitlements(entsToDelete); return entsToDelete.size(); }

Target:
Why is it not needed to not compute consumer compliance here any more? Unless there is a valid reason, perhaps we could kick off an asynchronous consumer compliance job from #1073 ? Looks like there were two APIs to remove all entitlements of a consumer, one with compliance check and other without, so this was an explicit decision at some point, hence the question
Source:
public void queueEvent(Event event) { if (log.isDebugEnabled()) { log.debug("Queuing event: " + event); } getEventQueue().add(event); }

Target:
With Logback, we don't need these types of guards. ``` java log.debug("Queing event: {}", event) ``` should do the trick with no penalty in performance.
Source:
public HornetqEventDispatcher(ObjectMapper mapper, Config config) { this.mapper = mapper; try { largeMsgSize = config.getInt(ConfigProperties.HORNETQ_LARGE_MSG_SIZE); factory = createClientSessionFactory(); } catch (HornetQException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
Could we consolidate these catch clauses? Or is HornetQException a RuntimeException?
Source:
public void sendEvent(Event event) { if (log.isDebugEnabled()) { log.debug("Sending event: " + event); } try { ClientMessage message = getClientSession().createMessage(true); String eventString = mapper.writeValueAsString(event); message.getBodyBuffer().writeString(eventString); getClientProducer().send(message); } catch (Exception e) { log.error("Error while trying to send event: " + event, e); } }

Target:
No `if` block required here either.
Source:
public void handleCreated(Event event) { curator.insert(new BasicDBObject(event.getNewEntity().toMap())); }

Target:
This seems a bit hairy, we're deconstructing and reconstructing a hashmap.
Source:
public List<Report> getReports() { return new ArrayList<Report>(this.reports.values()); }

Target:
Any reason not to use return type Collection<Report> here, then return reports.values()?
Source:
public String toString() { return "Pool[id: " + getId() + ", owner: " + ((owner == null) ? "null" : owner.getId()) + ", product: " + productId + ", quantity: " + getQuantity() + ", expires: " + getEndDate() + "]"; }

Target:
I think owner has a solid toString, it might be more useful to do something more like this: ``` java return "Pool[id: " + getId() + ", owner: " + owner + ``` May not even need "owner: ", because owner.toString returns ``` java return "Owner [id: " + getId() + ", key: " + getKey() + "]"; ``` but null will be all alone. (that shouldn't happen unless something else is wrong, so we're probably safe allowing it)
Source:
public Consumer(String name, String userName, Owner owner, ConsumerType type) { this(); this.name = name; this.username = userName; this.owner = owner; this.type = type; this.facts = new HashMap<String, String>(); this.installedProducts = new HashSet<ConsumerInstalledProduct>(); this.guestIds = new ArrayList<GuestId>(); this.autoheal = true; this.serviceLevel = null; }

Target:
I wouldn't change this line, by initializing as empty string, we don't have to worry about whether we've just created a Consumer with no serviceLevel in java(null string), vs loaded one with no serviceLevel from the database (empty string). Logically it probably shouldn't make a difference, just scary.
Source:
public ToolInstallation installVersion(String version) { autoInstall.check(); sleep(1000); control("properties/hudson-tools-InstallSourceProperty/installers/id").select(version); return this; }

Target:
Is this intended for `master`, or just "temporary" code?
Source:
public void tearDown(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { // null result means success so far. If no logs are found, it's probably because it was simply skipped if (build.getResult() == null) { SonarUtils.addBuildInfoTo(build, installation.getName(), true); } else { SonarUtils.addBuildInfoTo(build, installation.getName(), false); } }

Target:
How about putting the condition in the 3rd param to avoid duplication?
Source:
public LauncherSettingsValidator() { validationRules = new ArrayList<>(); setupRules(); }

Target:
Why not do ... ```java validationRules = setupRules(); ```
Source:
public void resetTheApp() { resetApp(); appWasReset(); try { Thread.sleep(10000); } catch (Throwable t) }

Target:
Why do we need this sleep?
Source:
void retrievePolicyForService(UUID serviceId) throws Throwable { ServicePolicy policy = getDirectoryClient().getServicePolicy(serviceId); currentServicePolicyEntity = policy == null ? null : ServicePolicyEntity.fromServicePolicy(policy); }

Target:
getServicePolicy shouldn't ever return null. Based on how the Python SDK functions we return a policy object every time. In the case that it is in fact empty ({"factors": [], "minimum_requirements": []}), we return a policy with all the minimum_factors set to false or 0.
Source:
void retrievePolicyForService(UUID serviceId) throws Throwable { ServicePolicy policy = client.getServicePolicy(serviceId); currentServicePolicyEntity = policy == null ? null : ServicePolicyEntity.fromServicePolicy(policy); }

Target:
getServicePolicy shouldn't ever return null. Based on how the Python SDK functions we return a policy object every time. In the case that it is in fact empty ({"factors": [], "minimum_requirements": []}), we return a policy with all the minimum_factors set to false or 0.
Source:
public static McMMOPlayerProfileLoadEvent callPlayerProfileLoadEvent(Player player, PlayerProfile profile){ McMMOPlayerProfileLoadEvent e = new McMMOPlayerProfileLoadEvent(player, profile); mcMMO.p.getServer().getPluginManager().callEvent(e); return e; }

Target:
not a fan of shorthand one letter variable names, would prefer a descriptive var name instead of a single character
Source:
public McMMOPlayerBrewEvent(Player player, Block brewingStand) { super(player, SkillType.ALCHEMY); this.setBrewingStandBlock(brewingStand); cancelled = false; }

Target:
For sake of consistency (and my OCD), use <code>this.brewingStand = brewingStand</code> rather than the setter here.
Source:
public McMMOPlayerCatalysisEvent(Player player, double speed) { super(player, SkillType.ALCHEMY); this.setSpeed(speed); cancelled = false; }

Target:
For sake of consistency (and my OCD), use <code>this.speed = speed</code> rather than the setter here.
Source:
public static boolean makeMossy(Block block) { switch (block.getType()) { case COBBLESTONE: case DIRT: case COBBLE_WALL return true; case SMOOTH_BRICK: if (block.getData() == 0) { return true; } default: return false; } }

Target:
This line needs a colon, to make it "case COBBLE_WALL:" I would also like to note that it should have been down lower, with the smooth brick check.
Source:
public void writeToFile(final File destination) { InputStream input = null; final OutputStream output; try { input = getDataSource().getInputStream(); output = new FileOutputStream(destination); StreamUtil.copy(input, output); } catch (final IOException ioex) { throw new MailException(ioex); } finally { StreamUtil.close(input); StreamUtil.close(output); } }

Target:
Hi, your change will produce a compiler error - see [travis](https://travis-ci.org/oblac/jodd/jobs/632646285). this should work: ``` public void writeToFile(final File destination) { InputStream input = null; OutputStream output = null; try { input = getDataSource().getInputStream(); output = new FileOutputStream(destination); StreamUtil.copy(input, output); } catch (final IOException ioex) { throw new MailException(ioex); } finally { StreamUtil.close(input); StreamUtil.close(output); } } ```
Source:
private static int zzUnpackAction() { int result = new int[184]; int offset = 0; zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; }

Target:
You could kill offset and pass 0
Source:
public String toHtmlString() { StringBuilder str = new StringBuilder("<html>"); str.append("&nbsp;name: ").append("<b>") .append(component.getName()).append("</b><br>") .append("&nbsp;class: ").append("<b>") .append(component.getClass().getName()).append("</b><br>"); return str.toString(); }

Target:
return new StringBuilder().append()....toString();
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("jtx{").append(propagationBehavior.toString()).append(',') .append(readOnlyMode ? "readonly" : "readwrite").append(',') .append(isolationLevel.toString()).append(',').append(timeout) .append('}'); return sb.toString(); }

Target:
Useless `toString()`, that's what StringBuilder.append(Object) does (just that i's protected against NPE and will print "null").
Source:
public Family createFamily(User creator) { return create(creator.getProfileDocument()); }

Target:
`creator` may be `null`, this needs a check.
Source:
protected List<String> getCodeFields() { ParameterizedType p = (ParameterizedType) this.getClass().getGenericSuperclass(); System.out.println(p.getActualTypeArguments()[0]); return getProperties(); }

Target:
Why is this printing to stdout?
Source:
public void checkEmptyFormGroupDisplay(){ Assert.assertEquals(testGroup.display(DisplayMode.Edit, new String[] { "phenotype", "negative_phenotype" }), ""); Assert.assertEquals(testGroup.display(DisplayMode.View, new String[] { "phenotype", "negative_phenotype" }), ""); }

Target:
Format for assertions is `Assert.assertSomthing(EXPECTED, ACTUAL)`. Change the order here
Source:
public void returnsNormallyWhenGivenNoMeasurementObjects() throws Exception { when(this.source.getXObjects(any(EntityReference.class))).thenReturn(null); NullPointerException exceptionWhenListIsNull = null; try { this.mocker.getComponentUnderTest().onEvent(event, source, data); } catch(NullPointerException e){ exceptionWhenListIsNull = e; } Assert.assertNull(exceptionWhenListIsNull); }

Target:
You don't need to do this. If there is an exception thrown, the test will automatically fail. If, however, you do want to test that calling a method will throw an exception, then you would annotate the method with: ``` @Test(expected=NullPointerException.class) ```
Source:
public String getId() { return this.id; }

Target:
Is this change still needed?
Source:
private Boolean addTermAndAncestors(Term t, Observations o) { try { int id = this.boqa.getTermIndex(t); o.observations[id] = true; this.boqa.activateAncestors(id, o.observations); } catch (Exception e) { this.logger.warn("Unable to find the boqa index of [{}].", t); return false; } return true; }

Target:
There's a difference between the primitive type `boolean` and the class `Boolean`, and you seem to be using a primitive in the rest of the code. Use `boolean` as the return type.
Source:
public String getExternalId() { try { for (ImmutablePair<String, String> identifier : this .<ImmutablePair<String, String>>getData("identifiers")) { if (identifier.getKey().equalsIgnoreCase("external_id")) { return identifier.getValue(); } } } catch (Exception ex) { return null; } return null; }

Target:
Actually this is a mock patient, you should just `return null` here.
Source:
private VCFColumn getColumn(String token) { String lkToken = token.toLowerCase(); VCFColumn matchedColumn = null; for (VCFColumn column : VCFColumn.values()) { if (column.getName().equals(lkToken)) { matchedColumn = column; } } return matchedColumn; }

Target:
You should read http://blog.thetaphi.de/2012/07/default-locales-default-charsets-and.html
Source:
public List<String> getAllExtensions() { final List<String> extensions = new LinkedList<>(); extensions.add(defaultExtension); Optional.ofNullable(otherExtensions).map(Arrays::asList).ifPresent(extensions::addAll); return Collections.unmodifiableList(extensions); }

Target:
I would prefer to assume, and fix if necessary, that `otherExtensions` cannot be `null` (it can be empty anyway), and this way code would look easier: ``` final List<String> extensions = new LinkedList<>(); extensions.add(defaultExtension); extensions.addAll(Arrays.asList(otherExtensions)); return Collections.unmodifiableList(extensions); ``` Also IMO using `Optional.ofNullable` for null-checking of an instance becomes unnecessary and produce a bit of overhead, I prefer just using a conditional sentence instead... `if (null != whatever) {}`
Source:
public SpiTransaction createQueryTransaction(Object tenantId) { SpiTransaction t = transactionManager.createQueryTransaction(tenantId); try { transactionScopeManager.set(t); } catch (PersistenceException existingTransactionError) { t.end(); throw existingTransactionError; } return t; }

Target:
This breaks MySql in theory ... DefaultBeanLoader line 224
Source:
public BeanCollection<E> getShallowCopy() { BeanList<E> copy = new BeanList<>(new CopyOnFirstWriteList<>(list)); copy.setFromOriginal(copy); return copy; }

Target:
copy.setFromOriginal(this); -- should use this here ?
Source:
private boolean containsInstance(Object bean) { for (Object element : list) { if (JHelper.objectSameReference(element, bean)) { return true; } } return false; }

Target:
Use == here. Method name makes usage clear
Source:
Class<?> forName(String name) throws ClassNotFoundException { if (preferredLoader != null) { // only use the explicitly set classLoader return classForName(name, preferredLoader); } try { // try the context loader first return classForName(name, contextLoader); } catch (ClassNotFoundException e) { if (JHelper.objectSameReference(callerLoader, contextLoader)) { throw e; } else { // fallback to the caller classLoader return classForName(name, callerLoader); } } }

Target:
It does not matter if you use == or .equals here
Source:
private DbPlatformType getJsonType(DbType type, boolean withScale) { DbPlatformType dbType = get(type); if (JHelper.objectSameReference(dbType, JSON_CLOB_PLACEHOLDER)) { // if we have scale that implies this maps to varchar return withScale ? get(DbType.VARCHAR) : get(DbType.CLOB); } if (JHelper.objectSameReference(dbType, JSON_BLOB_PLACEHOLDER)) { return get(DbType.BLOB); } if (JHelper.objectSameReference(dbType, JSON_VARCHAR_PLACEHOLDER)) { return get(DbType.VARCHAR); } // Postgres has specific type return get(type); }

Target:
DbType is an enum, so == can be used
Source:
public Matrix4 rotate(double x, double y, double z, double angle) { if (angle == 0) return this; return rotate(mQuat.fromAngleAxis(x, y, z, angle)); }

Target:
return angle == 0 ? this : rotate(mQuat.fromAngleAxis(x,y,z,angle));
Source:
private AuthService authService() { if (null == authService) { throw new IllegalStateException("The auth-server endpoint is not configured."); } return authService; }

Target:
I'm no big fan of [Yoda conditions](https://en.wikipedia.org/wiki/Yoda_conditions) I think it reduces readability significantly and also we don't have it anywhere else in the code base. I would suggest that either the condition is reversed: ``` if (authservice == null) { ``` Or we actually do use an `Optional` to store the authservice here and use something like this to access it as a property: ``` private final Optional<Authservice> authservice; [...] public Authservice authservice(){ authservice.isPresent() ? return authservice.get() : throw new IllegalStateException("message"); } ```
Source:
public StringAttribute(String value){ this.value = value; }

Target:
This was only made public for the sake of a test. Please revert change and fix the test. (see below: https://github.com/osiam/connector4java/pull/47/files#r8397645)
Source:
protected Object doGetValue() { //System.out.println("NumberCellEditor doGetValue -->" + (data != null ? data : "null")); //BigDecimal value = NumberUtils.createBigDecimal(StringUtils.isNotEmpty(text.getText()) ? text.getText() : null ); //data = value; try { return convertToNumber(); } catch (NumberFormatException e) { e.printStackTrace(); } return null; }

Target:
This causes errors logged in console / error view and the value is cleared for feature. I tested to override `isValueValid` which leaves the feature untouched in case of any NumberFormatException. With this change the try/catch block in doGetValue isn't required anymore.. ``` @Override public boolean isValueValid() { try { Number number = convertToNumber(); return (number != null); } catch (NumberFormatException e) { return false; } } ```
Source:
public void setActive(final boolean active) { super.setActive(active); DELETE_SEARCH_SIZE = Platform.getPreferencesService().getInt( EditPlugin.ID, PreferenceConstants.P_DELETE_TOOL_RADIUS, 6, null); DELETE_CONFIRM = Platform.getPreferencesService().getBoolean( EditPlugin.ID, PreferenceConstants.P_DELETE_TOOL_CONFIRM, true, null); setStatusBarMessage(active); }

Target:
Can we use global definition of Defaults here as well?
Source:
public static long getMillisFromString(String strDate) { long millis = ISO8601.parse(strDate).getTimeInMillis(); return millis; }

Target:
I would say "return ISO8601.parse(strDate).getTimeInMillis();" would be enough.
Source:
private boolean isScheduled() { long lastStatsUpdateTime = asyncIndexesSizeStatsUpdate.getLastStatsUpdateTime(indexPath); long defaultStatsUpdateTime = asyncIndexesSizeStatsUpdate.getScheduleTimeInMillis(); return (System.currentTimeMillis() > lastStatsUpdateTime + defaultStatsUpdateTime); }

Target:
Brackets are not needed here
Source:
public void loggingAppenderStop() { listAppender.stop(); System.setProperty("oak.repository.property.logWarnStringSizeThreshold", ""); }

Target:
You might want to use `TemporarySystemProperty` ... the rule would reset sys props to their initial state after test. Similarly for logger, it might be easier (better??) to use `LogCustomizer` maybe
Source:
private String getResult(QueryResult result, String propertyName) throws RepositoryException { StringBuilder buff = new StringBuilder(); RowIterator it = result.getRows(); while (it.hasNext()) { if (buff.length() > 0) { buff.append(", "); } buff.append(it.nextRow().getValue(propertyName).getString()); } return buff.toString(); }

Target:
I think this could be static... could you make all such helper methods static please?
Source:
public static boolean waitForCopy(CloudBlob blob) throws StorageException, InterruptedException { boolean continueLoop = true; CopyStatus status = CopyStatus.PENDING; while (continueLoop) { blob.downloadAttributes(); status = blob.getCopyState().getStatus(); continueLoop = status == CopyStatus.PENDING; // Sleep if retry is needed if (continueLoop) { Thread.sleep(500); } } return status == CopyStatus.SUCCESS; }

Target:
Shouldn't this method should be private?
Source:
public void setShouldRenderWhilePanning( boolean shouldRender ) { mShouldRenderWhilePanning = shouldRender; if( shouldRender ) { mTileCanvasViewGroup.setRenderBuffer( TileCanvasViewGroup.FAST_RENDER_BUFFER ); } else { mTileCanvasViewGroup.setRenderBuffer( TileCanvasViewGroup.DEFAULT_RENDER_BUFFER ); } }

Target:
when a condition just determines a value (rather than an "action" - think: method), i think ternary is appropriate: ``` int buffer = shouldRender ? TileCanvasViewGroup.FAST_RENDER_BUFFER : TileCanvasViewGroup.DEFAULT_RENDER_BUFFER; mTileCanvasViewGroup.setRenderBuffer( buffer ); ```
Source:
protected String tryResourceLookup(Resource resource) { try { // added in Java EE 6 / Java SE 7 Method lookup = Resource.class.getDeclaredMethod("lookup"); return (String) lookup.invoke(resource); } catch (NoSuchMethodException e) { return ""; } catch (IllegalAccessException e) { return ""; } catch (InvocationTargetException e) { return ""; } }

Target:
```suggestion } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { return ""; } ```
Source:
public void should_replace_classpath_in_arquillian_xml() throws Exception { final String xml = desc.get().exportAsString(); System.out.println(xml); AssertXPath.assertXPath(xml, "/arquillian/container/@qualifier", VALUE_EL_OVERRIDE); final URL resource = Thread.currentThread().getContextClassLoader().getResource("arquillian_sysprop.xml"); assertXPath(xml, "/arquillian/container/configuration/property", String.format("-Djavax.net.ssl.trustStore=%s", resource.toString())); }

Target:
I would say "start doing it" - btw, you have already started in `ArquillianDescriptorClasspathPropertiesTestCase` ;-) https://github.com/arquillian/arquillian-core/pull/162/files#diff-3f0690a66704804b5e1a1a151cae218cR15
Source:
protected void shutdown(TestRunnerAdaptor adaptor) { State.runnerFinished(); try { if (State.isLastRunner()) { try { if (adaptor != null) { adaptor.afterSuite(); adaptor.shutdown(); } } finally { State.clean(); } } setAdaptor(null); } catch (Exception e) { throw new RuntimeException("Could not run @AfterSuite", e); } }

Target:
This can be package-private
Source:
Set<T> doGetNextGroup(Set<T> idle, Set<T> active) { if (active.isEmpty()) { return idle; } else { return ImmutableSet.of(); } }

Target:
I would copy the current `BatchStrategy` impl of this since it is the same: `return active.isEmpty() ? idle : ImmutableSet.of();`
Source:
public void willReturnCommandIgnoreOnPipelineInternalLine() { final MarkupText markupText = new MarkupText("Some internal line"); markupText.addMarkup(0, "<span class=\"pipeline-new-node\">"); System.out.println(markupText.toString(false)); final ColorizedAction colorizedAction = ColorizedAction.parseAction(markupText, buildRun); assertEquals(ColorizedAction.Command.IGNORE, colorizedAction.getCommand()); }

Target:
Debugging? Remove.
Source:
public String getX() { return x; }

Target:
change to package-private access
Source:
public String getCurve() { return curve; }

Target:
change to package-private access
Source:
private String getAuthorizationHeader(String clientId, String clientSecret) { if(clientId == null || clientSecret == null) { logger.debug("Null Client ID or Client Secret detected. Endpoint that requires authentication will reject request with 401 error."); } String creds = String.format("%s:%s", clientId, clientSecret); try { return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Could not convert String"); } }

Target:
DEBUG is a bit of a weak signal, don't you think, given that this is almost certainly going to fail?
Source:
public Response getExport(ExportRequest exportRequest) throws Exception { context.getExhibitor().getLog().add(ActivityLog.Type.INFO, "Starting export"); Exporter exporter = new Exporter(context, exportRequest.getStartPath()); return Response.ok(exporter.generate().toString()) .header("content-disposition", "attachment; filename=exhibitor_export.json") .build(); }

Target:
toString() is unnecessary
Source:
public String id() { return getString("id"); }

Target:
Can you add getId() and mark id() as deprecated?
Source:
public boolean equals(Object obj){ boolean result; if (obj == null) { result = false; } else { User other = (User) obj; result = macAddress.equals(other.getMacAddress()) && bluetoothID.equals(other.getBluetoothID()); } return result; }

Target:
Needs a test for if obj instanceof User...if it isnt, return false.
Source:
public void onTerminate() { unregisterExtranlControlClient(); super.onTerminate(); }

Target:
I'm not sure where this method is, but can we refactor it to spell external correctly?
Source:
public void reassignColors(){ userColors.clear(); for(User u: connectedUsers){ u.setColor(userColors.getNextAvailableColor()); } }

Target:
private
Source:
private UserList getUserListFromService(){ UserList activeUsers = new UserList(); UserListService userService = getUserListService(); if(userService != null){ return userService.getUserList(); } else { Log.i(TAG, "UserListService null, returning empty userlist"); } return activeUsers; }

Target:
It seems like we make this variable for no real reason. We could just return a new UserList in the bottom return
Source:
public static void eToast(Context context, int resId) { Log.e(Thread.currentThread().getStackTrace()[methodDepth].toString(), context.getString(resId)); toastWorker(context, context.getString(resId)); }

Target:
This should call the eToast method that takes a string, and pass in context.getString(resId) as that string. See iToast.
Source:
public List<SongMetadata> getLibrary() { synchronized(metadataMutex) { //sorts the list before returning it - for now, //order is simply alphabetical by artist, album, then song. ArrayList<SongMetadata> music = new ArrayList<SongMetadata>(metadataList); Collections.sort(music); //unmodifiable copy, for safety return Collections.unmodifiableList(music); } }

Target:
For large libraries, sorting on each call to getLibrary may introduce a lot of latency. At a minimum, I think we want to move the sort outside the synchronized block, but what might be better in the short and long term would be to sort in updateLibrary, because that is a relatively infrequent action.
Source:
public IBinder onBind(Intent intent) { this.audioPlayer = new SingleFileAudioPlayer( new OnCompletionListener(){ @Override public void onCompletion(MediaPlayer mp) { new BroadcastIntent(SingleFileAudioPlayer.ACTION_SONG_FINISHED).send(PlaylistService.this); } }); this.mPlaylist = new Playlist(); // TODO: kick off a thread to feed the monster that is the audio service registerReceivers(); return new PlaylistServiceBinder(); }

Target:
It looks like we send this broadcast action, receive it several lines down, and the broadcast a different action. Can we collapse that process and just broadcast the different action from here?
Source:
protected void onDestroy() { super.onDestroy(); //Make sure to destroy services when the application closes Toaster.iToast(this, "Destroying MusicLibrary Service"); Intent intent = new Intent(this, MusicLibraryService.class); stopService(intent); }

Target:
Hardcoded toast text :baby:
Source:
public void deserialize(InputStream input) throws IOException { byte[] bytes = new byte[1024]; int read = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); while((read = input.read(bytes)) > 0) out.write(bytes, 0, read); this.setString(out.toString()); }

Target:
Can you put brackets on the `while`?
Source:
private static boolean isX86(IVMInstall vm) { return (vm instanceof AbstractVMInstall) && PlatformUtil.ARCH_X86.equals(PreferencesUtil.getArchitecture((AbstractVMInstall) vm)); }

Target:
why is instanceof still needed here ?
Source:
protected void onSetSSLParameters(SSLParameters sslParameters) { if (endpointIdentificationAlgorithm == null) { super.onSetSSLParameters(sslParameters); } else { sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); } }

Target:
If I understand correctly, endpointIdentificationAlgorithm is never actually null in this test. An empty string is used instead.
Source:
public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { SSLEngine e = sslcontext.createSSLEngine(); e.setUseClientMode(false); if (sslParameters != null) { e.setSSLParameters(sslParameters); } return new SSLSocketChannel2(channel, e, exec, key); }

Target:
No check needed since we throw an IllegalArgumentException()
Source:
public void testBasicRoundTrip() { byte[] serialized = serialize(kryo, UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); try { assertSame(deserialize(kryo, serialized, UnicodeBlock.class), UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); } catch (NullPointerException e) { // Temporary debugging code e.printStackTrace(); throw e; } }

Target:
Can be removed now?
Source:
public static Set<ArtifactVersion> ensureDefaultAndPreviousVersionAvailable(final Set<ArtifactVersion> versions) { // add default version final ArtifactVersion defaultVersion = parseVersion(NewSwitchYardProjectWizard.DEFAULT_RUNTIME_VERSION); if (!versions.contains(defaultVersion)) { versions.add(defaultVersion); } // add previous version as well final ArtifactVersion previousVersion = parseVersion(NewSwitchYardProjectWizard.PREVIOUS_RUNTIME_VERSION); if (!versions.contains(previousVersion)) { versions.add(previousVersion); } return versions; }

Target:
Just realizing now: if it is a Set we don't need to check if it is contained inside first
Source:
private void refreshProject(IProgressMonitor monitor) throws CoreException { // update the project so we ensure a Project->Clean is done so the // MANIFEST.MF is built and we don't run into trouble deploying the // project on a Fuse server. if (_projectMetatData.getNewProjectHandle() != null) { _projectMetatData.getNewProjectHandle().refreshLocal(IProject.DEPTH_INFINITE, monitor); // also, update the maven project so we start in a deployable state // with a valid MANIFEST.MF built as part of the build process. Job updateJob = new UpdateMavenProjectJob(new IProject[] {_projectMetatData.getNewProjectHandle() }); updateJob.schedule(); } }

Target:
_projectMetatData.getNewProjectHandle() can be extracted as local variable as it is used 3 times
Source:
public void setShipping(final Shipping shipping) { this.shipping = shipping; addUnsavedProperty("shipping"); }

Target:
from what I remember, the `addUnsavedProperty` doesn't really do anything useful and therefore should be removed. So as not to pollute the code, please confirm it and refactor it as needed.
Source:
public void setSplitRules(final Collection<SplitRule> splitRules) { this.splitRules = splitRules; if (this.splitRules.size() != 0) { addUnsavedProperty("splitRules"); } }

Target:
Is the property used in any form? If not, is this line required?
Source:
public void setUpdatableParameters(String cardId, String cardHash, String planId){ this.planId = planId; if(!Strings.isNullOrEmpty(cardId)){ this.cardHash = cardId; }else if(!Strings.isNullOrEmpty(cardHash)){ this.cardHash = cardHash; } }

Target:
Trocar cardHash para cardId, verificar a necessidade do if
Source:
public void deleteAnticipation(BulkAnticipation anticipation) throws PagarMeException{ validateId(); String path = String.format("/%s/%s/%s/%s", getClassName(), getId(), anticipation.getClassName(), anticipation.getId()); final PagarMeRequest request = new PagarMeRequest(HttpMethod.DELETE, path); request.execute(); }

Target:
Verificar se é necessário usar o validateId(todos) no momento.
Source:
public String getTransactionId() { return transactionId; }

Target:
Verificar essa troca de tipos. Será que irá quebrar alguém?
Source:
public Collection<Payable> findCollection(final Integer totalPerPage, Integer page, final Map<String, Object> filters) throws PagarMeException { String path = String.format("/%s", getClassName()); return _findCollection(path, totalPerPage, page, filters); }

Target:
Seria bom reutilizar o método paginate do PagarMeModel
Source:
private static boolean checkForValidityOfAttributes(ArrayList<String> attributeList) { for (String str : attributeList) { if (str == "-1") { return false; } } return true; }

Target:
`==` tests for reference equality, hence it could be error-prone -- it'd be better to use the `.equals()` method...
Source:
private ItemGroup getItemGroup(Run<?, ?> build) { if (build instanceof AbstractBuild) { return ((AbstractBuild) build).getProject().getRootProject().getParent(); } else { // TODO: hmmm ??? return build.getParent().getParent(); } }

Target:
This is fine. There is no equivalent of `getRootProject` for non-`AbstractProject`s, and none is needed. (The original code here is just the usual hacks to make things work with `matrix-project`.)
Source:
private void flattenList(List<K> unflat, List<K> flat) { unflat.forEach(x -> { if (x instanceof KItem && ((KItem) x).klabel().toString().equals(KLabels.AND)) { flattenList(((KItem) x).items(), flat); } else { flat.add(x); } }); }

Target:
do not check equality based on `toString`
Source:
private Parser(Module module) throws IOException { // TODO: remove hack once the frontend is cleaner; also remove the IOException once the hack is cleared if (module.name().endsWith(RuleGrammarGenerator.RULE_CELLS)) { org.kframework.definition.Definition definitionWithBuiltins = Definition.from("require \"domians.k\"", "K"); this.parseInModule = new RuleGrammarGenerator(definitionWithBuiltins, true).getCombinedGrammar(module); } else { this.parseInModule = new ParseInModule(module); } }

Target:
To generate parsers only `kast.k` is needed. Why are you including ALL the builtins?
Source:
public ConstrainedTerm(Term term, ConjunctiveFormula constraint, TermContext context) { this.data = new Data(term, constraint); this.context = context.fork(); }

Target:
are you still creating new contexts here?
Source:
public List<Map<KVariable, K>> match(K k, org.kframework.definition.Rule rule) { return (List<Map<KVariable, K>>) search(k, Optional.of(0), Optional.empty(), rule); }

Target:
I suggest instead to make it be a List<? extends Map<? extends KVariabale, ? extends K>> because technically this is not a safe cast.
Source:
public File mainDefinitionFile() { File m = mainDefinitionFile; if (m == null) { if (parameters == null || parameters.size() == 0) { throw KEMException.criticalError("You have to provide exactly one main file in order to compile."); } m = mainDefinitionFile = files.get().resolveWorkingDirectory(parameters.get(0)); } return m; }

Target:
OK, I just checked the JLS and I was wrong about the read in `m = mainDefinitionFile` can see null value. It can only happen if the last line is written as `return mainDefinitionFile`. Anyway, I don't think it's a good idea to assume Guice is absolutely thread-safe when there is a simpler and equally efficient solution available.
Source:
public Kompile(KompileOptions kompileOptions, FileUtil files, KExceptionManager kem, boolean cacheParses) { this.files = files; this.kem = kem; this.kompileOptions = kompileOptions; this.parser = new ParserUtils(files, kem, kompileOptions.global); this.cacheParses = cacheParses; this.loader = new BinaryLoader(kem); this.sw = new Stopwatch(kompileOptions.global); }

Target:
can you make this constructor this() the one above?
Source:
public boolean isGround() { if (isGround == null) { if (variableSet == null || !variableSet.isEmpty()) { new IsGroundFieldInitializer().visitNode(this); } else { isGround = true; } } return isGround; }

Target:
`if (variableSet == null) {`
Source:
public Definition addProgramModule(Definition d) { Module programsModule = gen.getProgramsGrammar(d.mainSyntaxModule()).module(); java.util.Set<Module> allModules = mutable(d.modules()); allModules.add(programsModule); return Definition(d.mainModule(), programsModule, immutable(allModules)); }

Target:
again, none of this is necessary as far as I can tell.
Source:
public BiFunction<String, Source, K> getProgramParser(KExceptionManager kem) { ParseInModule parseInModule = getParserModule(kompiledDefinition.mainSyntaxModule()); return getParser(parseInModule, programStartSymbol, kem); }

Target:
if you keep the getParser method's signature the same, then getGroundParser is no longer a method that needs to exist.
Source:
public ParseInModule(Module seedModule) { this.seedModule = seedModule; this.extensionModule = seedModule; this.disambModule = seedModule; this.parsingModule = seedModule; this.grammar = KSyntax2GrammarStatesFilter.getGrammar(parsingModule); }

Target:
this constructor feels wrong now... I think it should be a Module and a Definition and then the constructor calls getCombinedGrammar.
Source:
public static K parseWithModule(CharSequence theTextToParse, String startSymbol, org.kframework.definition.Module kastModule) { ParseInModule parser = new ParseInModule(kastModule); Term cleaned = parser.parseString(theTextToParse, startSymbol)._1().right().get(); return TreeNodesToKORE.apply(cleaned); }

Target:
this code needs to be factored to support the fact that we will eventually need to compute Grammar objects during kompile and serialize them.
Source:
public SearchResults stepAll(int steps) throws KRunExecutionException { if (currentState == null) { throw new IllegalStateException("Cannot step without a current state to step from. " + "If you previously used the search command you must" + "first select a solution with the select command before executing steps of rewrites!"); } SearchResults results = executor.search(null, steps, SearchType.PLUS, defaultPattern, getState(currentState).getRawResult(), defaultPatternInfo, false); mergeSearchGraph(results.getGraph()); currentState = null; return results; }

Target:
This should be true actually
Source:
protected Object fastClone(final Object o, final Map<Object, Object> clones) throws IllegalAccessException { if ((o instanceof Term && !((Term) o).isMutable())) { return o; } else { return super.fastClone(o, clones); } }

Target:
what are these extra parentheses for?
Source:
public void save(File file, String content) { try { File dir = file.getAbsoluteFile().getParentFile(); if (!dir.exists() && !dir.mkdirs()) { throw KExceptionManager.criticalError("Could not create directory " + dir); } FileUtils.writeStringToFile(file, content); } catch (IOException e) { throw KExceptionManager.criticalError("Could not write to file " + file.getAbsolutePath(), e); } }

Target:
I know it's not part of this diff, but why isn't this function static?
Source:
public AbstractVisitor(String name, Context context) { this.context = context; this.currentDefinition = null; this.currentModule = null; this.kompileOptions = context == null ? null : context.kompileOptions; this.globalOptions = context == null ? null : context.globalOptions; this.name = name; }

Target:
please use constructor inheritance for these
Source:
public boolean isExactSort() { return true; }

Target:
not a big deal, but I would like to make it `final`
Source:
public boolean isConcreteCollection() { return collectionPatterns.isEmpty() && collectionVariables.isEmpty() && collectionFunctions.isEmpty(); }

Target:
final?
Source:
public boolean isGround() { return isConcreteCollection() && super.isGround(); }

Target:
final
Source:
public Sort sort() { // TODO(AndreiS): track the original sort from the grammar return KSorts.MAP; }

Target:
I don't like that you have both Sort and KSorts containing Sort constants.
Source:
public static void setTool(Tool tool) { if (K.tool != null) { assert false : "Can only call setTool once"; } K.tool = tool; }

Target:
Why not use ``` java assert (K.tool == null) : "Can only call setTool once"; ``` instead?
Source:
public JavaSymbolicKRun(Context context) throws KRunExecutionException { /* context is unused for directory paths; the actual context is de-serialized */ /* load the definition from a binary file */ definition = (Definition) BinaryLoader.load( new File(context.kompiled, JavaSymbolicBackend.DEFINITION_FILENAME).toString()); if (definition == null) { throw new KRunExecutionException("cannot load definition"); } /* initialize the builtin function table */ builtins = new BuiltinFunction(definition); this.context = definition.context(); this.context.kompiled = context.kompiled; this.context.globalOptions = context.globalOptions; transformer = new KILtoBackendJavaKILTransformer(this.context); }

Target:
seems like you're calling this constructor in a couple places. Is it really necessary to construct more than one BuiltinFunction object per definition?
Source:
public void putAll(Map<Term, Term> map) { Preconditions.checkArgument(!setEntries, "Cannot put in new key-value pair once the entries are set."); for (Map.Entry<Term, Term> e : map.entrySet()) { entries.put(e.getKey(), e.getValue()); } }

Target:
entires.putAll(map)?