auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>@NotNull @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { private int idx = -1; @Override public boolean hasNext() { <START> return bitSet.nextSetBit(idx + 1) != -1; <END> } @Override public Integer next() { int nextIdx = bitSet.nextSetBit(idx + 1); if (nextIdx == -1) throw new NoSuchElementException(); idx = nextIdx; return idx; } }; }</code><technical_language>I suggest optimization: store nextIdx in field calculation. easily support invariant: - idx == nextIdx - "hasNext" invoked set is empty. - idx != nextIdx - "hasNext" invoked set is empty, "next" invoked (each "next" invocation execute "nextIdx = idx = nextIdx"). do think? reduce number of array scans 1 instead of 2</technical_language>

Target:
@NotNull @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { private int idx = -1; private int nextIdx = -1; @Override public boolean hasNext() { return nextIdx == idx ? (nextIdx = bitSet.nextSetBit(idx + 1)) != -1 : nextIdx != -1; } @Override public Integer next() { if (nextIdx == idx) nextIdx = bitSet.nextSetBit(idx + 1); if (nextIdx == -1) throw new NoSuchElementException(); idx = nextIdx; return idx; } }; }
Source:
<code>public Client(Context androidContext, String apiKey, boolean enableExceptionHandler) { if(androidContext == null) { throw new NullPointerException("You must provide a non-null android Context"); } appContext = androidContext.getApplicationContext(); try { ApplicationInfo ai = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), PackageManager.GET_META_DATA); String manifestApiKey = ai.metaData.getString("com.bugsnag.android.API_KEY"); <START> if(!TextUtils.isEmpty(manifestApiKey)) { <END> apiKey = manifestApiKey; } } catch (Exception e) { } if(apiKey == null) { throw new NullPointerException("You must provide a Bugsnag API key"); } config = new Configuration(apiKey); appData = new AppData(appContext, config); deviceData = new DeviceData(appContext); AppState.init(); breadcrumbs = new Breadcrumbs(); setProjectPackages(appContext.getPackageName()); setUserId(deviceData.getUserId()); errorStore = new ErrorStore(config, appContext); if(enableExceptionHandler) { enableExceptionHandler(); } errorStore.flush(); }</code><technical_language>Oh, this work. I thinking java if (TextUtils.isEmpty(apiKey)) { try { /* load manifest */ } catch } crash if in places? prevent people stupid (like changing in future unexpected behavior)</technical_language>

Target:
public Client(Context androidContext, String apiKey, boolean enableExceptionHandler) { if(androidContext == null) { throw new NullPointerException("You must provide a non-null android Context"); } appContext = androidContext.getApplicationContext(); if (TextUtils.isEmpty(apiKey)) { try { ApplicationInfo ai = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), PackageManager.GET_META_DATA); apiKey = ai.metaData.getString("com.bugsnag.android.API_KEY"); } catch (Exception e) { } } if(apiKey == null) { throw new NullPointerException("You must provide a Bugsnag API key"); } config = new Configuration(apiKey); appData = new AppData(appContext, config); deviceData = new DeviceData(appContext); AppState.init(); breadcrumbs = new Breadcrumbs(); setProjectPackages(appContext.getPackageName()); setUserId(deviceData.getUserId()); errorStore = new ErrorStore(config, appContext); if(enableExceptionHandler) { enableExceptionHandler(); } errorStore.flush(); }
Source:
<code>private static RexNode isDistinctFromInternal( RexBuilder rexBuilder, RexNode x, RexNode y, boolean neg) { SqlOperator nullOp; SqlOperator eqOp; if (neg) { nullOp = SqlStdOperatorTable.IS_NULL; eqOp = SqlStdOperatorTable.EQUALS; } else { nullOp = SqlStdOperatorTable.IS_NOT_NULL; eqOp = SqlStdOperatorTable.NOT_EQUALS; } RexNode[] whenThenElse = { rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, x), rexBuilder.makeCall(nullOp, y), rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, y), rexBuilder.makeCall(nullOp, x), rexBuilder.makeCall(SqlStdOperatorTable.IS_TRUE, <START> rexBuilder.makeCall(eqOp, x, y)) <END> }; return rexBuilder.makeCall( SqlStdOperatorTable.CASE, whenThenElse); }</code><technical_language>I if instead: return rexBuilder.makeCall(SqlStdOperatorTable.OR, rexBuilder.makeCall(eqOp, rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, x), rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, y)), rexBuilder.makeCall(SqlStdOperatorTable.IS_TRUE, rexBuilder.makeCall(eqOp, x, y))); nullOp obsolete</technical_language>

Target:
private static RexNode isDistinctFromInternal( RexBuilder rexBuilder, RexNode x, RexNode y, boolean neg) { if (neg) { return rexBuilder.makeCall(SqlStdOperatorTable.OR, rexBuilder.makeCall(SqlStdOperatorTable.AND, rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, x), rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, y)), rexBuilder.makeCall(SqlStdOperatorTable.IS_TRUE, rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, x, y))); } else { return rexBuilder.makeCall(SqlStdOperatorTable.AND, rexBuilder.makeCall(SqlStdOperatorTable.OR, rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, x), rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, y)), rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_TRUE, rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, x, y))); } }
Source:
<code>public PushPartitionIntoTableSourceScanRule() { super(operand(Filter.class, operand(LogicalTableScan.class, none())), <START> "PushPartitionTableSourceScanRule"); <END> }</code><technical_language>"PushPartitionTableSourceScanRule" -> "PushPartitionIntoTableSourceScanRule"</technical_language>

Target:
public PushPartitionIntoTableSourceScanRule() { super(operand(Filter.class, operand(LogicalTableScan.class, none())), "PushPartitionIntoTableSourceScanRule"); }
Source:
<code>protected Sku determineSku(Product product, Long skuId, Map<String, String> attributeValues, ActivityMessages messages) throws InventoryUnavailableException { Sku sku = null; if (!useSku) { sku = findMatchingSku(product, attributeValues, messages); } if (sku == null && skuId != null) { sku = catalogService.findSkuById(skuId); } if (sku == null && product != null) { if (cannotSellDefaultSku(product)) { <START> throw new InventoryUnavailableException("Sku is not Available"); <END> } else { sku = product.getDefaultSku(); } } return sku; }</code><technical_language>Yeah change this. RequiredAttributeNotProvidedException is needs thrown here. send valid product option values</technical_language>

Target:
protected Sku determineSku(Product product, Long skuId, Map<String, String> attributeValues, ActivityMessages messages) { Sku sku = null; if (!useSku) { sku = findMatchingSku(product, attributeValues, messages); } if (sku == null && skuId != null) { sku = catalogService.findSkuById(skuId); } if (sku == null && product != null) { if (cannotSellDefaultSku(product)) { throw new SkuNotAvailableException("Sku is not Available"); } else { sku = product.getDefaultSku(); } } return sku; }
Source:
<code>public void create(final String identifier, final ServerSideConfiguration config) throws EntityAlreadyExistsException, ClusterTierManagerCreationException, EntityBusyException, TimeoutException { Hold existingMaintenance = maintenanceHolds.get(identifier); Hold localMaintenance = null; if (existingMaintenance == null) { localMaintenance = createAccessLockFor(identifier).tryWriteLock(); } if (existingMaintenance == null && localMaintenance == null) { throw new EntityBusyException("Unable to create cluster tier manager for id " + identifier + ": another client owns the maintenance lease"); } boolean finished = false; try { EntityRef<ClusterTierManagerClientEntity, ClusterTierManagerConfiguration, Void> ref = getEntityRef(identifier); try { while (true) { ref.create(new ClusterTierManagerConfiguration(identifier, config)); try { ClusterTierManagerClientEntity entity = ref.fetchEntity(null); <START> try { <END> finished = true; return; } finally { if (finished) { entity.close(); } else { silentlyClose(entity, identifier); } } } catch (EntityNotFoundException e) { } } } catch (EntityConfigurationException e) { throw new ClusterTierManagerCreationException("Unable to configure cluster tier manager for id " + identifier, e); } catch (EntityNotProvidedException | EntityVersionMismatchException e) { LOGGER.error("Unable to create cluster tier manager for id {}", identifier, e); throw new AssertionError(e); } } finally { if (localMaintenance != null) { if (finished) { localMaintenance.unlock(); } else { silentlyUnlock(localMaintenance, identifier); } } } }</code><technical_language>calls, wondering if some of "finished" ugliness cleaned up</technical_language>

Target:
public void create(final String identifier, final ServerSideConfiguration config) throws EntityAlreadyExistsException, ClusterTierManagerCreationException, EntityBusyException { Hold existingMaintenance = maintenanceHolds.get(identifier); try(Hold localMaintenance = (existingMaintenance == null ? createAccessLockFor(identifier).tryWriteLock() : null)) { if (localMaintenance == null && existingMaintenance == null) { throw new EntityBusyException("Unable to obtain maintenance lease for " + identifier); } EntityRef<ClusterTierManagerClientEntity, ClusterTierManagerConfiguration, Void> ref = getEntityRef(identifier); try { ref.create(new ClusterTierManagerConfiguration(identifier, config)); } catch (EntityConfigurationException e) { throw new ClusterTierManagerCreationException("Unable to configure cluster tier manager for id " + identifier, e); } catch (EntityNotProvidedException | EntityVersionMismatchException e) { LOGGER.error("Unable to create cluster tier manager for id {}", identifier, e); throw new AssertionError(e); } } }
Source:
<code>private void assertCloudVersionRevisionResponseListWithExpectedValues(List<CloudVersionRevisionResponse> cloudVersionRevisionResponseList) throws MCSException { assertNotNull(cloudVersionRevisionResponseList); assertEquals(cloudVersionRevisionResponseList.size(), RECORDS_NUMBERS * 2); int sourceVersionsCount = 0; int destinationVersionCount = 0; String sourceRevisionId = RevisionUtils.getRevisionKey(SOURCE_PROVIDER_ID, SOURCE_REVISION_NAME); String destinationRevisionId = RevisionUtils.getRevisionKey(DESTINATION_PROVIDER_ID, DESTINATION_REVISION_NAME); for (CloudVersionRevisionResponse cloudVersionRevisionResponse : cloudVersionRevisionResponseList) { if (sourceRevisionId.equals(cloudVersionRevisionResponse.getRevisionId())) sourceVersionsCount++; <START> if (destinationRevisionId.equals(cloudVersionRevisionResponse.getRevisionId())) <END> destinationVersionCount++; } assertEquals(sourceVersionsCount, 3); assertEquals(destinationVersionCount, 3); }</code><technical_language>I a crucial part of system performance if previous condition is true (revision id is sourceRevisionId) this condition for false continue command avoid this comparison</technical_language>

Target:
private void assertCloudVersionRevisionResponseListWithExpectedValues(List<CloudVersionRevisionResponse> cloudVersionRevisionResponseList) throws MCSException { assertNotNull(cloudVersionRevisionResponseList); assertEquals(cloudVersionRevisionResponseList.size(), RECORDS_NUMBERS * 2); int sourceVersionsCount = 0; int destinationVersionCount = 0; String sourceRevisionId = RevisionUtils.getRevisionKey(SOURCE_PROVIDER_ID, SOURCE_REVISION_NAME); String destinationRevisionId = RevisionUtils.getRevisionKey(DESTINATION_PROVIDER_ID, DESTINATION_REVISION_NAME); for (CloudVersionRevisionResponse cloudVersionRevisionResponse : cloudVersionRevisionResponseList) { if (sourceRevisionId.equals(cloudVersionRevisionResponse.getRevisionId())) sourceVersionsCount++; else if (destinationRevisionId.equals(cloudVersionRevisionResponse.getRevisionId())) destinationVersionCount++; } assertEquals(sourceVersionsCount, 3); assertEquals(destinationVersionCount, 3); }
Source:
<code>public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) { super.bufferReceived(connectionID, buffer); try { Command command = (Command) inWireFormat.unmarshal(buffer); if (logger.isTraceEnabled()) { traceBufferReceived(connectionID, command); } if (AuditLogger.isAnyLoggingEnabled()) { <START> AuditLogger.setRemoteAddress(getRemoteAddress()); <END> } if (openWireActor != null) { openWireActor.act(command); } else { act(command); } } catch (Exception e) { ActiveMQServerLogger.LOGGER.debug(e); sendException(e); } }</code><technical_language>this work... openWireActor.act() transfer execution a thread. lose ThreadLocal here. netty loop is reused for connections</technical_language>

Target:
public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) { super.bufferReceived(connectionID, buffer); try { Command command = (Command) inWireFormat.unmarshal(buffer); if (logger.isTraceEnabled()) { traceBufferReceived(connectionID, command); } if (openWireActor != null) { openWireActor.act(command); } else { act(command); } } catch (Exception e) { ActiveMQServerLogger.LOGGER.debug(e); sendException(e); } }
Source:
<code>public void deleteRelationFromCatalog(final RelationKey relationKey) throws CatalogException { if (isClosed) { throw new CatalogException("Catalog is closed."); } try { queue.execute(new SQLiteJob<Void>() { @Override protected Void job(final SQLiteConnection sqliteConnection) throws CatalogException, SQLiteException { sqliteConnection.exec("BEGIN TRANSACTION;"); try { deleteRelationIfExists(sqliteConnection, relationKey); sqliteConnection.exec("COMMIT TRANSACTION;"); } catch (SQLiteException e) { try { sqliteConnection.exec("ROLLBACK TRANSACTION;"); } catch (SQLiteException e2) { <START> assert true; <END> } throw e; } return null; } }).get(); } catch (InterruptedException | ExecutionException e) { throw new CatalogException(e); } }</code><technical_language>log a warning least</technical_language>

Target:
public void deleteRelationFromCatalog(final RelationKey relationKey) throws CatalogException { if (isClosed) { throw new CatalogException("Catalog is closed."); } try { queue.execute(new SQLiteJob<Void>() { @Override protected Void job(final SQLiteConnection sqliteConnection) throws CatalogException, SQLiteException { sqliteConnection.exec("BEGIN TRANSACTION;"); try { deleteRelationIfExists(sqliteConnection, relationKey); sqliteConnection.exec("COMMIT TRANSACTION;"); } catch (SQLiteException e) { try { sqliteConnection.exec("ROLLBACK TRANSACTION;"); } catch (SQLiteException e2) { LOGGER.error("exception was thrown during transaction rollback ", e2); assert true; } throw e; } return null; } }).get(); } catch (InterruptedException | ExecutionException e) { throw new CatalogException(e); } }
Source:
<code>public List<SchemaTableName> getTableNames(@Nullable String schema) { try (Connection connection = driver.connect(connectionUrl, connectionProperties)) { DatabaseMetaData metadata = connection.getMetaData(); schema = finalizeSchemaName(metadata, schema); Map<String, Map<String, String>> schemaMappedNames = new HashMap<>(); <START> ImmutableList.Builder<SchemaTableName> list = ImmutableList.builder(); <END> for (CaseSensitiveMappedSchemaTableName table : getOriginalTablesWithSchema(connection, schema)) { Map<String, String> mappedNames = schemaMappedNames.computeIfAbsent(table.getSchemaName(), s -> new HashMap<>()); mappedNames.put(table.getSchemaNameLower(), table.getTableName()); list.add(new SchemaTableName(table.getSchemaNameLower(), table.getTableNameLower())); } for (Map.Entry<String, Map<String, String>> entry : schemaMappedNames.entrySet()) { updateTableMapping(entry.getKey(), entry.getValue()); } return list.build(); } catch (SQLException e) { throw new PrestoException(JDBC_ERROR, e); } }</code><technical_language>call this tableNames, perhaps</technical_language>

Target:
public List<SchemaTableName> getTableNames(@Nullable String schema) { try (Connection connection = driver.connect(connectionUrl, connectionProperties)) { DatabaseMetaData metadata = connection.getMetaData(); schema = finalizeSchemaName(metadata, schema); Map<String, Map<String, String>> schemaMappedNames = new HashMap<>(); ImmutableList.Builder<SchemaTableName> tableNameList = ImmutableList.builder(); for (CaseSensitiveMappedSchemaTableName table : getOriginalTablesWithSchema(connection, schema)) { Map<String, String> mappedNames = schemaMappedNames.computeIfAbsent(table.getSchemaName(), s -> new HashMap<>()); mappedNames.put(table.getSchemaNameLower(), table.getTableName()); tableNameList.add(new SchemaTableName(table.getSchemaNameLower(), table.getTableNameLower())); } for (Map.Entry<String, Map<String, String>> entry : schemaMappedNames.entrySet()) { updateTableMapping(entry.getKey(), entry.getValue()); } return tableNameList.build(); } catch (SQLException e) { throw new PrestoException(JDBC_ERROR, e); } }
Source:
<code>public Attribute getAttributeValue(PerunSessionImpl sess, User user, AttributeDefinition attributeDefinition) throws InternalErrorException { Attribute attribute = new Attribute(attributeDefinition); List<String> groupNames = new ArrayList<>(); List<Map<String, Object>> names = sess.getPerunBl().getDatabaseManagerBl().getJdbcPerunTemplate().queryForList("SELECT" + " DISTINCT vos.short_name AS vo_short_name, groups.name AS group_name" + " FROM" + " members" + " JOIN vos ON vos.id = members.vo_id" + " JOIN groups_members ON groups_members.member_id = members.id" + " JOIN groups ON groups_members.group_id = groups.id" + " WHERE" + " groups_members.source_group_status = ?" + " AND members.user_id = ?", MemberGroupStatus.VALID.getCode(), user.getId()); Set<String> voNames = new HashSet<>(); for (Map<String, Object> one : names) { <START> if (!VosManager.MEMBERS_GROUP.equals(one.get("group_name"))) { <END> String voShortName = (String) one.get("vo_short_name"); voNames.add(voShortName); String groupName = (String) one.get("group_name"); groupNames.add(voShortName + ":" + groupName); } } groupNames.addAll(voNames); attribute.setValue(groupNames); return attribute; }</code><technical_language>Move this IF condition resolving storing VO name. this skipping names for vos, user is in "members" group. In previous implementation included in resulting list. voShortName:members, voShortName</technical_language>

Target:
public Attribute getAttributeValue(PerunSessionImpl sess, User user, AttributeDefinition attributeDefinition) throws InternalErrorException { Attribute attribute = new Attribute(attributeDefinition); Set<String> groupNames = new TreeSet<>(); List<Pair<String, String>> names; try { names = sess.getPerunBl().getDatabaseManagerBl().getJdbcPerunTemplate().query( "SELECT" + " DISTINCT vos.short_name AS vo_short_name, groups.name AS group_name" + " FROM" + " members" + " JOIN vos ON vos.id = members.vo_id AND members.user_id = ?" + " JOIN groups_members ON groups_members.member_id = members.id AND groups_members.source_group_status = ?" + " JOIN groups ON groups_members.group_id = groups.id" + " ORDER BY vo_short_name, group_name", ROW_MAPPER, user.getId(), MemberGroupStatus.VALID.getCode()); } catch(EmptyResultDataAccessException e) { names = new ArrayList<>(); } catch (RuntimeException e) { throw new InternalErrorException(e); } for (Pair<String, String> one : names) { String voShortName = one.getLeft(); groupNames.add(voShortName); if (!VosManager.MEMBERS_GROUP.equals(one.getRight())) { String groupName = one.getRight(); groupNames.add(voShortName + ":" + groupName); } } attribute.setValue(new ArrayList<>(groupNames)); return attribute; }
Source:
<code>public SerializationSchema<Row> createSerializationSchema(Map<String, String> properties) { final DescriptorProperties descriptorProperties = getValidatedProperties(properties); final CsvRowSerializationSchema.Builder schemaBuilder = new CsvRowSerializationSchema.Builder( createTypeInformation(descriptorProperties)); descriptorProperties.getOptionalCharacter(CsvValidator.FORMAT_FIELD_DELIMITER) .ifPresent(schemaBuilder::setFieldDelimiter); if (descriptorProperties.getOptionalBoolean(CsvValidator.FORMAT_DISABLE_QUOTE_CHARACTER).orElse(false)) { schemaBuilder.disableQuoteCharacter(); <START> } else { <END> descriptorProperties.getOptionalCharacter(CsvValidator.FORMAT_QUOTE_CHARACTER).ifPresent(schemaBuilder::setQuoteCharacter); } descriptorProperties.getOptionalString(CsvValidator.FORMAT_ARRAY_ELEMENT_DELIMITER) .ifPresent(schemaBuilder::setArrayElementDelimiter); descriptorProperties.getOptionalCharacter(CsvValidator.FORMAT_ESCAPE_CHARACTER) .ifPresent(schemaBuilder::setEscapeCharacter); descriptorProperties.getOptionalString(CsvValidator.FORMAT_NULL_LITERAL) .ifPresent(schemaBuilder::setNullLiteral); return schemaBuilder.build(); }</code><technical_language>I recommend changing legacy csv format</technical_language>

Target:
public SerializationSchema<Row> createSerializationSchema(Map<String, String> properties) { final DescriptorProperties descriptorProperties = getValidatedProperties(properties); final CsvRowSerializationSchema.Builder schemaBuilder = new CsvRowSerializationSchema.Builder( createTypeInformation(descriptorProperties)); descriptorProperties.getOptionalCharacter(CsvValidator.FORMAT_FIELD_DELIMITER) .ifPresent(schemaBuilder::setFieldDelimiter); descriptorProperties.getOptionalString(CsvValidator.FORMAT_LINE_DELIMITER) .ifPresent(schemaBuilder::setLineDelimiter); if (descriptorProperties.getOptionalBoolean(CsvValidator.FORMAT_DISABLE_QUOTE_CHARACTER).orElse(false)) { schemaBuilder.disableQuoteCharacter(); } else { descriptorProperties.getOptionalCharacter(CsvValidator.FORMAT_QUOTE_CHARACTER).ifPresent(schemaBuilder::setQuoteCharacter); } descriptorProperties.getOptionalString(CsvValidator.FORMAT_ARRAY_ELEMENT_DELIMITER) .ifPresent(schemaBuilder::setArrayElementDelimiter); descriptorProperties.getOptionalCharacter(CsvValidator.FORMAT_ESCAPE_CHARACTER) .ifPresent(schemaBuilder::setEscapeCharacter); descriptorProperties.getOptionalString(CsvValidator.FORMAT_NULL_LITERAL) .ifPresent(schemaBuilder::setNullLiteral); return schemaBuilder.build(); }
Source:
<code>protected void onFetchVms() { <START> logBuilder = new StringBuilder(String.format("Poll %s:", vdsManager.getVdsId())); <END> super.onFetchVms(); logBuilder.append(String.format("(%d VMs)", vmsCounter)); log.info(logBuilder.toString()); }</code><technical_language>vmsCounter is reset 0. changedVms.size()? If not, call logVmsCounter highlight is for logging</technical_language>

Target:
protected void onFetchVms() { logBuilder = new StringBuilder(String.format("Poll %s:", vdsManager.getVdsId())); super.onFetchVms(); logBuilder.append(String.format("(%d VMs)", changedVms.size())); log.info(logBuilder.toString()); }
Source:
<code>private static List<IResource> getReadonlyFiles(IResource[] resources) { <START> List<IResource> readOnlyFiles= new ArrayList<IResource>(); <END> for (int i= 0; i < resources.length; i++) { IResource resource= resources[i]; ResourceAttributes resourceAttributes= resource.getResourceAttributes(); if (resource.getType() == IResource.FILE && resourceAttributes != null && resourceAttributes.isReadOnly()) readOnlyFiles.add(resource); } return readOnlyFiles; }</code><technical_language>ArrayList<></technical_language>

Target:
private static List<IResource> getReadonlyFiles(IResource[] resources) { List<IResource> readOnlyFiles= new ArrayList<>(); for (IResource resource : resources) { ResourceAttributes resourceAttributes= resource.getResourceAttributes(); if (resource.getType() == IResource.FILE && resourceAttributes != null && resourceAttributes.isReadOnly()) readOnlyFiles.add(resource); } return readOnlyFiles; }
Source:
<code>default String getTaskGroupId(DatastreamTask task, Optional<Logger> logger) { Set<String> groupIds = DatastreamUtils.getMetadataGroupIDs(task.getDatastreams()); if (!groupIds.isEmpty()) { if (groupIds.size() != 1) { String errMsg = String.format("Found multiple consumer group ids for connector task: %s. Group IDs: %s. Datastreams: %s", task.getId(), groupIds, task.getDatastreams()); throw new DatastreamRuntimeException(errMsg); } <START> if (logger.isPresent()) { <END> logger.get().info("Found overridden group ID for Kafka datastream task: . Overridden group id: Datastreams: %s", task.getId(), groupIds.toArray()[0], task.getDatastreams()); } return (String) groupIds.toArray()[0]; } else { String groupId = constructGroupId(task); if (logger.isPresent()) { logger.get().info(String.format("Constructed group ID: %s for task: %s", groupId, task.getId())); } return groupId; } }</code><technical_language>nit: this reduced 1 line: logger.ifPresent(logger -> logger.info...)</technical_language>

Target:
default String getTaskGroupId(DatastreamTask task, Optional<Logger> logger) { Set<String> groupIds = DatastreamUtils.getMetadataGroupIDs(task.getDatastreams()); if (!groupIds.isEmpty()) { if (groupIds.size() != 1) { String errMsg = String.format("Found multiple consumer group ids for connector task: %s. Group IDs: %s. Datastreams: %s", task.getId(), groupIds, task.getDatastreams()); throw new DatastreamRuntimeException(errMsg); } logger.ifPresent(log -> log.info( "Found overridden group ID for Kafka datastream task: . Overridden group id: Datastreams: {}", task.getId(), groupIds.toArray()[0], task.getDatastreams())); return (String) groupIds.toArray()[0]; } else { String groupId = constructGroupId(task); logger.ifPresent(log -> log.info("Constructed group ID: for task: {}", groupId, task.getId())); return groupId; } }
Source:
<code><START> public double injectEnergy( EnumFacing directionFrom, double amount, double voltage ) <END> { TunnelCollection<PartP2PIC2Power> outs; try { outs = this.getOutputs(); } catch( GridAccessException e ) { return amount; } if( outs.isEmpty() ) { return amount; } LinkedList<PartP2PIC2Power> options = new LinkedList<>(); for( PartP2PIC2Power o : outs ) { if( o.OutputEnergyA <= 0.01 ) { options.add( o ); } } if( options.isEmpty() ) { for( PartP2PIC2Power o : outs ) { if( o.OutputEnergyB <= 0.01 ) { options.add( o ); } } } if( options.isEmpty() ) { for( PartP2PIC2Power o : outs ) { options.add( o ); } } if( options.isEmpty() ) { return amount; } PartP2PIC2Power x = Platform.pickRandom( options ); if( x != null && x.OutputEnergyA <= 0.001 ) { this.queueTunnelDrain( PowerUnits.EU, amount ); x.OutputEnergyA = amount; x.OutputVoltageA = voltage; return 0; } if( x != null && x.OutputEnergyB <= 0.001 ) { this.queueTunnelDrain( PowerUnits.EU, amount ); x.OutputEnergyB = amount; x.OutputVoltageB = voltage; return 0; } return amount; }</code><technical_language>![CRITICAL](<LINK_0> Cyclomatic Complexity of this method "injectEnergy" is 20 is greater 10 authorized. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public double injectEnergy( EnumFacing directionFrom, double amount, double voltage ) { TunnelCollection<PartP2PIC2Power> outs; try { outs = this.getOutputs(); } catch( GridAccessException e ) { return amount; } if( outs.isEmpty() ) { return amount; } LinkedList<PartP2PIC2Power> options = new LinkedList<>(); for( PartP2PIC2Power o : outs ) { if( o.bufferedEnergy1 <= 0.01 ) { options.add( o ); } } if( options.isEmpty() ) { for( PartP2PIC2Power o : outs ) { if( o.bufferedEnergy2 <= 0.01 ) { options.add( o ); } } } if( options.isEmpty() ) { for( PartP2PIC2Power o : outs ) { options.add( o ); } } if( options.isEmpty() ) { return amount; } PartP2PIC2Power x = Platform.pickRandom( options ); if( x != null && x.bufferedEnergy1 <= 0.001 ) { this.queueTunnelDrain( PowerUnits.EU, amount ); x.bufferedEnergy1 = amount; x.bufferedVoltage1 = voltage; return 0; } if( x != null && x.bufferedEnergy2 <= 0.001 ) { this.queueTunnelDrain( PowerUnits.EU, amount ); x.bufferedEnergy2 = amount; x.bufferedVoltage2 = voltage; return 0; } return amount; }
Source:
<code>public static void setup(Level level, String logLocation) { if (logLocation != null && !ConsoleAppender.SYSTEM_ERR.equals(logLocation) && !ConsoleAppender.SYSTEM_OUT.equals(logLocation)) { RollingFileAppender fa = new RollingFileAppender(); fa.setName("FileLogger"); fa.setFile(logLocation); fa.setMaxFileSize("5MB"); fa.setMaxBackupIndex(1); fa.setLayout(new PatternLayout(LOGGER_LAYOUT)); fa.setThreshold(level); fa.setAppend(true); fa.activateOptions(); Logger.getRootLogger().addAppender(fa); LOGGER.info("File Handler set"); } else { <START> ConsoleAppender consoleAppender = new ConsoleAppender(new PatternLayout(LOGGER_LAYOUT), logLocation); <END> if (logLocation != null) { consoleAppender.setTarget(logLocation); } consoleAppender.setThreshold(level); Logger.getRootLogger().addAppender(consoleAppender); } }</code><technical_language>log4j docs I logLocation _"System.out"_ _"System.err"_, if defensive enough here, unsure behavior is otherwise</technical_language>

Target:
public static void setup(Level level, String logLocation) { if (logLocation != null && !ConsoleAppender.SYSTEM_ERR.equals(logLocation) && !ConsoleAppender.SYSTEM_OUT.equals(logLocation)) { RollingFileAppender fa = new RollingFileAppender(); fa.setName("FileLogger"); fa.setFile(logLocation); fa.setMaxFileSize("5MB"); fa.setMaxBackupIndex(1); fa.setLayout(new PatternLayout(LOGGER_LAYOUT)); fa.setThreshold(level); fa.setAppend(true); fa.activateOptions(); Logger.getRootLogger().addAppender(fa); LOGGER.info("File Handler set"); } else { ConsoleAppender consoleAppender = new ConsoleAppender(new PatternLayout(LOGGER_LAYOUT)); if (logLocation != null) { consoleAppender.setTarget(logLocation); } consoleAppender.setThreshold(level); Logger.getRootLogger().addAppender(consoleAppender); } }
Source:
<code>public Iterator<T> iterator() { return new Iterator<T>() { int a = start; T prev = null; T next = null; private void peekNext() { while (next == null && a < start + size) { <START> T e = (T) data[++a - 1]; <END> if (toRemove.remove(e)) { dataAsSet.remove(e); data[--a] = data[start + --size]; } else { next = e; } } } @Override public boolean hasNext() { peekNext(); return next != null; } @Override public T next() { peekNext(); if (next == null) throw new ArrayIndexOutOfBoundsException(); prev = next; next = null; return prev; } @Override public void remove() { dataAsSet.remove(prev); data[--a] = data[start + --size]; } }; }</code><technical_language>split 2 lines increment properly do data[i++]</technical_language>

Target:
public Iterator<T> iterator() { return new Iterator<T>() { int i = start; T prev = null; T next = null; private void peekNext() { while (next == null && i < start + size) { T e = (T) data[i++]; if (!toRemove.contains(e)) { next = e; } } } @Override public boolean hasNext() { peekNext(); return next != null; } @Override public T next() { peekNext(); if (next == null) throw new ArrayIndexOutOfBoundsException(); prev = next; next = null; return prev; } @Override public void remove() { toRemove.add(prev); } }; }
Source:
<code><START> public DbUser(DbUser dbUser) { <END> id = dbUser.getId(); externalId = dbUser.getExternalId(); domain = dbUser.getDomain(); namespace = dbUser.getNamespace(); loginName = dbUser.getLoginName(); firstName = dbUser.getFirstName(); lastName = dbUser.getLastName(); department = dbUser.getDepartment(); email = dbUser.getEmail(); note = dbUser.getNote(); groupIds = new ArrayList<>(dbUser.getGroupIds()); groupNames = new ArrayList<>(dbUser.getGroupNames()); isAdmin = dbUser.isAdmin(); }</code><technical_language>prefer following: public DbUser() { this(null); } public DbUser(DirectoryUser directoryUser) { if (directoryUser == null) { loginName = ""; firstName = ""; lastName = ""; department = ""; groupNames = Collections.emptyList(); groupIds = Collections.emptyList(); note = ""; } else { externalId = directoryUser.getId(); domain = directoryUser.getDirectoryName(); namespace = directoryUser.getNamespace(); loginName = directoryUser.getPrincipal() != null ? directoryUser.getPrincipal() : directoryUser.getName(); firstName = directoryUser.getFirstName(); lastName = directoryUser.getLastName(); department = directoryUser.getDepartment(); email = directoryUser.getEmail(); note = ""; groupNames = new HashSet<>(); for (DirectoryGroup directoryGroup : directoryUser.getGroups()) { groupNames.add(directoryGroup.getName()); } }</technical_language>

Target:
public DbUser(DbUser dbUser) { if (dbUser == null) { loginName = ""; firstName = ""; lastName = ""; department = ""; groupNames = Collections.emptyList(); groupIds = Collections.emptyList(); note = ""; } else { id = dbUser.getId(); externalId = dbUser.getExternalId(); domain = dbUser.getDomain(); namespace = dbUser.getNamespace(); loginName = dbUser.getLoginName(); firstName = dbUser.getFirstName(); lastName = dbUser.getLastName(); department = dbUser.getDepartment(); email = dbUser.getEmail(); note = dbUser.getNote(); groupIds = new ArrayList<>(dbUser.getGroupIds()); groupNames = new ArrayList<>(dbUser.getGroupNames()); isAdmin = dbUser.isAdmin(); } }
Source:
<code>public int compareTo(ComparableSplit other) { try { long cmp = rawInputSplit.getLength() - other.rawInputSplit.getLength(); <START> return cmp == 0 ? (id == other.id ? 0 : id < other.id ? -1 : 1) : cmp < 0 ? 1 : -1; <END> } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } }</code><technical_language>Long.signum(cmp)</technical_language>

Target:
public int compareTo(ComparableSplit other) { try { int cmp = -Long.signum(rawInputSplit.getLength() - other.rawInputSplit.getLength()); return cmp == 0 ? Long.signum(id - other.id) : cmp; } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } }
Source:
<code>public Cluster getSingleCluster() { <START> Preconditions.checkState(getClusters().getClustersCount() != 0, <END> "There must be at least one matching cluster for this method to work"); Preconditions.checkState(getClusters().getClustersCount() == 1, "There can only be one cluster for this method to work."); return getClusters().getClusters(0); }</code><technical_language>Delete this precondition check, is need</technical_language>

Target:
public Cluster getSingleCluster() { ListClustersResponse response = getClusters(); Preconditions.checkState(response.getClustersCount() != 0, "The instance does not exist."); Preconditions.checkState(response.getClustersCount() == 1, "There can only be one cluster for this method to work."); return response.getClusters(0); }
Source:
<code>public static double getNightFactor(final double value, final World world) { if (isNight(world)) { <START> return getConfig().getDouble("Properties.Water.NightFactor") * value; <END> } else { return value; } }</code><technical_language>For ease of uniformity, this return return getNightFactor() * value;. This implies a new method, double getNightFactor(), created sole purpose is return Properties.Water.NightFactor config option instead of referencing it</technical_language>

Target:
public static double getNightFactor(final double value, final World world) { if (isNight(world)) { return value * getNightFactor(); } return value; }
Source:
<code>public void removeContainer(final String containerId, final RemoveContainerParam... params) throws DockerException, InterruptedException { try { WebTarget resource = resource().path("containers").path(containerId); for (final RemoveContainerParam param : params) { <START> resource = resource.queryParam(param.name().toLowerCase(Locale.ROOT), param.value()); <END> } request(DELETE, resource, resource.request(APPLICATION_JSON_TYPE)); } catch (DockerRequestException e) { switch (e.status()) { case 404: throw new ContainerNotFoundException(containerId, e); default: throw e; } } }</code><technical_language>I this pattern exists in class, instead of .name().toLowerCase(locale) enum .name() method returns in query parameter? explicitly name enum method enum.queryParameterName() locale bit is part throws</technical_language>

Target:
public void removeContainer(final String containerId, final RemoveContainerParam... params) throws DockerException, InterruptedException { try { WebTarget resource = resource().path("containers").path(containerId); for (final RemoveContainerParam param : params) { resource = resource.queryParam(param.name(), param.value()); } request(DELETE, resource, resource.request(APPLICATION_JSON_TYPE)); } catch (DockerRequestException e) { switch (e.status()) { case 404: throw new ContainerNotFoundException(containerId, e); default: throw e; } } }
Source:
<code>protected void runTask() { OwlTelescopeReporter telescope = OwlTelescopeReporterFactory.getInstance().getTelescopeReporter( OwlTelescopeReporters.AMAZON_UNBOX_UPDATE_TASK, Event.Type.INGEST ); telescope.startReporting(); try { AmazonUnboxProcessor<UpdateProgress> processor = processor(itemPreProcessor, telescope); ImmutableList<AmazonUnboxItem> items = feedSupplier.get(); for (AmazonUnboxItem item : items) { processor.process(item); } itemPreProcessor.finish(telescope); reportStatus("Preprocessor: " + processor.getResult().toString()); processor = processor(itemProcessor, telescope); for (AmazonUnboxItem item : items) { processor.process(item); } itemProcessor.finish(telescope); reportStatus(processor.getResult().toString()); } catch (Exception e) { telescope.reportFailedEvent(e.getMessage()); reportStatus(e.getMessage()); Throwables.propagate(e); } finally { <START> telescope.endReporting(); <END> } }</code><technical_language>I remembered, stopped .endReporting() in a finally, if wrong want task unfinished signal wrong</technical_language>

Target:
protected void runTask() { OwlTelescopeReporter telescope = OwlTelescopeReporterFactory.getInstance().getTelescopeReporter( OwlTelescopeReporters.AMAZON_UNBOX_UPDATE_TASK, Event.Type.INGEST ); telescope.startReporting(); try { AmazonUnboxProcessor<UpdateProgress> processor = processor(itemPreProcessor, telescope); ImmutableList<AmazonUnboxItem> items = feedSupplier.get(); for (AmazonUnboxItem item : items) { processor.process(item); } itemPreProcessor.finish(telescope); reportStatus("Preprocessor: " + processor.getResult().toString()); processor = processor(itemProcessor, telescope); for (AmazonUnboxItem item : items) { processor.process(item); } itemProcessor.finish(telescope); reportStatus(processor.getResult().toString()); } catch (Exception e) { telescope.reportFailedEvent("An exception has prevented this task from completing properly (" + e.getMessage() + ")"); reportStatus(e.getMessage()); Throwables.propagate(e); } telescope.endReporting(); }
Source:
<code>void configureWithCustomSetIntervalProperties() { <START> this.contextRunner.withPropertyValues("spring.elasticsearch.rest.sniffInterval=15s, " + <END> "spring.elasticsearch.rest.sniffFailureDelay=15s").run((context) -> { Assert.assertNotNull(context.getBean(Sniffer.class)); }); }</code><technical_language>15s, is a valid duration. forget complete this test maybe</technical_language>

Target:
void configureWithCustomSetIntervalProperties() { this.contextRunner.withPropertyValues( "spring.elasticsearch.rest.sniffInterval=1m, " + "spring.elasticsearch.rest.sniffFailureDelay=1m") .run((context) -> { Assert.assertNotNull(context.getBean(Sniffer.class)); assertThat(context).hasSingleBean(RestHighLevelClient.class); RestHighLevelClient restClient = context.getBean(RestHighLevelClient.class); assertThat(restClient.getLowLevelClient()).extracting("spring.elasticsearch.rest.sniffInterval") .isEqualTo(Math.toIntExact(Duration.ofMinutes(1L).toMillis())); assertThat(restClient.getLowLevelClient()).extracting("spring.elasticsearch.rest.sniffFailureDelay") .isEqualTo(Math.toIntExact(Duration.ofMinutes(1L).toMillis())); }); }
Source:
<code>public void onConfigureClusterSnapshotOptions() { GlusterClusterSnapshotConfigModel clusterSnapshotConfigModel = (GlusterClusterSnapshotConfigModel) getWindow(); if (!clusterSnapshotConfigModel.validate()) { return; <START> } <END> Guid clusterId = clusterSnapshotConfigModel.getClusters().getSelectedItem().getId(); List<GlusterVolumeSnapshotConfig> vdsParams = new ArrayList<GlusterVolumeSnapshotConfig>(); for (EntityModel<GlusterVolumeSnapshotConfig> clusterCfg : clusterSnapshotConfigModel.getClusterConfigOptions() .getItems()) { vdsParams.add(new GlusterVolumeSnapshotConfig(clusterId, null, clusterCfg.getEntity().getParamName(), clusterCfg.getEntity().getParamValue())); } Frontend.getInstance().runAction(VdcActionType.UpdateGlusterVolumeSnapshotConfig, new UpdateGlusterVolumeSnapshotConfigParameters(clusterId, null, vdsParams), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { if (result.getReturnValue() != null && result.getReturnValue().getSucceeded()) { cancel(); } if (getConfirmWindow() != null) { setConfirmWindow(null); } } }, this); }</code><technical_language>validation done in function</technical_language>

Target:
public void onConfigureClusterSnapshotOptions() { GlusterClusterSnapshotConfigModel clusterSnapshotConfigModel = (GlusterClusterSnapshotConfigModel) getWindow(); Guid clusterId = clusterSnapshotConfigModel.getClusters().getSelectedItem().getId(); List<GlusterVolumeSnapshotConfig> vdsParams = new ArrayList<GlusterVolumeSnapshotConfig>(); for (EntityModel<GlusterVolumeSnapshotConfig> clusterCfg : clusterSnapshotConfigModel.getClusterConfigOptions() .getItems()) { vdsParams.add(new GlusterVolumeSnapshotConfig(clusterId, null, clusterCfg.getEntity().getParamName(), clusterCfg.getEntity().getParamValue())); } Frontend.getInstance().runAction(VdcActionType.UpdateGlusterVolumeSnapshotConfig, new UpdateGlusterVolumeSnapshotConfigParameters(clusterId, null, vdsParams), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { if (result.getReturnValue() != null && result.getReturnValue().getSucceeded()) { cancel(); } if (getConfirmWindow() != null) { setConfirmWindow(null); } } }, this); }
Source:
<code>public XmlWorkflowItem createWorkflowItem(Context context, Request currentRequest) throws SQLException, AuthorizeException, WorkflowException { Reader reader = null; XmlWorkflowItem wi = null; try { reader = currentRequest.getHttpServletRequest().getReader(); char[] arr = new char[1024]; StringBuilder buffer = new StringBuilder(); int numCharsRead = reader.read(arr, 0, arr.length); buffer.append(arr, 0, numCharsRead); if (numCharsRead == arr.length) { throw new RuntimeException("Malformed body... too long"); } String regex = "\\/api\\/" + WorkspaceItemRest.CATEGORY + "\\/" + English.plural(WorkspaceItemRest.NAME) + "\\/"; String[] split = buffer.toString().split(regex, 2); if (split.length != 2) { throw new RuntimeException("Malformed body..." + buffer); } WorkspaceItem wsi = workspaceItemService.find(context, Integer.parseInt(split[1])); if (!workspaceItemConverter.convert(wsi).getErrors().isEmpty()) { throw new UnprocessableEntityException( "Start workflow failed due to validation error on workspaceitem"); } wi = workflowService.start(context, wsi); context.addEvent(new Event(Event.MODIFY, Constants.ITEM, wi.getItem().getID(), null, itemService.getIdentifiers(context, wi.getItem()))); } catch (IOException e) { <START> throw new RuntimeException(e.getMessage(), e); <END> } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } } return wi; }</code><technical_language>Needs a more descriptive error message</technical_language>

Target:
public XmlWorkflowItem createWorkflowItem(Context context, Request currentRequest) throws SQLException, AuthorizeException, WorkflowException { Reader reader = null; XmlWorkflowItem wi = null; try { reader = currentRequest.getHttpServletRequest().getReader(); char[] arr = new char[1024]; StringBuilder buffer = new StringBuilder(); int numCharsRead = reader.read(arr, 0, arr.length); if (numCharsRead > 0) { buffer.append(arr, 0, numCharsRead); } if (numCharsRead == arr.length) { throw new UnprocessableEntityException("Malformed body... too long"); } String regex = "\\/api\\/" + WorkspaceItemRest.CATEGORY + "\\/" + English.plural(WorkspaceItemRest.NAME) + "\\/"; String[] split = buffer.toString().split(regex, 2); if (split.length != 2) { throw new UnprocessableEntityException("Malformed body..." + buffer); } END FIXME WorkspaceItem wsi = null; try { wsi = workspaceItemService.find(context, Integer.parseInt(split[1])); } catch (NumberFormatException e) { throw new UnprocessableEntityException("The provided workspaceitem URI is not valid"); } if (wsi == null) { throw new UnprocessableEntityException("Workspace item is not found"); } if (!workspaceItemConverter.convert(wsi).getErrors().isEmpty()) { throw new UnprocessableEntityException( "Start workflow failed due to validation error on workspaceitem"); } wi = workflowService.start(context, wsi); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } } return wi; }
Source:
<code>protected void executeCommand() { VmDevice watchdogDevice = new VmDevice(); watchdogDevice.setId(new VmDeviceId(new Guid(), getParameters().getId())); watchdogDevice.setDevice(VmDeviceType.WATCHDOG.getName()); watchdogDevice.setType(VmDeviceType.WATCHDOG.getName()); watchdogDevice.setAddress(StringUtils.EMPTY); watchdogDevice.setSpecParams(getSpecParams()); getVmDeviceDao().save(watchdogDevice); setSucceeded(true); <START> setActionReturnValue(watchdogDevice); <END> }</code><technical_language>watchdog id entire watchdog</technical_language>

Target:
protected void executeCommand() { VmDevice watchdogDevice = new VmDevice(); watchdogDevice.setId(new VmDeviceId(new Guid(), getParameters().getId())); watchdogDevice.setDevice(VmDeviceType.WATCHDOG.getName()); watchdogDevice.setType(VmDeviceGeneralType.WATCHDOG); watchdogDevice.setAddress(StringUtils.EMPTY); watchdogDevice.setSpecParams(getSpecParams()); getVmDeviceDao().save(watchdogDevice); setSucceeded(true); setActionReturnValue(watchdogDevice.getId()); }