auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void createAndAddDocumentIdsForClient(ClientExpanded clientExpanded) throws MambuApiException { boolean areOtherDocIdsAllowed = getOtherDocumentTemplateIdsEnabeled(); if (areOtherDocIdsAllowed) { <START> List<IdentificationDocument> idDocs = new ArrayList<IdentificationDocument>(); <END> IdentificationDocument doc = new IdentificationDocument(); doc.setDocumentId("DFG1234"); doc.setDocumentType("Passport"); doc.setIssuingAuthority("Vancouver"); idDocs.add(doc); clientExpanded.setIdDocuments(idDocs); } }</code><technical_language>diamond operator here</technical_language>

Target:
private static void createAndAddDocumentIdsForClient(ClientExpanded clientExpanded) throws MambuApiException { boolean areOtherDocIdsAllowed = getOtherDocumentTemplateIdsEnabeled(); if (areOtherDocIdsAllowed) { List<IdentificationDocument> idDocs = new ArrayList<>(); IdentificationDocument doc = new IdentificationDocument(); doc.setDocumentId("DFG1234"); doc.setDocumentType("Passport"); doc.setIssuingAuthority("Vancouver"); idDocs.add(doc); clientExpanded.setIdDocuments(idDocs); } }
Source:
<code>protected synchronized void persist( final TimelineRecord... records ) throws IOException { verify( records ); OutputStream out = null; try { <START> out = new FileOutputStream( getDataFile(), true ); <END> for ( TimelineRecord record : records ) { toProto( record ).writeDelimitedTo( out ); } out.flush(); } finally { IOUtil.close( out ); } }</code><technical_language>BufferedOutputStream here</technical_language>

Target:
protected synchronized void persist( final TimelineRecord... records ) throws IOException { verify( records ); OutputStream out = null; try { out = new BufferedOutputStream( new FileOutputStream( getDataFile(), true ) ); for ( TimelineRecord record : records ) { toProto( record ).writeDelimitedTo( out ); } out.flush(); } finally { IOUtil.close( out ); } }
Source:
<code>public List<Condition> getConditions() { <START> return conditions == null ? new ArrayList<>() : conditions; <END> }</code><technical_language>Is a reason create ArrayList instead of Collections.emptyList()</technical_language>

Target:
public List<Condition> getConditions() { return conditions == null ? Collections.emptyList() : conditions; }
Source:
<code>public void testNotClosing() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); List<Map<String, Object>> results = h.createQuery("select * from something order by id").list(); assertThat(results).hasSize(2); <START> assertThat(results.get(0).get("name")).isEqualTo("eric"); <END> assertThat(h.isClosed()).isFalse(); }</code><technical_language>a Map-specific assertion class: assertThat(results.get(0)).containsEntry("name", "eric");</technical_language>

Target:
public void testNotClosing() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); List<Map<String, Object>> results = h.createQuery("select * from something order by id").list(); assertThat(results).hasSize(2); assertThat(results.get(0)).containsEntry("name", "eric"); assertThat(h.isClosed()).isFalse(); }
Source:
<code>public void marshal(ITypeMarshalBuffer buffer, boolean includeValue) throws CoreException { buffer.putShort(ITypeMarshalBuffer.EXEC_IF); <START> buffer.putByte((byte) (isConstexpr ? 1 : 0)); <END> buffer.marshalExecution(initStmtExec, includeValue); buffer.marshalEvaluation(conditionExprEval, includeValue); buffer.marshalExecution(conditionDeclExec, includeValue); buffer.marshalExecution(thenClauseExec, includeValue); buffer.marshalExecution(elseClauseExec, includeValue); }</code><technical_language>Booleans this packed short execution type (ITypeMarshalBuffer.EXEC_IF), need a byte for them. EvalID.marshal() for example</technical_language>

Target:
public void marshal(ITypeMarshalBuffer buffer, boolean includeValue) throws CoreException { short firstBytes = ITypeMarshalBuffer.EXEC_IF; if (isConstexpr) { firstBytes |= ITypeMarshalBuffer.FLAG1; } buffer.putShort(firstBytes); buffer.marshalExecution(initStmtExec, includeValue); buffer.marshalEvaluation(conditionExprEval, includeValue); buffer.marshalExecution(conditionDeclExec, includeValue); buffer.marshalExecution(thenClauseExec, includeValue); buffer.marshalExecution(elseClauseExec, includeValue); }
Source:
<code>public static EnvironmentDto asDto(EnvironmentState environment) { final List<MachineConfigDto> machineConfigs = environment.getMachineConfigs() .stream() .map(org.eclipse.che.api.machine.server.DtoConverter::asDto) .collect(toList()); <START> return newDto(EnvironmentDto.class).withName(environment.getName()).withMachineConfigs(machineConfigs); <END> }</code><technical_language>write java return newDto(EnvironmentDto.class).withName(environment.getName()) .withMachineConfigs(environment.getMachineConfigs().stream() .map(org.eclipse.che.api.machine.server.DtoConverter::asDto) .collect(toList()));</technical_language>

Target:
public static EnvironmentDto asDto(EnvironmentState environment) { return newDto(EnvironmentDto.class).withName(environment.getName()) .withMachineConfigs(environment.getMachineConfigs().stream() .map(org.eclipse.che.api.machine.server.DtoConverter::asDto) .collect(toList())); }
Source:
<code>public static List<URL> parseURLs(String address, Map<String, String> defaults) { <START> return UrlUtils.parseURLs(address, defaults).stream().map(e -> new URL(e)).collect(Collectors.toList()); <END> }</code><technical_language>endless recursion? org.apache.dubbo.common.utils.UrlUtils.parseURLs(address, defaults).stream()</technical_language>

Target:
public static List<URL> parseURLs(String address, Map<String, String> defaults) { return org.apache.dubbo.common.utils.UrlUtils.parseURLs(address, defaults).stream().map(e -> new URL(e)).collect(Collectors.toList()); }
Source:
<code>private void injectTestId(Xpp3Dom config) { Xpp3Dom properties = config.getChild("properties"); <START> String propertyName = "liberty.dev.test.run.id"; <END> if (properties == null || properties.getChild(propertyName) == null) { Element e = element(name("properties"), element(name(propertyName), String.valueOf(runId++))); config.addChild(e.toDom()); } else { properties.getChild(propertyName).setValue(String.valueOf(runId++)); } }</code><technical_language>This a constant (static final class level)</technical_language>

Target:
private void injectTestId(Xpp3Dom config) { Xpp3Dom properties = config.getChild("properties"); if (properties == null || properties.getChild(TEST_RUN_ID_PROPERTY_NAME) == null) { Element e = element(name("properties"), element(name(TEST_RUN_ID_PROPERTY_NAME), String.valueOf(runId++))); config.addChild(e.toDom()); } else { properties.getChild(TEST_RUN_ID_PROPERTY_NAME).setValue(String.valueOf(runId++)); } }
Source:
<code>public boolean equals(Object o) { <START> return o == this; <END> }</code><technical_language>Instead of reference equality, change implementation query field in equals hashCode computations</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; ScoreValueSource other = (ScoreValueSource) o; return Objects.equals(query, other.query); }
Source:
<code>protected void removeAdditionalListeners() { super.removeAdditionalListeners(); ActivityPartition activityPartition = getUMLElement(); if (activityPartition == null) { return; } getDiagramEventBroker().removeNotificationListener(activityPartition, this); <START> ConnectableElement el = (ConnectableElement) activityPartition.getRepresents(); <END> if (el != null) { getDiagramEventBroker().removeNotificationListener(el, this); if (el.getType() != null) { getDiagramEventBroker().removeNotificationListener(el.getType(), this); } } }</code><technical_language>assume ConnectableElement either</technical_language>

Target:
protected void removeAdditionalListeners() { super.removeAdditionalListeners(); ActivityPartition activityPartition = getUMLElement(); if (activityPartition == null) { return; } getDiagramEventBroker().removeNotificationListener(activityPartition, this); Element el = activityPartition.getRepresents(); if (el != null) { getDiagramEventBroker().removeNotificationListener(el, this); } }
Source:
<code>private Record updateRecordsWithHeader(Record record) throws IOException { <START> List<Column> columnList = sasFileReader.getColumns(); <END> Object[] rows = sasFileReader.readNext(); headers = new ArrayList<>(); for (Column col : sasFileReader.getColumns()) { headers.add(Field.create(col.getName())); } LinkedHashMap<String, Field> listMap = new LinkedHashMap<>(); for (int i = 0; i < columnList.size(); i++) { String key; Field header = (headers != null) ? headers.get(i) : null; if (header != null) { key = header.getValueAsString(); } else { key = Integer.toString(i); } listMap.put(key, Field.create(Field.Type.STRING, rows[i])); } record.set(Field.createListMap(listMap)); return record; }</code><technical_language>do this in constructor need get columns once, right</technical_language>

Target:
private Record updateRecordsWithHeader(Record record) throws IOException { currentOffset = Integer.valueOf(sasFileReader.getOffset()); record = context.createRecord(id + "::" + currentOffset); Object rows[] = sasFileReader.readNext(); if (rows == null || rows.length == 0) { eof = true; return null; } headers = new ArrayList<Field>(); for (Column col : sasFileReader.getColumns()) { headers.add(Field.create(col.getName())); } LinkedHashMap<String, Field> listMap = new LinkedHashMap<String, Field>(); for (int i = 0; i < columnlist.size(); i++) { Field header = headers.get(i); String key = header.getValueAsString(); if (rows[i] == null) { listMap.put(key, Field.create(Field.Type.STRING, "")); } listMap.put(key, Field.create(Field.Type.STRING, rows[i])); } record.set(Field.createListMap(listMap)); return record; }
Source:
<code>private void runAction(VdcActionType action, VdcActionParametersBase param) { if (getConfirmWindow() == null) { return; } ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); if (model.getProgress() != null) { <START> return; <END> } model.startProgress(null); Frontend.getInstance().runAction(action, param, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) getConfirmWindow(); localModel.stopProgress(); setConfirmWindow(null); } }); }</code><technical_language>this happen if window simply progress indication happen</technical_language>

Target:
private void runAction(VdcActionType action, VdcActionParametersBase param) { if (getConfirmWindow() == null) { return; } ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); model.startProgress(null); Frontend.getInstance().runAction(action, param, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) getConfirmWindow(); localModel.stopProgress(); setConfirmWindow(null); } }); }
Source:
<code>public List<Network> getAllByLabelForCluster(String label, Guid clusterId) { <START> List<Network> networksInCluster = getAllForCluster(clusterId, null, false); <END> List<Network> labeledNetworks = new ArrayList<>(); for (Network network : networksInCluster) { if (StringUtils.equals(network.getLabel(), label)) { labeledNetworks.add(network); } } return labeledNetworks; }</code><technical_language>call id</technical_language>

Target:
public List<Network> getAllByLabelForCluster(String label, Guid clusterId) { List<Network> networksInCluster = getAllForCluster(clusterId); List<Network> labeledNetworks = new ArrayList<>(); for (Network network : networksInCluster) { if (StringUtils.equals(network.getLabel(), label)) { labeledNetworks.add(network); } } return labeledNetworks; }
Source:
<code>private String getCacheSubcommandDesc(CacheCommand cmd) { switch (cmd) { case LIST: return "Show information about caches, groups or sequences that match a regular expression. When executed without parameters, this subcommand prints the list of caches."; case CONTENTION: return "Show the keys that are point of contention for multiple transactions."; case IDLE_VERIFY: return "Verify counters and hash sums of primary and backup partitions for the specified caches/cache groups on an idle cluster and print out the differences, if any. " + "Cache filtering options configure the set of caches that will be processed by " + IDLE_VERIFY + " command. " + "Default value for the set of cache names (or cache group names) is all user cache groups. Default value for " + EXCLUDE_CACHES + " is empty set. " + "Therefore, the set of all caches is sequently filtered by cache name regexps, by cache type (if specified) and after that by exclude regexps."; <START> <END> case VALIDATE_INDEXES: return "Validate indexes on an idle cluster and print out the keys that are missing in the indexes."; case DISTRIBUTION: return "Prints the information about partition distribution."; case RESET_LOST_PARTITIONS: return "Reset the state of lost partitions for the specified caches."; default: throw new IllegalArgumentException("Unknown command: " + cmd); } }</code><technical_language>I define behaviour for CacheFilterEnum values</technical_language>

Target:
private String getCacheSubcommandDesc(CacheCommand cmd) { switch (cmd) { case LIST: return "Show information about caches, groups or sequences that match a regular expression. When executed without parameters, this subcommand prints the list of caches."; case CONTENTION: return "Show the keys that are point of contention for multiple transactions."; case IDLE_VERIFY: return "Verify counters and hash sums of primary and backup partitions for the specified caches/cache " + "groups on an idle cluster and print out the differences, if any. When no parameters are specified, " + "all user caches are verified. Cache filtering options configure the set of caches that will be " + "processed by " + IDLE_VERIFY + " command. If cache names are specified, in form of regular " + "expressions, only matching caches will be verified. Caches matched by regexes specified after " + EXCLUDE_CACHES + " parameter will be excluded from verification. Using parameter " + CACHE_FILTER + " you can verify: only " + USER + " caches, only user " + PERSISTENT + " caches, only user " + NOT_PERSISTENT + " caches, only " + SYSTEM + " caches, or " + ALL + " of the above."; case VALIDATE_INDEXES: return "Validate indexes on an idle cluster and print out the keys that are missing in the indexes."; case DISTRIBUTION: return "Prints the information about partition distribution."; case RESET_LOST_PARTITIONS: return "Reset the state of lost partitions for the specified caches."; default: throw new IllegalArgumentException("Unknown command: " + cmd); } }
Source:
<code>public void execute(DocumentReference documentReference, DocumentReference authorReference, String version) { MentionsData data = new MentionsData() <START> .setDocumentReference(documentReference.toString()) <END> .setAuthorReference(Objects.toString(authorReference, "")) .setVersion(version) .setWikiId(documentReference.getWikiReference().getName()); try { this.queue.put(data); } catch (InterruptedException e) { this.logger .warn("Error while adding the task to the mentions analysis queue. Cause [{}]", data, getRootCauseMessage(e)); } }</code><technical_language>toString() need "print" reference (like in a log message). Otherwise, if some other code resolving string reference a proper reference serializer</technical_language>

Target:
public void execute(DocumentReference documentReference, DocumentReference authorReference, String version) { MentionsData mentionsData = new MentionsData() .setDocumentReference(this.serializer.serialize(documentReference)); if (authorReference != null) { mentionsData = mentionsData .setAuthorReference(this.serializer.serialize(authorReference)); } MentionsData data = mentionsData .setVersion(version) .setWikiId(documentReference.getWikiReference().getName()); try { this.queue.put(data); } catch (InterruptedException e) { this.logger .warn("Error while adding the task to the mentions analysis queue. Cause [{}]", data, getRootCauseMessage(e)); } }
Source:
<code>private String getDisplayNameFromContentResolver(Uri uri) { String displayName = null; String mimeType = getContentResolver().getType(uri); if (mimeType != null) { String displayNameColumn; if (mimeType.startsWith("image/")) { displayNameColumn = MediaStore.Images.ImageColumns.DISPLAY_NAME; } else if (mimeType.startsWith("video/")) { displayNameColumn = MediaStore.Video.VideoColumns.DISPLAY_NAME; } else if (mimeType.startsWith("audio/")) { displayNameColumn = MediaStore.Audio.AudioColumns.DISPLAY_NAME; } else { displayNameColumn = MediaStore.Files.FileColumns.DISPLAY_NAME; } Cursor cursor = null; try { cursor = getContentResolver().query( uri, new String[]{displayNameColumn}, null, null, null ); if (cursor != null) { cursor.moveToFirst(); displayName = cursor.getString(cursor.getColumnIndex(displayNameColumn)); } <START> } catch (Exception e) { <END> Log.e(TAG, "Could not retrieve display name for " + uri.toString(), e); } finally { if (cursor != null) { cursor.close(); } } } return displayName; }</code><technical_language>Please catch Exception directly, catch specific exception class(es). Actually, this code some other dont throw anything</technical_language>

Target:
private String getDisplayNameFromContentResolver(Uri uri) { String displayName = null; String mimeType = getContentResolver().getType(uri); if (mimeType != null) { String displayNameColumn; if (mimeType.startsWith("image/")) { displayNameColumn = MediaStore.Images.ImageColumns.DISPLAY_NAME; } else if (mimeType.startsWith("video/")) { displayNameColumn = MediaStore.Video.VideoColumns.DISPLAY_NAME; } else if (mimeType.startsWith("audio/")) { displayNameColumn = MediaStore.Audio.AudioColumns.DISPLAY_NAME; } else { displayNameColumn = MediaStore.Files.FileColumns.DISPLAY_NAME; } Cursor cursor = getContentResolver().query( uri, new String[]{displayNameColumn}, null, null, null ); if (cursor != null) { cursor.moveToFirst(); displayName = cursor.getString(cursor.getColumnIndex(displayNameColumn)); } if (cursor != null) { cursor.close(); } } return displayName; }
Source:
<code>public boolean isInExclusiveGroup() { <START> return grouping.equals(Grouping.EXCLUSIVE); <END> }</code><technical_language>== work</technical_language>

Target:
public boolean isInExclusiveGroup() { return grouping == Grouping.EXCLUSIVE; }
Source:
<code>public static Collection<ExportConfig> exportConfigs() { <START> return Arrays.asList(new ExportConfig[] { <END> new ExportConfig(TestType.FILE, "org.voltdb.exportclient.ExportToFileClient", new Pair<String, String>("type", "csv"), new Pair<String, String>("nonce", "basic1")), new ExportConfig(TestType.HTTP, "org.voltdb.exportclient.HttpExportClient", new Pair<String, String>("method", "post"), new Pair<String, String>("type", "form")), new ExportConfig(TestType.JDBC, "org.voltdb.exportclient.JDBCExportClient", new Pair<String, String>("jdbcdriver", HSQL_DRIVER), new Pair<String, String>("jdbcurl", JDBC_URL), new Pair<String, String>("jdbcuser", JDBC_USER)), }); }</code><technical_language>Arrays.asList is varargs new ExportConfig[] {</technical_language>

Target:
public static Collection<ExportConfig> exportConfigs() { return Arrays.asList( new ExportConfig(TestType.FILE, "org.voltdb.exportclient.ExportToFileClient", new Pair<String, String>("type", "csv"), new Pair<String, String>("nonce", "basic1")), new ExportConfig(TestType.HTTP, "org.voltdb.exportclient.HttpExportClient", new Pair<String, String>("method", "post"), new Pair<String, String>("type", "form")), new ExportConfig(TestType.JDBC, "org.voltdb.exportclient.JDBCExportClient", new Pair<String, String>("jdbcdriver", HSQL_DRIVER), new Pair<String, String>("jdbcurl", JDBC_URL), new Pair<String, String>("jdbcuser", JDBC_USER)) ); }
Source:
<code>public boolean performNextOperation(int completedChildCount) { if (getParameters().getLiveDiskMigrateStage() == LiveDiskMigrateStage.IMAGE_PLACEHOLDER_CREATION) { updateStage(LiveDiskMigrateStage.VM_REPLICATE_DISK_START); replicateDiskStart(); updateStage(LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_START); syncImageData(); updateStage(LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_END); return true; } if (getParameters().getLiveDiskMigrateStage() == LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_END) { updateStage(LiveDiskMigrateStage.VM_REPLICATE_DISK_FINISH); completeLiveMigration(); updateStage(LiveDiskMigrateStage.SOURCE_IMAGE_DELETION); LiveStorageMigrationHelper.removeImage(this, getParameters().getSourceStorageDomainId(), getParameters() .getImageGroupID(), getParameters().getDestinationImageId(), AuditLogType .USER_MOVE_IMAGE_GROUP_FAILED_TO_DELETE_SRC_IMAGE); <START> return true; <END> } return false; }</code><technical_language>return false</technical_language>

Target:
public boolean performNextOperation(int completedChildCount) { if (getParameters().getLiveDiskMigrateStage() == LiveDiskMigrateStage.IMAGE_PLACEHOLDER_CREATION) { updateStage(LiveDiskMigrateStage.VM_REPLICATE_DISK_START); replicateDiskStart(); updateStage(LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_START); syncImageData(); updateStage(LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_END); return true; } if (getParameters().getLiveDiskMigrateStage() == LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_END) { updateStage(LiveDiskMigrateStage.VM_REPLICATE_DISK_FINISH); completeLiveMigration(); updateStage(LiveDiskMigrateStage.SOURCE_IMAGE_DELETION); LiveStorageMigrationHelper.removeImage(this, getParameters().getSourceStorageDomainId(), getParameters() .getImageGroupID(), getParameters().getDestinationImageId(), AuditLogType .USER_MOVE_IMAGE_GROUP_FAILED_TO_DELETE_SRC_IMAGE); return false; } return false; }
Source:
<code>int[] scores() { <START> return highScores; <END> }</code><technical_language>practice: a defensive copy. suggestion return highScores.clone();</technical_language>

Target:
int[] scores() { return highScores.clone(); }
Source:
<code>private void configureImageView(ThemeViewHolder themeViewHolder, String screenshotURL) { String requestURL = (String) themeViewHolder.imageView.getTag(); if (requestURL == null) { requestURL = screenshotURL; <START> themeViewHolder.imageView.setDefaultImageResId(R.drawable.theme_loading); <END> themeViewHolder.imageView.setTag(requestURL); } if (!requestURL.equals(screenshotURL)) { requestURL = screenshotURL; } int mViewWidth = AppPrefs.getThemeImageSizeWidth(); themeViewHolder.imageView.setImageUrl(requestURL + THEME_IMAGE_PARAMETER + mViewWidth, WPNetworkImageView.ImageType.PHOTO); }</code><technical_language>theme_loading drawable part of changes, want optimize it. replace theme_loading theme_loading_background theme_loading_background overlays ic_themes_grey_lighten_30_18dp completely in theme_loading. Alternatively, replace theme_loading_background drawable in theme_loading a shape this. xml <item> <shape android:shape="rectangle"> <solid android:color="@color/grey_lighten_20" /> <size android:height="75dp" android:width="100dp" /> </shape> </item> I for file size scalability benefits vector drawables</technical_language>

Target:
private void configureImageView(ThemeViewHolder themeViewHolder, String screenshotURL) { String requestURL = (String) themeViewHolder.imageView.getTag(); if (requestURL == null) { requestURL = screenshotURL; themeViewHolder.imageView.setDefaultImageResId(R.drawable.theme_loading); themeViewHolder.imageView.showDefaultImage(); themeViewHolder.imageView.setTag(requestURL); } if (!requestURL.equals(screenshotURL)) { requestURL = screenshotURL; } int mViewWidth = AppPrefs.getThemeImageSizeWidth(); themeViewHolder.imageView.setImageUrl(requestURL + THEME_IMAGE_PARAMETER + mViewWidth, WPNetworkImageView.ImageType.PHOTO); }
Source:
<code>public void buildEnvironmentFor(Job job, EnvVars env, TaskListener listener) throws IOException, InterruptedException { <START> for (Object property : job.getProperties().values()) { <END> if (property instanceof EnvInjectJobProperty) { EnvInjectJobProperty jobProperty = (EnvInjectJobProperty) property; EnvInjectJobPropertyInfo jobPropertyInfo = jobProperty.getInfo(); Map<String, String> result = jobPropertyInfo.getPropertiesContentMap(new HashMap<String, String>()); if (result != null) { env.putAll(result); } } } }</code><technical_language>get properties class cycles</technical_language>

Target:
public void buildEnvironmentFor(Job job, EnvVars env, TaskListener listener) throws IOException, InterruptedException { EnvInjectJobProperty jobProperty = (EnvInjectJobProperty) job.getProperty(EnvInjectJobProperty.class); if (jobProperty != null) { EnvInjectJobPropertyInfo jobPropertyInfo = jobProperty.getInfo(); Map<String, String> result = jobPropertyInfo.getPropertiesContentMap(env); if (result != null) { env.putAll(result); } } }
Source:
<code>public void bindConsumer(MessageChannel inputChannel, String inputChannelName) { String channelBindingTarget = this.channelBindingServiceProperties.getBindingDestination(inputChannelName); String transport = this.channelBindingServiceProperties.getBinder(inputChannelName); Binder<MessageChannel> binder = binderFactory.getBinder(transport); if (BinderUtils.isChannelPubSub(channelBindingTarget)) { BindingProperties bindingProperties = this.channelBindingServiceProperties.getBindings() .get(inputChannelName); <START> String group = bindingProperties == null ? null : bindingProperties.getGroup(); <END> binder.bindPubSubConsumer(removePrefix(channelBindingTarget), inputChannel, consumerGroup(inputChannelName), this.channelBindingServiceProperties.getConsumerProperties(inputChannelName)); } else { binder.bindConsumer(channelBindingTarget, inputChannel, this.channelBindingServiceProperties.getConsumerProperties(inputChannelName)); } }</code><technical_language>group String is (but consumerGroup() method called repeat properties lookup based channel name, current code is "correct" this line method call is superfluous)</technical_language>

Target:
public void bindConsumer(MessageChannel inputChannel, String inputChannelName) { String channelBindingTarget = this.channelBindingServiceProperties.getBindingDestination(inputChannelName); Binder<MessageChannel> binder = getBinderForChannel(inputChannelName); if (BinderUtils.isChannelPubSub(channelBindingTarget)) { binder.bindPubSubConsumer(removePrefix(channelBindingTarget), inputChannel, consumerGroup(inputChannelName), this.channelBindingServiceProperties.getConsumerProperties(inputChannelName)); } else { binder.bindConsumer(channelBindingTarget, inputChannel, this.channelBindingServiceProperties.getConsumerProperties(inputChannelName)); } }
Source:
<code>private void setTokenRefreshCredentials(LogicalPlan dag, Configuration conf) throws IOException { String principal; String keytab = null; String keytabPath = conf.get(StramClientUtils.KEY_TAB_FILE); if ((principal = StramUserLogin.getPrincipal()) == null) { <START> principal = conf.get(StramUserLogin.DT_AUTH_PRINCIPAL); <END> if (keytabPath == null) { keytab = conf.get(StramUserLogin.DT_AUTH_KEYTAB); } } else { if (keytabPath == null) { keytab = StramUserLogin.getKeytab(); } } if (keytab != null) { Path localKeyTabPath = new Path(keytab); try (FileSystem fs = StramClientUtils.newFileSystemInstance(conf)) { Path destPath = new Path(StramClientUtils.getDTDFSRootDir(fs, conf), localKeyTabPath.getName()); if (!fs.exists(destPath)) { fs.copyFromLocalFile(false, false, localKeyTabPath, destPath); } keytabPath = destPath.toString(); } } if ((principal != null) && (keytabPath != null)) { dag.setAttribute(LogicalPlan.PRINCIPAL, principal); dag.setAttribute(LogicalPlan.KEY_TAB_FILE, keytabPath); } else { LOG.warn("Credentials for refreshing tokens not available, application may not be able to run indefinitely"); } }</code><technical_language>logic get principal keytab encapsulated StramUserLogin? For example: public static String getPrincipal(Configuration conf) { if (principal == null) { principal = conf.get(StramUserLogin.DT_AUTH_PRINCIPAL); } return principal; } public static String getKeytab(Configuration conf) { if (keytab == null) { keytab = conf.get(StramUserLogin.DT_AUTH_KEYTAB); } return keytab; }</technical_language>

Target:
private void setTokenRefreshCredentials(LogicalPlan dag, Configuration conf) throws IOException { String principal = StramUserLogin.getPrincipal(); String keytabPath = conf.get(StramClientUtils.KEY_TAB_FILE); if (keytabPath == null) { String keytab = StramUserLogin.getKeytab(); if (keytab != null) { Path localKeyTabPath = new Path(keytab); try (FileSystem fs = StramClientUtils.newFileSystemInstance(conf)) { Path destPath = new Path(StramClientUtils.getDTDFSRootDir(fs, conf), localKeyTabPath.getName()); if (!fs.exists(destPath)) { fs.copyFromLocalFile(false, false, localKeyTabPath, destPath); } keytabPath = destPath.toString(); } } } if ((principal != null) && (keytabPath != null)) { dag.setAttribute(LogicalPlan.PRINCIPAL, principal); dag.setAttribute(LogicalPlan.KEY_TAB_FILE, keytabPath); } else { LOG.warn("Credentials for refreshing tokens not available, application may not be able to run indefinitely"); } }
Source:
<code>public static String getDepartmentsMapping() throws IOException { <START> InputStream mappingSourceStream = Indexer.class.getResourceAsStream("/search/departments/departments-mapping.json"); <END> String mappingSource = IOUtils.toString(mappingSourceStream); elasticSearchLog("departmentsMapping").addParameter("mappingSource", mappingSource).log(); return mappingSource; }</code><technical_language>this stream in a try-with-resources block? I want leave this open</technical_language>

Target:
public static String getDepartmentsMapping() throws IOException { try (InputStream mappingSourceStream = ZebedeeContentIndexer.class.getResourceAsStream("/search/departments/departments-mapping.json")) { String mappingSource = IOUtils.toString(mappingSourceStream); elasticSearchLog("departmentsMapping").addParameter("mappingSource", mappingSource).log(); return mappingSource; } }
Source:
<code>private String buildShardingKey() { <START> return _clusterName.charAt(0) == '/' ? _clusterName : SLASH + _clusterName; <END> }</code><technical_language>Nit: point declaring SLASH if character counter-part is a local variable</technical_language>

Target:
private String buildShardingKey() { return _clusterName.charAt(0) == '/' ? _clusterName : "/" + _clusterName; }
Source:
<code>public void acknowledge() { if (this.ackClient != null || !this.ackClient.equals(MqttPahoMessageDrivenChannelAdapter.this.client)) { try { this.ackClient.messageArrivedComplete(this.id, this.qos); } catch (MqttException e) { throw new IllegalStateException(e); } } else { <START> throw new IllegalStateException("Client has changed"); <END> } }</code><technical_language>I do care this. self-containing AcknowledgmentImpl client created. If client invalid moment of acknowledge() do anyway. I missing</technical_language>

Target:
public void acknowledge() { if (this.ackClient != null) { try { this.ackClient.messageArrivedComplete(this.id, this.qos); } catch (MqttException e) { throw new IllegalStateException(e); } } else { throw new IllegalStateException("Client has changed"); } }
Source:
<code>public void visitMethodInvocation(MethodInvocationTree tree) { <START> if (isFindMethod(tree) && (slingQueryWasNotUsed() || "$".equals(slingQueryName) || SLING_QUERY.equals(slingQueryName))) { <END> slingQueries.replace(slingQueryName, slingQueryStates.FINDUSED); } else if (isSearchStrategyMethod(tree)) { slingQueries.replace(slingQueryName, slingQueryStates.STRATEGYUSED); } super.visitMethodInvocation(tree); }</code><technical_language>This if statement is long please shorten introducing method for slingQueryWasNotUsed() || "$".equals(slingQueryName) || SLING_QUERY.equals(slingQueryName)</technical_language>

Target:
public void visitMethodInvocation(MethodInvocationTree tree) { if (isFindMethod(tree) && (slingQueryWasNotUsed() || isThisANewSlingQuery())) { slingQueries.replace(currentSlingQueryVariableName, SlingQueryStates.FIND_USED_WITHOUT_STRATEGY); } else if (isSearchStrategyMethod(tree)) { slingQueries.replace(currentSlingQueryVariableName, SlingQueryStates.STRATEGY_USED); ignoreIssues = true; } if (DOLLAR_SIGN.equals(tree.methodSelect().firstToken().text()) && isDollarCase()) { context.reportIssue(this, tree, RULE_MESSAGE); } else if (isFindMethod(tree)) { findMethodUsed = true; } else if (isSearchStrategyMethod(tree)) { searchStrategyMethodUsed = true; } super.visitMethodInvocation(tree); }
Source:
<code><START> public org.eclipse.core.resources.IProject getProject(IReferencePoint referencePoint) { <END> return referencePointToProjectMapper.get(referencePoint); }</code><technical_language>check arguments null in methods below. in other methods (as here)? If check type of variable please introduce a small private method check instead of repeating check multiple times</technical_language>

Target:
public IProject getProject(IReferencePoint referencePoint) { checkArgument(referencePoint, "Reference point is null"); return referencePointToProjectMapper.get(referencePoint); }
Source:
<code>public SamplingDistribution(Operator child, int sampleSize, SamplingType sampleType, Long randomSeed) { this(child, sampleType, randomSeed); this.sampleSize = sampleSize; <START> Preconditions.checkState(this.sampleSize >= 0, <END> "Sample Size must be >= 0: %s", this.sampleSize); }</code><technical_language>Preconditions.checkArgument() form</technical_language>

Target:
public SamplingDistribution(Operator child, int sampleSize, SamplingType sampleType, Long randomSeed) { this(child, sampleType, randomSeed); Preconditions.checkArgument(sampleSize >= 0, "Sample Size must be >= 0: %s", sampleSize); this.sampleSize = sampleSize; }
Source:
<code><START> public Result filterUnitsThatCanMove( <END> final Collection<Unit> units, final Map<Unit, Collection<Unit>> dependentUnits) { final Collection<Unit> transportsToLoad = getPossibleTransportsToLoad(units, dependentUnits, route); List<Unit> best = new ArrayList<>(units); if (route.getStart().isWater() && route.getEnd().isWater() && !route.isLoad()) { best = CollectionUtils.getMatches(best, Matches.unitIsLand().negate()); } if (route.isUnload()) { best = CollectionUtils.getMatches(best, Matches.unitIsNotSea()); } if (!units.isEmpty()) { best.sort(getUnitComparator(best).reversed()); } MoveValidationResultWithDependents lastResult = validateMoveWithDependents(best, dependentUnits, transportsToLoad); final MoveValidationResult allUnitsResult = lastResult.getResult(); if (!allUnitsResult.isMoveValid()) { if (!nonCombat && route.isUnload() && Matches.isTerritoryEnemy(player, data).test(route.getEnd())) { lastResult = validateMoveWithDependents(best, dependentUnits, transportsToLoad); } while (!best.isEmpty() && !lastResult.getResult().isMoveValid()) { best = best.subList(1, best.size()); lastResult = validateMoveWithDependents(best, dependentUnits, transportsToLoad); } } @Nullable String errorMessage = null; @Nullable String warningMessage = null; if (!allUnitsResult.isMoveValid()) { @Nullable String message = allUnitsResult.getError(); if (message == null) { message = allUnitsResult.getDisallowedUnitWarning(0); } if (message == null) { message = allUnitsResult.getUnresolvedUnitWarning(0); } if (!lastResult.getResult().isMoveValid()) { errorMessage = message; } else { warningMessage = message; } } return new Result(lastResult.getUnitsWithDependents(), errorMessage, warningMessage); }</code><technical_language>Method filterUnitsThatCanMove 43 lines of code (exceeds 25 allowed). Consider refactoring</technical_language>

Target:
public FilterOperationResult filterUnitsThatCanMove( final Collection<Unit> units, final Map<Unit, Collection<Unit>> dependentUnits) { final Collection<Unit> transportsToLoad = getPossibleTransportsToLoad(units, dependentUnits, route); List<Unit> best = getInitialUnitList(units); MoveValidationResultWithDependents lastResult = validateMoveWithDependents(best, dependentUnits, transportsToLoad); final MoveValidationResult allUnitsResult = lastResult.getResult(); if (!allUnitsResult.isMoveValid()) { if (!nonCombat && route.isUnload() && Matches.isTerritoryEnemy(player, data).test(route.getEnd())) { best = CollectionUtils.getMatches(best, Matches.unitCanInvade()); lastResult = validateMoveWithDependents(best, dependentUnits, transportsToLoad); } while (!best.isEmpty() && !lastResult.getResult().isMoveValid()) { best = best.subList(1, best.size()); lastResult = validateMoveWithDependents(best, dependentUnits, transportsToLoad); } } return new FilterOperationResult(allUnitsResult, lastResult); }
Source:
<code>public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { try { outputStream.close(); } catch (Exception e) { } } return; } try ( AutoCloseable closeable = () -> IOUtils.copy(inputStream, outputStream) ) { <START> } catch (Exception e) { <END> e.printStackTrace(); } }</code><technical_language>catch exceptions, this user operation failed</technical_language>

Target:
public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); } }
Source:
<code>public static String trl(@NonNull String locale, @NonNull String key, @NonNull Object ... args) { ResourceBundle rb; try { rb = ResourceBundle.getBundle(BASE_NAME, Locale.forLanguageTag(locale)); } catch (MissingResourceException ex) { throw new MissingResourceException("Missing locale '" + locale + "'. class=" + ex.getClassName(), ex.getClassName(), ex.getKey()); } String result; if (rb.containsKey(key)) { result = rb.getString(key); } else { ResourceBundle fallback = ResourceBundle.getBundle(BASE_NAME, Locale.forLanguageTag(FALLBACK_LOCALE)); if (fallback.containsKey(key)) { result = fallback.getString(key); } else { throw new MissingTranslationException("Could not find translation for key '" + key + "' in fallback locale", locale, key); } } for (int i = 0; i != args.length; i++) { result = result.replaceAll("\\{" + i + "\\}", args[i].toString()); } <START> return result; <END> }</code><technical_language>return ChatColor.translateAlternateColorCodes('&',result); do it</technical_language>

Target:
public static String trl(@NonNull String locale, @NonNull String key, @NonNull Object ... args) { ResourceBundle rb = getResource(locale); String result; if (rb.containsKey(key)) { result = rb.getString(key); } else { ResourceBundle fallback = ResourceBundle.getBundle(BASE_NAME, Locale.forLanguageTag(FALLBACK_LOCALE)); if (fallback.containsKey(key)) { result = fallback.getString(key); } else { throw new MissingTranslationException("Could not find translation for key '" + key + "' in fallback locale", locale, key); } } result = result.replaceAll("\\\\&", "\0"); result = ChatColor.translateAlternateColorCodes('&', result); result = result.replaceAll("\0", "&"); for (int i = 0; i != args.length; i++) { result = result.replace("{" + i + "}", args[i].toString()); } return result; }
Source:
<code>public Page<FactoryImpl> getByUser(String userId, int maxItems, long skipCount) { requireNonNull(userId); final Pair<String, String> factoryCreator = Pair.of("creator.userId", userId); <START> long totalCount = countFactoriesByAttributes(singletonList(factoryCreator)); <END> return new Page<>( getFactoriesByAttributes(maxItems, skipCount, singletonList(factoryCreator)), skipCount, maxItems, totalCount); }</code><technical_language>I runtime exception thrown entity manager of countFactoriesByAttributes method. mapped ServerException IS NOT. I right</technical_language>

Target:
public Page<FactoryImpl> getByUser(String userId, int maxItems, long skipCount) throws ServerException { requireNonNull(userId); final Pair<String, String> factoryCreator = Pair.of("creator.userId", userId); try { long totalCount = countFactoriesByAttributes(singletonList(factoryCreator)); return new Page<>( getFactoriesByAttributes(maxItems, skipCount, singletonList(factoryCreator)), skipCount, maxItems, totalCount); } catch (RuntimeException ex) { throw new ServerException(ex.getMessage(), ex); } }
Source:
<code>public void shouldUseMergeFunctionToHandleKeysCollisions() { final Seq<Tuple2<String, Integer>> input = Vector.of(Tuple.of("a",2), Tuple.of("a",55), Tuple.of("a",3), Tuple.of("b",2)); Map<String, Seq<Integer>> m = input.toMap( Tuple2::_1, t -> Vector.of(t._2), Seq::appendAll); assertThat(m.containsKey("a")).isTrue(); assertThat(m.get("a").get().size()).isEqualTo(3); assertThat(m.containsKey("b")).isTrue(); assertThat(m.get("b").get().size()).isEqualTo(1); Map<String, Integer> m1 = input.toMap( Tuple2::_1, Tuple2::_2, Integer::sum); assertThat(m1.containsKey("a")).isTrue(); assertThat(m1.get("a").get()).isEqualTo(60); assertThat(m1.containsKey("b")).isTrue(); assertThat(m1.get("b").get()).isEqualTo(2); Map<String, Integer> m2 = input.toMap( Function.identity(), Integer::sum); assertThat(m2.containsKey("a")).isTrue(); assertThat(m2.get("a").get()).isEqualTo(60); assertThat(m2.containsKey("b")).isTrue(); assertThat(m2.get("b").get()).isEqualTo(2); <START> } <END></code><technical_language>Please test m. m2 is obsolete (see above) m1 bring new table</technical_language>

Target:
public void shouldUseMergeFunctionToHandleKeysCollisions() { final Seq<Tuple2<String, Integer>> input = Vector.of(Tuple.of("a",2), Tuple.of("a",55), Tuple.of("a",3), Tuple.of("b",2)); Map<String, Seq<Integer>> m = input.toMap( Tuple2::_1, t -> Vector.of(t._2), Seq::appendAll); assertThat(m.containsKey("a")).isTrue(); assertThat(m.get("a").get().size()).isEqualTo(3); assertThat(m.containsKey("b")).isTrue(); assertThat(m.get("b").get().size()).isEqualTo(1); }
Source:
<code>private static int determineMajorJavaVersion() { int version = (int) Double.parseDouble(System.getProperty("java.class.version")); switch (version) { case 46: return 2; case 47: return 3; case 48: return 4; <START> case 49: return 5; <END> case 50: return 6; case 51: return 7; case 52: return 8; case 53: return 9; case 54: return 10; case 55: return 11; default: return 6; } }</code><technical_language>Gson run versions I reason include them</technical_language>

Target:
private static int determineMajorJavaVersion() { int version = (int) Double.parseDouble(System.getProperty("java.class.version")); switch (version) { case 50: return 6; case 51: return 7; case 52: return 8; case 53: return 9; case 54: return 10; case 55: return 11; default: return 6; } }
Source:
<code>public FeedbackQuestionAttributes(FeedbackQuestion fq) { this.feedbackQuestionId = fq.getId(); this.feedbackSessionName = fq.getFeedbackSessionName(); this.courseId = fq.getCourseId(); this.creatorEmail = fq.getCreatorEmail(); this.questionMetaData = fq.getQuestionMetaData(); this.questionNumber = fq.getQuestionNumber(); this.questionType = fq.getQuestionType(); <START> this.questionIsCompulsory = fq.isQuestionIsCompulsory(); <END> this.giverType = fq.getGiverType(); this.recipientType = fq.getRecipientType(); this.numberOfEntitiesToGiveFeedbackTo = fq.getNumberOfEntitiesToGiveFeedbackTo(); this.showResponsesTo = new ArrayList<FeedbackParticipantType>(fq.getShowResponsesTo()); this.showGiverNameTo = new ArrayList<FeedbackParticipantType>(fq.getShowGiverNameTo()); this.showRecipientNameTo = new ArrayList<FeedbackParticipantType>(fq.getShowRecipientNameTo()); this.createdAt = fq.getCreatedAt(); this.updatedAt = fq.getUpdatedAt(); removeIrrelevantVisibilityOptions(); }</code><technical_language>This existing questions throw error loaded. need handle cases new field is present in datastore</technical_language>

Target:
public FeedbackQuestionAttributes(FeedbackQuestion fq) { this.feedbackQuestionId = fq.getId(); this.feedbackSessionName = fq.getFeedbackSessionName(); this.courseId = fq.getCourseId(); this.creatorEmail = fq.getCreatorEmail(); this.questionMetaData = fq.getQuestionMetaData(); this.questionNumber = fq.getQuestionNumber(); this.questionType = fq.getQuestionType(); this.isQuestionCompulsory = fq.isQuestionCompulsory(); this.giverType = fq.getGiverType(); this.recipientType = fq.getRecipientType(); this.numberOfEntitiesToGiveFeedbackTo = fq.getNumberOfEntitiesToGiveFeedbackTo(); this.showResponsesTo = new ArrayList<FeedbackParticipantType>(fq.getShowResponsesTo()); this.showGiverNameTo = new ArrayList<FeedbackParticipantType>(fq.getShowGiverNameTo()); this.showRecipientNameTo = new ArrayList<FeedbackParticipantType>(fq.getShowRecipientNameTo()); this.createdAt = fq.getCreatedAt(); this.updatedAt = fq.getUpdatedAt(); removeIrrelevantVisibilityOptions(); }
Source:
<code>public void removePaymentAccount(String id) { PaymentAccount paymentAccount = user.getPaymentAccount(id); if (paymentAccount == null) { throw new NotFoundException(format("Payment account %s not found", id)); } boolean isPaymentAccountUsed = openOfferManager.getObservableList().stream() .anyMatch(openOffer -> id.equals(openOffer.getOffer().getMakerPaymentAccountId())); if (isPaymentAccountUsed) { <START> throw new PaymentAccountInUseException(format("Payment account %s is used for open offer", id)); <END> } isPaymentAccountUsed = tradeManager.getTradableList().stream() .anyMatch(trade -> { Offer offer = trade.getOffer(); return null != offer && id.equals(offer.getMakerPaymentAccountId()) || id.equals(trade.getTakerPaymentAccountId()); }); if (isPaymentAccountUsed) { throw new PaymentAccountInUseException(format("Payment account %s is used for open trade", id)); } user.removePaymentAccount(paymentAccount); }</code><technical_language>I prefer exceptions in exceptional cases in valid case (user remove account app allow in trades offers). refactor check out 'canRemove()' method call method if is allowed remove</technical_language>

Target:
public boolean removePaymentAccount(String id) { PaymentAccount paymentAccount = user.getPaymentAccount(id); if (paymentAccount == null) { throw new NotFoundException(format("Payment account %s not found", id)); } return removePaymentAccount(paymentAccount); }
Source:
<code>StreamProcessor createStreamProcessor(Config config, ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc, StreamProcessor.StreamProcessorLifecycleListenerFactory listenerFactory, Optional<ExternalContext> externalContextOptional) { TaskFactory taskFactory = TaskFactoryUtil.getTaskFactory(appDesc); Map<String, MetricsReporter> reporters = new HashMap<>(); <START> String processorId = createProcessorId(new ApplicationConfig(config)); <END> appDesc.getMetricsReporterFactories().forEach((name, factory) -> reporters.put(name, factory.getMetricsReporter(name, processorId, config))); return new StreamProcessor(config, processorId, reporters, taskFactory, appDesc.getApplicationContainerContextFactory(), appDesc.getApplicationTaskContextFactory(), externalContextOptional, listenerFactory, null); }</code><technical_language>Please get a review @atoomula check if of changes affect BrooklinStreamProcessor</technical_language>

Target:
StreamProcessor createStreamProcessor(Config config, ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc, StreamProcessor.StreamProcessorLifecycleListenerFactory listenerFactory, Optional<ExternalContext> externalContextOptional) { TaskFactory taskFactory = TaskFactoryUtil.getTaskFactory(appDesc); Map<String, MetricsReporter> reporters = new HashMap<>(); String processorId = createProcessorId(new ApplicationConfig(config)); appDesc.getMetricsReporterFactories().forEach((name, factory) -> reporters.put(name, factory.getMetricsReporter(name, processorId, config))); return new StreamProcessor(processorId, config, reporters, taskFactory, appDesc.getApplicationContainerContextFactory(), appDesc.getApplicationTaskContextFactory(), externalContextOptional, listenerFactory, null); }