auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean isRunningInAuthProcess() { try { String procName = ""; int pid = android.os.Process.myPid(); final ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); final List<RunningAppProcessInfo> processInfos = manager.getRunningAppProcesses(); if (processInfos != null) { for (final RunningAppProcessInfo procInfo : processInfos) { if (procInfo != null && procInfo.pid == pid) { <START> procName = procInfo.processName; <END> } } } if (procName.endsWith(":auth")) { return true; } } catch (Exception e) { Log.e("SalesforceSDKManager:isRunningInAuthProcess", "Exception occurred while getting process name.", e); } return false; }</code><technical_language>break here</technical_language>

Target:
private boolean isRunningInAuthProcess() { try { String procName = ""; int pid = android.os.Process.myPid(); final ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); final List<RunningAppProcessInfo> processInfos = manager.getRunningAppProcesses(); if (processInfos != null) { for (final RunningAppProcessInfo procInfo : processInfos) { if (procInfo != null && procInfo.pid == pid) { procName = procInfo.processName; break; } } } if (procName.endsWith(":auth")) { return true; } } catch (Exception e) { Log.e("SalesforceSDKManager:isRunningInAuthProcess", "Exception occurred while getting process name.", e); } return false; }
Source:
<code>public int hashCode() { int result = _networkDomainUuid != null ? _networkDomainUuid.hashCode() : 0; result = 31 * result + (_networkUuid != null ? _networkUuid.hashCode() : 0); result = 31 * result + (_vpcOrSubnetUuid != null ? _vpcOrSubnetUuid.hashCode() : 0); result = 31 * result + (_isL3Network ? 1 : 0); result = 31 * result + (_isVpc ? 1 : 0); result = 31 * result + (_staticNatDetails != null ? _staticNatDetails.hashCode() : 0); return result; <START> } <END></code><technical_language>Please implement toString() provide debugging state information for debugging purposes</technical_language>

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (_networkDomainUuid != null ? _networkDomainUuid.hashCode() : 0); result = 31 * result + (_networkUuid != null ? _networkUuid.hashCode() : 0); result = 31 * result + (_vpcOrSubnetUuid != null ? _vpcOrSubnetUuid.hashCode() : 0); result = 31 * result + (_isL3Network ? 1 : 0); result = 31 * result + (_isVpc ? 1 : 0); result = 31 * result + (_staticNatDetails != null ? _staticNatDetails.hashCode() : 0); return result; }
Source:
<code>protected Connection compute() { try { builder.connectionFactory.setBrokerURL("failover:("+builder.addresses+")?initialReconnectDelay=100"); connection = builder.connectionFactory.createConnection(); Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); Destination destination = session.createQueue(builder.queue); MessageConsumer messageConsumer = session.createConsumer(destination); Collector collector = builder.delegate.build(); CollectorMetrics metrics = builder.metrics; messageConsumer.setMessageListener(new ActiveMQSpanConsumerMessageListener(collector,metrics)); <START> }catch (Exception e){ <END> throw new IllegalStateException("Unable to establish connection to ActiveMQ server", e); } return connection; }</code><technical_language>multi-catch for is thrown, literally Exception is thrown</technical_language>

Target:
protected Connection compute() { try { builder.connectionFactory.setBrokerURL("failover:("+builder.addresses+")?initialReconnectDelay=100&maxReconnectAttempts=10"); connection = builder.connectionFactory.createConnection(); connection.start(); Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(builder.queue); MessageConsumer messageConsumer = session.createConsumer(destination); Collector collector = builder.delegate.build(); CollectorMetrics metrics = builder.metrics; messageConsumer.setMessageListener(new ActiveMQSpanConsumerMessageListener(collector,metrics)); }catch (JMSException e){ throw new IllegalStateException("Unable to establish connection to ActiveMQ server", e); } return connection; }
Source:
<code>public TermFilter(final String term, final Integer minShouldMatch, final boolean fuzzy, final boolean exact, final boolean parsed) { <START> this.term = term; <END> this.minShouldMatch = minShouldMatch; this.fuzzy = fuzzy; this.exact = exact; this.parsed = parsed; }</code><technical_language>Trim incoming term remove custom trimming concrete search request implementations</technical_language>

Target:
public TermFilter(final String term, final Integer minShouldMatch, final boolean fuzzy, final boolean exact, final boolean parsed) { if (term == null) { throw new BadRequestException("'term' filter parameter was null."); } this.term = term.trim(); this.minShouldMatch = minShouldMatch; this.fuzzy = fuzzy; this.exact = exact; this.parsed = parsed; }
Source:
<code>public CircleMenu(Block block) { super((StackPane) block, null); this.block = block; ImageView image = new ImageView(new Image(this.getClass().getResourceAsStream("/ui/cut32.png"))); image.getStyleClass().add("hoverMenu"); <START> MenuItem delete = new MenuItem("cut", image); <END> delete.setOnAction(t -> delete()); image = new ImageView(new Image(this.getClass().getResourceAsStream("/ui/copy32.png"))); image.getStyleClass().add("hoverMenu"); MenuItem copy = new MenuItem("copy", image); copy.setOnAction(t -> copy()); image = new ImageView(new Image(this.getClass().getResourceAsStream("/ui/paste32.png"))); image.getStyleClass().add("hoverMenu"); MenuItem paste = new MenuItem("paste", image); paste.setOnAction(t -> paste()); image = new ImageView(new Image(this.getClass().getResourceAsStream("/ui/save32.png"))); image.getStyleClass().add("hoverMenu"); MenuItem save = new MenuItem("save", image); save.setOnAction(t -> saveBlock()); this.getItems().addAll(copy, paste, delete, save); this.setAnimationInterpolation(CircularPane::animateOverTheArcWithFade); this.setAnimationDuration(Duration.ONE); }</code><technical_language>refactor this a private static ImageView makeImageView(String path) factory method</technical_language>

Target:
public CircleMenu(Block block) { super((StackPane) block, null); this.block = block; ImageView image = makeImageView("/ui/cut32.png"); MenuItem delete = new MenuItem("cut", image); delete.setOnAction(t -> delete()); image = makeImageView("/ui/copy32.png"); MenuItem copy = new MenuItem("copy", image); copy.setOnAction(t -> copy()); image = makeImageView("/ui/paste32.png"); MenuItem paste = new MenuItem("paste", image); paste.setOnAction(t -> paste()); image = makeImageView("/ui/save32.png"); MenuItem save = new MenuItem("save", image); save.setOnAction(t -> saveBlock()); this.getItems().addAll(copy, paste, delete, save); this.setAnimationInterpolation(CircularPane::animateOverTheArcWithFade); this.setAnimationDuration(Duration.ONE); }
Source:
<code>public void generateRequest(final Ds3Request ds3Request) throws IOException, TemplateException { Template requestTemplate = null; Request request = null; System.out.println("Generating Request[" + ds3Request.getName() + "]"); if (ds3Request.getClassification() == Classification.amazons3) { request = RequestConverter.toRequest(ds3Request); System.out.println("Loading template AmazonS3InitRequestHandler.tmplt"); requestTemplate = config.getTemplate("AmazonS3InitRequestHandler.tmplt"); System.out.println("Template loaded!"); } else if (ds3Request.getClassification() == Classification.spectrads3) { System.out.println("AmazonS3 request"); } else if (ds3Request.getClassification() == Classification.spectrainternal) { System.out.println("Spectra internal request"); } else { throw new TemplateException("Unknown dDs3Request Classification: " + ds3Request.getClassification().toString(), Environment.getCurrentEnvironment()); } final Path outputPath = getOutputPath(request); System.out.println("outputPath[" + outputPath.toString() + "]"); final OutputStream outStream = fileUtils.getOutputFile(outputPath); final Writer writer = new OutputStreamWriter(outStream); try { requestTemplate.process(request, writer); <START> } catch ( NullPointerException e) { <END> System.out.println("Encountered NullPointerException while processing template " + requestTemplate.getName()); e.printStackTrace(); } }</code><technical_language>missing final</technical_language>

Target:
public void generateRequest(final Ds3Request ds3Request) throws IOException, TemplateException { Template requestTemplate = null; Request request = null; if (ds3Request.getClassification() == Classification.amazons3) { request = RequestConverter.toRequest(ds3Request); System.out.println("Loading template AmazonS3InitRequestHandler.tmplt"); requestTemplate = config.getTemplate("AmazonS3InitRequestHandler.tmplt"); System.out.println("Template loaded!"); } else if (ds3Request.getClassification() == Classification.spectrads3) { System.out.println("AmazonS3 request"); } else if (ds3Request.getClassification() == Classification.spectrainternal) { System.out.println("Spectra internal request"); } else { throw new TemplateException("Unknown dDs3Request Classification: " + ds3Request.getClassification().toString(), Environment.getCurrentEnvironment()); } final Path outputPath = getOutputPath(request); final OutputStream outStream = fileUtils.getOutputFile(outputPath); final Writer writer = new OutputStreamWriter(outStream); try { requestTemplate.process(request, writer); } catch (final NullPointerException e) { System.out.println("Encountered NullPointerException while processing template " + requestTemplate.getName()); e.printStackTrace(); } }
Source:
<code>keyExtractor(Function<IStatistics<@NonNull ISegment>, E> segExtractor, Function<M, E> modelExtractor) { return new Function<TmfTreeViewerEntry, E>() { @Override public E apply(TmfTreeViewerEntry entry) { if (entry instanceof SegmentStoreStatisticsEntry) { return segExtractor.apply(((SegmentStoreStatisticsEntry) entry).getEntry()); } else if (entry instanceof TmfGenericTreeEntry) { return modelExtractor.apply(((TmfGenericTreeEntry<M>) entry).getModel()); } <START> return (E) UNCOMPARABLE; <END> } }; }</code><technical_language>Try: return (E) (Comparable<E>) o -> 0;</technical_language>

Target:
keyExtractor(Function<IStatistics<@NonNull ISegment>, E> segExtractor, Function<M, E> modelExtractor) { return new Function<TmfTreeViewerEntry, E>() { @Override public E apply(TmfTreeViewerEntry entry) { if (entry instanceof SegmentStoreStatisticsEntry) { return segExtractor.apply(((SegmentStoreStatisticsEntry) entry).getEntry()); } else if (entry instanceof TmfGenericTreeEntry) { return modelExtractor.apply(((TmfGenericTreeEntry<M>) entry).getModel()); } return (E) (Comparable<E>) o -> 0; } }; }
Source:
<code>public boolean syncDiskCheck(final CacheKey key){ <START> if(containsSync(key)){ <END> return true; } EncodedImage result = mStagingArea.get(key); if (result != null) { result.close(); FLog.v(TAG, "Found image for %s in staging area", key.toString()); mImageCacheStatsTracker.onStagingAreaHit(); return true; } else { FLog.v(TAG, "Did not find image for %s in staging area", key.toString()); mImageCacheStatsTracker.onStagingAreaMiss(); try { return mFileCache.hasKey(key); } catch (Exception exception) { return false; } } }</code><technical_language>Space missing opening bracket</technical_language>

Target:
public boolean syncDiskCheck(final CacheKey key) { if(containsSync(key)) { return true; } return checkInStagingAreaAndFileCache(key); }
Source:
<code>public void setOldClusterVersionOfSnapshotWithMemory(VM vm) { if (!isVMWithMemoryCompatible(vm)) { Version originalClusterVersion = vm.getClusterCompatibilityVersionOrigin(); originalClusterVersion = (originalClusterVersion == null) ? <START> Version.v4_2 : <END> originalClusterVersion; oldClusterVersionOfSnapshotWithMemory = originalClusterVersion; } else { oldClusterVersionOfSnapshotWithMemory = null; } }</code><technical_language>Version.getLowest() instead of changing this line time a version stops supported</technical_language>

Target:
public void setOldClusterVersionOfSnapshotWithMemory(VM vm) { if (!isVMWithMemoryCompatible(vm)) { Version originalClusterVersion = vm.getClusterCompatibilityVersionOrigin(); originalClusterVersion = (originalClusterVersion == null) ? Version.getLowest() : originalClusterVersion; oldClusterVersionOfSnapshotWithMemory = originalClusterVersion; } else { oldClusterVersionOfSnapshotWithMemory = null; } }
Source:
<code>private void populateViews(final View view, final AssignmentAward award) { final String titleString = getString(AssignmentStringMap.get(assignmentAward.getUniqueName())); TextView titleView = ((TextView) view.findViewById(R.id.title)); setTitle(titleView, titleString); populateOverviewBox(view, award); if (assignment.getPrerequisites().size() > 0) { populatePreRequisites(view); populateAwardRequirements(view); populateRewardBox(view); } else { final ViewGroup containerView = (ViewGroup) view.findViewById(R.id.assignment_prereq_container); containerView.removeAllViews(); final View tempView = layoutInflater.inflate(R.layout.list_item_assignment_prereq, containerView, false); <START> containerView.addView(populatePreRequisite(tempView, fetchPrerequisiteForExpansion())); <END> view.findViewById(R.id.wrap_assignment_tasks).setVisibility(View.GONE); view.findViewById(R.id.wrap_assignment_rewards).setVisibility(View.GONE); } }</code><technical_language>This a NPE in fetchPrerequisiteForExpansion() due assignmentAward.getExpansionPack() null for single-player. :-( Previously, called fetchPrerequisiteForExpansion() checking assignmentAward.hasExpansionPack() is true</technical_language>

Target:
private void populateViews(final View view, final AssignmentAward award) { final String titleString = getString(AssignmentStringMap.get(assignmentAward.getUniqueName())); TextView titleView = ((TextView) view.findViewById(R.id.title)); setTitle(titleView, titleString); populateOverviewBox(view, award); if (assignment.getPrerequisites().size() > 0) { populatePreRequisites(view); populateAwardRequirements(view); populateRewardBox(view); } else if(assignmentAward.getCode().startsWith("SP_")) { view.findViewById(R.id.wrap_assignment_prereq).setVisibility(View.GONE); populateAwardRequirements(view); populateRewardBox(view); } else { final ViewGroup containerView = (ViewGroup) view.findViewById(R.id.assignment_prereq_container); containerView.removeAllViews(); final View tempView = layoutInflater.inflate(R.layout.list_item_assignment_prereq, containerView, false); containerView.addView(populatePreRequisite(tempView, fetchPrerequisiteForExpansion())); view.findViewById(R.id.wrap_assignment_tasks).setVisibility(View.GONE); view.findViewById(R.id.wrap_assignment_rewards).setVisibility(View.GONE); } }
Source:
<code>public void testQueryMaxSpillPerNodeLimit() throws Exception { Map<String, String> properties = ImmutableMap.<String, String>builder() .put("experimental.spiller-spill-path", spillPath.getAbsolutePath()) .put("experimental.spill-enabled", "true") .put("experimental.operator-memory-limit-before-spill", "1B") .put("experimental.query-max-spill-per-node", "10B") .put("experimental.spiller-max-used-space-threshold", "1.0") .build(); <START> try (QueryRunner queryRunner = createLocalQueryRunner( <END> new NodeSpillConfig().setQueryMaxSpillPerNode(DataSize.succinctBytes(10)))) { queryRunner.execute(queryRunner.getDefaultSession(), "SELECT COUNT(DISTINCT clerk) as count, orderdate FROM orders GROUP BY orderdate ORDER BY count, orderdate"); } }</code><technical_language>need wrap</technical_language>

Target:
public void testQueryMaxSpillPerNodeLimit() throws Exception { Map<String, String> properties = ImmutableMap.<String, String>builder() .put("experimental.spiller-spill-path", spillPath.getAbsolutePath()) .put("experimental.spill-enabled", "true") .put("experimental.aggregation-operator-unspill-memory-limit", "1B") .put("experimental.query-max-spill-per-node", "10B") .put("experimental.spiller-max-used-space-threshold", "1.0") .build(); try (QueryRunner queryRunner = createLocalQueryRunner(new NodeSpillConfig().setQueryMaxSpillPerNode(DataSize.succinctBytes(10)))) { queryRunner.execute(queryRunner.getDefaultSession(), "SELECT COUNT(DISTINCT clerk) as count, orderdate FROM orders GROUP BY orderdate ORDER BY count, orderdate"); } }
Source:
<code>static void writeConfiguration(XMLExtendedStreamWriter writer, ModelNode config) throws XMLStreamException { for (AttributeDefinition def : ModClusterConfigResourceDefinition.ATTRIBUTES) { <START> if (def instanceof StringListAttributeDefinition) { <END> def.getAttributeMarshaller().marshallAsAttribute(def, config, false, writer); } else { def.getAttributeMarshaller().marshallAsAttribute(def, config, true, writer); } } }</code><technical_language>conditional marshalling here? use: def.getAttributeMarshaller().marshallAsAttribute(def, config, false, writer); ? Marshalling behavior encapsulated AttributeMarshaller implementation. Otherwise, encapsulation is broken</technical_language>

Target:
static void writeConfiguration(XMLExtendedStreamWriter writer, ModelNode config) throws XMLStreamException { for (AttributeDefinition def : ModClusterConfigResourceDefinition.ATTRIBUTES) { def.getAttributeMarshaller().marshallAsAttribute(def, config, true, writer); } }
Source:
<code>private void readInternal() throws IOException { while (next == 0) { byte[] header = new byte[8]; int todo = 8; while (todo > 0) { int i = multiplexed.read(header, 8-todo, todo); if (i < 0) return; todo -= i; } int size = ((header[4] & 0xff) << 24) + ((header[5] & 0xff) << 16) + ((header[6] & 0xff) << 8) + (header[7] & 0xff); switch (header[0]) { case 1: next = size; break; case 2: byte[] payload = new byte[size]; int received = 0; while (received < size) { int i = multiplexed.read(payload, received, size - received); <START> if (i < 0) return; END> received += i; } System.err.println(new String(payload, StandardCharsets.UTF_8)); break; default: throw new IOException("Unexpected application/vnd.docker.raw-stream frame type " + header); } } }</code><technical_language>convinced this is correct handling of this case. correct this case handled, if simply exit this point, discarding partially-received stderr message - output received (and complain ended early)</technical_language>

Target:
private void readInternal() throws IOException { while (next == 0) { byte[] header = new byte[8]; int todo = 8; while (todo > 0) { int i = multiplexed.read(header, 8-todo, todo); if (i < 0) return; todo -= i; } int size = ((header[4] & 0xff) << 24) + ((header[5] & 0xff) << 16) + ((header[6] & 0xff) << 8) + (header[7] & 0xff); switch (header[0]) { case 1: next = size; break; case 2: byte[] payload = new byte[size]; int received = 0; while (received < size) { int i = multiplexed.read(payload, received, size - received); if (i < 0) break; received += i; } LOGGER.warn("Unexpected data on container stderr: {}", new String(payload, 0, received, StandardCharsets.UTF_8)); break; default: throw new IOException("Unexpected application/vnd.docker.raw-stream frame type " + header); } } }
Source:
<code>private void updateGraphicsDevices() { <START> final Set<Map.Entry<GraphicsType, <END> GraphicsDevice>> graphicalDevicesSet = getParameters().getGraphicsDevices().entrySet(); final ArrayList<Map.Entry<GraphicsType, GraphicsDevice>> nullFirstGraphicalDevices = new ArrayList<>(graphicalDevicesSet); nullFirstGraphicalDevices.sort(getNullValueFirstComparator()); for (Map.Entry<GraphicsType, GraphicsDevice> entry : nullFirstGraphicalDevices) { updateGraphicsDevice(entry.getKey()); } }</code><technical_language>convention is set variables 'final' need it, please remove</technical_language>

Target:
private void updateGraphicsDevices() { final Set<Map.Entry<GraphicsType, GraphicsDevice>> graphicalDevicesSet = getParameters().getGraphicsDevices().entrySet(); for (Map.Entry<GraphicsType, GraphicsDevice> entry : graphicalDevicesSet) { if (entry.getValue() == null) { updateGraphicsDevice(entry.getKey()); } } for (Map.Entry<GraphicsType, GraphicsDevice> entry : graphicalDevicesSet) { if (entry.getValue() != null) { updateGraphicsDevice(entry.getKey()); } } }
Source:
<code>public StudyParticipant getParticipant(Study study, Account account, boolean includeHistory) { if (account == null) { LOG.error("getParticipant() called with no account. Was the account deleted in the middle of the call?"); throw new EntityNotFoundException(Account.class); } if (BridgeUtils.filterForSubstudy(account) == null) { throw new EntityNotFoundException(Account.class); } StudyParticipant.Builder builder = new StudyParticipant.Builder(); SubstudyAssociations assoc = BridgeUtils.substudyAssociationsVisibleToCaller(account.getAccountSubstudies()); addAccount(builder, assoc, account); CriteriaContext.Builder contextBuilder = new CriteriaContext.Builder(); contextBuilder.withStudyIdentifier(study.getStudyIdentifier()); contextBuilder.withUserId(account.getId()); contextBuilder.withHealthCode(account.getHealthCode()); contextBuilder.withUserDataGroups(account.getDataGroups()); <START> contextBuilder.withUserSubstudyIds(assoc.getSubstudyIdsVisibleToCaller()); <END> RequestInfo requestInfo = cacheProvider.getRequestInfo(account.getId()); if (requestInfo != null) { contextBuilder.withClientInfo(requestInfo.getClientInfo()); contextBuilder.withLanguages(requestInfo.getLanguages()); } CriteriaContext context = contextBuilder.build(); if (includeHistory) { addHistory(builder, account, context); } if (requestInfo != null) { addConsentStatus(builder, account, context); } return builder.build(); }</code><technical_language>addHistory() need context, include this in if (requestInfo != null) below? This code simpler reduces amount of code churn</technical_language>

Target:
public StudyParticipant getParticipant(Study study, Account account, boolean includeHistory) { if (account == null) { LOG.error("getParticipant() called with no account. Was the account deleted in the middle of the call?"); throw new EntityNotFoundException(Account.class); } if (BridgeUtils.filterForSubstudy(account) == null) { throw new EntityNotFoundException(Account.class); } StudyParticipant.Builder builder = new StudyParticipant.Builder(); SubstudyAssociations assoc = BridgeUtils.substudyAssociationsVisibleToCaller(account.getAccountSubstudies()); addAccount(builder, assoc, account); if (includeHistory) { addHistory(builder, account, study.getStudyIdentifier()); } RequestInfo requestInfo = cacheProvider.getRequestInfo(account.getId()); if (requestInfo != null) { CriteriaContext context = new CriteriaContext.Builder() .withStudyIdentifier(study.getStudyIdentifier()) .withUserId(account.getId()) .withHealthCode(account.getHealthCode()) .withUserDataGroups(account.getDataGroups()) .withUserSubstudyIds(assoc.getSubstudyIdsVisibleToCaller()) .withClientInfo(requestInfo.getClientInfo()) .withLanguages(requestInfo.getLanguages()).build(); addConsentStatus(builder, account, context); } return builder.build(); }
Source:
<code>public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); if (value.isDefined()) { final String suffix = value.asString(); try { String suffixToCheck = suffix.replaceAll("'([^']*?)'", ""); <START> if (denySeconds && (suffixToCheck.contains("s") || suffixToCheck.contains("S"))) { <END> throw ElytronSubsystemMessages.ROOT_LOGGER.suffixContainsMillis(suffix); } DateTimeFormatter.ofPattern(suffix); } catch (IllegalArgumentException e) { throw ElytronSubsystemMessages.ROOT_LOGGER.invalidSuffix(suffix); } } }</code><technical_language>a huge deal this is invoked perform a bit better. java for (int i = 0; i < suffix.length(); i++) { char c = suffix.charAt(i); if (c == '\'') { c = suffix.charAt(++i); while (c != '\'') { c = suffix.charAt(++i); } } if (c == 's' || c == 'S') { throw ElytronSubsystemMessages.ROOT_LOGGER.suffixContainsMillis(suffix); } } denySeconds checked regex string. This is change in other validators, logging subsystem management audit logging, well. fixing other in a separate PR making issue more generic fixing in PR</technical_language>

Target:
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); if (value.isDefined()) { final String suffix = value.asString(); try { DateTimeFormatter.ofPattern(suffix); if (denySeconds) { for (int i = 0; i < suffix.length(); i++) { char c = suffix.charAt(i); if (c == '\'') { c = suffix.charAt(++i); while (c != '\'') { c = suffix.charAt(++i); } } if (c == 's' || c == 'S') { throw ElytronSubsystemMessages.ROOT_LOGGER.suffixContainsMillis(suffix); } } } } catch (IllegalArgumentException e) { throw ElytronSubsystemMessages.ROOT_LOGGER.invalidSuffix(suffix); } } }
Source:
<code>public TranslatedExpression<T> visitCall(CallExpression call, C context) { Optional<TranslatedExpression<T>> defaultTranslated = rowExpressionTranslator.translateCall(call, context, RowExpressionTreeTranslator.this); <START> if (defaultTranslated.isPresent()) { <END> return defaultTranslated.get(); } List<TranslatedExpression<T>> translatedArguments = call.getArguments().stream() .map(expression -> expression.accept(this, context)) .collect(Collectors.toList()); Optional<T> result = rowExpressionTranslator.translateCall(call.getFunctionHandle(), translatedArguments, context); return new TranslatedExpression<>(result, call, translatedArguments); }</code><technical_language>nit: return defaultTranslated.orElse(...);</technical_language>

Target:
public TranslatedExpression<T> visitCall(CallExpression call, C context) { return rowExpressionTranslator.translateCall(call, context, RowExpressionTreeTranslator.this); }
Source:
<code>public int getPointAreaWidth() { IAxis[] xAxes = getSwtChart().getAxisSet().getXAxes(); ISeries[] series = fSwtChart.getSeriesSet().getSeries(); if ((xAxes.length > 0) && (series.length > 0) && (series[0].getXSeries() != null) && (series[0].getXSeries().length > 0)) { IAxis axis = xAxes[0]; double[] xSeries = series[0].getXSeries(); <START> double maxx = Double.MIN_VALUE; <END> for (double x : xSeries) { if (maxx < x) { maxx = x; } } int x1 = getPointAreaOffset(); int x2 = axis.getPixelCoordinate(maxx); x2 = getSwtChart().toControl(getSwtChart().getPlotArea().toDisplay(x2, 0)).x; int width = x2 - x1; return width; } return getSwtChart().getPlotArea().getSize().x; }</code><technical_language>this maxX</technical_language>

Target:
public int getPointAreaWidth() { IAxis[] xAxes = getSwtChart().getAxisSet().getXAxes(); ISeries[] series = fSwtChart.getSeriesSet().getSeries(); if ((xAxes.length > 0) && (series.length > 0) && (series[0].getXSeries() != null) && (series[0].getXSeries().length > 0)) { IAxis axis = xAxes[0]; double[] xSeries = series[0].getXSeries(); double maxX = Double.MIN_VALUE; for (double x : xSeries) { if (maxX < x) { maxX = x; } } int x1 = getPointAreaOffset(); int x2 = axis.getPixelCoordinate(maxX); x2 = getSwtChart().toControl(getSwtChart().getPlotArea().toDisplay(x2, 0)).x; int width = x2 - x1; return width; } return getSwtChart().getPlotArea().getSize().x; }
Source:
<code>protected void configureServlets() { serve("/say-hello").with(HelloWorldServlet.class); <START> serve("/say-hello/*").with(HelloWorldServlet.class); <END> }</code><technical_language>bindings</technical_language>

Target:
protected void configureServlets() { serve("/say-hello/*").with(HelloWorldServlet.class); }
Source:
<code>public static Configuration get() { <START> return conf; <END> }</code><technical_language>Configuration is mutable safer return a new instance here. Global mutable state is a recipe for hard-to-diagnose bugs</technical_language>

Target:
public static Configuration get() { return new Configuration(conf); }
Source:
<code>private void setAuthMechanism(String mechanism, Authorization authorization) { <START> switch (mechanism) { <END> case "basic": authorization.setMechanism(Mechanism.BASIC); break; case "digest": authorization.setMechanism(Mechanism.DIGEST); break; default: break; } }</code><technical_language>if a user calls this method "BASIC"? Is this error</technical_language>

Target:
private void setAuthMechanism(String mechanism, Authorization authorization) { switch (mechanism.toLowerCase()) { case "basic": authorization.setMechanism(Mechanism.BASIC); break; case "digest": authorization.setMechanism(Mechanism.DIGEST); break; default: break; } }
Source:
<code>protected void executeVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getParameters().getInterface().getType()).getDescription()).toString()); this.setVmName(getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); if (StringUtils.isEmpty(getMacAddress())) { getParameters().getInterface().setMacAddress(MacPoolManager.getInstance().allocateNewMac()); } getParameters().getInterface().setSpeed( VmInterfaceType.forValue( getParameters().getInterface().getType()).getSpeed()); getParameters().getInterface().setId(Guid.NewGuid()); getParameters().getInterface().setVmId(getParameters().getVmId()); boolean succeeded = false; <START> try { <END> TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addInterfaceToDb(getParameters().getInterface()); addInterfaceDeviceToDb(); getCompensationContext().stateChanged(); return null; } }); if (getParameters().getInterface().isPlugged()) { succeeded = activateOrDeactivateNic(getParameters().getInterface().getId(), PlugAction.PLUG); } else { succeeded = true; } } finally { setSucceeded(succeeded); if (!succeeded) { MacPoolManager.getInstance().freeMac(getMacAddress()); } } }</code><technical_language>move start of try-finally block earlier possible, line 62</technical_language>

Target:
protected void executeVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getParameters().getInterface().getType()).getDescription()).toString()); this.setVmName(getVmStaticDAO().get(getParameters().getVmId()).getVmName()); if (StringUtils.isEmpty(getMacAddress())) { getParameters().getInterface().setMacAddress(MacPoolManager.getInstance().allocateNewMac()); } boolean succeeded = false; try { getParameters().getInterface().setSpeed( VmInterfaceType.forValue( getParameters().getInterface().getType()).getSpeed()); getParameters().getInterface().setId(Guid.NewGuid()); getParameters().getInterface().setVmId(getParameters().getVmId()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addInterfaceToDb(getParameters().getInterface()); addInterfaceDeviceToDb(); getCompensationContext().stateChanged(); return null; } }); if (getParameters().getInterface().isPlugged()) { succeeded = activateOrDeactivateNic(getParameters().getInterface().getId(), PlugAction.PLUG); } else { succeeded = true; } } finally { setSucceeded(succeeded); if (!succeeded) { MacPoolManager.getInstance().freeMac(getMacAddress()); } } }
Source:
<code>protected void evictExpiredTokens() { try { for (final String token : getTokens()) { <START> if (isExpired(token)) { <END> log.evictToken(getTokenDisplayText(token)); removeToken(token); } } } catch(final Exception e) { log.failedExpiredTokenEviction(e); } }</code><technical_language>wondering if allow some "grace period" expiration if renewal is for a token evicting it</technical_language>

Target:
protected void evictExpiredTokens() { for (final String token : getTokens()) { try { if (needsEviction(token)) { log.evictToken(getTokenDisplayText(token)); removeToken(token); } } catch (final Exception e) { log.failedExpiredTokenEviction(getTokenDisplayText(token), e); } } }
Source:
<code>public Row buildRow() { Preconditions.checkState(committed, "Cannot build a Row object if we have not yet encountered a COMMIT_ROW chunk."); Row.Builder rowBuilder = Row.newBuilder().setKey(currentRowKey); <START> if (!families.isEmpty()) { <END> if (hasMultipleOfSameFamily()) { mergeFamilies(rowBuilder); } else { rowBuilder.addAllFamilies(families); } } return rowBuilder.build(); }</code><technical_language>I agree merge families end, looping families multiple times? do following? Map<String, <Family.Builder> family_builder_map ... for (Family family : families) { Family.Builder builder = family_builder_map.get(family.getName()); if (builder == null) { builder = Family.newBuilder().setName(family.getName()); } builder.addFamilies(family.getColumnsList()); }</technical_language>

Target:
public Row buildRow() { Preconditions.checkState(committed, "Cannot build a Row object if we have not yet encountered a COMMIT_ROW chunk."); Row.Builder currentRowBuilder = Row.newBuilder(); currentRowBuilder.setKey(currentRowKey); for (Family.Builder builder : familyMap.values()) { currentRowBuilder.addFamilies(builder.build()); } return currentRowBuilder.build(); }
Source:
<code>private VirtualFile createDirectory(VirtualFile parent, String name) { <START> MutableVirtualFile file = new MutableVirtualFile(parent, name); <END> file.withCanCreateChildren(ignored -> true); file.withCanProvideInputStream(ignored -> false); file.withCanProvideOutputStream(ignored -> false); file.withDirectoryFlagSupplier(ignored -> true); file.withExistsFlagSupplier(ignored -> true); file.withCanRenameHandler(ignored -> false); file.withCanDeleteHandler(ignored -> false); file.withCanMoveHandler(ignored -> false); file.withDeleteHandler(ignored -> false); file.withCanCreateDirectoryHandler(ignored -> false); file.withChildren(this); return file; }</code><technical_language>file -> directory</technical_language>

Target:
private VirtualFile createDirectory(VirtualFile parent, String name) { MutableVirtualFile directory = new MutableVirtualFile(parent, name); directory.withCanCreateChildren(ignored -> true); directory.withCanProvideInputStream(ignored -> false); directory.withCanProvideOutputStream(ignored -> false); directory.withDirectoryFlagSupplier(ignored -> true); directory.withExistsFlagSupplier(ignored -> true); directory.withCanRenameHandler(ignored -> false); directory.withCanDeleteHandler(ignored -> false); directory.withCanMoveHandler(ignored -> false); directory.withDeleteHandler(ignored -> false); directory.withCanCreateDirectoryHandler(ignored -> false); directory.withChildren(this); return directory; }
Source:
<code>private void completeWhenRetryRejected(RejectedExecutionException e) { if (context.logger.isFinestEnabled()) { context.logger.finest(e); } <START> notifyError(new HazelcastInstanceNotActiveException(e.getMessage())); <END> }</code><technical_language>Similar IndeterminateOperationStateException case, want complete immediately, check</technical_language>

Target:
private void completeWhenRetryRejected(RejectedExecutionException e) { if (context.logger.isFinestEnabled()) { context.logger.finest(e); } completeExceptionally(new HazelcastInstanceNotActiveException(e.getMessage())); }
Source:
<code>protected void registerGetters() { <START> registerFieldGetter(Keys.ITEM_DURABILITY, () -> this.durability); <END> registerKeyValue(Keys.ITEM_DURABILITY, this::durability); registerFieldGetter(Keys.UNBREAKABLE, this.unbreakable::get); registerKeyValue(Keys.UNBREAKABLE, this::unbreakable); }</code><technical_language>a method reference others</technical_language>

Target:
protected void registerGetters() { registerFieldGetter(Keys.ITEM_DURABILITY, this.durability::get); registerKeyValue(Keys.ITEM_DURABILITY, this::durability); registerFieldGetter(Keys.UNBREAKABLE, this.unbreakable::get); registerKeyValue(Keys.UNBREAKABLE, this::unbreakable); }
Source:
<code>protected boolean validate() { macPool = getMacPool(); if (getCluster() == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CLUSTER_CAN_NOT_BE_EMPTY); } List<VmNetworkInterface> nicsUnableToBeImported = getVm().getInterfaces() .stream() .filter(this::ifaceMacCannotBeAddedToMacPool) .collect(Collectors.toList()); if (!nicsUnableToBeImported.isEmpty()) { EngineMessage engineMessage = EngineMessage.ACTION_TYPE_FAILED_CANNOT_ADD_IFACE_DUE_TO_MAC_DUPLICATES; Collection<String> replacements = ReplacementUtils.getListVariableAssignmentString(engineMessage, nicsUnableToBeImported); <START> validate(new ValidationResult(engineMessage, replacements)); <END> } return true; }</code><technical_language>missing "return", right</technical_language>

Target:
protected boolean validate() { macPool = getMacPool(); if (getCluster() == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CLUSTER_CAN_NOT_BE_EMPTY); } List<VmNetworkInterface> nicsUnableToBeImported = getVm().getInterfaces() .stream() .filter(this::ifaceMacCannotBeAddedToMacPool) .collect(Collectors.toList()); if (!nicsUnableToBeImported.isEmpty()) { EngineMessage engineMessage = EngineMessage.ACTION_TYPE_FAILED_CANNOT_ADD_IFACE_DUE_TO_MAC_DUPLICATES; Collection<String> replacements = ReplacementUtils.getListVariableAssignmentString(engineMessage, nicsUnableToBeImported); return validate(new ValidationResult(engineMessage, replacements)); } return true; }
Source:
<code>private SortedMap<String, RefRightsForPattern> retainExclusives( SortedMap<String, RefRightsForPattern> perPatternRights) { SortedMap<String, RefRightsForPattern> rights = new TreeMap<String, RefRightsForPattern>(); <START> for (Iterator iterator = perPatternRights.entrySet().iterator(); iterator <END> .hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); RefRightsForPattern patternRights = (RefRightsForPattern) entry.getValue(); if (patternRights.containsExclusive()) { rights.put((String) entry.getKey(), patternRights); } } return rights; }</code><technical_language>Java-5 style iterators easier use: for (Map.Entry<String, RefRightsForPattern> entry : perPatternRights.entrySet())</technical_language>

Target:
private SortedMap<String, RefRightsForPattern> retainExclusives( SortedMap<String, RefRightsForPattern> perPatternRights) { SortedMap<String, RefRightsForPattern> rights = new TreeMap<String, RefRightsForPattern>(); for (Map.Entry<String, RefRightsForPattern> entry : perPatternRights.entrySet()) { RefRightsForPattern patternRights = (RefRightsForPattern) entry.getValue(); if (patternRights.containsExclusive()) { rights.put((String) entry.getKey(), patternRights); } } return rights; }
Source:
<code>public void evaluateUnaryExpression() { assertTrue(expressionEvaluator.evaluateUnaryExpression("not( true )", false, boolean.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression(">2, >5", BigDecimal.valueOf(6), BigDecimal.class)); try { expressionEvaluator.evaluateUnaryExpression(new Object(), null, Object.class); } catch (IllegalArgumentException e) { assertEquals("Raw expression should be a string", e.getMessage()); } try { expressionEvaluator.evaluateUnaryExpression("! true", null, null); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("Impossible to parse the expression")); <START> } <END> }</code><technical_language>Assertj nice fluent aby avoid try catch blocks: java Assertions.assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression(new Object(), null, Object.class)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Raw expression a string"); Assertions.assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("! true", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Impossible parse expression");</technical_language>

Target:
public void evaluateUnaryExpression() { assertTrue(expressionEvaluator.evaluateUnaryExpression("not( true )", false, boolean.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression(">2, >5", BigDecimal.valueOf(6), BigDecimal.class)); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression(new Object(), null, Object.class)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Raw expression should be a string"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("variable", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Error during evaluation:"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("! true", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Syntax error:"); }
Source:
<code>public void testImportVMFromConfigurationWhenStorageDomainIsInactive() { initCommand(getOvfEntityData()); StorageDomain storageDomain = createStorageDomain(); storageDomain.setStatus(StorageDomainStatus.Inactive); doReturn(storageDomain).when(cmd).getStorageDomain(); <START> assertFalse(cmd.canDoAction()); <END> }</code><technical_language>Please CanDoActionAssertUtils</technical_language>

Target:
public void testImportVMFromConfigurationWhenStorageDomainIsInactive() { initCommand(getOvfEntityData()); StorageDomain storageDomain = createStorageDomain(); storageDomain.setStatus(StorageDomainStatus.Inactive); doReturn(storageDomain).when(cmd).getStorageDomain(); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); }
Source:
<code>public Object get(DataFetchingEnvironment env) { User user = MutationHelpers.getUser(env); String dataSetName = env.getArgument("dataSetName"); String capabilityListUri = env.getArgument("capabilityListUri"); String userSpecifiedDataSet = env.getArgument("userSpecifiedDataSet"); DataSet dataSet; ResourceSyncImport.ResourceSyncReport resourceSyncReport = null; try { dataSet = dataSetRepository.createDataSet(user, dataSetName); ResourceSyncImport resourceSyncImport = new ResourceSyncImport(resourceSyncFileLoader, dataSet, false); resourceSyncReport = resourceSyncImport.filterAndImport(capabilityListUri, userSpecifiedDataSet); } catch (DataStoreCreationException | IllegalDataSetNameException | IOException | CantRetrieveFileException | CantDetermineDataSetException e) { LOG.error("Failed to do a resource sync import. ", e); throw new RuntimeException(e); } <START> return new DataSetWithDatabase(dataSet); <END> }</code><technical_language>move return resourceSync try block, code a bit compacter more readable for me</technical_language>

Target:
public Object get(DataFetchingEnvironment env) { User user = MutationHelpers.getUser(env); String dataSetName = env.getArgument("dataSetName"); String capabilityListUri = env.getArgument("capabilityListUri"); String userSpecifiedDataSet = env.getArgument("userSpecifiedDataSet"); String authString = env.getArgument("authorization"); try { ImportInfo importInfo = new ImportInfo(capabilityListUri, Date.from(Instant.now())); DataSet dataSet = dataSetRepository.createDataSet(user, dataSetName, Lists.newArrayList(importInfo)); ResourceSyncImport resourceSyncImport = new ResourceSyncImport(resourceSyncFileLoader, dataSet, false); return resourceSyncImport.filterAndImport( capabilityListUri, userSpecifiedDataSet, false, authString ); } catch (DataStoreCreationException | IllegalDataSetNameException | IOException | CantRetrieveFileException | CantDetermineDataSetException e) { LOG.error("Failed to do a resource sync import. ", e); throw new RuntimeException(e); } }
Source:
<code><START> private static List<MediaDB> getAllInLocal() { <END> return new Select(). from(MediaDB.class). where(MediaDB_Table.filename.isNotNull()). and(MediaDB_Table.resource_url.isNotNull()). orderBy(MediaDB_Table.id_media, true). queryList(); }</code><technical_language>static in this method is necessary</technical_language>

Target:
private List<MediaDB> getAllInLocal() { return new Select(). from(MediaDB.class). where(MediaDB_Table.filename.isNotNull()). and(MediaDB_Table.resource_url.isNotNull()). orderBy(MediaDB_Table.id_media, true). queryList(); }
Source:
<code>private void sanityCheckFragmentedPlan(SubPlan subPlan, WarningCollector warningCollector, int maxStageCount, int stageCountSoftLimit) { subPlan.sanityCheck(); int fragmentCount = subPlan.getAllFragments().size(); if (fragmentCount > maxStageCount) { throw new PrestoException(QUERY_HAS_TOO_MANY_STAGES, format( "Number of stages in the query (%s) exceeds the allowed maximum (%s). " + "If the query contains multiple DISTINCTs, please set the use_mark_distinct session property to false. " + "If the query contains multiple CTEs that are referenced more than once, please create temporary table(s) for one or more of the CTEs.", fragmentCount, maxStageCount)); } if (fragmentCount > stageCountSoftLimit) { warningCollector.add(new PrestoWarning(TOO_MANY_STAGES, format( "Number of stages in the query (%s) exceeds the soft limit (%s). " + <START> "If the query contains multiple DISTINCTs, please set the use_mark_distinct session property to false. " + <END> "If the query contains multiple CTEs that are referenced more than once, please create temporary table(s) for one or more of the CTEs.", fragmentCount, stageCountSoftLimit))); } }</code><technical_language>pull of string a variable</technical_language>

Target:
private void sanityCheckFragmentedPlan(SubPlan subPlan, WarningCollector warningCollector, int maxStageCount, int stageCountSoftLimit) { subPlan.sanityCheck(); int fragmentCount = subPlan.getAllFragments().size(); if (fragmentCount > maxStageCount) { throw new PrestoException(QUERY_HAS_TOO_MANY_STAGES, format( "Number of stages in the query (%s) exceeds the allowed maximum (%s). " + TOO_MANY_STAGES_MESSAGE, fragmentCount, maxStageCount)); } if (fragmentCount > stageCountSoftLimit) { warningCollector.add(new PrestoWarning(TOO_MANY_STAGES, format( "Number of stages in the query (%s) exceeds the soft limit (%s). " + TOO_MANY_STAGES_MESSAGE, fragmentCount, stageCountSoftLimit))); } }
Source:
<code>void clear() { <START> Arrays.fill(sparse, Integer.MAX_VALUE); <END> size = 0; }</code><technical_language>If cost of clear is significant running time, want benchmark array of Entry = (thread, pc), arrays, of Thread of pcs, avoid need allocate Entries. (In original Go, array of entries is flat, avoids allocation. I missed I port.) avoid need fill entire sparse array MAX_VALUE, get expensive for complex state machines</technical_language>

Target:
void clear() { size = 0; }
Source:
<code>public void onStart(ISuite suite) { if (!hasResultVersionSpecified() || !hasZapiRegexCycleSpecified()) { logger.info("ResultVersion and/or ZapiCycleRegex not set. " <START> + "Skipping CreateJiraCycleListener as it is not needed..."); <END> return; } final String targetProjectKey = getProjectKey(suite); final List<String> jiraTestLinksInSuite = getAllTestLinksInSuite(suite); final ProjectDto targetProjectDto = jiraService.project().getProject(targetProjectKey); createExecutionCyclesInJiraIfNeeded(targetProjectDto, jiraTestLinksInSuite); }</code><technical_language>This a bit more descriptive describe is done properties set "Skipping CreateJiraCycleListener...". Suggestion: - "Skipping automated generation of Jira version and/or Zapi cycle is needed..."</technical_language>

Target:
public void onStart(ISuite suite) { if (!hasResultVersionSpecified() || !hasZapiRegexCycleSpecified()) { logger.info("ResultVersion and/or ZapiCycleRegex was not set. " + "Skipping automated creation of JIRA version and Zephyr cycle as it is not needed..."); return; } final String targetProjectKey = getProjectKey(suite); final List<String> jiraTestLinksInSuite = getAllTestLinksInSuite(suite); final ProjectDto targetProjectDto = jiraService.project().getProject(targetProjectKey); createExecutionCyclesInJiraIfNeeded(targetProjectDto, jiraTestLinksInSuite); }