auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void consumeFieldAlias(Field field, Schema.Field recordField) { if (field.isAnnotationPresent(AvroAlias.class)) { AvroAlias alias = field.getAnnotation(AvroAlias.class); if (!alias.space().equals(AvroAlias.NULL)) { throw new AvroRuntimeException( "Namespaces are not allowed on field aliases. " + "Offending field: " + recordField.name()); } recordField.addAlias(alias.alias()); } }

Target:
Field.isAnnotationPresent(Class) checks whether Field.getAnnotation(Class) returns null. I would suggest checking for alias != null to avoid the double invocation.
Source:
public Object getRecordState(Object record, Schema schema) { return null; }

Target:
With the recent writer change, I don't think this needs to be exposed any longer.
Source:
public void put(String orcid, OrcidProfile orcidProfile) { try { profileCache.acquireWriteLockOnKey(orcid); profileCache.put(new Element(new OrcidCacheKey(orcid, releaseName), orcidProfile)); } finally { profileCache.releaseWriteLockOnKey(orcid); } }

Target:
Hey @rcpeters, i think here you should create the key _new OrcidCacheKey(orcid, releaseName)_ and acquire the lock on that key, not in the orcid id right?
Source:
public PentahoOrcInputFormat( NamedCluster namedCluster ) { if ( namedCluster == null ) { conf = new Configuration(); } else { conf = inClassloader( () -> { Configuration confProxy = new ConfigurationProxy(); confProxy.addResource( "hive-site.xml" ); BiConsumer<InputStream, String> consumer = ( is, filename ) -> { confProxy.addResource( is, filename ); }; ShimConfigsLoader.addConfigsAsResources( namedCluster, consumer ); return confProxy; } ); } }

Target:
Can we roll this functionality directly into the NamedCluster object and start to eliminate ShimConfigsLoader?
Source:
public ExtensionBean getDetail(String extensionName) { EntityManager entityManager = getEntityManager(); beginTransaction(entityManager); Query q = entityManager.createNamedQuery(PersistenceConstants.GET_EXTENSION); q.setParameter(EXTENSION_NAME, extensionName); try { List resultList = q.getResultList(); if (resultList.size()>0) { return (ExtensionBean)resultList.get(0); } else { return null; } } finally { commitAndCloseTransaction(entityManager); } }

Target:
Nit : use isEmpty instead.
Source:
public Response getDetail(@PathParam("extension-name") String extensionName){ checkIfExtensionServiceIsEnabled(); validateExtensionName(extensionName); JSONObject result = new JSONObject(); try { result.put(EXTENSION_DETAIL,buildDetailResult(extensionName)); return Response.ok(result).build(); } catch (Throwable e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }

Target:
why JSON inside a JSON? Can you send the json object from buildDetailResult directly?
Source:
public void onRemove(Entity entity) throws FalconException{ if (entity.getEntityType() != EntityType.PROCESS){ return; } synchronized (this){ backlogMetricStore.deleteEntityInstance(entity.getName()); entityBacklogs.remove(entity); } }

Target:
Should be sufficient to synchronize on entityBacklogs, right? Same applies for onChange method.
Source:
public void putMonitoredEntity(String entityName, String entityType) throws FalconException{ MonitoredEntityBean monitoredEntityBean = new MonitoredEntityBean(); monitoredEntityBean.setEntityName(entityName); monitoredEntityBean.setEntityType(entityType.toLowerCase()); EntityManager entityManager = getEntityManager(); try { beginTransaction(entityManager); entityManager.persist(monitoredEntityBean); } finally { commitAndCloseTransaction(entityManager); } }

Target:
Why this change?
Source:
public EntityList getDependency(String entityType, String entityName, String doAsUser) { ClientResponse clientResponse = new ResourceBuilder().path(Entities.DEPENDENCY.path, entityType, entityName) .addQueryParam(DO_AS_OPT, doAsUser).call(Entities.DEPENDENCY); printClientResponse(clientResponse); checkIfSuccessful(clientResponse); EntityList result = clientResponse.getEntity(EntityList.class); if (result == null || result.getElements() == null) { return new EntityList(); } return result; }

Target:
You dont need the " result.getElements() == null " condition
Source:
public static Sla getSLA(Cluster cluster, Process process) { final Sla clusterSla = cluster.getSla(); if (clusterSla != null) { return clusterSla; } final Sla processSla = process.getSla(); return processSla == null ? null : processSla; }

Target:
The additional null check seems unnecessary. You could just return process.getSla().
Source:
public void tearDown() throws Exception { // delete temporary jks files File credDir = new File("."); File file = new File(credDir, JKS_FILE_NAME); file.delete(); file = new File(credDir, "." + JKS_FILE_NAME + ".crc"); file.delete(); }

Target:
Can we define credDir as public static final String CRED_DIR so that it can be reused in tearDown and testResolveAlias? Thanks!
Source:
public static String getActionStatus(OozieClient oozieClient, String workflowId, String actionName) throws OozieClientException { List<WorkflowAction> wfAction = oozieClient.getJobInfo(workflowId).getActions(); for (WorkflowAction wf : wfAction) { if (wf.getName().contains(actionName)) { if (wf.getExternalStatus() != null) { return wf.getExternalStatus(); } } } return ""; }

Target:
please use 'and' operator in if condition and combine both the if statements for better readability.
Source:
public CatalogStorage(Cluster cluster, CatalogTable table) throws URISyntaxException { this(ClusterHelper.getInterface(cluster, Interfacetype.REGISTRY).getEndpoint(), table); verifyAndUpdateConfiguration(getConf()); }

Target:
You don't need it here. verifyAndUpdateConfiguration is already called in CatalogStorage(String catalogUrl, CatalogTable table).
Source:
public void putMonitoredFeed(String feedName){ MonitoredFeedsBean monitoredFeedsBean = new MonitoredFeedsBean(); monitoredFeedsBean.setFeedName(feedName); EntityManager entityManager = getEntityManager(); beginTransaction(entityManager); entityManager.persist(monitoredFeedsBean); commitAndCloseTransaction(entityManager); }

Target:
Should commitAndCloseTransaction be part of a finally statement?
Source:
public List<PendingInstanceBean> getAllInstances(){ EntityManager entityManager = getEntityManager(); Query q = entityManager.createNamedQuery(PersistenceConstants.GET_ALL_PENDING_INSTANCES); List result = q.getResultList(); if (CollectionUtils.isEmpty(result)) { return null; } entityManager.close(); return result; }

Target:
result seems to be implicitly type casted.
Source:
protected void initializeService() { lastCheckedAt = new Date(); lastSerializedAt = new Date(); }

Target:
Other two can be removed as well.
Source:
public void setup() throws Exception { System.out.println("Executing setup"); StateStoreProperties.get().setProperty(FalconJPAService.URL, url); Configuration localConf = new Configuration(); fs.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); fs.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); falconJPAService.init(); this.dfsCluster = EmbeddedCluster.newCluster("testCluster"); this.conf = dfsCluster.getConf(); // registerServices(); }

Target:
required?
Source:
private void kill(String cluster, String jobId, String rangeType, String scope) throws FalconException { try { OozieClientFactory.get(cluster).kill(jobId, rangeType, scope); assertStatus(cluster, jobId, Status.KILLED, Status.SUCCEEDED, Status.FAILED); LOG.info("Killed job for instances on cluster {}", jobId, scope, cluster); } catch (OozieClientException e) { throw new FalconException(e); } }

Target:
Did you miss to attach LocalOozieCoordClientProxy class ?
Source:
public void add(Edge<I, E> edge) { ExtendedDataOutput extendedDataOutput = getConf().createExtendedDataOutput( serializedEdges, serializedEdgesBytesUsed); try { WritableUtils.writeEdge(extendedDataOutput, edge); } catch (IOException e) { throw new IllegalStateException("add: Failed to write to the new " + "byte array"); } catch (NegativeArraySizeException negativeArraySizeException) { throw new IllegalStateException("add: Too many edges for a vertex, " + edge.getTargetVertexId() + "hence failed to write to byte array"); } serializedEdges = extendedDataOutput.getByteArray(); serializedEdgesBytesUsed = extendedDataOutput.getPos(); ++edgeCount; }

Target:
```suggestion edge.getTargetVertexId() + " hence failed to write to byte array"); ```
Source:
public PieceCount getPieceCount() { PieceCount ret = new PieceCount(0); for (AbstractPiece<I, V, E, M, WV, WM, S> innerPiece : innerPieces) { ret.add(innerPiece.getPieceCount()); } return ret; }

Target:
this should be 1, this executes all pieces simultaneously.
Source:
protected boolean addToBuffer(T persistenceItem) { try { return buffer.offer(persistenceItem, BUFFER_OFFER_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.error("Interrupted when trying to buffer data! Dropping data"); return false; } }

Target:
This should be a WARN instead of an ERROR.
Source:
private boolean sleep() { try { long sleepTime; if (retry == 1 && lastException != null && lastException instanceof ResourceNotFoundException) { sleepTime = WAIT_ON_FIRST_RESOURCE_NOT_FOUND_MILLIS; } else { sleepTime = WAIT_MILLIS_IN_RETRIES[retry]; } Thread.sleep(sleepTime); return true; } catch (InterruptedException e) { logger.error("Interrupted while writing data!"); return false; } }

Target:
I'd argue this should be DEBUG instead of ERROR.
Source:
private void parseFrame(IByteProvider byteProvider) { try { byte currentByte = byteProvider.getByte(); if (currentByte == Frame.START_BYTE) { int length = byteProvider.getByte(); if (length > 0) { byte[] data = byteProvider.getBytes(length + 1); ReceiveFrame frame = new ReceiveFrame(); frame.parse(data); receiveFrames.add(frame); } } } catch (Exception e) { logger.error("Error while parsing ReceiveFrame", e); } }

Target:
Please also change this to WARN instead of ERROR.
Source:
public synchronized boolean bridgeLogin() { logger.trace("bridgeLogin() called."); Login bcp = this.bridgeAPI().login(); bcp.setPassword(this.bridgeInstance.veluxBridgeConfiguration().bridgePassword); if (bridgeCommunicate(bcp, false)) { logger.trace("bridgeLogin(): communication succeeded."); if (bcp.isCommunicationSuccessful()) { logger.trace("bridgeLogin(): storing authentication token for further access."); authenticationToken = bcp.getAuthToken(); return true; } } return false; }

Target:
Drop all the unnecessary use of `this.` throughout.
Source:
public boolean modifyHSM(VeluxBridge bridge, boolean enableService) { logger.trace("modifyHSM({}) called.", enableService); ModifyHouseStatusMonitor bcp = bridge.bridgeAPI().modifyHouseStatusMonitor(); bcp.serviceActivation(enableService); if ((bridge.bridgeCommunicate(bcp)) && (bcp.isCommunicationSuccessful())) { logger.debug("modifyHSM() finished successfully."); return true; } else { logger.trace("modifyHSM() finished with failure."); return false; } }

Target:
redundant parentheses
Source:
public boolean execute(VeluxBridge bridge, int sceneNo) { logger.trace("execute({}) called.", sceneNo); RunScene bcp = bridge.bridgeAPI().runScene(); bcp.setSceneId(sceneNo); if ((bridge.bridgeCommunicate(bcp)) && (bcp.isCommunicationSuccessful())) { logger.debug("execute() finished successfully."); return true; } else { logger.trace("execute() finished with failure."); return false; } }

Target:
redundant parentheses
Source:
public boolean setSilentMode(VeluxBridge bridge, int sceneNo, boolean silentMode) { logger.trace("setSilentMode({},{}) called.", sceneNo, silentMode); SetSilentMode bcp = bridge.bridgeAPI().setSilentMode(); bcp.setMode(sceneNo, silentMode); if ((bridge.bridgeCommunicate(bcp)) && (bcp.isCommunicationSuccessful())) { logger.info("setSilentMode() finished successfully."); return true; } logger.trace("setSilentMode() finished with failure."); return false; }

Target:
redundant parentheses
Source:
public void setPassword(String thisPassword) { logger.trace("setPassword({}) called.",thisPassword); request.params.password = thisPassword; return; }

Target:
Remove this line.
Source:
private static boolean check4matchingAnyID(Logger logger, String idName, int requestID, int responseID) { logger.trace("check4matchingAnyID() called for request{} and response{} {}.", idName, requestID, idName, responseID); if (requestID != responseID) { logger.warn("Gateway response with unexpected as query asked for {}.", idName, requestID, idName, responseID); return false; } else { logger.trace("check4matchingAnyID() returns {}.", true); return true; } }

Target:
`else` is redundant here
Source:
public BridgeAPI bridgeAPI() { logger.error( "bridgeAPI({}) called. Should NEVER occur as it seems to be a lack of protocol-specific implementation of this bridge API."); return null; }

Target:
This should be a DEBUG.
Source:
public void receiveCommand(String itemName, Command command) { logger.trace("receiveCommand({},{}) called.", itemName, command.toString()); if (this.eventPublisher == null) { logger.error("receiveCommand(): eventPublisher is NULL. Should NEVER occur."); return; } super.receiveCommand(itemName, command); }

Target:
Revert to WARN.
Source:
public void onCommand(ProtocolRead c) throws IOException, Exception { try { myPlant.sendCommandAsync(OWNUtilities.createFrame(c), 1); } catch (MalformedCommandOPEN ex) { logger.error("onCommand error : {}", ex.getMessage()); } }

Target:
This should be a WARN instead of an ERROR.
Source:
public void run() { try { while (!Thread.interrupted()) { // synchronizes the software with the system status // Every x seconds do a full bus scan checkForBusScan(); Thread.sleep(1000); } } catch (InterruptedException p_i_ex) { logger.error("Openwebnet.run, InterruptedException : " + p_i_ex.getMessage()); } catch (Exception p_i_ex) { logger.error("Openwebnet.run, Exception : {}", p_i_ex.getMessage()); } finally { // interrupt handler on monitor thread will stop thread monitorSessionThread.interrupt(); logger.info("Stopped monitorSessionThread thread"); } logger.info("Stopped OpenWebNet thread"); }

Target:
This should be a WARN instead of an ERROR.
Source:
public void notifyEvent(ProtocolRead p_i_event) { for (IBticinoEventListener l_event_listener : m_event_listener_list) { try { l_event_listener.handleEvent(p_i_event); } catch (Exception p_ex) { logger.error("notifyEvent, Exception : {}", p_ex.getMessage()); } } }

Target:
This should be a WARN instead of an ERROR.
Source:
public void start(BundleContext bc) throws Exception { context = bc; logger.info("Slack action has been started."); }

Target:
Could this and the next logger statement be reduced to debug?
Source:
public void stateUpdated(Item item, State state) { if (exposedItems != null && exposedItems.contains(item.getName())) { logger.debug("Sending item update to openhab Cloud: - {}", item.getName(), state.toString()); cloudClient.sendItemUpdate(item.getName(), state.toString()); } }

Target:
The `.toString()` can be left to the logger for performance.
Source:
public Object getValueParameter() { if (valueParameter == null) { return null; } else { return valueParameter; } }

Target:
This should be simplified to just: >return valueParameter;
Source:
public void start() throws Exception { logger.trace("Starting Dmx transmitter ..."); transmitter = new DmxTransmitter(this); transmitter.setTransmitRefresh(transmitRefreshMs); transmitterTimer = new Timer(true); transmitterTimer.schedule(transmitter, 0, TRANSMIT_FREQUENCY_MS); logger.trace("Dmx transmitter started."); }

Target:
Could the variables/members/methods all use the phrase `refreshInterval` so the changed code is easier to follow?
Source:
public DmxTransmitter(DmxService service) { this.service = service; lastTransmit = 0; }

Target:
Could `lastTransmit` be initialized to 0 above, instead of one private member being initialized that way, and the other initialized in the constructor?
Source:
public static String updateStatusVar(LcnDefs.Var var, int value) throws IllegalArgumentException { int id = LcnDefs.Var.toVarId(var); if (id != -1) { // define variable to set, offset 0x01000000 int x2cmd = id |= 0x40; int b1 = (value >> 8) & 0xff; int b2 = value & 0xff; return String.format("X2%03d%03d%03d", x2cmd, b1, b2); } // Setting variables and thresholds absolute not implemented in LCN firmware yet throw new IllegalArgumentException(); }

Target:
It doesn't affect the result, but it would be clearer to use the simple bitwise OR operator (`|`) instead of the bitwise inclusive OR and assignment operator (`|=`).
Source:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config == null) { return; } validateKeyPatternsInConfig(config); stick = setupStick(config); if (stick != null) { setupNonStickDevices(config); setProperlyConfigured(true); } else { logger.error("Plugwise needs at least one Stick in order to operate"); } }

Target:
This would be better as a `logger.warn`, since `logger.error` is reserved for messages that affect system stability.
Source:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { e.printStackTrace(); } }

Target:
Please use logger instead of e.printStackTrace()
Source:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { logger.debug("ERROR: " + e.getMessage()); } }

Target:
Use parameterized logging instead of string concatenation.
Source:
public boolean sizeIsZero() { return somestring.length == 0; }

Target:
@amihaiemil should be `length()`
Source:
private static boolean isJavadocLineEmpty(final String line) { return null != line && "*".equals(line.trim()); }

Target:
@dskalenko when line can be null?
Source:
private static int getLineNoOfPreviousNode(final DetailAST node) { int start = 0; final DetailAST previous = node.getPreviousSibling(); if (null != previous) { start = previous.getLineNo(); } return start; }

Target:
@dskalenko move `null` to right hand side
Source:
public LineRanges within(final LineRanges ranges) { final LineRanges result = new LineRanges(); final Iterator<LineRange> iterator = ranges.iterate(); while (iterator.hasNext()) { final LineRange next = iterator.next(); for (final LineRange line : this.lines.collection()) { if (next.within(line)) { result.add(line); } } } return result; }

Target:
@JimDeanSpivey can we go with a foreach? `for (final LineRange range : ranges)`?
Source:
public void forbidsNonPublicCloneMethod() throws Exception { final String file = "CloneMethodMustBePublic.java"; new PMDAssert( file, Matchers.is(false), Matchers.containsString( String.format( PMDValidatorTest.BRACKETS, "CloneMethodMustBePublic" ) ) ).validate(); }

Target:
@Happy-Neko we can inline this variable
Source:
public void failValidationWithoutSchema() throws Exception { final Environment env = new Environment.Mock() .withFile( "src/main/resources/noschema.xml", // @checkstyle LineLength (1 line) "<Configuration><Appenders><Console name=\"CONSOLE\" target=\"SYSTEM_OUT\"><PatternLayout pattern=\"[%p] %t %c: %m%n\"/></Console></Appenders></Configuration>" ); final Validator validator = new XmlValidator(true); validator.validate(env); }

Target:
@Happy-Neko how about ``` java new XmlValidator(true).validate( new Environment.Mock().withFile( ... ) ); ```
Source:
private static String toLegacyPathString(String moduleName) { final ModuleIdentifier moduleIdentifier = ModuleIdentifier.fromString(moduleName); return moduleIdentifier.getName().replace('.', '/') + '/' + moduleIdentifier.getSlot() + '/'; }

Target:
Same problem with ending slash here.
Source:
public MulticurveProviderDiscount getMulticurveProvider() { IssuerProviderInterface issuerProvider = getIssuerProvider(); if (issuerProvider instanceof IssuerProviderDiscount) { return ((IssuerProviderDiscount) issuerProvider).getMulticurveProvider(); } else if (issuerProvider instanceof IssuerProviderIssuerDecoratedSpreadPeriodic) { return (MulticurveProviderDiscount) ((IssuerProviderIssuerDecoratedSpreadPeriodic) issuerProvider) .getMulticurveProvider(); } throw new IllegalArgumentException("unsupported type of issuer provider"); }

Target:
Why this "if"? The original code does not work anymore? I should be a direct pass-through of the underlying curves.
Source:
public void penaltyMatrixDiffOrderTooHighTest() { @SuppressWarnings("unused") DoubleMatrix2D p = getPenaltyMatrix(6, 10); }

Target:
As above, no need to assign.
Source:
List<String> headers() { if (node.hasProperty(HEADERS) && !DYNAMIC_HEADERS.matcher(node.getPropertyValue(HEADERS)).find()) { return Arrays.asList(node.getPropertyValue(HEADERS).split("\\s+")).stream().filter(header -> !header.isEmpty()).collect(Collectors.toList()); } else { return Collections.emptyList(); } }

Target:
You can use `Arrays.stream` instead
Source:
private static boolean hasHeader(TagNode node) { if (node.getChildren().stream().anyMatch(TableWithoutHeaderCheck::isTableHeader)) { return true; } else { return node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutHeaderCheck::hasHeader); } }

Target:
You could use shortcircuit evaluation to avoid `if-else` block here: ``` return node.getChildren().stream().anyMatch(TableWithoutHeaderCheck::isTableHeader) || node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutHeaderCheck::hasHeader); ```
Source:
private static boolean isLayout(TagNode node) { String role = node.getAttribute("ROLE"); return role != null && ("PRESENTATION".equalsIgnoreCase(role) || "NONE".equalsIgnoreCase(role)); }

Target:
null check seems unnecessary, given the yoda condition
Source:
private static boolean isHidden(TagNode node) { String ariaHidden = node.getAttribute("ARIA-HIDDEN"); return ariaHidden != null && "TRUE".equalsIgnoreCase(ariaHidden); }

Target:
unneeded null check
Source:
private static boolean hasCaption(TagNode node) { if (node.getChildren().stream().anyMatch(TableWithoutCaptionCheck::isCaption)) { return true; } else { return node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutCaptionCheck::hasCaption); } }

Target:
per [html spec](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) caption can only be first child of `<table>` element. We don't need to recurse through all children. (you can also update RSPEC of the rule with this)
Source:
private static boolean hasFigCaption(TagNode node) { if (node.getChildren().stream().anyMatch(TableWithoutCaptionCheck::isFigCaption)) { return true; } else { return node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutCaptionCheck::hasFigCaption); } }

Target:
similar as above, `figcaption` is only allowed as first or last child. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption
Source:
public JobInfo(String jobName_, String groupName_, Class job_, String shouldRecover) { this(jobName_, groupName_, job_); if(shouldRecover == null) { this.shouldRecover= true; } else { this.shouldRecover = Boolean.getBoolean(shouldRecover); } }

Target:
you should use Boolean.valueOf instead of Boolean.getBoolean.
Source:
public boolean apply(Game game, Ability source) { Player targetPlayer = game.getPlayer(targetPointer.getFirst(game, source)); if (targetPlayer == null) { return true; } int count = targetPlayer.discard(targetPlayer.getHand(), source, game).size(); targetPlayer.drawCards(count, source.getSourceId(), game); return false; }

Target:
Must return `true`. Also must return `false` on code above (`targetPlayer == null`).
Source:
public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getFirstTarget()); if (player != null) { player.discard(player.getHand(), source, game); } return false; }

Target:
Missing return true
Source:
public FilterInstantSpell(String name) { super(name); this.add(Predicates.or(CardType.INSTANT.getPredicate())); }

Target:
You don't need `Predicates.or` here
Source:
public FirecannonBlast(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{1}{R}{R}"); // Firecannon Blast deals 3 damage to target creature. // Raid - Firecannon Blast deals 6 damage to that creature instead if you attacked with a creature this turn. this.getSpellAbility().addEffect(new ConditionalOneShotEffect( new DamageTargetEffect(6), new DamageTargetEffect(3), new InvertCondition(RaidCondition.instance), "{this} deals 3 damage to target creature.<br><i>Raid</i> &mdash; {this} deals 6 damage instead if you attacked with a creature this turn")); this.getSpellAbility().addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addWatcher(new PlayerAttackedWatcher()); }

Target:
```suggestion RaidCondition.instance, ```
Source:
public FilterMana getPhyrexianColors() { return this.phyrexianColors.copy(); }

Target:
Why it's makes copies in every getter call instead simple ref? Normal code: return ref objects and create copy on Copy/Create method (but you are using ref in copy -- see above/below).
Source:
public boolean checkTrigger(GameEvent event, Game game) { Spell spell = game.getStack().getSpell(event.getTargetId()); if (spell != null) { for (Ability ability : spell.getAbilities()) { if (ability instanceof KickerAbility && ((KickerAbility) ability).getKickedCounter(game, spell.getSpellAbility()) > 0) { return true; } } } return false; }

Target:
This will only trigger once for a multikicked spell, it needs to trigger separately for each kick.
Source:
public TreacherousUrge(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{4}{B}"); this.subtype.add(SubType.ARCANE); // Target opponent reveals his or her hand. You may put a creature card from it onto the battlefield under your control. That creature gains haste. Sacrifice it at the beginning of the next end step. this.getSpellAbility().addEffect(new TreacherousUrgeEffect()); this.getSpellAbility().addTarget(new TargetOpponent()); }

Target:
This needs to be removed
Source:
public DeeprootWaters(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{U}"); // Whenever you cast a Merfolk spell, create a 1/1 blue Merfolk creature token with hexproof. this.addAbility(new SpellCastControllerTriggeredAbility(new CreateTokenEffect(new MerfolkHexproofToken(), 1, true, false), filter, false)); }

Target:
You can use the constructor for CreateTokenEffect that just takes the token as its only argument. The one you're using has tapped set to true.
Source:
public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.DREW_CARD) { amountOfCardsDrawnThisTurn.putIfAbsent(event.getPlayerId(), 0); amountOfCardsDrawnThisTurn.compute(event.getPlayerId(), (k, amount) -> amount += 1); } }

Target:
`amount + 1` is enough. You don't need to mutate `amount`.
Source:
public boolean isEnchantedCreature(MageObject input, Game game) { if (!input.getCardType().contains(CardType.CREATURE)) { return false; } for (UUID attachmentId : ((Permanent)input).getAttachments()) { Permanent attachment = game.getPermanent(attachmentId); if (attachment != null && attachment.getCardType().contains(CardType.ENCHANTMENT)) { return true; } } return false; }

Target:
check input to be != null
Source:
public boolean apply(Game game, Ability source) { Player activePlayer = game.getPlayer(game.getActivePlayerId()); return activePlayer != null && game.getPlayer(game.getActivePlayerId()).hasOpponent(source.getControllerId(), game) && game.getPhase().getStep().getType().getIndex() < 5; }

Target:
Use the activePlayer object instead of retrieving it again
Source:
public boolean configure( StaplerRequest req, JSONObject formData) throws FormException { this.stashRootUrl = null; this.ignoreUnverifiedSsl = false; this.includeBuildNumberInKey = false; this.credentialsId = null; this.projectKey = null; this.prependParentProjectKey = false; this.disableInprogressNotification = false; this.considerUnstableAsSuccess = false; req.bindJSON(this, formData); save(); return true; }

Target:
I suggest to keep the order consistent for easier reading/comparison: * field declarations in `StashNotifier` (maybe) * setters/getters in `StashNotifier` (maybe) * default values (lines 751-758) in `StashNotifier::configure` * assertThat calls (lines 27-33) in `ConfigAsCodeTest::should_support_jcasc_from_yaml` * setter calls (lines 40-47) in `ConfigAsCodeTest::should_support_jcasc_to_yaml`
Source:
public String getStashRootUrl() { if ((stashRootUrl == null) || (stashRootUrl.trim().isEmpty())) { return null; } else { return stashRootUrl; } }

Target:
Now that `trimToNull()` is used in `setStashRootUrl()` this can simply return the `stashRootUrl` value (like all other getters).
Source:
public StashNotifier( String stashServerBaseUrl, String stashUserName, String stashUserPassword, boolean ignoreUnverifiedSSLPeer) { this.stashServerBaseUrl = stashServerBaseUrl; this.stashUserName = stashUserName; this.stashUserPassword = stashUserPassword; this.ignoreUnverifiedSSLPeer = ignoreUnverifiedSSLPeer; jenkins = Jenkins.getInstance(); httpClientfactory = new ConcreteHttpClientFactory(); notifierService = new ConfigurableStashNotifierService( stashServerBaseUrl, new JsonBuildEntityFactory(), new BasicStashRequestConfigurator(stashUserName, stashUserPassword)); }

Target:
stashnotifier fails with a `NullPointerException` when trying to access `jenkins` in line `134`. The only explanation I can come up with is that `Jenkins.getInstance()` returns `null` when it is called during construction time of this plugin. I have no idea why that should be the case, though. Here's the exception I see in the Jenkins console output ``` ERROR: Publisher org.jenkinsci.plugins.stashNotifier.StashNotifier aborted due to exception java.lang.NullPointerException at org.jenkinsci.plugins.stashNotifier.StashNotifier.perform(StashNotifier.java:134) at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:36) at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:810) at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:785) at hudson.maven.MavenModuleSetBuild$MavenModuleSetBuildExecution.post2(MavenModuleSetBuild.java:946) at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:732) at hudson.model.Run.execute(Run.java:1582) at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:477) at hudson.model.ResourceController.execute(ResourceController.java:88) at hudson.model.Executor.run(Executor.java:236) Finished: FAILURE ```
Source:
public void onNewSourceColumn() { if (!userPrefs_.allowSourceColumns().getValue()) pGlobalDisplay_.get().showMessage(GlobalDisplay.MSG_INFO, "Cannot Add Column", "Allow Source Columns preference is disabled."); else if (additionalSourceCount_ == MAX_COLUMN_COUNT) pGlobalDisplay_.get().showMessage(GlobalDisplay.MSG_INFO, "Cannot Add Column", "You can't add more than " + MAX_COLUMN_COUNT + " columns."); else createSourceColumn(); }

Target:
Nit: although it's a constant now, if we ever make max column count configurable then maybe want this to be a `>=` comparison just to be safe in case where max changes to be smaller than current number of columns?
Source:
public boolean equals(LogicalWindow window) { if(normal_.equals(window.normal_)) return true; return false; }

Target:
Maybe simplify to `return normal_.equals(window.normal_)`?
Source:
private void installConnectionsToolbar() { toolbar_.removeAllWidgets(); newConnectionButton_ = toolbar_.addLeftWidget(commands_.newConnection().createToolbarButton()); toolbar_.addLeftSeparator(); toolbar_.addRightWidget(searchWidget_); setSecondaryToolbarVisible(false); }

Target:
Addition of this member variable looks unnecessary, and can be un-done I think?
Source:
protected Toolbar createMainToolbar() { toolbar_ = new Toolbar("Tutorial Tab"); // TODO: managing history within an iframe is surprisingly challenging, // so we just leave these buttons unavailable for now and just allow // navigation to home // toolbar_.addLeftWidget(commands_.tutorialBack().createToolbarButton()); // toolbar_.addLeftWidget(commands_.tutorialForward().createToolbarButton()); toolbar_.addLeftWidget(homeButton_ = commands_.tutorialHome().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialPopout().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialStop().createToolbarButton()); toolbar_.addRightWidget(commands_.tutorialRefresh().createToolbarButton()); return toolbar_; }

Target:
Don't need the added `homeButton_` member variable.
Source:
public SourceAppCommand getSourceCommand(AppCommand command, SourceColumn column) { // check if we've already create a SourceAppCommand for this command for (SourceAppCommand cmd : sourceAppCommands_) { if (cmd.getCommand() == command && cmd.getColumn() == column.getName()) return cmd; } // if not found, create it SourceAppCommand sourceCommand = new SourceAppCommand(command, column.getName(), this); sourceAppCommands_.add(sourceCommand); return sourceCommand; }

Target:
Testing JavaScript objects for equality has a bunch of weird edge cases so I'd recommend avoiding it. For example the object could be cloned and the clone won't match, but they'll look like the same object in the debugger so it won't be obvious WHY they don't match! How about storing `sourceAppCommands_` as a `HashMap`, using the command ID (from `command.getId()`) plus the column name as a key? Then lookups will be faster, plus identity will be more reliable as you'll just need to check for existence in the map.
Source:
public void setActive(String name) { if (StringUtil.isNullOrEmpty(name)) { Debug.logWarning("Active column should be set to the main source window instead of null."); if (activeColumn_ != null) { activeColumn_.setActiveEditor(""); activeColumn_ = null; } return; } // If we can't find the column, use the main column. This may happen on start up. SourceColumn column = getByName(name); if (column == null) column = getByName(MAIN_SOURCE_NAME); setActive(column); }

Target:
Did you want to leave this in?
Source:
void onDevtoolsLoadAll() { source_.withSaveFilesBeforeCommand(new Command() { @Override public void execute() { withDevtoolsLoadAllPath(new CommandWithArg<String>() { @Override public void execute(String loadAllPath) { sendLoadCommandToConsole( "devtools::load_all(\"" + loadAllPath + "\")"); } }); } }, new Command() { public void execute() { } }, "Build"); }

Target:
While you're touching this... could be lambda-fied. Braces and newlines as you see fit: ``` source_.withSaveFilesBeforeCommand(() -> { withDevtoolsLoadAllPath(loadAllPath -> { sendLoadCommandToConsole("devtools::load_all(\"" + loadAllPath + "\")"); }); }, () -> {}, "Build"); ```
Source:
public Command revertUnsavedChangesBeforeExitCommand( final Command onCompleted) { return new Command() { @Override public void execute() { handleUnsavedChangesBeforeExit( new ArrayList<UnsavedChangesTarget>(), onCompleted); } }; }

Target:
Reduce this whole method to: ``` public Command revertUnsavedChangesBeforeExitCommand(final Command onCompleted) { return () -> handleUnsavedChangesBeforeExit(new ArrayList<>(), onCompleted); } ```
Source:
private void runShinyApp() { source_.withSaveFilesBeforeCommand(() -> { events_.fireEvent(new LaunchShinyApplicationEvent(getPath(), prefs_.shinyBackgroundJobs().getValue() ? ShinyApplication.BACKGROUND_APP : ShinyApplication.FOREGROUND_APP, getExtendedFileType())); }, new Command() { public void execute() { } }, "Run Shiny Application"); }

Target:
labmda: `() -> {}`
Source:
private void runPlumberAPI() { source_.withSaveFilesBeforeCommand(new Command() { @Override public void execute() { events_.fireEvent(new LaunchPlumberAPIEvent(getPath())); } }, new Command() { public void execute() { } }, "Run Plumber API"); }

Target:
lambda: `() -> {}`
Source:
public void executeCallback() { // This method must be called by a single HighlightPair, but because there can be multiple // pairs per query, we need to check if the callback has already executed before proceeding. if(!highlighter_.getCallbackProcessed(index_)) { highlighter_.setCallbackProcessed(index_, true); highlighter_.getServer().executeRCode(callback_, new ServerRequestCallback<String>(){ @Override public void onResponseReceived(String results) { // Remove listener from this element and all other elements with the same query highlighter_.clearEvents(); } @Override public void onError(ServerError error) { Debug.logError(error); } }); } }

Target:
Should we clear highlight on error as well?
Source:
public void ensureInputVisible() { // NOTE: we don't scroll immediately as this is normally called // in response to mutations of the console input buffer, and so // we need to wait until Ace has finished rendering in response // to that change. scrollIntoViewPending_ = true; // In case there wasn't an Ace render in-flight, force a check // for pending scroll (which will then force the cursor into view) Scheduler.get().scheduleDeferred(() -> checkForPendingScroll()); }

Target:
Should we skip doing this if `scrollIntoViewPending_` is already true so there's no way for requests to stack up?
Source:
public boolean visible() { switch (state_) { case HIDE: return false; case MINIMIZE: return false; default: return true; } }

Target:
nit: don't need this `return false;` line
Source:
public boolean presentationVisible() { CheckBox lastCheckBox = checkBoxes_.get(checkBoxes_.size() - 1); return StringUtil.equals(lastCheckBox.getText(), "Presentation") && lastCheckBox.isVisible(); }

Target:
Is there any risk of this being called where checkBoxes_ is empty, so checkBoxes_.size() - 1 would be negative and (I think) end up throwing an exception? Might be worth a check for this if any chance of it happening.
Source:
public void focus() { widgets_.forEach(widget -> { if (widget.isVisible()) { widget.focus(); } }); }

Target:
Should this exit after finding the first visible widget that can be focused?
Source:
public TerminalPopupMenu(TerminalList terminals) { super(); RStudioGinjector.INSTANCE.injectMembers(this); terminals_ = terminals; }

Target:
A Java constructor automatically does a call to no-argument `super()` so this isn't needed.
Source:
private void nudgeAutosave() { // Cancel any existing autosave timer if (autoSaveTimer_.isRunning()) autoSaveTimer_.cancel(); // Start new timer if enabled if (prefs_.autoSaveOnIdle().getValue() == UserPrefs.AUTO_SAVE_ON_IDLE_COMMIT) autoSaveTimer_.schedule(prefs_.autoSaveMs()); }

Target:
FWIW you can call `cancel()` directly (it will be a no-op if the timer is not running)
Source:
public boolean contains(@Nonnull User user) { return user.getProperty(GithubAccessTokenProperty.class) != null; }

Target:
This class has no fields so its methods should be `static`.
Source:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = super.getCreatableProperties(); description.addProperty("deathdateEstimated"); description.addProperty("birthtime"); return description; }

Target:
I think that `deathdateEstimated` was only added in 1.11.x, it should not be known in the context of 1.10.x compatibility.
Source:
public String getUuidProperty() { return RestTestConstants2_2.ORDER_UUID; }

Target:
This should be the resource uuid and not that of the parent, in this case the FulfillerDetails has no uuid property so this should possibly return null
Source:
public long getAllCount() { return 1; }

Target:
I believe this should be zero
Source:
public FulfillerDetails save(FulfillerDetails delegate) { Context.getOrderService().updateOrderFulfillerStatus(delegate.getOrder(), delegate.getFulfillerStatus(), delegate.getFulfillerComment()); return delegate; }

Target:
I'm thinking this should return null, you don't need to send back any data to the client given the nature of the resource, the framework sends back an http OK status to the user in case of a success or 500 in case of an exception and that should be sufficient.
Source:
public String getDisplayString(Diagnosis diagnosis) { if (diagnosis.getDiagnosis() == null) { return ""; } else { if (diagnosis.getDiagnosis().getCoded() != null) return diagnosis.getDiagnosis().getCoded().getName().getName(); return diagnosis.getDiagnosis().getNonCoded(); } }

Target:
Can you use curly braces? https://wiki.openmrs.org/display/docs/Java+Conventions#JavaConventions-CodeStyle
Source:
public DelegatingResourceDescription getCreatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); description.addRequiredProperty("uuid"); description.addRequiredProperty("condition"); description.addRequiredProperty("certainty"); description.addRequiredProperty("patient"); description.addRequiredProperty("rank"); description.addRequiredProperty("voided"); return description; }

Target:
Remove voided from the creatable.
Source:
public DelegatingResourceDescription getCreatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); description.addRequiredProperty("uuid"); description.addRequiredProperty("condition"); description.addRequiredProperty("certainty"); description.addRequiredProperty("patient"); description.addRequiredProperty("rank"); return description; }

Target:
uuid is not creatable
Source:
public void started() { log.info("Started the REST Web Service module"); // Cache Swagger Spec new SwaggerSpecificationCreator("host/openmrs/ws/rest").BuildJSON(); }

Target:
Since this is running from the server itself, can't you just use localhost?
Source:
public void shutDownTask(TaskDefinition task) throws SchedulerException { if (Context.getSchedulerService().getTaskByName(task.getName()).getStarted()) { Context.getSchedulerService().shutdownTask(task); } }

Target:
Same here as above. So let us get rid of this whole class. Because it is not adding value. And where it does, that is the business of the service layer API.
Source:
public void shutDownTask(TaskDefinition task) throws SchedulerException { for (String taskDef : scheduledTasks) { if (taskDef.equals(task.getName())) { scheduledTasks.remove(taskDef); break; } } }

Target:
Shouldn't this also just call Context.getSchedulerService(). shutDownTask(task) Same for the others.
Source:
public TaskDefinition save(TaskDefinition taskDefinition) { taskServiceWrapper.saveTaskDefinition(taskDefinition); return Context.getSchedulerService().getTaskByName(taskDefinition.getName()); }

Target:
Why do you fetch the task again?
Source:
public void deleteTask(TaskDefinition task) throws SchedulerException { if (Context.getSchedulerService().getTaskByName(task.getName()).getStarted()) { Context.getSchedulerService().shutdownTask(task); } Context.getSchedulerService().deleteTask(task.getId()); }

Target:
What is the use of this logic? Isn't it taken care of by the service layer? Why don't you just Context.getSchedulerService().deleteTask?
Source:
public void shouldShutdownTask() throws Exception { mockTaskServiceWrapper.scheduledTasks.add(testTask); deserialize(handle(newPostRequest(getURI(), "{\"action\": \"shutdowntask\", \"tasks\":[\"" + getTestTaskName() + "\"]}"))); assertThat(mockTaskServiceWrapper.scheduledTasks, not(hasItem(testTask))); }

Target:
How how are you that the task wasn't already shutdown even before the shutdown command?
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SearchParameter that = (SearchParameter) o; if (!name.equals(that.name)) return false; return value != null ? value.equals(that.value) : that.value == null; }

Target:
What if you use SubresourceParameter? You should use instanceof here.
Source:
private boolean operationHasRepresentationParam(Operation o) { boolean ret = false; for (Parameter p : o.getParameters()) { if (p.getName().equals("v")) { ret = true; } } return ret; }

Target:
Shouldn't we return immediately to save some unnecessary cycles? Or at least break out of the for loop.
Source:
public Allergy newObject() { Allergy allergy = Context.getPatientService().getAllergyByUuid(RestTestConstants2_0.ALLERGY_UUID); return allergy; }

Target:
Isn't this supposed to create and return a new (not yet in the database) allergy?
Source:
public SimpleObject getValue(PersonAttribute pa) { if (pa.getHydratedObject() == null) return null; SimpleObject simpleObject = new SimpleObject(); simpleObject.put("value", ConversionUtil.convertToRepresentation(pa.getHydratedObject(),Representation.REF)); return simpleObject; }

Target:
Could you please try returning plain Object returned from pa.getHudratedObject() without converting to SimpleObject?
Source:
private List<String> getIgnorePatterns() { int index = arguments.indexOf(toArg(IOptionKeys.IGNORE_PATTERN)); return this.getValues(index); }

Target:
if the argument expected doesnt exist the code will take another argument as the value for the Input argument. Should we check and complain or default ?
Source:
public LabelMetadataBuilder(String ID, String description) { super(ID); this.description = description; this.priority = Integer.MAX_VALUE; }

Target:
we could replace this with `this(ID, description, Integer.MAX_VALUE);`
Source:
public Object getDefaultValue() { if (Boolean.class.isAssignableFrom(this.getType())) { return false; } else return null; }

Target:
You probably also want to support "boolean.class"
Source:
public static XSLTTransformation using(String location) { // classLoader instance needed to see the file passed in the location contextClassLoader = Thread.currentThread().getContextClassLoader(); XSLTTransformation tansformation = new XSLTTransformation(); tansformation.location = location; return tansformation; }

Target:
Good!
Source:
public void perform(GraphRewrite event, EvaluationContext context) { checkVariableName(event, context); WindupVertexFrame payload = resolveVariable(event, getVariableName()); if (payload instanceof FileReferenceModel) { perform(event, context, ((FileReferenceModel) payload).getFile()); } else { perform(event, context); } }

Target:
this is self-reference that I accidentally did. This would cause OutOfMemory when the classification is created for example on the variable that is FileModel (right now there is any such case). Could you please fix that in your PR to be `super.perform(event,context)` ?
Source:
public GraphService(Class<T> type) { this.type = type; }

Target:
Should this constructor be protected?
Source:
public void testListDList() { DList<Integer> d = listDList(List.range(0, 1000)); assertThat(d.toJavaList(), is(d.run().toJavaList())); }

Target:
instead of testing `assertThat(d.toJavaList(), is(d.run().toJavaList()));` (that only check that `toJavaList()` is an alias of `run().toJavaList()`) I think we better test something like `assertThat(d.toJavaList(), is(List.range(0, 1000).toJavaList()));` (same for below methods)
Source:
private Always(F0<A> supplier) { this.supplier = supplier; }

Target:
package private
Source:
private PureTrampolineEval(Eval<A> start) { this.start = start; }

Target:
package private
Source:
private BindTrampolineEval(F<A, Eval<B>> f, TrampolineEval<A> next) { this.next = next; this.f = f; }

Target:
package private
Source:
public <B> Eval<B> flatMap(final F<A, Eval<B>> f) { return bind(f); }

Target:
could be `final`.
Source:
TrampolineEval<A> asTrampoline() { return this; }

Target:
`final`.
Source:
public static <K, A> PriorityQueue<K, A> priorityQueue(Equal<K> e, FingerTree<K, P2<K, A>> ft) { return new PriorityQueue<K, A>(e, ft); }

Target:
nitpicking: could be `new PriorityQueue<>(`
Source:
public static <A> PriorityQueue<Integer, A> emptyInt() { return priorityQueue(Equal.intEqual, FingerTree.empty(Monoid.intMaxMonoid, (P2<Integer, A> p) -> p._1())); }

Target:
could be `return empty(Monoid.intMaxMonoid, Equal.intEqual);`
Source:
public IO<Unit> println(final String s) { return () -> { result = s; return Unit.unit(); }; }

Target:
Would it make sense to make this return the string, rather than assign it to the instance variable `result`. Longer term, perhaps we need a bind method like: `IO<A> bindLeft(IO<A> io, F<A, IO<B>> f)` which binds, but returns the a from the left argument. But this would be another issue. I would have to check the Haskell doc to see if this exists.