auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static boolean hasMoreThanOneStatement(ForEachStatementTree forEach) { if (forEach.statements().size() > 1) { return true; } START StatementTree body = forEach.statements().get(0); END if (body.is(Tree.Kind.BLOCK)) { return ((BlockTree) body).statements().size() > 1; } return false; } what if it's alternative syntax with 0 statements?

Target:
private static boolean hasMoreThanOneStatement(ForEachStatementTree forEach) { if (forEach.statements().size() > 1) { return true; } if (forEach.statements().isEmpty()) { // just to be sure // will never happen in this rule, because we are hooked on jumps inside loops return false; } StatementTree body = forEach.statements().get(0); if (body.is(Tree.Kind.BLOCK)) { return ((BlockTree) body).statements().size() > 1; } return false; }
Source:
void addPredecessor(PhpCfgBlock predecessor) { START this.predecessors.add(predecessor); END } be consistent on `this` usages (use always or never)

Target:
void addPredecessor(PhpCfgBlock predecessor) { predecessors.add(predecessor); }
Source:
public void visitSwitchStatement(SwitchStatementTree tree) { START tree.cases().stream().forEach(this::checkCaseClause); END super.visitSwitchStatement(tree); } No need to call stream() here.

Target:
public void visitSwitchStatement(SwitchStatementTree tree) { tree.cases().forEach(this::checkCaseClause); super.visitSwitchStatement(tree); }
Source:
START private static boolean isCountCall(ExpressionTree testedValue) { END return testedValue.is(Tree.Kind.FUNCTION_CALL) && "count".equals(((FunctionCallTree) testedValue).callee().toString()); } No, I don't think there's anything better for the moment. Feel free to create it. Note that function names are case insensitive: ``` <?php echo count([42, 43]) . "\n"; echo coUNt([42, 43]) . "\n"; // ok! function greet($name) { echo "Hello $name\n"; } greet("john"); GrEet("jack"); // ok! $a = 42; echo $A; // fails ```

Target:
private static boolean isCountCall(ExpressionTree testedValue) { return testedValue.is(Tree.Kind.FUNCTION_CALL) && "count".equalsIgnoreCase(((FunctionCallTree) testedValue).callee().toString()); }
Source:
public TestSuites parse(File report) { try (InputStream inputStream = new FileInputStream(report)) { final Object parsedObject = xstream().fromXML(inputStream); TestSuites testSuites = (TestSuites) parsedObject; START return testSuites; END } catch (IOException e) { throw new IllegalStateException("Can't read PhpUnit report : " + report.getAbsolutePath(), e); } } @inverno `return (TestSuites) xstream().fromXML(inputStream)` instead?

Target:
public TestSuites parse(File report) { try (InputStream inputStream = new FileInputStream(report)) { final Object parsedObject = xstream().fromXML(inputStream); return (TestSuites) parsedObject; } catch (IOException e) { throw new IllegalStateException("Can't read PhpUnit report : " + report.getAbsolutePath(), e); } }
Source:
public List<ExpressionTree> expressions() { START return ImmutableList.copyOf(Iterables.filter(elements, input -> input != null ? !input.is(Kind.HEREDOC_STRING_CHARACTERS) : false)); END } @vilchik-elena Why do we need to check for null elements?

Target:
public List<ExpressionTree> expressions() { return ImmutableList.copyOf(Iterables.filter(elements, input -> !input.is(Kind.HEREDOC_STRING_CHARACTERS))); }
Source:
public void visitMemberAccess(MemberAccessTree tree) { START if (tree.is(Tree.Kind.CLASS_MEMBER_ACCESS) && "self".equals(tree.object().toString()) && !isException(tree) && !isPrivate(tree.member())) { END context().newIssue(this, MESSAGE).tree(tree); } super.visitMemberAccess(tree); } @ivandalbosco IMHO it's better to move the call to `isPrivate` into `isException`

Target:
public void visitMemberAccess(MemberAccessTree tree) { if (tree.is(Tree.Kind.CLASS_MEMBER_ACCESS) && "self".equals(tree.object().toString()) && !isException(tree)) { context().newIssue(this, tree.object(), MESSAGE); } super.visitMemberAccess(tree); }
Source:
public void visitClassPropertyDeclaration(ClassPropertyDeclarationTree tree) { START if (tree.hasModifiers("private")) { END tree.declarations().forEach(varDec -> privateProperties.add(varDec.identifier().text())); } // don't enter inside class property declarations } @ivandalbosco this call we check that `tree` has 1 modifier, which is `private`. Can `private` be combined with smth else?

Target:
public void visitClassPropertyDeclaration(ClassPropertyDeclarationTree tree) { // don't enter inside class property declarations }
Source:
private RuleKey getParsingErrorRuleKey() { List<RuleKey> keys = checks.all().stream() .filter(check -> check instanceof ParsingErrorCheck) START .map(check -> checks.ruleKeyFor((ParsingErrorCheck) check)) END .collect(Collectors.toList()); return keys.isEmpty() ? null : keys.get(0); } @ivandalbosco casting to ParsingErrorCheck is useless

Target:
private RuleKey getParsingErrorRuleKey() { List<RuleKey> keys = checks.all().stream() .filter(check -> check instanceof ParsingErrorCheck) .map(checks::ruleKeyFor) .collect(Collectors.toList()); return keys.isEmpty() ? null : keys.get(0); }
Source:
public YieldExpressionTree yieldFromExpression(InternalSyntaxToken yieldToken, InternalSyntaxToken fromToken, ExpressionTree expr) { return "from".equals(fromToken.text()) ? new YieldExpressionTreeImpl(yieldToken, fromToken, expr) START : null; END } @vilchik-elena This method should not return null.

Target:
public YieldExpressionTree yieldFromExpression(InternalSyntaxToken yieldToken, InternalSyntaxToken fromToken, ExpressionTree expr) { return new YieldExpressionTreeImpl(yieldToken, fromToken, expr); }
Source:
START private boolean isOpenParenthesis(SyntaxToken token) { END return TokenUtils.isType(token, PHPPunctuator.LPARENTHESIS); } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "isOpenParenthesis" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.internal.sonarsource.com/coding_rules#rule_key=squid%3AS2325)

Target:
private static boolean isOpenParenthesis(SyntaxToken token) { return TokenUtils.isType(token, PHPPunctuator.LPARENTHESIS); }
Source:
public void visitIfStatement(IfStatementTree tree) { ExpressionTree condition = tree.condition().expression(); if (condition.is(Kind.BOOLEAN_LITERAL)) { START context().newIssue(this.KEY, MESSAGE).tree(condition); END } super.visitIfStatement(tree); } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Change this instance-reference to a static reference. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://nemo.sonarqube.org/coding_rules#rule_key=squid%3AS2209)

Target:
public void visitIfStatement(IfStatementTree tree) { ExpressionTree condition = tree.condition().expression(); if (condition.is(Kind.BOOLEAN_LITERAL)) { context().newIssue(KEY, MESSAGE).tree(condition); } super.visitIfStatement(tree); }
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } START if (!(obj instanceof BaseEntity)) { END // This entity has a different type return false; } if (getId() == null) { // This entity has not been persisted return super.equals(obj); } BaseEntity other = (BaseEntity) obj; return getId().equals(other.getId()); } @timler I think that we should use do a class comparison using `getClass()` here instead of doing an "instance of" check so that different subclasses can't be considered equal e.g. a Donor and a Donation with the same id.

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (!(obj.getClass().equals(getClass()))) { // This entity has a different type return false; } if (getId() == null) { // This entity has not been persisted return super.equals(obj); } BaseEntity other = (BaseEntity) obj; return getId().equals(other.getId()); }
Source:
public boolean isDuplicateDonorNumber(Donor donor) { String donorNumber = donor.getDonorNumber(); if (StringUtils.isBlank(donorNumber)) return false; START Donor existingDonor = donorRepository.findDonorByDonorNumber(donorNumber,false); END if (existingDonor != null && !existingDonor.getId().equals(donor.getId())) return true; return false; } shouldn't this be: donorRepository.findDonorByDonorNumber(donorNumber,true); since we're including deleted donors

Target:
public boolean isDuplicateDonorNumber(Donor donor) { String donorNumber = donor.getDonorNumber(); if (StringUtils.isBlank(donorNumber)) return false; Donor existingDonor = donorRepository.findDonorByDonorNumber(donorNumber,true); if (existingDonor != null && !existingDonor.getId().equals(donor.getId())) return true; return false; }
Source:
private static String getSettingValue( String tag, String defaultValue ) { final PluginSettings settings = PluginEnvironment.env().getPluginSettings(); START String value = settings.getTagValue( tag ).get( 0 ); END if ( value == null ) { value = defaultValue; } return value; } I think we get an IndexOutOfBoundException here. You probably want to check something lke this: ``` List<String> values = settings.getTagValue(tag); return values.isEmpty() ? defaultValue : values.get(0); ```

Target:
private static String getSettingValue( String tag, String defaultValue ) { final PluginSettings settings = PluginEnvironment.env().getPluginSettings(); List<String> values = settings.getTagValue( tag ); return values.isEmpty() ? defaultValue : values.get( 0 ); }
Source:
public void testPostNullMessage() throws Exception { WebResource resource = client().resource("/api/metrics/store"); WebResource.Builder builder = resource.type(MediaType.APPLICATION_JSON_TYPE); boolean badStatus = false; try { builder.post(Control.class, null); } catch (UniformInterfaceException e) { badStatus = true; assertEquals("Unexpected status", 400, e.getResponse().getClientResponseStatus().getStatusCode()); } START if (!badStatus){ END fail("expected 400 status"); } } If you're expecting an exception you could just invoke fail() after the call to builder.post() on line 47.

Target:
public void testPostNullMessage() throws Exception { WebResource resource = client().resource("/api/metrics/store"); WebResource.Builder builder = resource.type(MediaType.APPLICATION_JSON_TYPE); try { builder.post(Control.class, null); fail("expected 400 status"); } catch (UniformInterfaceException e) { assertEquals("Unexpected status", 400, e.getResponse().getClientResponseStatus().getStatusCode()); } }
Source:
private static EventDataConverter createConverter() { if (eventDataLoaded == null) { try { LoaderUtil.loadClass("org.slf4j.ext.EventData"); eventDataLoaded = true; } catch (final ClassNotFoundException cnfe) { eventDataLoaded = false; } } START return eventDataLoaded ? new EventDataConverter() : null; END } Instead of modifying this method, what if we update the `converter` field to be static and call this method on class initialization? That way instead of requiring work (and allocation!) every time a logger is created, it's done once when the application loads.

Target:
private static EventDataConverter createConverter() { try { LoaderUtil.loadClass("org.slf4j.ext.EventData"); return new EventDataConverter(); } catch (final ClassNotFoundException cnfe) { return null; } }
Source:
public DefaultLogBuilder(Logger logger, Level level) { this.logger = logger; this.level = level; this.inUse = false; this.threadId = Thread.currentThread().getId(); START this.inUse = true; END } `inUse` is set twice in this constructor

Target:
public DefaultLogBuilder(Logger logger, Level level) { this.logger = logger; this.level = level; this.threadId = Thread.currentThread().getId(); this.inUse = true; }
Source:
START public void testJdkVersionDetection() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { END assertEquals(1, Constants.getMajorVersion("1.1.2")); assertEquals(8, Constants.getMajorVersion("1.8.2")); assertEquals(9, Constants.getMajorVersion("9.1.1")); assertEquals(11, Constants.getMajorVersion("11.1.1")); } nit: No need to declare these exception types now that we're calling `getMajorVersion` directly.

Target:
public void testJdkVersionDetection() { assertEquals(1, Constants.getMajorVersion("1.1.2")); assertEquals(8, Constants.getMajorVersion("1.8.2")); assertEquals(9, Constants.getMajorVersion("9.1.1")); assertEquals(11, Constants.getMajorVersion("11.1.1")); }
Source:
JedisPool createPool(String host, int port, SslConfiguration sslConfiguration) { if (sslConfiguration != null) { return new JedisPool( poolConfiguration, START URI.create(host + ":" + String.valueOf(port)), END sslConfiguration.getSslSocketFactory(), sslConfiguration.getSslContext().getSupportedSSLParameters(), null ); } else { return new JedisPool(poolConfiguration, host, port, false); } } What is the purpose of explicitly stringifying `port `?

Target:
JedisPool createPool(String host, int port, SslConfiguration sslConfiguration) { if (sslConfiguration != null) { return new JedisPool( poolConfiguration, URI.create(host + ":" + port), sslConfiguration.getSslSocketFactory(), sslConfiguration.getSslContext().getSupportedSSLParameters(), null ); } else { return new JedisPool(poolConfiguration, host, port, false); } }
Source:
private boolean shouldFlushLogQueue(boolean endOfBatch) { START return immediateFlush || endOfBatch || logQueue.size() >= queueCapacity; END } I think we always want to use the result of `BlockingQueue.offer` instead of `logQueue.size() >= queueCapacity`

Target:
private boolean shouldFlushLogQueue(boolean endOfBatch) { return immediateFlush || endOfBatch; }
Source:
void setUserCancel(boolean isUserCancel) { synchronized (this) { START this.isUserCancel = isUserCancel; END } } 这里有问题，如果设置需要加锁，那么获取就应该也有锁。然后如果是单个 boolean，完全可以考虑设计成原子变量，加锁毕竟太重了。

Target:
void setUserCancel(boolean isUserCancel) { this.isUserCancel = isUserCancel; }
Source:
public boolean isFirstData(){ START if (index == 0){ END return true; } else { return false; } } `return index == 0;`

Target:
public boolean isFirstData(){ return index == 0; }
Source:
public boolean shouldReportRequestLog(){ START if (requestType.equals(RequestTypeUpLog)){ END return false; } else { return true; } } `return !requestType.equals(RequestTypeUpLog);`

Target:
boolean shouldReportRequestLog(){ return requestType.equals(RequestTypeUpLog); }
Source:
private boolean shouldAction(long time){ START if (time < actionTime){ END return false; } else { return true; } } `return time >= actionTime;`

Target:
private boolean shouldAction(long time){ return time >= actionTime; }
Source:
public static DnsPrefetcher getDnsPrefetcher() { if (dnsPrefetcher == null) { dnsPrefetcher = new DnsPrefetcher(); synchronized (dnsPrefetcher) { if (dnsPrefetcher == null) { START dnsPrefetcher = new DnsPrefetcher(); END } } } return dnsPrefetcher; } @JemyCheung 为什么这里赋值了两次？一次是 synchronized 一次还不是？

Target:
public static DnsPrefetcher getDnsPrefetcher() { if (dnsPrefetcher == null) { synchronized (DnsPrefetcher.class) { if (dnsPrefetcher == null) { dnsPrefetcher = new DnsPrefetcher(); } } } return dnsPrefetcher; }
Source:
public List<InetAddress> getInetAddressByHost(String host) { START if (mConcurrentHashMap != null) { END return mConcurrentHashMap.get(host); } return null; } @JemyCheung 这变量不是 init 的时候初始化的吗？为什么会有 null 的可能性？

Target:
public List<InetAddress> getInetAddressByHost(String host) { return mConcurrentHashMap.get(host); }
Source:
private static String getRandomString(int length) { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); START StringBuffer sb = new StringBuffer(); END for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } 这个地方该用stringbuilder，性能更好，不需要考虑thread safe

Target:
private static String getRandomString(int length) { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); }
Source:
public void stop() { START System.gc(); END } why is this necessary?

Target:
public void stop() { }
Source:
public boolean equals(Object o) { if (this == o) { return true; } START if (o instanceof AbstractTreeNode) { END AbstractTreeNode other = (AbstractTreeNode)o; return Objects.equals(parent, other.parent) && Objects.equals(getId(), other.getId()); } return false; } I think you should re-work this code. Need to move code from if block.

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AbstractTreeNode)) { return false; } AbstractTreeNode other = (AbstractTreeNode)o; return Objects.equals(parent, other.parent) && Objects.equals(getId(), other.getId()); }
Source:
public void update(ActionEvent event) { Selection<?> select = selectionAgent.getSelection(); START Selection<Resource> selection = (Selection<Resource>)select; END if (selection.getFirstElement().getId() != null && select.getFirstElement() instanceof Resource) { event.getPresentation().setEnabled(true); } else event.getPresentation().setEnabled(false); } check first (select.getFirstElement() instanceof Resource)

Target:
public void update(ActionEvent event) { Selection<?> select = selectionAgent.getSelection(); if (select != null && select.getFirstElement() != null && select.getFirstElement() instanceof Resource) { Selection<Resource> selection = (Selection<Resource>)select; event.getPresentation().setEnabled(selection.getFirstElement().getId() != null); } else event.getPresentation().setEnabled(false); }
Source:
protected INDArray createGain(long nOut, double gainInit, INDArray gainParamView, boolean initializeParameters) { if (initializeParameters) { INDArray ret = Nd4j.valueArrayOf(new long[] {1, nOut}, gainInit); START gainParamView.assign(ret); END } return gainParamView; } Don't create this temporary ret array. Use ```gainParamView.assign(gainInit)``` instead.

Target:
protected INDArray createGain(long nOut, double gainInit, INDArray gainParamView, boolean initializeParameters) { if (initializeParameters) { gainParamView.assign(gainInit); } return gainParamView; }
Source:
public void close() throws Exception { // empty arrays have no buffer at all if (released || isEmpty()) return; if (!closeable()) START throw new ND4JIllegalStateException("Can't release this INDArray"); END data.close(); released = true; } Would be great to know why it is not closeable.

Target:
public void close() { // empty arrays have no buffer at all if (released || isEmpty()) return; if (!closeable()) throw new ND4JIllegalStateException("Can't release this INDArray"); data.close(); released = true; }
Source:
private void initOptionsIfNeeded() { //setup the status object to be used for all tensorflow calls if(status == null) { status = TF_NewStatus(); } if (options == null) { options = TF_NewSessionOptions(); if(protoBufConfigProto != null) { BytePointer bytePointer = new BytePointer(protoBufConfigProto.toByteArray()); TF_SetConfig(options,bytePointer,bytePointer.getStringBytes().length,status); if (TF_GetCode(status) != TF_OK) { START throw new RuntimeException("ERROR: Unable to set value configuration:" + TF_Message(status).getString()); END } } } } Same thing..IllegalStateException.

Target:
private void initOptionsIfNeeded() { //setup the status object to be used for all tensorflow calls if(status == null) { status = TF_NewStatus(); } if (options == null) { options = TF_NewSessionOptions(); if(protoBufConfigProto != null) { BytePointer bytePointer = new BytePointer(protoBufConfigProto.toByteArray()); TF_SetConfig(options,bytePointer,bytePointer.getStringBytes().length,status); if (TF_GetCode(status) != TF_OK) { throw new IllegalStateException("ERROR: Unable to set value configuration:" + TF_Message(status).getString()); } } } }
Source:
protected void init(long[] shape) { if (shape.length == 1) { rows = 1; START columns = (int) shape[0]; END } else if (this.shape().length == 2) { rows = (int) shape[0]; columns = (int) shape[1]; } rank = shape.length; } Let's also change those to `long` instead of casting.

Target:
protected void init(long[] shape) { if (shape.length == 1) { rows = 1; columns = shape[0]; } else if (this.shape().length == 2) { rows = shape[0]; columns = shape[1]; } rank = shape.length; }
Source:
START public Builder() { END super(new int[]{1, 1, 1}, new int[]{1, 1, 1}, new int[]{0, 0, 0}, new int[]{0, 0, 0}); } Different defaults here to the field defaults...

Target:
public Builder() { super(new int[]{2, 2, 2}, new int[]{1, 1, 1}, new int[]{0, 0, 0}, new int[]{1, 1, 1}, 3); }
Source:
public BaseLayer(NeuralNetConfiguration conf, INDArray input) { this.input = input; START this.conf = conf; END } this(conf) seems to have different behaviour: it does ```cacheMode = conf.getCacheMode();``` whereas this constructor (now) doesn't.

Target:
public BaseLayer(NeuralNetConfiguration conf, INDArray input) { this(conf); this.input = input; }
Source:
public Tokenizer create(String toTokenize) { if (toTokenize.isEmpty()) { throw new IllegalArgumentException("Unable to proceed; no sentence to tokenize"); } JapaneseTokenizer t = new JapaneseTokenizer(kuromoji, toTokenize, useBaseForm); START END if (preProcessor != null) { t.setTokenPreProcessor(preProcessor); } return t; } JapaneseTokenizer t -> Tokenizer t = new JapaneseTokenizer

Target:
public Tokenizer create(String toTokenize) { if (toTokenize.isEmpty()) { throw new IllegalArgumentException("Unable to proceed; no sentence to tokenize"); } Tokenizer t = new JapaneseTokenizer(kuromoji, toTokenize, useBaseForm); if (preProcessor != null) { t.setTokenPreProcessor(preProcessor); } return t; }
Source:
public boolean hasNextFor(int consumer) { START if (consumer >= numProducers) END throw new ND4JIllegalStateException("Non-existent consumer was requested"); return asyncIterators.get(consumer).hasNext(); } Again, being pedantic, but if we're checking, it might as well be ```consumer < 0 || consumer >= numProducers)```

Target:
public boolean hasNextFor(int consumer) { if (consumer >= numProducers || consumer < 0) throw new ND4JIllegalStateException("Non-existent consumer was requested"); return asyncIterators.get(consumer).hasNext(); }
Source:
public boolean hasNext() { if (throwable != null) throw throwable; try { if (nextElement != null && nextElement != terminator) { return true; } else if(nextElement == terminator) return false; nextElement = buffer.take(); if (nextElement == terminator) return false; return true; } catch (Exception e) { START log.error("Premature end of loop!"); END return false; } } Exception should be logged also for debugging purposes?

Target:
public boolean hasNext() { if (throwable != null) throw throwable; try { if (nextElement != null && nextElement != terminator) { return true; } else if(nextElement == terminator) return false; nextElement = buffer.take(); if (nextElement == terminator) return false; return true; } catch (Exception e) { log.error("Premature end of loop!"); throw new RuntimeException(e); } }
Source:
public void shutdown(){ buffer.clear(); if (thread != null) thread.interrupt(); try { // Shutdown() should be a synchronous operation since the iterator is reset after shutdown() is // called in AsyncLabelAwareIterator.reset(). if (thread != null) thread.join(); START } catch (InterruptedException e) { END } buffer.clear(); } This usually shouldn't happen, but should we be silently swallowing the exception here if it does?

Target:
public void shutdown(){ buffer.clear(); if (thread != null) thread.interrupt(); try { // Shutdown() should be a synchronous operation since the iterator is reset after shutdown() is // called in AsyncLabelAwareIterator.reset(). if (thread != null) thread.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } buffer.clear(); }
Source:
public Builder() { this.kernelSize = new int[] { 5, 1 }; START this.stride = new int[] { 1, 1 }; END this.padding = new int[] { 0, 0 }; } Where does the 5 come from? I feel like we should just throw an exception here.

Target:
public Builder() { this(0, 1, 0); this.kernelSize = null; }
Source:
START public static void main(String[] args) { END GatewayServer gatewayServer = new GatewayServer(new DeepLearning4jEntryPoint()); gatewayServer.start(); logger.info("DeepLearning4j Gateway server running"); } Use @Slf4j in lombok.

Target:
public static void main(String[] args) { GatewayServer gatewayServer = new GatewayServer(new DeepLearning4jEntryPoint()); gatewayServer.start(); log.info("DeepLearning4j Gateway server running"); }
Source:
public void setPreProcessor(DataSetPreProcessor preProcessor) { START throw new UnsupportedOperationException(); END } This doesn't strike me as reasonable. Just add a field for it and call set :D

Target:
public void setPreProcessor(DataSetPreProcessor preProcessor) { this.preProcessor = preProcessor; }
Source:
public INDArray params(boolean backwardOnly) { if(backwardOnly) return params(); // if(params != null) // return params; List<INDArray> params = new ArrayList<>(); for (Layer layer: getLayers()){ INDArray layerParams; if(layer instanceof BasePretrainNetwork) START layerParams = ((BasePretrainNetwork) layer).paramsBackprop(); END else layerParams = layer.params(); if(layerParams != null) params.add(layerParams); //may be null: subsampling etc layers } return Nd4j.toFlattened('f', params); } Same reason as noted about training. This is only for backwardOnly

Target:
public INDArray params(boolean backwardOnly) { if(backwardOnly) return params(); // if(params != null) // return params; List<INDArray> params = new ArrayList<>(); for (Layer layer: getLayers()){ INDArray layerParams = layer.params(); if(layerParams != null) params.add(layerParams); //may be null: subsampling etc layers } return Nd4j.toFlattened('f', params); }
Source:
START public void setPlayerState(PlayerState state) throws IllegalArgumentException { END if (!this.state.isAllowedTransistionTo(state)) { throw new IllegalArgumentException( "The player is not allowed to switch from the current state (" + this.state.name() + ") to the specified state (" + state.name() + ")"); } this.state = state; } player state setter mag niet public --> zie branch #145 (clear DB als player gewonnen is en removeCurrentPlayerFromDB als player verloren is)

Target:
void setPlayerState(PlayerState state) throws IllegalArgumentException { if (!this.state.isAllowedTransistionTo(state)) { throw new IllegalArgumentException( "The player is not allowed to switch from the current state (" + this.state.name() + ") to the specified state (" + state.name() + ")"); } this.state = state; }
Source:
public void addWall(Coordinate coordinate) { START if (!wallParts.add(coordinate)) END throw new IllegalArgumentException("There's already a wall at this coordinate"); if (playerStartingPositions.contains(coordinate)) throw new IllegalArgumentException("a startingpos cannot contain a wall"); // a wall may overwrite a square this.squares.remove(coordinate); } This one should be checked after `playerStartingPositions.contains(coordinate)`

Target:
public void addWall(Coordinate coordinate) { if (playerStartingPositions.contains(coordinate)) throw new IllegalArgumentException("a startingpos cannot contain a wall"); if (!wallParts.add(coordinate)) throw new IllegalArgumentException("There's already a wall at this coordinate"); // a wall may overwrite a square this.squares.remove(coordinate); }
Source:
START public Grid(Map<Coordinate, ASquare> grid, Map<IPlayer, Coordinate> players) { END if (grid == null || players == null) throw new IllegalArgumentException("Grid could not be created!"); this.grid = grid; this.players = players; } Package access? Want mag alleen aangeroepen worden door de Builder klasse?

Target:
Grid(Map<Coordinate, ASquare> grid, Map<IPlayer, Coordinate> players) { if (grid == null || players == null) throw new IllegalArgumentException("Grid could not be created!"); this.grid = grid; this.players = players; }
Source:
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { try { START return Timestamp.valueOf(LocalDateTime.parse(defaultStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))); END } catch (NumberFormatException e) { throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default LocalDateTime value: " + defaultStr, e); } } This caused problems in the tests for me. A better approach here (and ultimately more user friendly) would be variable length second fractions. An example of this is here: https://github.com/Bo98/ormlite-core/commit/00fed82b928ef4e2e5b6aad1d8ce54ddeccffc3b, along with adjustments to the tests to make sure they are consistently truncated (H2 supports milliseconds but the tests were comparing it to microseconds on my machine).

Target:
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { return Timestamp.valueOf((LocalDateTime) super.parseDefaultString(fieldType, defaultStr)); }
Source:
public void toSchemaOrgTest() throws IOException, URISyntaxException { FullBeanImpl bean = MockFullBean.mock(); String output = SchemaOrgUtils.toSchemaOrg(bean); Assert.assertNotNull(output); //Used for testing purposes, use the following call to update the expected output whenever the serialization is updated // writeToFile(output); InputStream stream = getClass().getResourceAsStream(FULL_BEAN_FILE); String expectedOutput = IOUtils.toString(stream, StandardCharsets.UTF_8); //we cannot string compare until the ordering of properties is implemented //still, a fast indication that the output was changed will be indicated through the length of the string START System.out.println(output); END assertEquals(expectedOutput.length(), output.length()); } Please do not use System.out Close the stream on line 49 and 67 Use spaces instead of tabs in the toSchemaOrgEdmOrganizationTest() and writeToFile(). Indentation looks very weird for me in IntelliJ

Target:
public void toSchemaOrgTest() throws IOException, URISyntaxException { FullBeanImpl bean = MockFullBean.mock(); String output = SchemaOrgUtils.toSchemaOrg(bean); Assert.assertNotNull(output); //Used for testing purposes, use the following call to update the expected output whenever the serialization is updated //writeToFile(output); try (InputStream stream = getClass().getResourceAsStream(FULL_BEAN_FILE)) { String expectedOutput = IOUtils.toString(stream, StandardCharsets.UTF_8); //we cannot string compare until the ordering of properties is implemented //still, a fast indication that the output was changed will be indicated through the length of the string assertEquals(expectedOutput.length(), output.length()); } }
Source:
public void testMult() { DoubleAD v1 = new DoubleAD(2.0, 4.0); DoubleAD v2 = new DoubleAD(3.0, 2.0); DoubleAD result = ADMath.mult(v1, v2); DoubleAD correctResult = new DoubleAD(6.0, 16.0); START testCompareValues(correctResult, result, 0.0); END } There's nothing about this class that makes it use exact floating point calculations, so I believe 0.0 is not appropriate for the allowed delta.

Target:
public void testMult() { DoubleAD v1 = new DoubleAD(2.0, 4.0); DoubleAD v2 = new DoubleAD(3.0, 2.0); DoubleAD result = ADMath.mult(v1, v2); DoubleAD correctResult = new DoubleAD(6.0, 16.0); assertEquals(correctResult, result); }
Source:
public void downloadAllNovelInfo() { START touchedForDownload = language + " Light Novels information"; END executeDownloadTask(listItems); } Ensure language is not null.

Target:
public void downloadAllNovelInfo() { if (language != null) { touchedForDownload = language + " Light Novels information"; executeDownloadTask(listItems); } }
Source:
public static boolean isFieldObjectType(String fieldName){ START if(fieldName == null){ END return false; } return OBJECTTYPE_FIELD.equalsIgnoreCase(fieldName); } No need for null check

Target:
public static boolean isFieldObjectType(String fieldName){ return OBJECTTYPE_FIELD.equalsIgnoreCase(fieldName); }
Source:
public static String createArrayFieldNameFromCountField(String countField){ START if(countField == null){ END return null; } if(!doesFieldNameMatchArrayCountPattern(countField)){ return countField; } return countField.substring(0, countField.length() - 1); } Just a single line is enough: if(doesFieldName...) then return countField.substring(...) else countField

Target:
public static String createArrayFieldNameFromCountField(String countField){ if(doesFieldNameMatchArrayCountPattern(countField)){ return countField.substring(0, countField.length() - 1); } return countField; }
Source:
public void explain(OperationContext ctx, CRUDFindRequest req) { initialize(ctx,req); ExecutionContext executionContext = new ExecutionContext(ctx,null); JsonDoc doc=new JsonDoc(executionPlan.explain(executionContext)); ArrayList<DocCtx> l=new ArrayList<>(1); l.add(new DocCtx(doc)); START ctx.setDocumentStream(new ListDocumentStream<DocCtx>(l)); END } Why not Arrays.asList(doc)?

Target:
public void explain(OperationContext ctx, CRUDFindRequest req) { initialize(ctx,req); ExecutionContext executionContext = new ExecutionContext(ctx,null); JsonDoc doc=new JsonDoc(executionPlan.explain(executionContext)); ctx.setDocumentStream(new ListDocumentStream<DocCtx>(Arrays.asList(new DocCtx(doc)))); }
Source:
protected EntityMetadata retrieveMetadata(Path injectionPath, String entityName, String entityVersion) { EntityMetadata emd = metadataMap.get(entityName); if (emd != null) { String defaultVersion = emd.getEntityInfo().getDefaultVersion(); if (!isValidReference(entityVersion, requestVersion, defaultVersion)) { throw Error.get(CrudConstants.ERR_METADATA_APPEARS_TWICE, entityName + ":" + entityVersion + " and " + requestVersion); } } START return metadataMap.get(entityName); END } return emd;

Target:
protected EntityMetadata retrieveMetadata(Path injectionPath, String entityName, String entityVersion) { return metadataMap.get(entityName); }
Source:
private static Set<String> asSet(String... x) { HashSet<String> set=new HashSet<>(); for(String a:x) START set.add(a); END return set; } My personal preference is to use brackets even for one line loops and condition. Not a blocker to merging.

Target:
private static Set<String> asSet(String... x) { return new HashSet<String>(Arrays.asList(x)); }
Source:
public Integer getTo() { if (to == null) { return null; } else START return this.to; END } return to; is enough.

Target:
public Integer getTo() { return this.to; }
Source:
public static void assertNoErrors(Response response) throws MultipleFailureException{ List<Throwable> errors = new ArrayList<Throwable>(); for(Error error : response.getErrors()){ START Exception e = new Exception(error.getMessage(), error); END e.printStackTrace(); errors.add(e); } if(!errors.isEmpty()){ throw new MultipleFailureException(errors); } } Error extends RuntimeException, this is unnecessary overhead.

Target:
public static void assertNoErrors(Response response) throws MultipleFailureException{ List<Throwable> errors = new ArrayList<Throwable>(response.getErrors()); if(!errors.isEmpty()){ throw new MultipleFailureException(errors); } }
Source:
START public static int getBrightness( Color color ) { if ( color == null ) { return BRIGHTNESS_THRESHOLD + 1; } final int r = color.getRed(); final int g = color.getGreen(); final int b = color.getBlue(); int brightness = ( r > g ) ? r : g; END if ( b > brightness ) { brightness = b; } return brightness; } Did you write this from scratch?

Target:
public static int getBrightness( Color color ) { if ( color == null ) { return BRIGHTNESS_THRESHOLD + 1; } final int r = color.getRed(); final int g = color.getGreen(); final int b = color.getBlue(); int brightness = r > g ? r : g; if ( b > brightness ) { brightness = b; } return brightness; }
Source:
public final LogicalPageKey getLogicalPage( final int page ) { if ( isPaginationFinished() == false ) { throw new IllegalStateException(); } try { return logicalPages.get( page ); } catch ( IndexOutOfBoundsException e ) { throw e; START } END } As there's no extra handling when an IndexOutOfBoundsException is caught, both old and new code behaves the same way: any exception thrown by `logicalPages.get( page )` will always be thrown back! As so, the try-catch is dispensable and it's best to leave the code as it was.

Target:
public final LogicalPageKey getLogicalPage( final int page ) { if ( isPaginationFinished() == false ) { throw new IllegalStateException(); } return logicalPages.get( page ); }
Source:
protected RenderNode getDeepestLastChild( RenderBox lineBox ) { if ( lineBox.getLastChild() != null && lineBox.getLastChild() instanceof RenderBox ) { START return getDeepestLastChild( lineBox ); END } return lineBox.getLastChild(); } Infinite loop? You probably wanted to pass a cast version of lineBox.getlastChild instead.

Target:
protected RenderNode getDeepestLastChild( RenderBox lineBox ) { if ( lineBox.getLastChild() != null && lineBox.getLastChild() instanceof RenderBox ) { return getDeepestLastChild( (RenderBox) lineBox.getLastChild() ); } return lineBox.getLastChild(); }
Source:
START protected Boolean getAutoCorrectFontMetrics() { END return false; } unless you want to allow <null> values, use the primitive boolean instead of the java.lang.Boolean object.

Target:
protected boolean getAutoCorrectFontMetrics() { return false; }
Source:
START public void setBaudRate(int b) { END baudRate = b; } I don't see any references to this setter, can you restore this class? This class is meant to be constructed with the appropriate values on creation. Maybe a properties file could support different serial settings, such as used in: /romraider/src/main/java/com/romraider/logger/external/apsx/plugin/ApsxDataSource.java

Target:
public void setBaudRate(int b) { }
Source:
public int hashCode() { START return Objects.hash(value); END } 👍 really minor, probably it can just return `value` to avoid integer boxing with `Objects.hash` or use `Integer#hashCode`.

Target:
public int hashCode() { return value; }
Source:
public T valueForInsert(Object value) { START return implicitCast(value); END } I think the default implementation should return the value as-is unchanged. Has a lower overhead and is closer to the prior behavior before the introduction of the method. Will also be easier to reason about what is happening.

Target:
public T valueForInsert(Object value) { return (T) value; }
Source:
public StringType(StreamInput in) throws IOException { if (in.getVersion().onOrAfter(Version.V_4_2_0)) { if (in.readBoolean()) { // see writeTo START lengthLimit = Integer.MAX_VALUE; } else { lengthLimit = in.readInt(); END } } else { lengthLimit = Integer.MAX_VALUE; } } Given that we already use `readInt` /`writeInt` instead of the `vInt` variants, couldn't we just write the `MAX_VALUE` directly and avoid the boolean?

Target:
public StringType(StreamInput in) throws IOException { if (in.getVersion().onOrAfter(Version.V_4_2_0)) { lengthLimit = in.readInt(); } else { lengthLimit = Integer.MAX_VALUE; } }
Source:
public static <I, O> LazyMapList<I, O> of(List<I> list, Function<? super I, ? extends O> mapper) { START if (!(list instanceof RandomAccess)) { END throw new IllegalArgumentException( "The argument of the List type must support " + "fast (generally constant time) random access."); } return new LazyMapList<>(list, mapper); } Btw I'm not sure if this restriction is necessary. E.g. if you look at the implementation of `get` of `LinkedList` there is no "extra" slow-down caused by using `LazyMapList`

Target:
public static <I, O> LazyMapList<I, O> of(List<I> list, Function<? super I, ? extends O> mapper) { return new LazyMapList<>(list, mapper); }
Source:
protected void doMerge(Mapper mergeWith, boolean updateAllTypes) { super.doMerge(mergeWith, updateAllTypes); var mw = ((KeywordFieldMapper) mergeWith); this.ignoreAbove = ((KeywordFieldMapper) mergeWith).ignoreAbove; if (!Objects.equals(this.lengthLimit, mw.lengthLimit)) { throw new IllegalArgumentException( "mapper [" + name() + "] has different length_limit settings, current [" START + this.fieldType().lengthLimit + "], merged [" + mw.fieldType().lengthLimit + "]"); END } } ```suggestion this.ignoreAbove = mw.ignoreAbove; ```

Target:
protected void doMerge(Mapper mergeWith, boolean updateAllTypes) { super.doMerge(mergeWith, updateAllTypes); var mw = ((KeywordFieldMapper) mergeWith); this.ignoreAbove = mw.ignoreAbove; if (!Objects.equals(this.lengthLimit, mw.lengthLimit)) { throw new IllegalArgumentException( "mapper [" + name() + "] has different length_limit settings, current [" + this.lengthLimit + "], merged [" + mw.lengthLimit + "]"); } }
Source:
START public void setNextDocId(int docId) throws IOException { END this.docId = docId; } Looks like we could remove the exception annotation from the parent class?

Target:
public void setNextDocId(int docId) { this.docId = docId; }
Source:
public static DataType<?> ofNameOrNull(String typeName) { START return TYPES_BY_NAME_OR_ALIAS.getOrDefault(typeName, null); END } Could use `.get` instead of `.getOrDefault`

Target:
public static DataType<?> ofNameOrNull(String typeName) { return TYPES_BY_NAME_OR_ALIAS.get(typeName); }
Source:
public static Map<String, Object> toMap(BytesReference bytes, XContentType xContentType) { START try { END final InputStream inputStream = getUncompressedInputStream(bytes); XContentParser parser = xContentType.xContent().createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, inputStream ); return parser.map(); } catch (IOException e) { throw new UncheckedIOException(e); } } shall we maybe utilize autoclosable on input stream? ``` try (InputStream inputStream = getUncompressedInputStream(bytes)) { .. ```

Target:
public static Map<String, Object> toMap(BytesReference bytes, XContentType xContentType) { try (InputStream inputStream = getUncompressedInputStream(bytes)) { XContentParser parser = xContentType.xContent().createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, inputStream ); return parser.map(); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
private static void checkLengthIs2(int actualLength) { START assert actualLength == 2 END : "The value of a GeoPoint must be a double array with 2 items, not " + actualLength; } Isn't this a runtime check method which should validate also without assertions enabled?

Target:
private static void checkLengthIs2(int actualLength) { if (actualLength != 2) { throw new IllegalArgumentException( "The value of a GeoPoint must be a double array with 2 items, not " + actualLength); } }
Source:
public static DataType<?> getCommonType(DataType<?> firstType, DataType<?> secondType) { START TypeCompatibility compatibility = compatibility(firstType, secondType); END if (!compatibility.isCompatible()) { return null; } return compatibility.getCommonType(); } Not sure if it's worth changing, but I think for common cases the TypeCompatibility creation could be avoided (if types match, undefined case, maybe even the "by precedence" case)

Target:
public static DataType<?> getCommonType(DataType<?> firstType, DataType<?> secondType) { return compatibility(firstType, secondType); }
Source:
public List<Symbol> outputs() { START return List.copyOf(outputs); END } Why is this required? Or why not at `AnalyzedView`?

Target:
public List<Symbol> outputs() { return outputs; }
Source:
private boolean isPrimaryKey(RelationInfo relationInfo) { START return relationInfo != null && (relationInfo.primaryKey().size() > 1 || (relationInfo.primaryKey().size() == 1 && !relationInfo.primaryKey().get(0).name().equals("_id"))); END } ```suggestion return relationInfo.primaryKey().size() > 1 || (relationInfo.primaryKey().size() == 1 && !relationInfo.primaryKey().get(0).name().equals("_id")); ``` I think we don't have `null` `RelationInfo` entries.

Target:
private boolean isPrimaryKey(RelationInfo relationInfo) { return (relationInfo.primaryKey().size() > 1 || (relationInfo.primaryKey().size() == 1 && !relationInfo.primaryKey().get(0).name().equals("_id"))); }
Source:
public void test_create_table_with_check_fail_on_update() { execute("create table t (id integer primary key, qty integer constraint check_1 check (qty > 0))"); execute("insert into t(id, qty) values(0, 1)"); refresh(); execute("select id, qty from t order by id"); assertEquals(1, response.rowCount()); assertEquals(printedTable(response.rows()), "0| 1\n"); execute("update t set qty = 1 where id = 0 returning id, qty"); START assertEquals(1, response.rowCount()); END assertEquals(printedTable(response.rows()), "0| 1\n"); expectedException.expectMessage(containsString("Failed CONSTRAINT check_1 CHECK (\"qty\" > 0) and values")); execute("update t set qty = -1 where id = 0"); } ```suggestion ```

Target:
public void test_create_table_with_check_fail_on_update() { execute("create table t (id integer primary key, qty integer constraint check_1 check (qty > 0))"); execute("insert into t(id, qty) values(0, 1)"); refresh(); execute("select id, qty from t order by id"); assertEquals(printedTable(response.rows()), "0| 1\n"); execute("update t set qty = 1 where id = 0 returning id, qty"); assertEquals(printedTable(response.rows()), "0| 1\n"); expectedException.expectMessage(containsString("Failed CONSTRAINT check_1 CHECK (\"qty\" > 0) and values")); execute("update t set qty = -1 where id = 0"); }
Source:
public <U> ColumnConstraint<U> map(Function<? super T, ? extends U> mapper) { START return new CheckColumnConstraint(name, columnName, expression, expressionStr); END } ```suggestion return new CheckColumnConstraint<>(name, columnName, mapper.apply(expression), expressionStr); ``` Please take care of generic warnings. Don't ignore them

Target:
public <U> ColumnConstraint<U> map(Function<? super T, ? extends U> mapper) { return new CheckColumnConstraint<>(name, columnName, mapper.apply(expression), expressionStr); }
Source:
public void test_update_by_id_with_subquery_returning_id() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = (select 1) returning id"); assertThat(printedTable(response.rows()), is("1\n" )); START refresh(); END } ```suggestion ```

Target:
public void test_update_by_id_with_subquery_returning_id() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = (select 1) returning id"); assertThat(printedTable(response.rows()), is("1\n" )); }
Source:
public void test_update_by_id_where_no_row_is_matching() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = 99 returning id"); assertThat(response.cols()[0], is("id")); assertThat(response.rowCount(), is(0L)); START refresh(); END } ```suggestion ```

Target:
public void test_update_by_id_where_no_row_is_matching() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = 99 returning id"); assertThat(response.cols()[0], is("id")); assertThat(response.rowCount(), is(0L)); }
Source:
public long averageSizePerRowInBytes() { if (numDocs == -1) { START return numDocs; END } return sizeInBytes / numDocs; } Maybe return `-1` directly. Had a "wait what?" moment here because looking at `return numDocs` isolated I didn't get why it's okay to return that as `averageSizePerRowInBytes` value.

Target:
public long averageSizePerRowInBytes() { if (numDocs == -1) { return -1; } return sizeInBytes / numDocs; }
Source:
public ByteBuf allocate(int capacity) { accountBytes.accept(capacity); // TODO: should we hold onto the buffers and release them as well? // contract would require it, but there is no resource behind it that must be released START return Unpooled.wrappedBuffer(new byte[capacity]); END } any reasons not to use platform aware `return Unpooled.buffer(capacity)` ?

Target:
public ByteBuf allocate(int capacity) { accountBytes.accept(capacity); // We don't track the ByteBuf instance to release it later because it is not necessary for on-heap buffers. return Unpooled.buffer(capacity); }