auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public void setSettings(ConfigurationSettingBoolean... settings) <END> throws AlgorithmConfigurationException { if (getNumberOfSettings() != ConfigurationRequirement.ARBITRARY_NUMBER_OF_VALUES && settings.length != getNumberOfSettings()) { throw new AlgorithmConfigurationException("The number of settings does not match the expected number!"); } this.settings = settings; }</code><technical_language>this moved ConfigurationRequirement avoid code-replication in subclasses</technical_language>

Target:
public void setSettings(ConfigurationSettingBoolean... settings) throws AlgorithmConfigurationException { checkNumberOfSettings(settings.length); this.settings = settings; }
Source:
<code>public void searchForProcesses() throws Exception { desktopPage.searchInSearchField("process"); int numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("proc"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("möhö"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be no process found",0,numberOfResults); <START> <END> }</code><technical_language>empty line much</technical_language>

Target:
public void searchForProcesses() throws Exception { desktopPage.searchInSearchField("process"); int numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("proc"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("möhö"); numberOfResults = searchResultPage.getNumberOfResults(); }
Source:
<code>private void register(VillagerCareer career) { Validate.isTrue(!careers.contains(career), "Attempted to register career that is already registered."); Validate.isTrue(career.profession == this, "Attempted to register career for the wrong profession."); career.id = careers.size(); careers.add(career); <START> TRADES.put(career, new ArrayList<List<ITradeList>>()); <END> }</code><technical_language>lists careers control is dumb. trade list is in career object</technical_language>

Target:
private void register(VillagerCareer career) { Validate.isTrue(!careers.contains(career), "Attempted to register career that is already registered."); Validate.isTrue(career.profession == this, "Attempted to register career for the wrong profession."); career.id = careers.size(); careers.add(career); }
Source:
<code>RtAssignees(final Repo repo, final Request req) { <START> repo.github(); <END> req.body(); }</code><technical_language>a bug, throw UnsupportedOperationException a method is implemented</technical_language>

Target:
RtAssignees(final Repo repo, final Request req) { throw new UnsupportedOperationException(); }
Source:
<code>protected boolean canDoAction() { parameter = getParameters(); if (parameter == null || parameter.getVolumeId() == null || parameter.getSlaveNodeIp() == null || parameter.getSlaveVolumeName() == null) { return false; } masterVolume = getGlusterVolumeDao().getById(parameter.getVolumeId()); <START> if (masterVolume.getStatus() == GlusterStatus.DOWN) { <END> return false; } return true; }</code><technical_language>Do need a null check for masterVolume ?</technical_language>

Target:
protected boolean canDoAction() { parameter = getParameters(); if (parameter == null || parameter.getVolumeId() == null || parameter.getSlaveNodeIp() == null || parameter.getSlaveVolumeName() == null) { return false; } if(masterVolume == null) { return false; } masterVolume = getGlusterVolumeDao().getById(parameter.getVolumeId()); if (masterVolume.getStatus() == GlusterStatus.DOWN) { return false; } return true; }
Source:
<code>public void compactInternally() { if (config.enableOracleEnterpriseFeatures()) { try { conns.get().executeUnregisteredQuery( "ALTER TABLE " + oracleTableNameGetter.getInternalShortTableName(conns, tableRef) + " MOVE ONLINE"); } catch (PalantirSqlException e) { log.error("Tried to clean up bloat after a sweep operation," + " but underlying Oracle database or configuration does not support this" + " (Enterprise Edition that requires this user to be able to perform DDL operations)" + " feature online. Since this can't be automated in your configuration," + " good practice would be do to occasional offline manual maintenance of rebuilding" + " IOT tables to compensate for bloat. You can contact Palantir Support if you'd" + " like more information. Underlying error was: {}", tableRef, e.getMessage()); } catch (TableMappingNotFoundException e) { throw new RuntimeException(e); } } else { try { log.warn("Tried to clean up table {}, but couldn't, because enterprise features are disabled. " + "This means that even if you are running sweep, you will need to manually clean up your " <START> + "tables, otherwise disk usage will continually increase. To free up space, run the SHRINK " <END> + "command on the underlying oracle table, {}.", tableRef, oracleTableNameGetter.getInternalShortTableName(conns, tableRef)); } catch (TableMappingNotFoundException e) { throw new RuntimeException(e); } } }</code><technical_language>SHRINK -> SHRINK SPACE</technical_language>

Target:
public void compactInternally() { String compactionFailureTemplate = "Tried to clean up bloat after a sweep operation," + " but underlying Oracle database or configuration does not support this feature online. " + " Since this can't be automated in your configuration," + " good practice would be do to occasional offline manual maintenance of rebuilding" + " IOT tables to compensate for bloat. You can contact Palantir Support if you'd" + " like more information."; if (config.enableOracleEnterpriseFeatures()) { try { conns.get().executeUnregisteredQuery( "ALTER TABLE " + oracleTableNameGetter.getInternalShortTableName(conns, tableRef) + " MOVE ONLINE"); } catch (PalantirSqlException e) { log.error(compactionFailureTemplate + " Underlying error was: {}", tableRef, "(Enterprise Edition that requires this user to be able to perform DDL operations)", e.getMessage()); } catch (TableMappingNotFoundException e) { throw new RuntimeException(e); } } else { log.warn(compactionFailureTemplate, tableRef, "(If you are running against Enterprise Edition," + " you can set enableOracleEnterpriseFeatures to true in the configuration.)"); } }
Source:
<code>public boolean addAll(final int index, final Collection<? extends T> coll) { try { return this.origin.addAll(index, coll); } catch (final IndexOutOfBoundsException ex) { <START> throw new IllegalArgumentException(this.message, ex); <END> } }</code><technical_language>@Happy-Neko IndexOutOfBoundsException custom message? This break usage of List interface for code is expecting IllegalArgumentException</technical_language>

Target:
public boolean addAll(final int index, final Collection<? extends T> coll) { try { return this.origin.addAll(index, coll); } catch (final IndexOutOfBoundsException ex) { throw this.wrapException(ex); } }
Source:
<code>public String readString() throws IOException { final int size = readInt32(); if (size > 0) { <START> if (size < getCurrentRemaining()) <END> { String value = Utf8Utils.decode(_currentSegment.getArray(), _localOffset, size, _textBuffer); _localOffset += size; return value; } else { ByteStringLongDecoderState state = new ByteStringLongDecoderState(_byteArrays, _currentIndex, _localOffset); String value = Utf8Utils.decodeLong(state, size, _textBuffer); _currentIndex = state.getCurrentIndex(); _currentSegment = _byteArrays.get(_currentIndex); _localOffset = state.getPosition(); return value; } } else if (size == 0) { return ""; } else { throw new IOException("Read negative size: " + size + ". Invalid string"); } }</code><technical_language>Similar puzzle of excluding =</technical_language>

Target:
public String readString() throws IOException { final int size = readInt32(); if (size > 0) { if (size <= getCurrentRemaining()) { String value = Utf8Utils.decode(_currentSegment.getArray(), _currentArrayOffset, size, _textBuffer); _currentArrayOffset += size; return value; } else { ByteStringLongDecoderState state = new ByteStringLongDecoderState(_byteArrays, _currentIndex, _currentArrayOffset); String value = Utf8Utils.decodeLong(state, size, _textBuffer); _currentIndex = state.getCurrentIndex(); _currentSegment = _byteArrays.get(_currentIndex); _currentArrayOffset = state.getPosition(); return value; } } else if (size == 0) { return ""; } else { throw new IOException("Read negative size: " + size + ". Invalid string"); } }
Source:
<code>private BinaryLatch enqueuePopulateIndex( WritableFulltext index, GraphDatabaseService db, Supplier<ResourceIterable<? extends Entity>> entitySupplier ) throws IOException { BinaryLatch completedLatch = new BinaryLatch(); FulltextIndexUpdate population = () -> { PartitionedIndexWriter indexWriter = index.getIndexWriter(); String[] indexedPropertyKeys = index.properties().toArray( new String[0] ); <START> try ( Transaction ignore = db.beginTx( 10, TimeUnit.HOURS ) ) <END> { ResourceIterable<? extends Entity> entities = entitySupplier.get(); for ( Entity entity : entities ) { long entityId = entity.getId(); Map<String,Object> properties = entity.getProperties( indexedPropertyKeys ); if ( !properties.isEmpty() ) { updateDocument( indexWriter, entityId, properties ); } } } return Pair.of( index, completedLatch ); }; enqueueUpdate( population ); return completedLatch; }</code><technical_language>this applier started recovery instead? this timeout _should_ fine, avoid timeouts altogether change ordering, if possible</technical_language>

Target:
private AsyncFulltextIndexOperation enqueuePopulateIndex( WritableFulltext index, GraphDatabaseService db, Supplier<ResourceIterable<? extends Entity>> entitySupplier ) throws IOException { Latch completedLatch = new Latch(); FulltextIndexUpdate population = () -> { PartitionedIndexWriter indexWriter = index.getIndexWriter(); String[] indexedPropertyKeys = index.properties().toArray( new String[0] ); ArrayList<Supplier<Document>> documents = new ArrayList<>(); try ( Transaction ignore = db.beginTx( 1, TimeUnit.DAYS ) ) { ResourceIterable<? extends Entity> entities = entitySupplier.get(); for ( Entity entity : entities ) { long entityId = entity.getId(); Map<String,Object> properties = entity.getProperties( indexedPropertyKeys ); if ( !properties.isEmpty() ) { documents.add( documentBuilder( entityId, properties ) ); } if ( documents.size() > POPULATING_BATCH_SIZE ) { indexWriter.addDocuments( documents.size(), reifyDocuments( documents ) ); documents.clear(); } } } indexWriter.addDocuments( documents.size(), reifyDocuments( documents ) ); return Pair.of( index, completedLatch ); }; enqueueUpdate( population ); return completedLatch; }
Source:
<code>private static void addSecurityStandards(NewRule rule, SecurityStandards securityStandards) { for (String s : securityStandards.OWASP) { rule.addOwaspTop10(OwaspTop10.valueOf(s)); } <START> int[] cweNumbers = Arrays.stream(securityStandards.CWE).map(cwe -> cwe.substring(4)).mapToInt(Integer::valueOf).toArray(); <END> rule.addCwe(cweNumbers); }</code><technical_language>hm... do want change API? accept full names</technical_language>

Target:
private static void addSecurityStandards(NewRule rule, SecurityStandards securityStandards) { for (String s : securityStandards.OWASP) { rule.addOwaspTop10(OwaspTop10.valueOf(s)); } rule.addCwe(securityStandards.CWE); }
Source:
<code>public void separateLoopsTest() { Dominoes dominoes = new Dominoes(); <START> Domino[] dominoesList = {new Domino(1, 2), new Domino(2, 3), new Domino(3, 1), new Domino(1, 1), new Domino(2, 2), new Domino(3, 3)}; <END> ArrayList<Domino> dominoesArray = new ArrayList<>(Arrays.asList(dominoesList)); ArrayList<Domino> chain = dominoes.formChain(dominoesArray); assertValidChain(dominoesArray, chain); }</code><technical_language>This a bit easier read if split multiple lines</technical_language>

Target:
public void separateLoopsTest() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); Domino[] dominoesArray = {new Domino(1, 2), new Domino(2, 3), new Domino(3, 1), new Domino(1, 1), new Domino(2, 2), new Domino(3, 3)}; List<Domino> dominoesList = Arrays.asList(dominoesArray); List<Domino> chain = dominoes.formChain(dominoesList); assertValidChain(dominoesList, chain); }
Source:
<code>protected boolean validateInputs() { if (!super.validateInputs()) { return false; } if (getVdsId() == null) { getQueryReturnValue().setExceptionString(EngineMessage.VDS_ID_IS_NULL.name()); getQueryReturnValue().setSucceeded(false); return false; } if (getVds() == null) { <START> getQueryReturnValue().setExceptionString(EngineMessage.VDS_ID_NOT_EXIST.name()); <END> getQueryReturnValue().setSucceeded(false); return false; } return true; }</code><technical_language>VDS_INVALID_SERVER_ID</technical_language>

Target:
protected boolean validateInputs() { if (!super.validateInputs()) { return false; } if (getVdsId() == null) { getQueryReturnValue().setExceptionString(EngineMessage.VDS_ID_IS_NULL.name()); getQueryReturnValue().setSucceeded(false); return false; } if (getVds() == null) { getQueryReturnValue().setExceptionString(EngineMessage.VDS_INVALID_SERVER_ID.name()); getQueryReturnValue().setSucceeded(false); return false; } return true; }
Source:
<code>protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { <START> while (buf.readableBytes() > 0 && Character.isDigit(buf.getByte(buf.readerIndex()))) { <END> buf.readByte(); } if (buf.readableBytes() < 11) { return null; } int version = buf.getUnsignedByte(buf.readerIndex() + 1); int offset = 1 + 1 + 3; if ((version & 0x80) != 0) { offset += 4; } int length = buf.getUnsignedShort(buf.readerIndex() + offset); offset += 2; if ((version & 0x40) != 0) { offset += 3; } length += offset; if (buf.readableBytes() >= length) { return buf.readBytes(length); } return null; }</code><technical_language>I buf.readable() here</technical_language>

Target:
protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { while (buf.readable() && Character.isDigit(buf.getByte(buf.readerIndex()))) { buf.readByte(); } if (buf.readableBytes() < 11) { return null; } int version = buf.getUnsignedByte(buf.readerIndex() + 1); int offset = 1 + 1 + 3; if ((version & 0x80) != 0) { offset += 4; } int length = buf.getUnsignedShort(buf.readerIndex() + offset); offset += 2; if ((version & 0x40) != 0) { offset += 3; } length += offset; if (buf.readableBytes() >= length) { return buf.readBytes(length); } return null; }
Source:
<code>public ODatabasePoolInternal get(String database, String username, String password, OrientDBConfig parentConfig) { checkForClose(); String key = OSecurityManager.instance().createSHA256(database + username + password); ODatabasePoolInternal pool = getByKey(key); if (pool != null) { return pool; } <START> return poolCache.computeIfAbsent(key, hash -> { <END> OrientDBConfig config = OrientDBConfig.builder() .addConfig(OGlobalConfiguration.DB_POOL_MAX, maxPoolSize) .build(); if (parentConfig != null) { config.setParent(parentConfig); } return new ODatabasePoolImpl(orientDB, database, username, password, config); }); }</code><technical_language>cool a check returned pool is closed, reduce cases return a closed pool</technical_language>

Target:
public ODatabasePoolInternal get(String database, String username, String password, OrientDBConfig parentConfig) { checkForClose(); String key = OSecurityManager.instance().createSHA256(database + username + password); ODatabasePoolInternal pool = getByKey(key); if (pool != null) { return pool; } ODatabasePoolInternal db = poolCache.get(key); if (db != null && !db.isClosed()) { return db; } OrientDBConfig config = OrientDBConfig.builder() .addConfig(OGlobalConfiguration.DB_POOL_MAX, maxPoolSize) .build(); if (parentConfig != null) { config.setParent(parentConfig); } db = new ODatabasePoolImpl(orientDB, database, username, password, config); poolCache.put(key, db); return db; }
Source:
<code>public void setupProperties() { super.setupProperties(); <START> apiMode.setPossibleValues((Object[]) MarketoComponentProperties.APIMode.values()); <END> apiMode.setValue(MarketoComponentProperties.APIMode.REST); connection.setApiMode(apiMode.getValue()); batchSize.setValue(100); dieOnError.setValue(true); }</code><technical_language>For Enum type, need set values here. set apiMode created <LINK_0></technical_language>

Target:
public void setupProperties() { super.setupProperties(); apiMode.setValue(MarketoComponentProperties.APIMode.REST); connection.setApiMode(apiMode.getValue()); batchSize.setValue(100); dieOnError.setValue(true); }
Source:
<code>public void close() throws IOException { try { if (lineIterator != null) { <START> lineIterator.close(); <END> } } catch (Throwable t) { try { if (closer != null) { closer.close(); } } catch (Exception e) { t.addSuppressed(e); } throw t; } if (closer != null) { closer.close(); } }</code><technical_language>here. Please Closer</technical_language>

Target:
public void close() throws IOException { Closer firehoseCloser = Closer.create(); if (lineIterator != null) { firehoseCloser.register(lineIterator); } firehoseCloser.register(closer); firehoseCloser.close(); }
Source:
<code>public static boolean isLogicalType(OpType type) { <START> return type == And || type == Or; <END> }</code><technical_language>'not' is missed</technical_language>

Target:
public static boolean isLogicalType(OpType type) { return type == Not || type == And || type == Or; }
Source:
<code><START> public ComparisonCondition(final ConditionType conditionType, final String fieldName, final Object comparisonValue) { <END> super(conditionType); this.fieldName = fieldName; this.comparisonValue = comparisonValue; }</code><technical_language>mentioned above, hide this construction</technical_language>

Target:
private ComparisonCondition(final ConditionType conditionType, final String fieldName, final Object comparisonValue) { super(conditionType); this.fieldName = fieldName; this.comparisonValue = comparisonValue; }
Source:
<code>public int getTransactionTimeout() throws XAException { <START> log.infof("getTransactionTimeout: returning timeout: %s", transactionTimeout); <END> return transactionTimeout; }</code><technical_language>tracef</technical_language>

Target:
public int getTransactionTimeout() throws XAException { log.tracef("getTransactionTimeout: returning timeout: %s", transactionTimeout); return transactionTimeout; }
Source:
<code>public MessageHandler cassandraSinkMessageHandler() { CassandraMessageHandler<?> cassandraMessageHandler = new CassandraMessageHandler<>(this.template, cassandraSinkProperties.getQueryType()); cassandraMessageHandler.setProducesReply(false); if (cassandraSinkProperties.getConsistencyLevel() != null || cassandraSinkProperties.getRetryPolicy() != null || cassandraSinkProperties.getTtl() > 0) { cassandraMessageHandler.setWriteOptions( new WriteOptions(cassandraSinkProperties.getConsistencyLevel(), cassandraSinkProperties.getRetryPolicy(), cassandraSinkProperties.getTtl())); } if (StringUtils.hasText(cassandraSinkProperties.getIngestQuery())) { cassandraMessageHandler.setIngestQuery(cassandraSinkProperties.getIngestQuery()); } else if (StringUtils.hasText(cassandraSinkProperties.getStatementExpression())) { <START> Expression expression = PARSER.parseExpression(cassandraSinkProperties.getStatementExpression()); <END> cassandraMessageHandler.setStatementExpression(expression); } return cassandraMessageHandler; }</code><technical_language>find compromise this Expression stuff ? least, follow FileSinkConfiguration experience</technical_language>

Target:
public MessageHandler cassandraSinkMessageHandler() { CassandraMessageHandler<?> cassandraMessageHandler = new CassandraMessageHandler<>(this.template, cassandraSinkProperties.getQueryType()); cassandraMessageHandler.setProducesReply(false); if (cassandraSinkProperties.getConsistencyLevel() != null || cassandraSinkProperties.getRetryPolicy() != null || cassandraSinkProperties.getTtl() > 0) { cassandraMessageHandler.setWriteOptions( new WriteOptions(cassandraSinkProperties.getConsistencyLevel(), cassandraSinkProperties.getRetryPolicy(), cassandraSinkProperties.getTtl())); } if (StringUtils.hasText(cassandraSinkProperties.getIngestQuery())) { cassandraMessageHandler.setIngestQuery(cassandraSinkProperties.getIngestQuery()); } else if (cassandraSinkProperties.getStatementExpression() != null) { cassandraMessageHandler.setStatementExpression(cassandraSinkProperties.getStatementExpression()); } return cassandraMessageHandler; }
Source:
<code>public RichResource getRichResourceById(PerunSession sess, int id) throws InternalErrorException, ResourceNotExistsException { try { List<RichResource> rich = temp.query("select " + resourceMappingSelectQuery + ", " + VosManagerImpl.voMappingSelectQuery + ", " + FacilitiesManagerImpl.facilityMappingSelectQuery + ", "+ resourceTagMappingSelectQuery +" from resources join vos on resources.vo_id=vos.id " + "join facilities on resources.facility_id=facilities.id left outer join tags_resources on resources.id=tags_resources.resource_id left outer join res_tags on tags_resources.tag_id=res_tags.id where resources.id=?", new RichResourceExtractor(), id); if (rich != null && !rich.isEmpty()) { if (rich.get(0) != null) { return rich.get(0); } } <START> throw new ResourceNotExistsException("Resource with ID="+id+" not exists"); <END> } catch (EmptyResultDataAccessException e) { throw new ResourceNotExistsException(e); } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }</code><technical_language>jdcb.queryForObject, catch IncorrectResultSizeDataAccessException method getActualSize determine if resource exists is some consistency error (in case size > 1)</technical_language>

Target:
public RichResource getRichResourceById(PerunSession sess, int id) throws InternalErrorException, ResourceNotExistsException { try { List<RichResource> rich = temp.query("select " + resourceMappingSelectQuery + ", " + VosManagerImpl.voMappingSelectQuery + ", " + FacilitiesManagerImpl.facilityMappingSelectQuery + ", "+ resourceTagMappingSelectQuery +" from resources join vos on resources.vo_id=vos.id " + "join facilities on resources.facility_id=facilities.id left outer join tags_resources on resources.id=tags_resources.resource_id left outer join res_tags on tags_resources.tag_id=res_tags.id where resources.id=?", RICH_RESOURCE_WITH_TAGS_EXTRACTOR, id); if (rich != null && rich.size()>1) { throw new ConsistencyErrorException("There are more than one Resources under ID="+id); } else if (rich != null && rich.isEmpty()) { throw new ResourceNotExistsException("Resource with ID="+id+" not exists"); } if (rich != null && rich.size() == 1) { if (rich.get(0) != null) { return rich.get(0); } else { throw new InternalErrorException("RichResource with ID="+id+" in null."); } } throw new InternalErrorException("Response from SQL RowExttractor is null."); } catch (EmptyResultDataAccessException e) { throw new ResourceNotExistsException(e); } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
<code>protected Composite createControlComposite(Composite composite) { final Composite controlComposite = new Composite(composite, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).align(SWT.FILL, SWT.FILL).hint(1, getTableHeightHint()) <START> .applyTo(controlComposite); <END> GridLayoutFactory.fillDefaults().numColumns(1).applyTo(controlComposite); return controlComposite; }</code><technical_language>remove this call do later</technical_language>

Target:
protected Composite createControlComposite(Composite composite) { final Composite controlComposite = new Composite(composite, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(1).applyTo(controlComposite); return controlComposite; }
Source:
<code>public void doStart() { <START> Thread thread = new Thread(() -> { <END> try { SoroushBotAbstractConsumer.this.run(); } catch (InterruptedException e) { e.printStackTrace(); } }); thread.start(); thread.setName("Soroush Receiver"); }</code><technical_language>Camel's ExecutorServiceStrategy create a single thread instead, get camel context</technical_language>

Target:
public void doStart() { run(); }
Source:
<code>private void removeMissingModuleTypes(Collection<String> moduleTypes) { Map<String, List<String>> mapMissingHandlers = null; for (Iterator<String> it = moduleTypes.iterator(); it.hasNext();) { String moduleTypeName = it.next(); Set<String> rules = null; synchronized (this) { rules = mapModuleTypeToRules.get(moduleTypeName); } if (rules != null) { for (String rUID : rules) { RuleStatus ruleStatus = getRuleStatus(rUID); <START> if (ruleStatus == null) { <END> logger.debug("Missing status for:" + rUID); } switch (ruleStatus) { case RUNNING: case IDLE: mapMissingHandlers = mapMissingHandlers != null ? mapMissingHandlers : new HashMap<String, List<String>>(20); List<String> list = mapMissingHandlers.get(rUID); if (list == null) { list = new ArrayList<String>(5); } list.add(moduleTypeName); mapMissingHandlers.put(rUID, list); break; default: break; } } } } if (mapMissingHandlers != null) { for (Entry<String, List<String>> e : mapMissingHandlers.entrySet()) { String rUID = e.getKey(); List<String> missingTypes = e.getValue(); StringBuffer sb = new StringBuffer(); sb.append("Missing handlers: "); for (String typeUID : missingTypes) { sb.append(typeUID).append(", "); } unregister(getRule0(rUID)); setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.NOT_INITIALIZED, RuleStatusDetail.HANDLER_MISSING_ERROR, sb.substring(0, sb.length() - 2))); } } for (Iterator<String> it = moduleTypes.iterator(); it.hasNext();) { String moduleTypeName = it.next(); moduleHandlerFactories.remove(moduleTypeName); } }</code><technical_language>If ruleStatus is null, call switch (ruleStatus) that. This is a grant for a NPE</technical_language>

Target:
private void removeMissingModuleTypes(Collection<String> moduleTypes) { Map<String, List<String>> mapMissingHandlers = null; for (Iterator<String> it = moduleTypes.iterator(); it.hasNext();) { String moduleTypeName = it.next(); Set<String> rules = null; synchronized (this) { rules = mapModuleTypeToRules.get(moduleTypeName); } if (rules != null) { for (String rUID : rules) { RuleStatus ruleStatus = getRuleStatus(rUID); switch (ruleStatus) { case RUNNING: case IDLE: mapMissingHandlers = mapMissingHandlers != null ? mapMissingHandlers : new HashMap<String, List<String>>(20); List<String> list = mapMissingHandlers.get(rUID); if (list == null) { list = new ArrayList<String>(5); } list.add(moduleTypeName); mapMissingHandlers.put(rUID, list); break; default: break; } } } } if (mapMissingHandlers != null) { for (Entry<String, List<String>> e : mapMissingHandlers.entrySet()) { String rUID = e.getKey(); List<String> missingTypes = e.getValue(); StringBuffer sb = new StringBuffer(); sb.append("Missing handlers: "); for (String typeUID : missingTypes) { sb.append(typeUID).append(", "); } unregister(getRule0(rUID)); setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.NOT_INITIALIZED, RuleStatusDetail.HANDLER_MISSING_ERROR, sb.substring(0, sb.length() - 2))); } } for (Iterator<String> it = moduleTypes.iterator(); it.hasNext();) { String moduleTypeName = it.next(); moduleHandlerFactories.remove(moduleTypeName); } }
Source:
<code>public void testDefaultConfiguration() { String[] values = new String[] { "zookeeper1", "Client1", "true", "zookeeper/hadoop.hadoop.com", "true", "ClientCnxnSocketNetty", "true" }; String[] properties = new String[] { ZK_SASL_CLIENT_USERNAME, LOGIN_CONTEXT_NAME_KEY, ENABLE_CLIENT_SASL_KEY, ZOOKEEPER_SERVER_REALM, DISABLE_AUTO_WATCH_RESET, ZOOKEEPER_CLIENT_CNXN_SOCKET, SECURE_CLIENT }; assertEquals(properties.length,values.length); for (int i = 0; i < properties.length; i++) { String prop = properties[i]; System.setProperty(prop, values[i]); } ZKClientConfig conf = new ZKClientConfig(); for (int i = 0; i < properties.length; i++) { String prop = properties[i]; String result = conf.getProperty(prop); assertEquals(values[i], result); } <START> for (int i = 0; i < properties.length; i++) { <END> String prop = properties[i]; System.clearProperty(prop); } conf = new ZKClientConfig(); for (int i = 0; i < properties.length; i++) { String prop = properties[i]; String result = conf.getProperty(prop); assertNull(result); } }</code><technical_language>@arshadmohammad Java7 target platform, rewrite this as: for (String prop: properties) { System.clearProperty(prop); }</technical_language>

Target:
public void testDefaultConfiguration() { Map<String, String> properties = new HashMap<>(); properties.put(ZK_SASL_CLIENT_USERNAME, "zookeeper1"); properties.put(LOGIN_CONTEXT_NAME_KEY, "Client1"); properties.put(ENABLE_CLIENT_SASL_KEY, "true"); properties.put(ZOOKEEPER_SERVER_REALM, "zookeeper/hadoop.hadoop.com"); properties.put(DISABLE_AUTO_WATCH_RESET, "true"); properties.put(ZOOKEEPER_CLIENT_CNXN_SOCKET, "ClientCnxnSocketNetty"); properties.put(SECURE_CLIENT, "true"); for (Map.Entry<String, String> e : properties.entrySet()) { System.setProperty(e.getKey(), e.getValue()); } ZKClientConfig conf = new ZKClientConfig(); for (Map.Entry<String, String> e : properties.entrySet()) { assertEquals(e.getValue(), conf.getProperty(e.getKey())); } for (Map.Entry<String, String> e : properties.entrySet()) { System.clearProperty(e.getKey()); } conf = new ZKClientConfig(); for (Map.Entry<String, String> e : properties.entrySet()) { String result = conf.getProperty(e.getKey()); assertNull(result); } }
Source:
<code>public static JSONObject readLogLines(File file, int startOffset, int lines) { JSONObject json = new JSONObject(); String content = ""; long off = 0; long endOffset = 0; int linesRead = 0; int bytesRead = 0; try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { long len = raf.length(); if (startOffset < 0 || startOffset > len) { off = len; while (lines > 0 && --off >= 0) { raf.seek(off); if (off == 0 || raf.read() == '\n') { lines--; linesRead++; } } bytesRead = (int) (len - off); byte[] buf = null; <START> if(bytesRead >= logBufLimit) { <END> buf = new byte[logBufLimit]; raf.read(buf); addExceedingMsg(buf, "UTF-8"); } else { buf = new byte[bytesRead]; raf.read(buf); } content = LessBytes.toString(buf); endOffset = len; } else if (len > 0 && startOffset < len) { off = startOffset; while (lines > 0 && off < len) { raf.seek(off++); if (raf.read() == '\n') { lines--; linesRead++; } } bytesRead = (int) (off - startOffset); byte[] buf = null; if(bytesRead >= logBufLimit) { buf = new byte[logBufLimit]; raf.seek(startOffset); raf.read(buf); addExceedingMsg(buf, "UTF-8"); } else { buf = new byte[bytesRead]; raf.seek(startOffset); raf.read(buf); } content = LessBytes.toString(buf); endOffset = off; } else if (startOffset == len) { endOffset = len; linesRead = 0; content = ""; } json.put("offset", endOffset); json.put("lines", linesRead); json.put("lastModified", file.lastModified()); json.put("out", content); } catch (Exception e) { log.warn("", e); } return json; }</code><technical_language>of 4 sections replaced a call a new method create. raf.seek() calls call method. "readFileBytesLimited(long requestedBytes)" returns a new byte[] created in method</technical_language>

Target:
public static JSONObject readLogLines(File file, int startOffset, int lines) { JSONObject json = new JSONObject(); String content = ""; long off = 0; long endOffset = 0; int linesRead = 0; int bytesRead = 0; try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { long len = raf.length(); if (startOffset < 0 || startOffset > len) { off = len; while (lines > 0 && --off >= 0) { raf.seek(off); if (off == 0 || raf.read() == '\n') { lines--; linesRead++; } } bytesRead = (int) (len - off); byte[] buf = readFileBytesLimited(raf, bytesRead); content = LessBytes.toString(buf); endOffset = len; } else if (len > 0 && startOffset < len) { off = startOffset; while (lines > 0 && off < len) { raf.seek(off++); if (raf.read() == '\n') { lines--; linesRead++; } } bytesRead = (int) (off - startOffset); raf.seek(startOffset); byte[] buf = readFileBytesLimited(raf, bytesRead); content = LessBytes.toString(buf); endOffset = off; } else if (startOffset == len) { endOffset = len; linesRead = 0; content = ""; } json.put("offset", endOffset); json.put("lines", linesRead); json.put("lastModified", file.lastModified()); json.put("out", content); } catch (Exception e) { log.warn("", e); } return json; }
Source:
<code>public Mono<ServiceBusManagementNode> getManagementNode(String entityPath) { if (isDisposed()) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format( "connectionId[%s]: Connection is disposed. Cannot get management instance for '%s'", connectionId, entityPath)))); } final ServiceBusManagementNode existing = managementNodes.get(entityPath); if (existing != null) { return Mono.just(existing); } return getReactorConnection().then( Mono.fromCallable(() -> { final ServiceBusManagementNode node = managementNodes.computeIfAbsent(entityPath, key -> { final String sessionName = entityPath + "-" + MANAGEMENT_SESSION_NAME; final String linkName = entityPath + "-" + MANAGEMENT_LINK_NAME; final String address = entityPath + "/" + MANAGEMENT_ADDRESS; logger.info("Creating management node. entityPath: [{}]. address: [{}]. linkName: [{}]", entityPath, address, linkName); <START> TokenManager cbsBasedTokenManager = new AzureTokenManagerProvider( <END> CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, fullyQualifiedNamespace, entityPath) .getTokenManager(getClaimsBasedSecurityNode(), entityPath) ; final Mono<RequestResponseChannel> requestResponseChannel = createRequestResponseChannel(sessionName, linkName, address); return new ManagementChannel(requestResponseChannel, entityPath, tokenCredential, tokenManagerProvider, messageSerializer, scheduler, cbsBasedTokenManager); }); return node; })); }</code><technical_language>time a peek operation is called, create another management channel node. This is a bit wasteful if management node recreate it</technical_language>

Target:
public Mono<ServiceBusManagementNode> getManagementNode(String entityPath) { if (isDisposed()) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format( "connectionId[%s]: Connection is disposed. Cannot get management instance for '%s'", connectionId, entityPath)))); } final ServiceBusManagementNode existing = managementNodes.get(entityPath); if (existing != null) { return Mono.just(existing); } return getReactorConnection().then( Mono.fromCallable(() -> { final ServiceBusManagementNode node = managementNodes.computeIfAbsent(entityPath, key -> { final String sessionName = entityPath + "-" + MANAGEMENT_SESSION_NAME; final String linkName = entityPath + "-" + MANAGEMENT_LINK_NAME; final String address = entityPath + "/" + MANAGEMENT_ADDRESS; logger.info("Creating management node. entityPath: [{}]. address: [{}]. linkName: [{}]", entityPath, address, linkName); TokenManager cbsBasedTokenManager = new AzureTokenManagerProvider( CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, fullyQualifiedNamespace, entityPath) .getTokenManager(getClaimsBasedSecurityNode(), entityPath); final Mono<RequestResponseChannel> requestResponseChannel = createRequestResponseChannel(sessionName, linkName, address); return new ManagementChannel(requestResponseChannel, messageSerializer, scheduler, cbsBasedTokenManager); }); return node; })); }
Source:
<code>public static Map<String, KnoxDataSource> loadDataSources() throws IOException { Map<String, KnoxDataSource> datasources = null; String home = System.getProperty("user.home"); String json = null; File dsFile = new File( home + File.separator + ".knoxshell" + File.separator + KNOXDATASOURCES_JSON); synchronized(KnoxSession.class) { <START> json = readFileToString(dsFile, "UTF8"); <END> } datasources = getMapOfDataSourcesFromJsonString(json); return datasources; }</code><technical_language>nit: sense readFileToString synchronized. avoid calling method synchronization. move synchronized block readFileToString method</technical_language>

Target:
public static Map<String, KnoxDataSource> loadDataSources() throws IOException { Map<String, KnoxDataSource> datasources = null; String home = System.getProperty("user.home"); String json = null; File dsFile = new File( home + File.separator + ".knoxshell" + File.separator + KNOXDATASOURCES_JSON); if (dsFile.exists()) { json = readFileToString(dsFile, "UTF8"); datasources = getMapOfDataSourcesFromJsonString(json); } return datasources; }
Source:
<code>private static List<String> buildColumnsNames() { ImmutableList.Builder<String> columnNamesBuilder = ImmutableList.builder(); columnNamesBuilder.add("column_name"); columnNamesBuilder.add("data_size"); columnNamesBuilder.add("distinct_values_count"); columnNamesBuilder.add("nulls_count"); columnNamesBuilder.add("row_count"); <START> return columnNamesBuilder.build(); <END> }</code><technical_language>chain this builder. return ImmutableList.<String>builder() .add(...) ... .build(); is is static of method</technical_language>

Target:
private static List<String> buildColumnsNames() { return ImmutableList.<String>builder() .add("column_name") .add("data_size") .add("distinct_values_count") .add("nulls_fraction") .add("row_count") .build(); }
Source:
<code>public void testZoneKeyIdRange() { boolean[] hasValue = new boolean[MAX_TIME_ZONE_KEY + 1]; for (TimeZoneKey timeZoneKey : TimeZoneKey.getTimeZoneKeys()) { short key = timeZoneKey.getKey(); assertTrue(key >= 0, timeZoneKey + " has a negative time zone key"); assertFalse(hasValue[key], "Another time zone has the same zone key as " + timeZoneKey); hasValue[key] = true; } for (int i = 0; i < hasValue.length; i++) { switch (i) { case 2040: continue; <START> default: <END> break; } assertTrue(hasValue[i], "There is no time zone with key " + i); } }</code><technical_language>This strange. remove it</technical_language>

Target:
public void testZoneKeyIdRange() { boolean[] hasValue = new boolean[MAX_TIME_ZONE_KEY + 1]; for (TimeZoneKey timeZoneKey : TimeZoneKey.getTimeZoneKeys()) { short key = timeZoneKey.getKey(); assertTrue(key >= 0, timeZoneKey + " has a negative time zone key"); assertFalse(hasValue[key], "Another time zone has the same zone key as " + timeZoneKey); hasValue[key] = true; } assertFalse(hasValue[2040]); hasValue[2040] = true; for (int i = 0; i < hasValue.length; i++) { assertTrue(hasValue[i], "There is no time zone with key " + i); } }
Source:
<code>public void emit(final Event event) { if(event instanceof ServiceMetricEvent) { if(event == null) { return; } } try { TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; HashMap<String, Object> result = jsonMapper.readValue(jsonMapper.writeValueAsString(event), typeRef); result.put("clusterName", config.getClusterName()); producer.send(new ProducerRecord<String, String>(config.getTopic(), jsonMapper.writeValueAsString(result)), new Callback() { @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if(exception != null) { log.warn(exception, "Exception is occured! Retry."); <START> emit(event); <END> } } }); } catch (Exception e) { log.warn(e, "Failed to generate json"); } }</code><technical_language>This retrying infinitely if lets kafka brokers down. In opinion retries in case of emitting events necessary if want retry set retires property KafkaProducer - props.put("retries", <num retires>); KafkaProducer retry throw exception if send fails retires</technical_language>

Target:
public void emit(final Event event) { if (event != null) { ImmutableMap.Builder<String, Object> resultBuilder = ImmutableMap.<String, Object>builder().putAll(event.toMap()); if (config.getClusterName() != null) { resultBuilder.put("clusterName", config.getClusterName()); } Map<String, Object> result = resultBuilder.build(); try { String resultJson = jsonMapper.writeValueAsString(result); ObjectContainer<String> objectContainer = new ObjectContainer<>(resultJson, resultJson.getBytes().length); if (event instanceof ServiceMetricEvent) { if (!metricQueue.offer(objectContainer)) { metricLost.incrementAndGet(); } } else if (event instanceof AlertEvent) { if (!alertQueue.offer(objectContainer)) { alertLost.incrementAndGet(); } } else { invalidLost.incrementAndGet(); } } catch (JsonProcessingException e) { invalidLost.incrementAndGet(); } } }
Source:
<code>private static void setParamsOfView(View view, int highlightRectangleIndex, int widthModifier, int heightModifier) { int width = 1; int height = 1; int[] coords = new int[2]; <START> coords[0] = 0; <END> coords[1] = 0; if (view != null) { width = view.getWidth() * widthModifier + (widthModifier - 1) * MODIFIER_ADDITION; height = view.getHeight() * heightModifier + (widthModifier - 1) * MODIFIER_ADDITION; view.getLocationOnScreen(coords); } highlightAreas[highlightRectangleIndex] = new Rectangle(coords[0], coords[1], width, height); }</code><technical_language>this initialization is necessary: <LINK_0> > class variable, instance variable, array component is initialized a default is created</technical_language>

Target:
private static void setParamsOfView(View view, int highlightRectangleIndex, int widthModifier, int heightModifier) { int width = 1; int height = 1; int[] coords = new int[2]; if (view != null) { width = view.getWidth() * widthModifier + (widthModifier - 1) * MODIFIER_ADDITION; height = view.getHeight() * heightModifier + (widthModifier - 1) * MODIFIER_ADDITION; view.getLocationOnScreen(coords); } highlightAreas[highlightRectangleIndex] = new Rectangle(coords[0], coords[1], width, height); }
Source:
<code>private static long getGeometryMemorySize(OGCGeometry geometry) { if (geometry == null) { return 0; } <START> else if (geometry.isEmpty()) { <END> return OGC_GEOMETRY_BASE_INSTANCE_SIZE; } else { return geometry.estimateMemorySize(); } }</code><technical_language>style: drop redundant elses: if (geometry == null) { return 0; } if (geometry.isEmpty()) { return ... } return geometry.estimateMemorySize(); add a reference ESRI issue explain special handling for empty geometries</technical_language>

Target:
private static long getGeometryMemorySize(OGCGeometry geometry) { if (geometry == null) { return 0; } if (geometry.isEmpty()) { return OGC_GEOMETRY_BASE_INSTANCE_SIZE; } return geometry.estimateMemorySize(); }
Source:
<code>void setNetworkInterface(NetworkInterface netInterface, InternetProtocolFamily family) throws IOException { InetAddress address = deriveInetAddress(netInterface, family == InternetProtocolFamily.IPv6); <START> if (address.equals(family == InternetProtocolFamily.IPv4 ? INET6_ANY : INET_ANY)) { <END> throw new IOException("NetworkInterface does not support " + family); } final NativeInetAddress nativeAddress = NativeInetAddress.newInstance(address); setInterface(intValue(), ipv6, nativeAddress.address(), nativeAddress.scopeId(), interfaceIndex(netInterface)); }</code><technical_language>is this reversed</technical_language>

Target:
void setNetworkInterface(NetworkInterface netInterface, InternetProtocolFamily family) throws IOException { InetAddress address = deriveInetAddress(netInterface, family == InternetProtocolFamily.IPv6); if (address.equals(family == InternetProtocolFamily.IPv4 ? INET_ANY : INET6_ANY)) { throw new IOException("NetworkInterface does not support " + family); } final NativeInetAddress nativeAddress = NativeInetAddress.newInstance(address); setInterface(intValue(), ipv6, nativeAddress.address(), nativeAddress.scopeId(), interfaceIndex(netInterface)); }
Source:
<code>private Predicate<String> currentOrSubpackage(final String controllerPackageName) { return new Predicate<String>() { @Override public boolean apply(String input) { <START> return controllerPackageName.contains(input); <END> } }; }</code><technical_language>write a simple test case (if there), sence startsWith</technical_language>

Target:
private Predicate<String> currentOrSubpackage(final String controllerPackageName) { return new Predicate<String>() { @Override public boolean apply(String input) { return controllerPackageName.startsWith(input); } }; }
Source:
<code><START> public static AtomicReference<Map<String, MantaErrorCode>> createErrorMap() throws MantaClientException { <END> errorMap = new AtomicReference<>(); if (errorMap.get() == null) { Map<String, MantaErrorCode> backing = new HashMap<>(nonDeprecatedList.size()); for (MantaErrorCode m : getNonDeprecatedList()) { try { backing.put(m.getCode(), m); } catch (UnsupportedOperationException e) { throw new MantaClientException("Operation Unsupported by Map ", e); } } errorMap.compareAndSet(null, Collections.unmodifiableMap(backing)); } return errorMap; }</code><technical_language>need AtomicReference instantiate in static scope eagerly</technical_language>

Target:
public static Map<String, MantaErrorCode> createErrorMap() throws MantaClientException { final Map<String, MantaErrorCode> map = new LinkedHashMap<>(values().length); for (MantaErrorCode errorCode : values()) { final MantaErrorCode replaced = map.put(errorCode.code, errorCode); if (replaced != null) { String msg = String.format("Duplicate error code specified in enum: %s", replaced.code); throw new IllegalArgumentException(msg); } } return map; }
Source:
<code>public ConfigBuilder withMaxIdleSessions( int size ) { <START> return withMaxConnectionPoolSize( size ); <END> }</code><technical_language>I suggest give a warning here, realized do a logger this moment... I feel delegate maxIdle max, this config changes meaning already. I wondering if sense ignore set this method. do of changes? MaxPoolSize -> MaxConnectionPoolSize MaxIdleConnections -> MaxIdleSessions -></technical_language>

Target:
public ConfigBuilder withMaxIdleSessions( int size ) { return this; }
Source:
<code>protected static FunctionImplementation sqlInvokedFunctionToImplementation(SqlInvokedRegularFunction function) { checkArgument(function.getLanguage().equals(SQL)); <START> return new SqlInvokedRegularSqlFunctionImplementation(function.getBody()); <END> }</code><technical_language>I this class in PR</technical_language>

Target:
protected static ScalarFunctionImplementation sqlInvokedFunctionToImplementation(SqlInvokedRegularFunction function) { checkArgument(function.getFunctionImplementationType().equals(SQL)); return new SqlInvokedScalarFunctionImplementation(function.getBody()); }
Source:
<code>public Map<String, String> getStrings(Set<String> keys) { Objects.requireNonNull(keys); Map<String, String> kvMap = new HashMap<>(keys.size()); Block<Document> block = doc -> { String key = doc.getString(ID_KEY); Object value = doc.get(VALUE_KEY); String strValue = null; if (value instanceof String) { strValue = (String) value; } else if (value instanceof Binary) { byte[] bytes = ((Binary) value).getData(); try { strValue = bytesToString(bytes); } catch (CharacterCodingException e) { } } if (strValue == null) { <START> throw new IllegalArgumentException("Value is not a String for key: " + key); <END> } kvMap.put(key, strValue); }; findByKeys(keys, block); return kvMap; }</code><technical_language>Missing values legal, throw</technical_language>

Target:
public Map<String, String> getStrings(Set<String> keys) { Objects.requireNonNull(keys); Map<String, String> map = new HashMap<>(keys.size()); Block<Document> block = doc -> { String key = doc.getString(ID_KEY); Object value = doc.get(VALUE_KEY); if (value != null) { String strValue = null; if (value instanceof String) { strValue = (String) value; } else if (value instanceof Binary) { byte[] bytes = ((Binary) value).getData(); try { strValue = bytesToString(bytes); } catch (CharacterCodingException e) { } } if (strValue == null) { throw new IllegalArgumentException("Value is not a String for key: " + key); } map.put(key, strValue); } }; findByKeys(keys, block); return map; }
Source:
<code>public void bitwise() { counter trueCount = new Counter(true); <START> counter falseCount = new Counter(false); <END> String x = "Hai"; if (trueCount.count() | falseCount.count()) { x = "kthxbai"; } assertEquals(x, __); assertEquals(trueCount.count, __); assertEquals(falseCount.count, __); }</code><technical_language>Counter class a suitable constructor initialize returnValue attribute? public Counter(boolean b) { this.returnValue = b; }</technical_language>

Target:
public void bitwise() { Counter trueCount = new Counter(true); Counter falseCount = new Counter(false); String x = "Hai"; if (trueCount.count() | falseCount.count()) { x = "kthxbai"; } assertEquals(x, __); assertEquals(trueCount.count, __); assertEquals(falseCount.count, __); }