auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object saveInstance(EntityRecord entityRecord, Long deleteValueFieldId) { EntityDto entity = getEntity(entityRecord.getEntitySchemaId()); validateCredentials(entity); validateNonEditableProperty(entity); List<FieldDto> entityFields = getEntityFields(entityRecord.getEntitySchemaId()); try { MotechDataService service = getServiceForEntity(entity); Class<?> entityClass = getEntityClass(entity); boolean newObject = entityRecord.getId() == null; Object instance; if (newObject) { instance = entityClass.newInstance(); for (FieldDto entityField : entityFields) { if (entityField.getType().isMap() && entityField.getBasic().getDefaultValue() != null) { setInstanceFieldMap(instance, entityField); } } } else { instance = service.retrieve(ID_FIELD_NAME, entityRecord.getId()); if (instance == null) { throw new ObjectNotFoundException(entity.getName(), entityRecord.getId()); } } updateFields(instance, entityRecord.getFields(), service, deleteValueFieldId, !newObject); if (newObject) { return service.create(instance); } else { return service.update(instance); } } catch (JDODataStoreException e) { <START> throw new DuplicateEntryException(entity.getName(), e); <END> } catch (Exception e) { if (entityRecord.getId() == null) { throw new ObjectCreateException(entity.getName(), e); } else { throw new ObjectUpdateException(entity.getName(), entityRecord.getId(), e); } } }</code><technical_language>want "DuplicateEntryException" thrown in case of datastore exceptions, in case of unique violations. This is place check reasons of exception</technical_language>

Target:
public Object saveInstance(EntityRecord entityRecord, Long deleteValueFieldId) { EntityDto entity = getEntity(entityRecord.getEntitySchemaId()); validateCredentials(entity); validateNonEditableProperty(entity); List<FieldDto> entityFields = getEntityFields(entityRecord.getEntitySchemaId()); try { MotechDataService service = getServiceForEntity(entity); Class<?> entityClass = getEntityClass(entity); boolean newObject = entityRecord.getId() == null; Object instance; if (newObject) { instance = entityClass.newInstance(); for (FieldDto entityField : entityFields) { if (entityField.getType().isMap() && entityField.getBasic().getDefaultValue() != null) { setInstanceFieldMap(instance, entityField); } } } else { instance = service.retrieve(ID_FIELD_NAME, entityRecord.getId()); if (instance == null) { throw new ObjectNotFoundException(entity.getName(), entityRecord.getId()); } } updateFields(instance, entityRecord.getFields(), service, deleteValueFieldId, !newObject); if (newObject) { return service.create(instance); } else { return service.update(instance); } } catch (Exception e) { if (entityRecord.getId() == null) { throw new ObjectCreateException(entity.getName(), e); } else { throw new ObjectUpdateException(entity.getName(), entityRecord.getId(), e); } } }
Source:
<code>public File resolveFile(String fileName) { File file = new File(fileName); if (cwd != null && !file.isAbsolute()) { file = new File(cwd, fileName); } <START> if (!fileSystemOptions.isClassPathResolvingEnabled()) { <END> return file; } synchronized (this) { if (!file.exists()) { File cacheFile = new File(cacheDir, fileName); if (fileSystemOptions.isFileResolverCachingEnabled() && cacheFile.exists()) { return cacheFile; } ClassLoader cl = getClassLoader(); if (NON_UNIX_FILE_SEP) { fileName = fileName.replace(FILE_SEP, "/"); } String parentFileName = file.getParent(); if (parentFileName != null) { URL directoryContents = cl.getResource(parentFileName); if (directoryContents != null) { unpackUrlResource(directoryContents, parentFileName, cl, true); } } URL url = cl.getResource(fileName); if (url != null) { return unpackUrlResource(url, fileName, cl, false); } } } return file; }</code><technical_language>add a final enableCpResolving field class instead</technical_language>

Target:
public File resolveFile(String fileName) { File file = new File(fileName); if (cwd != null && !file.isAbsolute()) { file = new File(cwd, fileName); } if (!this.enableCpResolving) { return file; } synchronized (this) { if (!file.exists()) { File cacheFile = new File(cacheDir, fileName); if (this.enableCaching && cacheFile.exists()) { return cacheFile; } ClassLoader cl = getClassLoader(); if (NON_UNIX_FILE_SEP) { fileName = fileName.replace(FILE_SEP, "/"); } String parentFileName = file.getParent(); if (parentFileName != null) { URL directoryContents = cl.getResource(parentFileName); if (directoryContents != null) { unpackUrlResource(directoryContents, parentFileName, cl, true); } } URL url = cl.getResource(fileName); if (url != null) { return unpackUrlResource(url, fileName, cl, false); } } } return file; }
Source:
<code><START> private void createLuceneIndex(JackrabbitSession session, String name, String property) throws Exception { <END> Node n = session.getRootNode().getNode(INDEX_DEFINITIONS_NAME); n = n.addNode(name); n.setPrimaryType(IndexConstants.INDEX_DEFINITIONS_NODE_TYPE); n.setProperty("compatVersion", 2); n.setProperty(TYPE_PROPERTY_NAME, "lucene"); n.setProperty(REINDEX_PROPERTY_NAME, true); n.setProperty(FulltextIndexConstants.FULL_TEXT_ENABLED, false); n.setProperty("includePropertyNames", new String[]{property}); session.save(); }</code><technical_language>here, I static</technical_language>

Target:
private static Node createLuceneIndex(JackrabbitSession session, String name, String property) throws Exception { Node n = session.getRootNode().getNode(INDEX_DEFINITIONS_NAME); n = n.addNode(name); n.setPrimaryType(IndexConstants.INDEX_DEFINITIONS_NODE_TYPE); n.setProperty("compatVersion", 2); n.setProperty(TYPE_PROPERTY_NAME, "lucene"); n.setProperty(REINDEX_PROPERTY_NAME, true); n.setProperty(FulltextIndexConstants.FULL_TEXT_ENABLED, false); n.setProperty("includePropertyNames", new String[]{property}); session.save(); return n; }
Source:
<code><START> void verifyMetadata(MessageMetadata metadata) throws Exception { <END> if (metadata.getSnapshotTimestamp() != srcGlobalSnapshot) { log.error("snapshot expected != recv snapshot {}, metadata {}", srcGlobalSnapshot, metadata.getSnapshotTimestamp(), metadata); throw new Exception("Message is out of order"); } }</code><technical_language>specific exception if possible</technical_language>

Target:
void verifyMetadata(MessageMetadata metadata) throws Exception { if (metadata.getMessageMetadataType() != MessageType.SNAPSHOT_MESSAGE || metadata.getSnapshotTimestamp() != srcGlobalSnapshot) { log.error("snapshot expected != recv snapshot {}, metadata {}", srcGlobalSnapshot, metadata.getSnapshotTimestamp(), metadata); throw new Exception("Message is out of order"); } }
Source:
<code>public RepositoryFileAttributes getAttributes(String storageId, String repositoryId, String path) <START> throws ArtifactTransportException, <END> ProviderImplementationException, NoSuchAlgorithmException { try { try { return artifactResolutionService.getAttributes(storageId, repositoryId, path); } catch (IOException e) { logger.debug("The REQUESTED path does not exist: - /" + storageId + "/" + repositoryId + "/" + path); } } catch (Exception e) { e.printStackTrace(); } return null; }</code><technical_language>Cosmetic: Please, split throws list clause separate lines</technical_language>

Target:
public RepositoryFileAttributes getAttributes(String storageId, String repositoryId, String path) throws ArtifactTransportException, ProviderImplementationException, NoSuchAlgorithmException { try { return artifactResolutionService.getAttributes(storageId, repositoryId, path); } catch (IOException e) { logger.debug("The requested path does not exist: - /" + storageId + "/" + repositoryId + "/" + path); } return null; }
Source:
<code>protected List<Action> createTransientActions() { Vector<Action> ta = new Vector<Action>(); for (JobProperty<? super P> p : Util.fixNull(properties)) ta.addAll(p.getJobActions((P)this)); for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all()) { try { ta.addAll(Util.fixNull(tpaf.createFor(this))); <START> } catch (Exception e) { <END> LOGGER.log(Level.SEVERE, "Error loading transient project action factory."); } } return ta; }</code><technical_language>Generally style guides catch RuntimeException clear is checked exception expecting, I do matters</technical_language>

Target:
protected List<Action> createTransientActions() { Vector<Action> ta = new Vector<Action>(); for (JobProperty<? super P> p : Util.fixNull(properties)) ta.addAll(p.getJobActions((P)this)); for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all()) { try { ta.addAll(Util.fixNull(tpaf.createFor(this))); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Could not load actions from " + tpaf + " for " + this, e); } } return ta; }
Source:
<code>public static void main(String[] args) { WriteDataOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(WriteDataOptions.class); Pipeline p = Pipeline.create(options); CloudBigtableTableConfiguration bigtableTableConfig = new CloudBigtableTableConfiguration.Builder() .withProjectId(options.getBigtableProjectId()) .withInstanceId(options.getBigtableInstanceId()) .withTableId(options.getBigtableTableId()) .build(); long rowSize = options.getMegabytesPerRow() * ONE_MB; final long max = (Math.round((options.getGigabytesWritten() * ONE_GB)) / rowSize); p.apply(GenerateSequence.from(0).to(max)) .apply( ParDo.of( new DoFn<Long, Mutation>() { @ProcessElement public void processElement(@Element Long rowkey, OutputReceiver<Mutation> out) { <START> int maxLength = ("" + max).length(); String paddedRowkey = String.format("%0" + maxLength + "d", rowkey); <END> String reversedRowkey = new StringBuilder(paddedRowkey).reverse().toString(); Put row = new Put(Bytes.toBytes(reversedRowkey)); byte[] b = new byte[(int) rowSize]; new Random().nextBytes(b); long timestamp = System.currentTimeMillis(); row.addColumn(Bytes.toBytes(COLUMN_FAMILY), Bytes.toBytes("C"), timestamp, b); out.output(row); } })) .apply(CloudBigtableIO.writeToTable(bigtableTableConfig)); p.run().waitUntilFinish(); }</code><technical_language>this done processElement() cached</technical_language>

Target:
public static void main(String[] args) { WriteDataOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(WriteDataOptions.class); Pipeline p = Pipeline.create(options); CloudBigtableTableConfiguration bigtableTableConfig = new CloudBigtableTableConfiguration.Builder() .withProjectId(options.getBigtableProjectId()) .withInstanceId(options.getBigtableInstanceId()) .withTableId(options.getBigtableTableId()) .build(); long rowSize = options.getMegabytesPerRow() * ONE_MB; final long max = (Math.round((options.getGigabytesWritten() * ONE_GB)) / rowSize); int maxLength = ("" + max).length(); String numberFormat = "%0" + maxLength + "d"; p.apply(GenerateSequence.from(0).to(max)) .apply( ParDo.of( new DoFn<Long, Mutation>() { @ProcessElement public void processElement(@Element Long rowkey, OutputReceiver<Mutation> out) { String paddedRowkey = String.format(numberFormat, rowkey); String reversedRowkey = new StringBuilder(paddedRowkey).reverse().toString(); Put row = new Put(Bytes.toBytes(reversedRowkey)); byte[] b = new byte[(int) rowSize]; new Random().nextBytes(b); long timestamp = System.currentTimeMillis(); row.addColumn(Bytes.toBytes(COLUMN_FAMILY), Bytes.toBytes("C"), timestamp, b); out.output(row); } })) .apply(CloudBigtableIO.writeToTable(bigtableTableConfig)); p.run().waitUntilFinish(); }
Source:
<code>private Span getSpan(Context context) { final Optional<Object> spanOptional = context.getData(PARENT_SPAN_KEY); <START> if (!spanOptional.isPresent()) { <END> logger.warning("Failed to find span in the context."); return null; } final Object value = spanOptional.get(); if (!(value instanceof Span)) { logger.warning("Could not extract span. Data in is not of type Span. Actual class: {}", PARENT_SPAN_KEY, value.getClass()); return null; } return (Span) value; }</code><technical_language>Is combine methods together, a shared helper method performing a similar operation</technical_language>

Target:
private Span getSpan(Context context) { final Object value = getOptionalObject(context, PARENT_SPAN_KEY); if (!(value instanceof Span)) { logger.warning("Could not extract span. Data in context for key is not of type Span.", PARENT_SPAN_KEY); return null; } return (Span) value; }
Source:
<code>JSONArray getPlatformPluginList() { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); JSONArray initialPluginList = null; updateSiteList: for (UpdateSite updateSite : Jenkins.getInstance().getUpdateCenter().getSiteList()) { String updateCenterJsonUrl = updateSite.getUrl(); String suggestedPluginUrl = updateCenterJsonUrl.replace("/update-center.json", "/platform-plugins.json"); try { URLConnection connection; try { connection = ProxyConfiguration.openAllowsRedirection(new URL(suggestedPluginUrl)); String initialPluginJson = IOUtils.toString(connection.getInputStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); break updateSiteList; } catch(IOException e) { <START> throw new IOException("Invalid response code from URL: " + suggestedPluginUrl); <END> } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); continue updateSiteList; } } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); } } if (initialPluginList == null) { try { ClassLoader cl = getClass().getClassLoader(); URL localPluginData = cl.getResource("jenkins/install/platform-plugins.json"); String initialPluginJson = IOUtils.toString(localPluginData.openStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } return initialPluginList; }</code><technical_language>Add Exception</technical_language>

Target:
JSONArray getPlatformPluginList() { Jenkins.get().checkPermission(Jenkins.ADMINISTER); JSONArray initialPluginList = null; updateSiteList: for (UpdateSite updateSite : Jenkins.get().getUpdateCenter().getSiteList()) { String updateCenterJsonUrl = updateSite.getUrl(); String suggestedPluginUrl = updateCenterJsonUrl.replace("/update-center.json", "/platform-plugins.json"); try { URLConnection connection; try { connection = ProxyConfiguration.openURLAllowingCrossProtocolRedirects(new URL(suggestedPluginUrl)); String initialPluginJson = IOUtils.toString(connection.getInputStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); break updateSiteList; } catch(IOException e) { throw new IOException("Invalid response code from URL: " + suggestedPluginUrl, e); } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); continue updateSiteList; } } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); } } if (initialPluginList == null) { try { ClassLoader cl = getClass().getClassLoader(); URL localPluginData = cl.getResource("jenkins/install/platform-plugins.json"); String initialPluginJson = IOUtils.toString(localPluginData.openStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } return initialPluginList; }
Source:
<code>public SMSMessage(String phoneNumber, String data) { if (phoneNumber == null) throw new NullPointerException("Phone number cannot be null."); if (data == null) throw new NullPointerException("Data cannot be null."); <START> <END> this.phoneNumber = phoneNumber; this.data = data; }</code><technical_language>I this class is instantiated SMS is received, check phone number is a valid phone number</technical_language>

Target:
public SMSMessage(String phoneNumber, String data) { if (phoneNumber == null) throw new NullPointerException("Phone number cannot be null."); if (data == null) throw new NullPointerException("Data cannot be null."); if (!Pattern.matches(PHONE_NUMBER_PATTERN, phoneNumber)) throw new IllegalArgumentException("Invalid phone number."); this.phoneNumber = phoneNumber; this.data = data; }
Source:
<code>public void testInvoicingSubscription() throws StripeException { Plan plan = Plan.create(getUniquePlanParams()); defaultCustomerParams.put("email", "test@stripe.com"); Customer customer = Customer.create(defaultCustomerParams); Map<String, Object> subscriptionParams = new HashMap<String, Object>(); subscriptionParams.put("plan", plan.getId()); subscriptionParams.put("billing", "send_invoice"); subscriptionParams.put("days_until_due", 30); subscriptionParams.put("customer", customer.getId()); Subscription sub = Subscription.create(subscriptionParams); assertEquals(sub.getPlan().getId(), plan.getId()); assertEquals(sub.getBilling(), "send_invoice"); assertEquals(sub.getDaysUntilDue(), (Integer) 30); <START> <END> Map<String, Object> updateParams = new HashMap<String, Object>(); updateParams.put("days_until_due", 10); Subscription subUpdated = sub.update(updateParams); assertEquals(subUpdated.getDaysUntilDue(), (Integer) 10); }</code><technical_language>Assertion orders reversed again</technical_language>

Target:
public void testInvoicingSubscription() throws StripeException { Plan plan = Plan.create(getUniquePlanParams()); defaultCustomerParams.put("email", "test@stripe.com"); Customer customer = Customer.create(defaultCustomerParams); Map<String, Object> subscriptionParams = new HashMap<String, Object>(); subscriptionParams.put("plan", plan.getId()); subscriptionParams.put("billing", "send_invoice"); subscriptionParams.put("days_until_due", 30); subscriptionParams.put("customer", customer.getId()); Subscription sub = Subscription.create(subscriptionParams); assertEquals(plan.getId(), sub.getPlan().getId()); assertEquals("send_invoice", sub.getBilling()); assertEquals((Integer) 30, sub.getDaysUntilDue()); Map<String, Object> updateParams = new HashMap<String, Object>(); updateParams.put("days_until_due", 10); Subscription subUpdated = sub.update(updateParams); assertEquals((Integer) 10, subUpdated.getDaysUntilDue()); }
Source:
<code>private String mapQueryPropertyToFeatureProperty( final String queryProperty, final Predicate<String> isWfsFeatureProperty) { final String featurePropertyName = Optional.ofNullable(metacardMapper.getFeatureProperty(queryProperty)).orElse(queryProperty); <START> if (isWfsFeatureProperty.test(featurePropertyName)) { <END> final FeatureAttributeDescriptor featureAttributeDescriptor = (FeatureAttributeDescriptor) featureMetacardType.getAttributeDescriptor(featurePropertyName); if (featureAttributeDescriptor.isIndexed()) { return featureAttributeDescriptor.getPropertyName(); } else { throw new IllegalArgumentException( String.format(PROPERTY_NOT_QUERYABLE, featurePropertyName)); } } LOGGER.debug( "The property '{}' could not be mapped to a feature property of feature type '{}'.", featurePropertyName, featureMetacardType.getFeatureType()); return null; }</code><technical_language>if (!isWfsFeatureProperty...) { LOGGER.debug(...); return null;} eliminate if/else nesting</technical_language>

Target:
private String mapQueryPropertyToFeatureProperty( final String queryProperty, final Predicate<String> isWfsFeatureProperty) { final String featurePropertyName = Optional.ofNullable(metacardMapper.getFeatureProperty(queryProperty)).orElse(queryProperty); if (!isWfsFeatureProperty.test(featurePropertyName)) { throw new IllegalArgumentException( String.format( "'%s' was mapped to '%s', which is not a feature property of '%s'", queryProperty, featurePropertyName, featureMetacardType.getFeatureType())); } final FeatureAttributeDescriptor featureAttributeDescriptor = (FeatureAttributeDescriptor) featureMetacardType.getAttributeDescriptor(featurePropertyName); if (!featureAttributeDescriptor.isIndexed()) { throw new IllegalArgumentException( String.format(PROPERTY_NOT_QUERYABLE, featurePropertyName)); } return featureAttributeDescriptor.getPropertyName(); }
Source:
<code>public void unregistered(SelectionKey key) { <START> logger.debug("Unregistering server"); <END> for (LogicalNode ln : subscriberGroups.values()) { ln.boot(); } eventloop.submit(new Runnable() { @Override public void run() { serverHelperExecutor.shutdown(); storageHelperExecutor.shutdown(); try { serverHelperExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS); storageHelperExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.debug("Executor Termination", ex); } logger.info("Server stopped listening at {}", getServerAddress()); latch.countDown(); latch = null; } }); }</code><technical_language>For debug, good add more information (this port listened to) buffer server. a missing call super.unregistered() (even is currently no-op, change). message "unregistered"</technical_language>

Target:
public void unregistered(SelectionKey key) { logger.debug("Unregistered {}", this); for (LogicalNode ln : subscriberGroups.values()) { ln.boot(); } super.unregistered(key); eventloop.submit(new Runnable() { @Override public void run() { serverHelperExecutor.shutdown(); storageHelperExecutor.shutdown(); try { serverHelperExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS); storageHelperExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.debug("Executor Termination", ex); } logger.info("Server stopped listening at {}", getServerAddress()); latch.countDown(); latch = null; } }); }
Source:
<code>protected boolean transitionRun(final Context context) { State state; State newState; do { state = _stateRef.get(); if (state.getType() != StateType.INIT) { if (!ParSeqGlobalConfiguration.isAllowCrossPlanSharingEnabled() && <START> _startPlanId != null && !_startPlanId.equals(context.getPlanId())) { <END> throw new IllegalStateException(this.toString() + " should not be shared across plans!!"); } return false; } newState = state.transitionRun(); } while (!_stateRef.compareAndSet(state, newState)); _startPlanId = context.getPlanId(); _traceBuilder = context.getTraceBuilder(); context.getTraceBuilder().addShallowTrace(_shallowTraceBuilder); return true; }</code><technical_language>This is bulletproof case _startPlanId == null here. State is CASed atomically _startPlanId belong State class. ensured _startPlanId != null</technical_language>

Target:
protected boolean transitionRun(final Context context) throws CrossPlanTaskSharingException { State state; State newState; do { state = _stateRef.get(); if (state.getType() != StateType.INIT) { if (!ParSeqGlobalConfiguration.allowCrossPlanTaskSharing() && state.getStartPlanId() != null && !state.getStartPlanId().equals(context.getPlanId())) { throw new CrossPlanTaskSharingException(this.toString() + " should not be shared across two plans!"); } return false; } newState = state.transitionRun(context.getPlanId()); } while (!_stateRef.compareAndSet(state, newState)); _traceBuilder = context.getTraceBuilder(); context.getTraceBuilder().addShallowTrace(_shallowTraceBuilder); return true; }
Source:
<code>private boolean updateIsUsingScsiReservationRequested(LunDisk lunDisk) { <START> return getVmDeviceForVm().isUsingScsiReservation() != lunDisk.isUsingScsiReservation(); <END> }</code><technical_language>if lunDisk.isUsingScsiReservation() is null a NPE</technical_language>

Target:
private boolean updateIsUsingScsiReservationRequested(LunDisk lunDisk) { return getVmDeviceForVm().isUsingScsiReservation() != Boolean.TRUE.equals(lunDisk.isUsingScsiReservation()); }
Source:
<code>public Query createReplacementQuery(EntityResolver resolver) { Object root; if (persistentType != null) { root = persistentType; } else if (dataMapName != null) { DataMap map = resolver.getDataMap(dataMapName); if (map == null) { throw new CayenneRuntimeException("Invalid dataMapName '%s'", dataMapName); } root = map; } else { root = null; } SQLTemplate template = new SQLTemplate(); template.setFetchingDataRows(isFetchingDataRows()); template.setRoot(root); template.setDefaultTemplate(getSql()); template.setCacheGroup(cacheGroup); template.setCacheStrategy(cacheStrategy); <START> template.addPrefetch(prefetches); <END> if (positionalParams != null) { template.setParamsList(positionalParams); } else { template.setParams(params); } template.setColumnNamesCapitalization(columnNameCaps); template.setFetchLimit(limit); template.setFetchOffset(offset); template.setPageSize(pageSize); template.setStatementFetchSize(statementFetchSize); if (isFetchingScalars()) { SQLResult resultMap = new SQLResult(); resultMap.addColumnResult("x"); template.setResult(resultMap); } return template; }</code><technical_language>This NullPointerException prefetches set. This is visible in test also</technical_language>

Target:
public Query createReplacementQuery(EntityResolver resolver) { Object root; if (persistentType != null) { root = persistentType; } else if (dataMapName != null) { DataMap map = resolver.getDataMap(dataMapName); if (map == null) { throw new CayenneRuntimeException("Invalid dataMapName '%s'", dataMapName); } root = map; } else { root = null; } SQLTemplate template = new SQLTemplate(); template.setFetchingDataRows(isFetchingDataRows()); template.setRoot(root); template.setDefaultTemplate(getSql()); template.setCacheGroup(cacheGroup); template.setCacheStrategy(cacheStrategy); if (prefetches != null) { template.addPrefetch(prefetches); } if (positionalParams != null) { template.setParamsList(positionalParams); } else { template.setParams(params); } template.setColumnNamesCapitalization(columnNameCaps); template.setFetchLimit(limit); template.setFetchOffset(offset); template.setPageSize(pageSize); template.setStatementFetchSize(statementFetchSize); if (isFetchingScalars()) { SQLResult resultMap = new SQLResult(); resultMap.addColumnResult("x"); template.setResult(resultMap); } return template; }
Source:
<code>public void sendPullReplyMsg(final String destId, final K key, final V value, final int requestId, final long processingTime, @Nullable final TraceInfo traceInfo) { Span detached = null; <START> try (final TraceScope sendPullReplyScope = Trace.startSpan("send_pull_reply." + <END> " key: " + key + ", request_id: " + requestId, traceInfo)) { final PullReplyMsg pullReplyMsg = PullReplyMsg.newBuilder() .setKey(ByteBuffer.wrap(keyCodec.encode(key))) .setValue(ByteBuffer.wrap(valueCodec.encode(value))) .setRequestId(requestId) .setServerProcessingTime(processingTime) .build(); detached = sendPullReplyScope.detach(); send(destId, AvroPSMsg.newBuilder() .setType(Type.PullReplyMsg) .setPullReplyMsg(pullReplyMsg) .setTraceInfo(HTraceUtils.toAvro(TraceInfo.fromSpan(detached))) .build()); } finally { Trace.continueSpan(detached).close(); } }</code><technical_language>String.format() pretty-print this trace description</technical_language>

Target:
public void sendPullReplyMsg(final String destId, final K key, final V value, final int requestId, final long processingTime, @Nullable final TraceInfo traceInfo) { Span detached = null; try (final TraceScope sendPullReplyScope = Trace.startSpan( String.format("send_pull_reply. key: %s, request_id: %d", key, requestId), traceInfo)) { final PullReplyMsg pullReplyMsg = PullReplyMsg.newBuilder() .setKey(ByteBuffer.wrap(keyCodec.encode(key))) .setValue(ByteBuffer.wrap(valueCodec.encode(value))) .setRequestId(requestId) .setServerProcessingTime(processingTime) .build(); detached = sendPullReplyScope.detach(); send(destId, AvroPSMsg.newBuilder() .setType(Type.PullReplyMsg) .setPullReplyMsg(pullReplyMsg) .setTraceInfo(HTraceUtils.toAvro(TraceInfo.fromSpan(detached))) .build()); } finally { Trace.continueSpan(detached).close(); } }
Source:
<code>public void writeBlock(BlockEncodingSerde blockEncodingSerde, SliceOutput sliceOutput, Block block) { SingleMapBlock singleMapBlock = (SingleMapBlock) block; TypeSerde.writeType(sliceOutput, singleMapBlock.keyType); int offset = singleMapBlock.getOffset(); int positionCount = singleMapBlock.getPositionCount(); blockEncodingSerde.writeBlock(sliceOutput, singleMapBlock.getKeyBlock().getRegion(offset / 2, positionCount / 2)); <START> blockEncodingSerde.writeBlock(sliceOutput, singleMapBlock.getValueBlock().getRegion(offset / 2, positionCount / 2)); <END> int[] hashTable = singleMapBlock.getHashTable(); sliceOutput.appendInt(positionCount / 2 * HASH_MULTIPLIER); sliceOutput.writeBytes(wrappedIntArray(hashTable, offset / 2 * HASH_MULTIPLIER, positionCount / 2 * HASH_MULTIPLIER)); }</code><technical_language>a helper a big</technical_language>

Target:
public void writeBlock(BlockEncodingSerde blockEncodingSerde, SliceOutput sliceOutput, Block block) { SingleMapBlock singleMapBlock = (SingleMapBlock) block; TypeSerde.writeType(sliceOutput, singleMapBlock.keyType); int offset = singleMapBlock.getOffset(); int positionCount = singleMapBlock.getPositionCount(); blockEncodingSerde.writeBlock(sliceOutput, singleMapBlock.getRawKeyBlock().getRegion(offset / 2, positionCount / 2)); blockEncodingSerde.writeBlock(sliceOutput, singleMapBlock.getRawValueBlock().getRegion(offset / 2, positionCount / 2)); int[] hashTable = singleMapBlock.getHashTable(); sliceOutput.appendInt(positionCount / 2 * HASH_MULTIPLIER); sliceOutput.writeBytes(wrappedIntArray(hashTable, offset / 2 * HASH_MULTIPLIER, positionCount / 2 * HASH_MULTIPLIER)); }
Source:
<code><START> private ProjectNode project(String id, PlanNode source, VariableReferenceExpression variable, Expression expression) <END> { return new ProjectNode( new PlanNodeId(id), source, Assignments.of(variable, expression)); }</code><technical_language>This change is necessary. PlanNode is good enough</technical_language>

Target:
private PlanNode project(String id, PlanNode source, VariableReferenceExpression variable, Expression expression) { return new ProjectNode( new PlanNodeId(id), source, assignment(variable, expression)); }
Source:
<code>public void tearDown() { <START> if (applicationContext != null) { <END> applicationContext.close(); } }</code><technical_language>run tasks, do want add check confirm context is active</technical_language>

Target:
public void tearDown() { if (applicationContext != null && applicationContext.isActive() ) { applicationContext.close(); } }
Source:
<code>public void addToOrderBook(Order order) { if (order instanceof BuyOrder) { <START> if (buyOrders.get(order.getStockSymbol()) != null) { stockArray = buyOrders.get(order.getStockSymbol()); stockArray.add(order); } else { stockArray = new ArrayList<Order>(); stockArray.add(order); } buyOrders.put(order.getStockSymbol(), stockArray); <END> } else { if (sellOrders.get(order.getStockSymbol()) != null) { stockArray = sellOrders.get(order.getStockSymbol()); stockArray.add(order); } else { stockArray = new ArrayList<Order>(); stockArray.add(order); } sellOrders.put(order.getStockSymbol(), stockArray); } }</code><technical_language>Consider refactoring this a function named addBuyOrderToOrderBook simply addBuyOrder. Extract method refactoring</technical_language>

Target:
public void addToOrderBook(Order order) { if (order instanceof BuyOrder) { buyOrders.put(order.getStockSymbol(), addBuyOrder()); } else { sellOrders.put(order.getStockSymbol(), addSellOrder()); } }
Source:
<code>private void listFirmwares(Console console, String[] args) { if (args.length != 2) { <START> console.println("Specify thing type id to get its available firmwares: firmware list <thingTypeUID>"); <END> return; } ThingTypeUID thingTypeUID = new ThingTypeUID(args[1]); Collection<Firmware> firmwares = firmwareRegistry.getFirmwares(thingTypeUID); if (firmwares.isEmpty()) { console.println("No firmwares found."); } for (Firmware firmware : firmwares) { console.println(firmware.toString()); } }</code><technical_language>_the_ type id... (see too..</technical_language>

Target:
private void listFirmwares(Console console, String[] args) { if (args.length != 2) { console.println("Specify the thing type id to get its available firmwares: firmware list <thingTypeUID>"); return; } ThingTypeUID thingTypeUID = new ThingTypeUID(args[1]); Collection<Firmware> firmwares = firmwareRegistry.getFirmwares(thingTypeUID); if (firmwares.isEmpty()) { console.println("No firmwares found."); } for (Firmware firmware : firmwares) { console.println(firmware.toString()); } }
Source:
<code>public void clear(String tenantId) { String index = client.getIndex(tenantId); boolean indexExists = client.getClient() .admin() <START> .indices() <END> .prepareExists(index) .execute().actionGet().isExists(); if (indexExists) { client.getClient() .admin() .indices() .prepareDelete(index).execute().actionGet(); client.clear(tenantId); } }</code><technical_language>lines stored in a local var? I this code changing in future, of lines updated :)</technical_language>

Target:
public void clear(String tenantId) { String index = client.getIndex(tenantId); IndicesAdminClient indices = client.getClient().admin().indices(); boolean indexExists = indices.prepareExists(index) .execute() .actionGet() .isExists(); if (indexExists) { indices.prepareDelete(index) .execute() .actionGet(); client.clear(tenantId); } }
Source:
<code>public BinaryObject getMODS() { <START> Resource mods = this.getResource(); <END> Statement s = mods.getProperty(Cdr.hasMods); if (s != null) { PID binPid = PIDs.get(s.getResource().getURI()); return repository.getBinary(binPid); } else { return null; } }</code><technical_language>suggest renaming this too, is resource for current contentObject</technical_language>

Target:
public BinaryObject getMODS() { Resource res = this.getResource(); Statement s = res.getProperty(Cdr.hasMods); if (s != null) { PID binPid = PIDs.get(s.getResource().getURI()); return repository.getBinary(binPid); } else { return null; } }
Source:
<code>private List<Integer> calculateLastColumnsForPages(float[] relativeWidths) { <START> List<Integer> lastColumnsForPages = new LinkedList<>(); <END> lastColumnsForPages.add(1); float totalColumnsWidth = 0; for (int i = 1; i < relativeWidths.length; i++) { if (totalColumnsWidth + relativeWidths[i] > PAGE_WIDTH - relativeWidths[0]) { lastColumnsForPages.add(i); totalColumnsWidth = 0; } totalColumnsWidth += relativeWidths[i]; } lastColumnsForPages.add(-1); return lastColumnsForPages; }</code><technical_language>LinkedList? I get index list, for LinkedList complexity O(n), while for ArrayList this is O(1). plan access/delete elements iterators ArrayLists</technical_language>

Target:
private List<Integer> calculateLastColumnsForPages(float[] relativeWidths) { List<Integer> lastColumnsForPages = new ArrayList<>(); lastColumnsForPages.add(1); float totalColumnsWidth = 0; for (int i = 1; i < relativeWidths.length; i++) { if (totalColumnsWidth + relativeWidths[i] > PAGE_WIDTH - relativeWidths[0]) { lastColumnsForPages.add(i); totalColumnsWidth = 0; } totalColumnsWidth += relativeWidths[i]; } lastColumnsForPages.add(-1); return lastColumnsForPages; }
Source:
<code>private ClassModifierShouldBe(Class<?> actual, boolean positive, String modifier) { <START> super("%nExpecting:%n <%s>%n" + (positive ? "to" : "not to") + " be a %s class.", actual, modifier); <END> }</code><technical_language>suggestion: finish error message % add actual's modifier</technical_language>

Target:
private ClassModifierShouldBe(Class<?> actual, boolean positive, String modifier) { super("%nExpecting:%n <%s>%n" + (positive ? "to" : "not to") + " be a %s class but was %s.", actual, modifier, Modifier.toString(actual.getModifiers())); }
Source:
<code>public boolean mediate(MessageContext synCtx) { <START> List<PropertyMediator> propGroupList = this.getPropGroupList(); <END> for (PropertyMediator propertyMediator : propGroupList) { propertyMediator.mediate(synCtx); } return true; }</code><technical_language>field propGroupList</technical_language>

Target:
public boolean mediate(MessageContext synCtx) { for (PropertyMediator propertyMediator : propGroupList) { propertyMediator.mediate(synCtx); } return true; }
Source:
<code>public void destroy() throws Exception { restAPIStore.deleteApplication(tokenTestApiAppId, user.getUserDomain()); restAPIStore.deleteApplication(tokenTestAppId, user.getUserDomain()); restAPIStore.deleteApplication(oauthTokenTestApiId, user.getUserDomain()); restAPIPublisher.deleteAPI(apiId); restAPIPublisher.deleteAPI(apiIdForOauth); <START> super.cleanUp(); <END> }</code><technical_language>remove this</technical_language>

Target:
public void destroy() throws Exception { restAPIStore.deleteApplication(tokenTestApiAppId); restAPIStore.deleteApplication(tokenTestAppId); restAPIStore.deleteApplication(oauthTokenTestApiId); restAPIPublisher.deleteAPI(apiId); restAPIPublisher.deleteAPI(apiIdForOauth); }
Source:
<code>protected boolean processOperator(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { <START> VXQueryOptimizationContext vxqOptCtx = (VXQueryOptimizationContext) context; <END> IMetadataProvider iProvider = (IMetadataProvider) vxqOptCtx.getMetadataProvider(); VXQueryMetadataProvider vxqProvider = (VXQueryMetadataProvider) iProvider; dCtx = vxqProvider.getStaticContext(); AbstractLogicalOperator op1 = (AbstractLogicalOperator) opRef.getValue(); if (op1.getOperatorTag() != LogicalOperatorTag.UNNEST) { return false; } UnnestOperator unnest = (UnnestOperator) op1; AbstractLogicalOperator op2 = (AbstractLogicalOperator) unnest.getInputs().get(0).getValue(); if (op2.getOperatorTag() != LogicalOperatorTag.DATASOURCESCAN) { return false; } DataSourceScanOperator datascan = (DataSourceScanOperator) op2; if (!usedVariables.contains(datascan.getVariables())) { VXQueryCollectionDataSource ds = (VXQueryCollectionDataSource) datascan.getDataSource(); if (!updateDataSource(ds, unnest.getExpressionRef())) { return false; } Mutable<ILogicalExpression> varExp = ExpressionToolbox.findVariableExpression(unnest.getExpressionRef(), datascan.getVariables().get(0)); AssignOperator noOp = new AssignOperator(unnest.getVariable(), varExp); noOp.getInputs().addAll(unnest.getInputs()); opRef.setValue(noOp); return true; } return false; }</code><technical_language>create variables here. dCtx is in plan</technical_language>

Target:
protected boolean processOperator(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { IMetadataProvider iProvider = ((VXQueryOptimizationContext) context).getMetadataProvider(); dCtx = ((VXQueryMetadataProvider) iProvider).getStaticContext(); AbstractLogicalOperator op1 = (AbstractLogicalOperator) opRef.getValue(); if (op1.getOperatorTag() != LogicalOperatorTag.UNNEST) { return false; } UnnestOperator unnest = (UnnestOperator) op1; AbstractLogicalOperator op2 = (AbstractLogicalOperator) unnest.getInputs().get(0).getValue(); if (op2.getOperatorTag() != LogicalOperatorTag.DATASOURCESCAN) { return false; } DataSourceScanOperator datascan = (DataSourceScanOperator) op2; if (!usedVariables.contains(datascan.getVariables())) { VXQueryCollectionDataSource ds = (VXQueryCollectionDataSource) datascan.getDataSource(); if (!updateDataSource(ds, unnest.getExpressionRef())) { return false; } Mutable<ILogicalExpression> varExp = ExpressionToolbox.findVariableExpression(unnest.getExpressionRef(), datascan.getVariables().get(0)); AssignOperator noOp = new AssignOperator(unnest.getVariable(), varExp); noOp.getInputs().addAll(unnest.getInputs()); opRef.setValue(noOp); return true; } return false; }
Source:
<code>public Response toResponse(Throwable exception) { if (exception instanceof WebApplicationException) { WebApplicationException wae = (WebApplicationException) exception; return wae.getResponse(); } if (exception instanceof ClassCastException) { return Response.status(Status.BAD_REQUEST) .type(MediaType.APPLICATION_JSON) .entity(new ApiError(exception.getMessage())) .build(); } LOG.info("No exception mapping for " + exception.getClass() + ", responding 500", exception); return Response.status(Status.INTERNAL_SERVER_ERROR) .type(MediaType.APPLICATION_JSON) <START> .entity(new ApiError(exception.getMessage())) <END> .build(); }</code><technical_language>Some exceptions a null message. include exception class name well, is giving security experts</technical_language>

Target:
public Response toResponse(Throwable exception) { if (exception instanceof WebApplicationException) { WebApplicationException wae = (WebApplicationException) exception; return wae.getResponse(); } if (exception instanceof ClassCastException) { return Response.status(Status.BAD_REQUEST) .type(MediaType.APPLICATION_JSON) .entity(new ApiError(exception.getMessage())) .build(); } LOG.info("No exception mapping for " + exception.getClass() + ", responding 500", exception); String message = Optional.fromNullable(exception.getMessage()) .or("Internal error. Check server logs for details."); return Response.status(Status.INTERNAL_SERVER_ERROR) .type(MediaType.APPLICATION_JSON) .entity(new ApiError(message)) .build(); }
Source:
<code>void doCommonSPICompleteActions() { m_txnState.setDone(); if (m_txnDoneNotification != null) { <START> m_txnDoneNotification.transactionDone(m_txnState.m_spHandle); <END> } if (m_queue != null) { m_queue.flush(getTxnId()); } }</code><technical_language>@nshi " m_txnState.setDone();" means SPI receives duplicate counter DONE? SPI knows</technical_language>

Target:
void doCommonSPICompleteActions() { m_txnState.setDone(); if (m_queue != null) { m_queue.flush(getTxnId()); } }
Source:
<code>private String composeProxyClause() throws IOException { String proxyClause = "proxy"; final String proxyHost = System.getProperty(HTTP_PROXY_HOST); final String proxyporttxt = System.getProperty(HTTP_PROXY_PORT); if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyporttxt)) { int proxyPort = 0; try { proxyPort = Integer.parseInt(proxyporttxt); } catch (final NumberFormatException exception) { Logger.error( this, Joiner.on(" ").join( "Can't parse proxy port", proxyporttxt ) <START> ); <END> } if (proxyPort > 0) { proxyClause = Joiner.on("").join( "http-proxy=", proxyHost, ":", proxyPort ); } } return proxyClause; }</code><technical_language>throw IllegalStateException besides logging info</technical_language>

Target:
private String composeProxyClause() throws IOException { String clause = "proxy"; final String host = System.getProperty(HTTP_PROXY_HOST); final String porttxt = System.getProperty(HTTP_PROXY_PORT); if (StringUtils.isNotBlank(host)) { int proxyPort = 80; try { proxyPort = Integer.parseInt(porttxt); } catch (final NumberFormatException exception) { final String message = Joiner.on(" ").join( "Can't parse proxy port", porttxt ); Logger.error( this, message ); throw new IllegalStateException(message); } if (proxyPort > 0) { clause = Joiner.on("").join( "http-proxy=", host, ":", proxyPort ); } } return clause; }
Source:
<code>public String getNextIndexName(String aliasName, String oldIndexName) { <START> if (oldIndexName == null || oldIndexName.isEmpty()) { <END> return aliasName + SEP + "0000"; } int i = oldIndexName.lastIndexOf(SEP); if (i < 0) { throw new IllegalArgumentException("Invalid index name: " + oldIndexName); } int index = Integer.parseInt(oldIndexName.substring(i + 1)) + 1; return String.format("%s%s%04d", aliasName, SEP, index); }</code><technical_language>check isEmpty()? I guess empty index names eliminated here</technical_language>

Target:
public String getNextIndexName(String aliasName, String oldIndexName) { if (StringUtils.isEmpty(oldIndexName)) { return aliasName + SEP + "0000"; } int i = oldIndexName.lastIndexOf(SEP); if (i < 0) { throw new IllegalArgumentException("Invalid index name: " + oldIndexName); } int index = Integer.parseInt(oldIndexName.substring(i + 1)) + 1; return String.format("%s%s%04d", aliasName, SEP, index); }
Source:
<code>public DefaultQuestionView(@NonNull final View view) { this.view = view; titleTextView = (TextView) view.findViewById(R.id.amp_title_text_view); if (titleTextView == null) { throw new IllegalArgumentException("You must supply a layout that includes a TextView with id amp_title_text_view"); } positiveButton = view.findViewById(R.id.amp_positive_button); if (positiveButton == null) { <START> throw new IllegalArgumentException("You must supply a layout that includes a Button with id amp_positive_button"); <END> } negativeButton = view.findViewById(R.id.amp_negative_button); if (negativeButton == null) { throw new IllegalArgumentException("You must supply a layout that includes a Button with id amp_negative_button"); } }</code><technical_language>This string needs updating</technical_language>

Target:
public DefaultQuestionView(@NonNull final View view) { this.view = view; titleTextView = (TextView) view.findViewById(R.id.amp_title_text_view); questionTextView = (TextView) view.findViewById(R.id.amp_question_text_view); if (questionTextView == null) { throw new IllegalArgumentException("You must supply a layout that includes a TextView with id amp_question_text_view"); } positiveButton = view.findViewById(R.id.amp_positive_button); if (positiveButton == null) { throw new IllegalArgumentException("You must supply a layout that includes a View with id amp_positive_button"); } negativeButton = view.findViewById(R.id.amp_negative_button); if (negativeButton == null) { throw new IllegalArgumentException("You must supply a layout that includes a View with id amp_negative_button"); } }
Source:
<code>public boolean addReaction(String emojiName) { <START> return slackService.addReaction(channelId, ts, emojiName); <END> }</code><technical_language>suggestion if (slackService == null) return false; return slackService.addReaction(channelId, ts, emojiName);</technical_language>

Target:
public boolean addReaction(String emojiName) { if (slackService == null) { return false; } return slackService.addReaction(channelId, ts, emojiName); }
Source:
<code>public void updateRelationTupleCount(final RelationKey relation, final long count) throws CatalogException { Objects.requireNonNull(relation, "relation"); if (isClosed) { throw new CatalogException("Catalog is closed."); } try { queue.execute(new SQLiteJob<Void>() { @Override protected Void job(final SQLiteConnection sqliteConnection) throws CatalogException, SQLiteException { try { SQLiteStatement statement = sqliteConnection <START> .prepare("UPDATE relations SET num_tuples=? WHERE user_name=? AND program_name=? AND relation_name=? and tombstone=0;"); <END> statement.bind(1, count); statement.bind(2, relation.getUserName()); statement.bind(3, relation.getProgramName()); statement.bind(4, relation.getRelationName()); statement.stepThrough(); statement.dispose(); statement = null; } catch (final SQLiteException e) { throw new CatalogException(e); } return null; } }).get(); } catch (InterruptedException | ExecutionException e) { throw new CatalogException(e); } }</code><technical_language>want silently fail here? throw exception update operations tombstoned relation metadata</technical_language>

Target:
public void updateRelationTupleCount(final RelationKey relation, final long count) throws CatalogException { Objects.requireNonNull(relation, "relation"); if (isClosed) { throw new CatalogException("Catalog is closed."); } if (isDeletedRelation(relation)) { LOGGER.warn("Relation has already been deleted"); } try { queue.execute(new SQLiteJob<Void>() { @Override protected Void job(final SQLiteConnection sqliteConnection) throws CatalogException, SQLiteException { try { SQLiteStatement statement = sqliteConnection .prepare("UPDATE relations SET num_tuples=? WHERE user_name=? AND program_name=? AND relation_name=? and is_deleted=0;"); statement.bind(1, count); statement.bind(2, relation.getUserName()); statement.bind(3, relation.getProgramName()); statement.bind(4, relation.getRelationName()); statement.stepThrough(); statement.dispose(); statement = null; } catch (final SQLiteException e) { throw new CatalogException(e); } return null; } }).get(); } catch (InterruptedException | ExecutionException e) { throw new CatalogException(e); } }