auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void doInitialise(MuleContext muleContext) throws InitialisationException { super.doInitialise(muleContext); Optional<ProcessingStrategy> processingStrategy = empty(); if (flowLocation.isPresent()) { processingStrategy = getProcessingStrategy(locator, flowLocation.get()); } else if (getLocation() != null) { processingStrategy = getProcessingStrategy(locator, getRootContainerLocation()); } configuredMessageProcessors = newChain(processingStrategy, getMessageProcessors()); if (configuredMessageProcessors != null) { configuredMessageProcessors.setMuleContext(muleContext); } errorTypeMatcher = createErrorType(muleContext.getErrorTypeRepository(), errorType, configurationProperties); <START> if (this.getLocation() != null) { <END> errorHandlerLocation = this.getLocation().getLocation(); isLocalErrorHandlerLocation = ERROR_HANDLER_LOCATION_PATTERN.matcher(errorHandlerLocation).find(); if (isLocalErrorHandlerLocation) { errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); } } }</code><technical_language>this.getLocation() is expensive. execute store in var</technical_language>

Target:
protected void doInitialise(MuleContext muleContext) throws InitialisationException { super.doInitialise(muleContext); this.location = this.getLocation(); Optional<ProcessingStrategy> processingStrategy = empty(); if (flowLocation.isPresent()) { processingStrategy = getProcessingStrategy(locator, flowLocation.get()); } else if (location != null) { processingStrategy = getProcessingStrategy(locator, getRootContainerLocation()); } configuredMessageProcessors = newChain(processingStrategy, getMessageProcessors()); if (configuredMessageProcessors != null) { configuredMessageProcessors.setMuleContext(muleContext); } errorTypeMatcher = createErrorType(muleContext.getErrorTypeRepository(), errorType, configurationProperties); if (!inDefaultErrorHandler()) { errorHandlerLocation = this.location.getLocation(); isLocalErrorHandlerLocation = ERROR_HANDLER_LOCATION_PATTERN.matcher(errorHandlerLocation).find(); if (isLocalErrorHandlerLocation) { errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); } } }
Source:
<code>private MetadataValue getRelationMetadataFromOtherItem(Item otherItem, String relationName) { <START> MetadataValue metadataValue = constructMetadataValue("relation." + relationName); <END> metadataValue.setAuthority("virtual"); metadataValue.setValue(otherItem.getID().toString()); return metadataValue; }</code><technical_language>Enum here, instead of hardcoding string "relation"</technical_language>

Target:
private MetadataValue getRelationMetadataFromOtherItem(Item otherItem, String relationName) { MetadataValue metadataValue = constructMetadataValue( MetadataSchemaEnum.RELATION.getName() + "." + relationName); metadataValue.setAuthority("virtual"); metadataValue.setValue(otherItem.getID().toString()); return metadataValue; }
Source:
<code>void cacheData(Resource res, File file) throws IOException { assert res.getType()==Type.RESOURCE; <START> OutputStream out = new FileOutputStream(file); <END> try { InputStream in = res.in(); try { IOUtils.copy(in, out); } finally { in.close(); } } finally { out.close(); } }</code><technical_language>this a single try-with-resources block resources a single statement in body</technical_language>

Target:
void cacheData(Resource res, File file) throws IOException { assert res.getType()==Type.RESOURCE; try (OutputStream out = new FileOutputStream(file)) { try (InputStream in = res.in()) { IOUtils.copy(in, out); } } }
Source:
<code>public boolean isServerReadyToHandleMsg(RequestMsg request) { <START> if (getState() != ServerState.READY) return false; <END> if ((sequencerEpoch != serverContext.getServerEpoch()) && (!request.getPayload().getPayloadCase() .equals(PayloadCase.BOOTSTRAP_SEQUENCER_REQUEST))) { log.warn("Rejecting msg at sequencer : sequencerStateEpoch:{}, serverEpoch:{}, " + "header:{}", sequencerEpoch, serverContext.getServerEpoch(), request.getHeader()); return false; } return true; }</code><technical_language>Please standard formating here: wrap return statement curly brackets in new lines (as be)</technical_language>

Target:
public boolean isServerReadyToHandleMsg(RequestMsg request) { if (getState() != ServerState.READY) { return false; } if ((sequencerEpoch != serverContext.getServerEpoch()) && (!request.getPayload().getPayloadCase() .equals(PayloadCase.BOOTSTRAP_SEQUENCER_REQUEST))) { log.warn("Rejecting msg at sequencer : sequencerStateEpoch:{}, serverEpoch:{}, " + "header:{}", sequencerEpoch, serverContext.getServerEpoch(), request.getHeader()); return false; } return true; }
Source:
<code>boolean isSelected(MPart part) { MElementContainer<?> parent = part.getParent(); if (parent == null) { MPlaceholder placeholder = part.getCurSharedRef(); if (placeholder == null) { return false; } parent = placeholder.getParent(); return parent instanceof MGenericStack ? parent.getSelectedElement() == placeholder : parent != null; } <START> return parent instanceof MGenericStack ? parent.getSelectedElement() == part <END> : true; }</code><technical_language>!(parent instanceof MGenericStack) || parent.getSelectedElement() == part</technical_language>

Target:
boolean isSelected(MPart part) { MElementContainer<?> parent = part.getParent(); if (parent == null) { MPlaceholder placeholder = part.getCurSharedRef(); if (placeholder == null) { return false; } parent = placeholder.getParent(); return parent instanceof MGenericStack ? parent.getSelectedElement() == placeholder : parent != null; } return !(parent instanceof MGenericStack) || parent.getSelectedElement() == part; }
Source:
<code>protected String scanTokenForRangeSymbol(String token) { char character; <START> for (int charIndex = 0; charIndex < token.length(); charIndex++) { <END> character = token.charAt(charIndex); if (rangeSymbols.contains(character)) { return String.valueOf(character); } } return null; }</code><technical_language>Personal preference stream version cleaner array iteration version. Optional<Character> firstMatch = token.chars() .mapToObj(i -> (char) i) .filter(rangeSymbols::contains) .findFirst(); return Optional check if present instead of controlling flow null checks</technical_language>

Target:
String scanTokenForRangeSymbol(String token) { for (String whitelistValue : getWhitelistedValues()) { if (token.contains(whitelistValue)) { return null; } } if (!token.matches(".*\\d+[.]\\d+.*")) { return null; } for (char character : token.toCharArray()) { if (rangeSymbols.contains(character)) { return String.valueOf(character); } } return null; }
Source:
<code>private PlanNode getCostBasedJoin(JoinNode joinNode, Context context) { List<PlanNodeWithCost> possibleJoinNodes = new ArrayList<>(); if (joinNode.getCriteria().isEmpty() && joinNode.getType() == LEFT) { <START> addJoinsWithDifferentDistributions(joinNode, possibleJoinNodes, context); <END> } else if (joinNode.getCriteria().isEmpty() && joinNode.getType() == RIGHT) { addJoinsWithDifferentDistributions(joinNode.flipChildren(), possibleJoinNodes, context); } else { addJoinsWithDifferentDistributions(joinNode, possibleJoinNodes, context); addJoinsWithDifferentDistributions(joinNode.flipChildren(), possibleJoinNodes, context); } if (possibleJoinNodes.stream().anyMatch(result -> result.getCost().hasUnknownComponents()) || possibleJoinNodes.isEmpty()) { return getSyntacticOrderJoin(joinNode, context, AUTOMATIC); } Ordering<PlanNodeWithCost> planNodeOrderings = costComparator.forSession(context.getSession()).onResultOf(PlanNodeWithCost::getCost); return planNodeOrderings.min(possibleJoinNodes).getPlanNode(); }</code><technical_language>I replace if (canReplicate(joinNode, context)) { possibleJoinNodes.add(getJoinNodeWithCost(context, joinNode.withDistributionType(REPLICATED))); } is easier follow is in this special case</technical_language>

Target:
private PlanNode getCostBasedJoin(JoinNode joinNode, Context context) { List<PlanNodeWithCost> possibleJoinNodes = new ArrayList<>(); addJoinsWithDifferentDistributions(joinNode, possibleJoinNodes, context); addJoinsWithDifferentDistributions(joinNode.flipChildren(), possibleJoinNodes, context); if (possibleJoinNodes.stream().anyMatch(result -> result.getCost().hasUnknownComponents()) || possibleJoinNodes.isEmpty()) { return getSyntacticOrderJoin(joinNode, context, AUTOMATIC); } Ordering<PlanNodeWithCost> planNodeOrderings = costComparator.forSession(context.getSession()).onResultOf(PlanNodeWithCost::getCost); return planNodeOrderings.min(possibleJoinNodes).getPlanNode(); }
Source:
<code>public NavigationHelperImpl(Notifier emfRoot, BaseIndexOptions options, Logger logger) throws ViatraBaseException { this.baseIndexOptions = options.copy(); this.logger = logger; assert (logger != null); this.comprehension = new EMFModelComprehension(baseIndexOptions); this.wildcardMode = baseIndexOptions.getWildcardLevel(); this.subscribedInstanceListeners = new HashMap<InstanceListener, Set<EClass>>(); this.subscribedFeatureListeners = new HashMap<FeatureListener, Set<EStructuralFeature>>(); this.subscribedDataTypeListeners = new HashMap<DataTypeListener, Set<EDataType>>(); this.lightweightObservers = new HashMap<LightweightEObjectObserver, Collection<EObject>>(); this.observedFeatures = new HashMap<Object, IndexingLevel>(); this.ignoreResolveNotificationFeatures = new HashSet<Object>(); this.observedDataTypes = new HashMap<Object, IndexingLevel>(); metaStore = new EMFBaseIndexMetaStore(this); <START> instanceStore = new EMFBaseIndexInstanceStore(this, logger, options.isStrictNotificationMode()); <END> statsStore = new EMFBaseIndexStatisticsStore(); this.contentAdapter = new NavigationHelperContentAdapter(this); this.baseIndexChangeListeners = new HashSet<EMFBaseIndexChangeListener>(); this.errorListeners = new LinkedHashSet<IEMFIndexingErrorListener>(); this.notifier = emfRoot; this.modelRoots = new HashSet<Notifier>(); this.expansionAllowed = false; if (emfRoot != null) { addRootInternal(emfRoot); } }</code><technical_language>pass entire BaseIndexOptions more future-proof</technical_language>

Target:
public NavigationHelperImpl(Notifier emfRoot, BaseIndexOptions options, Logger logger) throws ViatraBaseException { this.baseIndexOptions = options.copy(); this.logger = logger; assert (logger != null); this.comprehension = new EMFModelComprehension(baseIndexOptions); this.wildcardMode = baseIndexOptions.getWildcardLevel(); this.subscribedInstanceListeners = new HashMap<InstanceListener, Set<EClass>>(); this.subscribedFeatureListeners = new HashMap<FeatureListener, Set<EStructuralFeature>>(); this.subscribedDataTypeListeners = new HashMap<DataTypeListener, Set<EDataType>>(); this.lightweightObservers = new HashMap<LightweightEObjectObserver, Collection<EObject>>(); this.observedFeatures = new HashMap<Object, IndexingLevel>(); this.ignoreResolveNotificationFeatures = new HashSet<Object>(); this.observedDataTypes = new HashMap<Object, IndexingLevel>(); metaStore = new EMFBaseIndexMetaStore(this); instanceStore = new EMFBaseIndexInstanceStore(this, logger, options); statsStore = new EMFBaseIndexStatisticsStore(); this.contentAdapter = new NavigationHelperContentAdapter(this); this.baseIndexChangeListeners = new HashSet<EMFBaseIndexChangeListener>(); this.errorListeners = new LinkedHashSet<IEMFIndexingErrorListener>(); this.notifier = emfRoot; this.modelRoots = new HashSet<Notifier>(); this.expansionAllowed = false; if (emfRoot != null) { addRootInternal(emfRoot); } }
Source:
<code>private Optional<Cookie> findCookieWithName(String cookieName, HttpClient httpClient) { <START> Optional<Cookie> cookie = <END> Arrays.stream(httpClient.getState().getCookies()) .filter(c -> cookieName.equals(c.getName())) .findFirst(); return cookie; }</code><technical_language>return immediately, need store in a local var</technical_language>

Target:
private Optional<Cookie> findCookieWithName(String cookieName, HttpClient httpClient) { return Arrays.stream(httpClient.getState().getCookies()) .filter(c -> cookieName.equals(c.getName())) .findFirst(); }
Source:
<code>private void updateBottomViews() { View currentBottomView = getCurrentBottomView(); if (currentBottomView != null) { if (mCurrentDragEdge == DragEdge.Left || mCurrentDragEdge == DragEdge.Right) { mDragDistance = currentBottomView.getMeasuredWidth() - dp2px(getCurrentOffset()); <START> } else <END> mDragDistance = currentBottomView.getMeasuredHeight() - dp2px(getCurrentOffset()); } if (mShowMode == ShowMode.PullOut) layoutPullOut(); else if (mShowMode == ShowMode.LayDown) layoutLayDown(); safeBottomView(); }</code><technical_language>missing brackets } else { ... }</technical_language>

Target:
private void updateBottomViews() { View currentBottomView = getCurrentBottomView(); if (currentBottomView != null) { if (mCurrentDragEdge == DragEdge.Left || mCurrentDragEdge == DragEdge.Right) { mDragDistance = currentBottomView.getMeasuredWidth() - dp2px(getCurrentOffset()); } else { mDragDistance = currentBottomView.getMeasuredHeight() - dp2px(getCurrentOffset()); } } if (mShowMode == ShowMode.PullOut) { layoutPullOut(); } else if (mShowMode == ShowMode.LayDown) { layoutLayDown(); } safeBottomView(); }
Source:
<code>public static void store(ConsumerWithException<OutputStream> store, File target) throws Exception { target.getParentFile() .mkdirs(); File tmp = createTempFile(target.getParentFile(), target.getName(), ".tmp"); try { <START> try (FileOutputStream outputStream = new FileOutputStream(tmp)) { <END> store.accept(outputStream); } rename(tmp, target); assert target.isFile(); } finally { if (tmp.exists()) tmp.delete(); } }</code><technical_language>stopped new FileOutputStream due some issues it. Please IO.outputStream(File) method instead</technical_language>

Target:
public static void store(ConsumerWithException<OutputStream> store, File target) throws Exception { target.getParentFile() .mkdirs(); File tmp = createTempFile(target.getParentFile(), target.getName(), ".tmp"); try { try (OutputStream outputStream = outputStream(tmp)) { store.accept(outputStream); } rename(tmp, target); assert target.isFile(); } finally { if (tmp.exists()) tmp.delete(); } }
Source:
<code>protected Control createContents(final Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); GridData fill = new GridData(); fill.horizontalAlignment = SWT.FILL; fill.verticalAlignment = SWT.FILL; fill.heightHint = 150; TableViewer tableViewer = new TableViewer(composite, SWT.SINGLE); tableViewer.getTable().setLayoutData(fill); tableViewer.setContentProvider(contentProvider); tableViewer.setLabelProvider(labelProvider); tableViewer.setInput(new Object()); <START> tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { selected = ((StructuredSelection) event.getSelection()).getFirstElement(); } }); <END> return super.createContents(parent); }</code><technical_language>this rewritten a lambda</technical_language>

Target:
protected Control createContents(final Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); GridData fill = new GridData(); fill.horizontalAlignment = SWT.FILL; fill.verticalAlignment = SWT.FILL; fill.heightHint = 150; TableViewer tableViewer = new TableViewer(composite, SWT.SINGLE); tableViewer.getTable().setLayoutData(fill); tableViewer.setContentProvider(contentProvider); tableViewer.setLabelProvider(labelProvider); tableViewer.setInput(new Object()); tableViewer.addSelectionChangedListener( event -> selected = ((StructuredSelection) event.getSelection()).getFirstElement()); return super.createContents(parent); }
Source:
<code>public List getLoggerNameList() { List<String> copy = new ArrayList<String>(); <START> synchronized (loggers) { <END> copy.addAll(loggers.keySet()); } return copy; }</code><technical_language>above. I java return new ArrayList<String>(loggers.keySet()); is enough</technical_language>

Target:
public List getLoggerNameList() { return new ArrayList<String>(loggers.keySet()); }
Source:
<code>public SecurityGroup createSecurityGroup(final String name, Location location) { checkNotNull(name, "name"); checkNotNull(location, "location"); final NetworkSecurityGroup networkSecurityGroup = NetworkSecurityGroup.create(name, name, location.getId(), null); String createNSGRequestId = api.getNetworkSecurityGroupApi().create(networkSecurityGroup); <START> operationSucceededPredicate.apply(createNSGRequestId); <END> return transformNetworkSecurityGroupToSecurityGroup(name); }</code><technical_language>if predicate returns false? throw exception instead of silently continuing? Apply reasoning rest of operations in this file</technical_language>

Target:
public SecurityGroup createSecurityGroup(final String name, Location location) { checkNotNull(name, "name"); checkNotNull(location, "location"); final NetworkSecurityGroup networkSecurityGroup = NetworkSecurityGroup.create(name, name, location.getId(), null); String createNSGRequestId = api.getNetworkSecurityGroupApi().create(networkSecurityGroup); if (operationSucceededPredicate.apply(createNSGRequestId)) { final String message = generateIllegalStateExceptionMessage(createNSGRequestId, azureComputeConstants.operationTimeout()); logger.warn(message); throw new IllegalStateException(message); } return transformNetworkSecurityGroupToSecurityGroup(name); }
Source:
<code>private Object resolveExpression(String value) { if (!(value.startsWith("#{") && value.endsWith("}"))) { return resolve(value); } <START> return this.resolver.evaluate(value, this.expressionContext); <END> }</code><technical_language>This is wrong. resolve check if is expression. I property-placeholder expression work: my.queue=#{myQueue.name} ... @RabbitListener(queues = "${my.queue}") This is valid variant, so, please, cover test</technical_language>

Target:
private Object resolveExpression(String value) { String resolvedValue = resolve(value); if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) { return resolvedValue; } return this.resolver.evaluate(resolvedValue, this.expressionContext); }
Source:
<code>protected String loadStyleSheet() { URL styleSheetURL = JFaceUtilsActivator.getInstance().getBundle() .getEntry(styleSheetFileName); if (styleSheetURL != null) { BufferedReader reader = null; <START> try { <END> reader = new BufferedReader(new InputStreamReader( styleSheetURL.openStream())); StringBuffer buffer = new StringBuffer(1500); String line = reader.readLine(); while (line != null) { buffer.append(line); buffer.append('\n'); line = reader.readLine(); } return buffer.toString(); } catch (IOException ex) { return ""; } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } } } return null; }</code><technical_language>Is complete try catch needed</technical_language>

Target:
protected String loadStyleSheet() { URL styleSheetURL = JFaceUtilsActivator.getInstance().getBundle().getEntry(styleSheetFileName); if (styleSheetURL != null) { try { InputStreamReader inputStreamReader = new InputStreamReader(styleSheetURL.openStream()); BufferedReader reader = new BufferedReader(inputStreamReader); String ret = reader.lines().collect(Collectors.joining("\n")); reader.close(); inputStreamReader.close(); return ret; } catch (IOException e) { return null; } } return null; }
Source:
<code>public void init() { initMocks(this); pid = PIDs.get(UUID.randomUUID().toString()); collection = new CollectionObject(pid, repository, dataLoader); folderChildPid = PIDs.get(UUID.randomUUID().toString()); when(repository.mintContentPid()).thenReturn(folderChildPid); workChildPid = PIDs.get(UUID.randomUUID().toString()); <START> when(repository.mintContentPid()).thenReturn(workChildPid); <END> folderChildObj = new FolderObject(folderChildPid, repository, dataLoader); when(repository.createFolderObject(any(PID.class), any(Model.class))) .thenReturn(folderChildObj); workChildObj = new WorkObject(workChildPid, repository, dataLoader); when(repository.createWorkObject(any(PID.class), any(Model.class))) .thenReturn(workChildObj); }</code><technical_language>I need of when(repository.mintContentPid()).thenReturn(...); overwrite one. If want repository.mindContentPid return specific pids in test, chain so: when(repository.mintContentPid()).thenReturn(folderChildPid).thenReturn(workChildPid); thenReturn call (and I repeat for call second))</technical_language>

Target:
public void init() { initMocks(this); pid = PIDs.get(UUID.randomUUID().toString()); collection = new CollectionObject(pid, repository, dataLoader); folderChildPid = PIDs.get(UUID.randomUUID().toString()); workChildPid = PIDs.get(UUID.randomUUID().toString()); when(repository.mintContentPid()).thenReturn(folderChildPid).thenReturn(workChildPid); folderChildObj = new FolderObject(folderChildPid, repository, dataLoader); when(repository.createFolderObject(any(PID.class), any(Model.class))) .thenReturn(folderChildObj); workChildObj = new WorkObject(workChildPid, repository, dataLoader); when(repository.createWorkObject(any(PID.class), any(Model.class))) .thenReturn(workChildObj); }
Source:
<code>private String getMessage(Multimap<EAttribute, String> wrongTypes) { StringBuilder sb = new StringBuilder(); sb.append(wrongTypes.size()); <START> sb.append(" variables available in interpreted expressions need type correction:"); <END> for (EAttribute attr : wrongTypes.keySet()) { sb.append("\n . "); sb.append(attr.eResource().getURIFragment(attr)); for (String v : wrongTypes.get(attr)) { sb.append("\n . " + v); } } return sb.toString(); }</code><technical_language>"variables" --> variable(s)</technical_language>

Target:
private String getMessage(Multimap<EAttribute, String> wrongTypes) { StringBuilder sb = new StringBuilder(); sb.append(wrongTypes.size()); sb.append(" variable(s) available in interpreted expressions need type correction:"); for (EAttribute attr : wrongTypes.keySet()) { sb.append("\n . "); sb.append(attr.eResource().getURIFragment(attr)); for (String v : wrongTypes.get(attr)) { sb.append("\n . " + v); } } return sb.toString(); }
Source:
<code>private void cacheVertex(final SequenceSegment vertex) { <START> int startBucket = (int) Math.floor((double) vertex.getUnifiedStart() <END> / bucketWidth); int endBucket = (int) Math.floor((double) vertex.getUnifiedEnd() / bucketWidth); for (int bucket = startBucket; bucket <= endBucket; bucket++) { buckets.get(bucket).add(vertex); } }</code><technical_language>need for Math.floor; casting int implicitly drops decimal</technical_language>

Target:
private void cacheVertex(final SequenceSegment vertex) { int startBucket = bucketPosition(vertex.getUnifiedStart()); int endBucket = 1 + bucketPosition(vertex.getUnifiedEnd()); for (SortedSet<SequenceSegment> bucket : buckets.subList(startBucket, endBucket)) { bucket.add(vertex); } }
Source:
<code>public MetricsManager metricsManager() { return MetricsManagers.createForTests(); <START> } <END></code><technical_language>Agreed. Yep - I mentioned fine, weird</technical_language>

Target:
public MetricsManager metricsManager() { return MetricsManagers.of(new MetricRegistry(), new DefaultTaggedMetricRegistry()); }
Source:
<code><START> public static Optional<Integer> getFirmwareVersionFromBuildInfo(final String buildInfoText) { <END> final Iterable<String> strings = Splitter.on("\n").split(buildInfoText); final Map<String, String> buildInfo = Maps.newHashMap(); for (final String line : strings) { if (line.contains(":")) { final String[] parts = line.split(":"); buildInfo.put(parts[0].trim(), parts[1].trim()); } } if (buildInfo.get("version").isEmpty()) { return Optional.absent(); } try { if (buildInfo.get("version").equals(buildInfo.get("travis_build_number"))) { return Optional.of(Integer.parseInt(buildInfo.get("version"), 10)); } else { return Optional.of(Integer.parseInt(buildInfo.get("version"), 16)); } } catch (NumberFormatException nfe) { return Optional.absent(); } }</code><technical_language>nit: If this need public (available this package), package-private (no access modifier). accessible test class elsewhere</technical_language>

Target:
static Optional<Integer> getFirmwareVersionFromBuildInfo(final String buildInfoText) { final Iterable<String> strings = Splitter.on("\n").split(buildInfoText); final Map<String, String> buildInfo = Maps.newHashMap(); for (final String line : strings) { if (line.contains(":")) { final String[] parts = line.split(":"); buildInfo.put(parts[0].trim(), parts[1].trim()); } } if (!buildInfo.containsKey("version")) { return Optional.absent(); } if (buildInfo.get("version").isEmpty()) { return Optional.absent(); } try { if (buildInfo.get("version").equals(buildInfo.get("travis_build_number"))) { return Optional.of(Integer.parseInt(buildInfo.get("version"), 10)); } else { return Optional.of(Integer.parseInt(buildInfo.get("version"), 16)); } } catch (NumberFormatException nfe) { return Optional.absent(); } }
Source:
<code>public void executeQuery(AsyncQuery queryObj, User user, String apiVersion) { QueryRunner runner = runners.get(apiVersion); if (runner == null) { throw new InvalidOperationException("Invalid API Version"); } AsyncQueryThread queryWorker = new AsyncQueryThread(queryObj, user, elide, runner, asyncQueryDao, apiVersion); Future<AsyncQueryResult> task = executor.submit(queryWorker); try { queryObj.setStatus(QueryStatus.PROCESSING); AsyncQueryResult queryResultObj = task.get(queryObj.getAsyncAfterSeconds(), TimeUnit.SECONDS); queryObj.setResult(queryResultObj); queryObj.setStatus(QueryStatus.COMPLETE); } catch (InterruptedException e) { log.error("InterruptedException: {}", e); queryObj.setStatus(QueryStatus.FAILURE); } catch (ExecutionException e) { log.error("ExecutionException: {}", e); queryObj.setStatus(QueryStatus.FAILURE); } catch (TimeoutException e) { log.error("TimeoutException: {}", e); if (task.isDone()) { <START> log.info("task is done."); <END> try { queryObj.setResult(task.get()); queryObj.setStatus(QueryStatus.COMPLETE); } catch (InterruptedException e1) { log.error("InterruptedException: {}", e); queryObj.setStatus(QueryStatus.FAILURE); } catch (ExecutionException e1) { log.error("ExecutionException: {}", e); queryObj.setStatus(QueryStatus.FAILURE); } } else { log.info("task is not done yet."); AsyncQueryUpdateThread queryUpdateWorker = new AsyncQueryUpdateThread(elide, task, queryObj, asyncQueryDao); updater.execute(queryUpdateWorker); } } }</code><technical_language>log debug instead of info</technical_language>

Target:
public void executeQuery(AsyncQuery queryObj, User user, String apiVersion) { QueryRunner runner = runners.get(apiVersion); if (runner == null) { throw new InvalidOperationException("Invalid API Version"); } AsyncQueryThread queryWorker = new AsyncQueryThread(queryObj, user, elide, runner, asyncQueryDao, apiVersion); Future<AsyncQueryResult> task = executor.submit(queryWorker); try { queryObj.setStatus(QueryStatus.PROCESSING); AsyncQueryResult queryResultObj = task.get(queryObj.getAsyncAfterSeconds(), TimeUnit.SECONDS); queryObj.setResult(queryResultObj); queryObj.setStatus(QueryStatus.COMPLETE); } catch (InterruptedException e) { log.error("InterruptedException: {}", e); queryObj.setStatus(QueryStatus.FAILURE); } catch (ExecutionException e) { log.error("ExecutionException: {}", e); queryObj.setStatus(QueryStatus.FAILURE); } catch (TimeoutException e) { log.error("TimeoutException: {}", e); queryObj.setQueryUpdateWorker(new AsyncQueryUpdateThread(elide, task, queryObj, asyncQueryDao)); } catch (Exception e) { log.error("Exception: {}", e); queryObj.setStatus(QueryStatus.FAILURE); } }
Source:
<code>protected IdeFrameFixture openProject(@NotNull String projectDirName) throws IOException { <START> final File projectPath = setUpProject(projectDirName); <END> WelcomeFrameFixture welcomeFrame = findWelcomeFrame(); welcomeFrame.openProjectButton().click(); FileChooserDialogFixture openProjectDialog = FileChooserDialogFixture.findOpenProjectDialog(myRobot); return openProjectAndWaitUntilOpened(projectPath, openProjectDialog); }</code><technical_language>checking: this create .idea files for a Gradle-only project missing .idea files right? If not, IntelliJ project in VCS project open action works</technical_language>

Target:
protected IdeFrameFixture openProject(@NotNull String projectDirName) throws IOException { final File projectPath = setUpProject(projectDirName, true); WelcomeFrameFixture welcomeFrame = findWelcomeFrame(); welcomeFrame.openProjectButton().click(); FileChooserDialogFixture openProjectDialog = FileChooserDialogFixture.findOpenProjectDialog(myRobot); return openProjectAndWaitUntilOpened(projectPath, openProjectDialog); }
Source:
<code>public InputStream lookupResponse(String id) { InputStream result = null; if (null != id) { try (Connection connection = getConnection(); PreparedStatement mySelectSQL = connection.prepareStatement(selectionString)) { mySelectSQL.setString(SELECT_COLUMN_RESPONSE, id); try (ResultSet rs = mySelectSQL.executeQuery()) { if (null == rs || !rs.next()) { LOGGER.warn("No response found for request id " + id); } else { <START> result = rs.getAsciiStream(1); <END> } } } catch (SQLException ex) { LOGGER.error("Could not look up response in database", ex); } if (null != result) { if (id.toLowerCase().contains("output") && !Boolean.parseBoolean(getDatabaseProperties("saveResultsToDB"))) { try { String outputFileLocation = IOUtils.toString(result); LOGGER.debug("ID is output and saved to disk instead of database. Path = " + outputFileLocation); if (Files.exists(Paths.get(outputFileLocation))) { result = new GZIPInputStream(new FileInputStream(outputFileLocation)); } else { LOGGER.warn("Response not found on disk for id " + id + " at " + outputFileLocation); } } catch (FileNotFoundException ex) { LOGGER.warn("Response not found on disk for id " + id, ex); } catch (IOException ex) { LOGGER.warn("Error processing response for id " + id, ex); } } } else { LOGGER.warn("response found but returned null"); } } else { LOGGER.warn("tried to look up response for null id, returned null"); } return result; }</code><technical_language>Magic number</technical_language>

Target:
public InputStream lookupResponse(String id) { InputStream result = null; if (null != id) { try (Connection connection = getConnection(); PreparedStatement selectStatement = connection.prepareStatement(selectionString)) { selectStatement.setString(SELECTION_STRING_REQUEST_ID_PARAM_INDEX, id); try (ResultSet rs = selectStatement.executeQuery()) { if (null == rs || !rs.next()) { LOGGER.warn("No response found for request id " + id); } else { result = rs.getAsciiStream(SELECTION_STRING_RESPONSE_COLUMN_INDEX); } } } catch (SQLException ex) { LOGGER.error("Could not look up response in database", ex); } if (null != result) { if (id.toLowerCase().contains("output") && !Boolean.parseBoolean(getDatabaseProperties("saveResultsToDB"))) { try { String outputFileLocation = IOUtils.toString(result); LOGGER.debug("ID is output and saved to disk instead of database. Path = " + outputFileLocation); if (Files.exists(Paths.get(outputFileLocation))) { result = new GZIPInputStream(new FileInputStream(outputFileLocation)); } else { LOGGER.warn("Response not found on disk for id " + id + " at " + outputFileLocation); } } catch (FileNotFoundException ex) { LOGGER.warn("Response not found on disk for id " + id, ex); } catch (IOException ex) { LOGGER.warn("Error processing response for id " + id, ex); } } } else { LOGGER.warn("response found but returned null"); } } else { LOGGER.warn("tried to look up response for null id, returned null"); } return result; }
Source:
<code>public URI createDepositRecord(URI path, Model model) throws FedoraException { URI depositRecordUri; try (FcrepoResponse response = getClient().put(path) <START> .body(RDFModelUtil.streamModel(model), "text/turtle") <END> .perform()) { depositRecordUri = response.getLocation(); ldpFactory.createDirectContainer(depositRecordUri, Cdr.hasManifest, RepositoryPathConstants.DEPOSIT_MANIFEST_CONTAINER); ldpFactory.createDirectContainer(depositRecordUri, Premis.hasEvent, RepositoryPathConstants.EVENTS_CONTAINER); } catch (IOException e) { throw new FedoraException("Unable to create deposit record at " + path, e); } catch (FcrepoOperationFailedException e) { throw ClientFaultResolver.resolve(e); } return depositRecordUri; }</code><technical_language>turtle</technical_language>

Target:
public URI createDepositRecord(URI path, Model model) throws FedoraException { URI depositRecordUri; try (FcrepoResponse response = getClient().put(path) .body(RDFModelUtil.streamModel(model), TURTLE_MIMETYPE) .perform()) { depositRecordUri = response.getLocation(); ldpFactory.createDirectContainer(depositRecordUri, Cdr.hasManifest, RepositoryPathConstants.DEPOSIT_MANIFEST_CONTAINER); ldpFactory.createDirectContainer(depositRecordUri, Premis.hasEvent, RepositoryPathConstants.EVENTS_CONTAINER); } catch (IOException e) { throw new FedoraException("Unable to create deposit record at " + path, e); } catch (FcrepoOperationFailedException e) { throw ClientFaultResolver.resolve(e); } return depositRecordUri; }
Source:
<code>private RexNode simplifyIs(RexCall call, RexUnknownAs unknownAs) { final SqlKind kind = call.getKind(); final RexNode argument = call.getOperands().get(0); if (kind == SqlKind.IS_TRUE && unknownAs == RexUnknownAs.FALSE) { return simplify(argument, unknownAs); } if (kind == SqlKind.IS_NOT_FALSE && unknownAs == RexUnknownAs.TRUE) { return simplify(argument, unknownAs); } <START> final RexNode a = simplify(call.getOperands().get(0), RexUnknownAs.UNKNOWN); <END> final RexNode pred = simplifyIsPredicate(kind, a); if (pred != null) { return pred; } final RexNode simplified = simplifyIs2(kind, a); if (simplified != null) { return simplified; } return call; }</code><technical_language>This O(N^2). please avoid simplifying nodes again</technical_language>

Target:
private RexNode simplifyIs(RexCall call, RexUnknownAs unknownAs) { final SqlKind kind = call.getKind(); final RexNode a = call.getOperands().get(0); if (kind == SqlKind.IS_TRUE && unknownAs == RexUnknownAs.FALSE) { return simplify(a, unknownAs); } if (kind == SqlKind.IS_FALSE && unknownAs == RexUnknownAs.FALSE) { return simplify(rexBuilder.makeCall(SqlStdOperatorTable.NOT, a), unknownAs); } if (kind == SqlKind.IS_NOT_FALSE && unknownAs == RexUnknownAs.TRUE) { return simplify(a, unknownAs); } if (kind == SqlKind.IS_NOT_TRUE && unknownAs == RexUnknownAs.TRUE) { return simplify(rexBuilder.makeCall(SqlStdOperatorTable.NOT, a), unknownAs); } final RexNode pred = simplifyIsPredicate(kind, a); if (pred != null) { return pred; } final RexNode simplified = simplifyIs2(kind, a, unknownAs); if (simplified != null) { return simplified; } return call; }
Source:
<code>private void setHttpClient(String host, int port) { try { client = HttpClients.custom() .setSSLSocketFactory(new SSLConnectionSocketFactory( SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build())) .build(); } catch (NoSuchAlgorithmException | eyManagementException | KeyStoreException e) { log.error("Exception : ", e); } baseUrl = "https://" + host + ":" + port; <START> userName = "admin"; <END> passWord = "admin"; }</code><technical_language>do hard coded user names, passwords, Read api a configuration file</technical_language>

Target:
private void setHttpClient(String host, int port) { try { client = HttpClients.custom() .setSSLSocketFactory(new SSLConnectionSocketFactory( SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build())) .build(); } catch (NoSuchAlgorithmException | keyManagementException | KeyStoreException e) { log.error(Constants.DEFAULT_EX, e); } baseUrl = Constants.URL_SCHEMA + host + ":" + port; }
Source:
<code>public boolean isProjectRegistered(String project) { ProjectPreferenceSetting projectSetting = getProjectSetting( project); <START> return (projectSetting != null <END> && projectSetting.startupQuestionAsked); }</code><technical_language>Legacy code, parens do sense this way</technical_language>

Target:
public boolean isProjectRegistered(String project) { ProjectPreferenceSetting projectSetting = getProjectSetting( project); return projectSetting != null && projectSetting.startupQuestionAsked; }
Source:
<code>public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { <START> String line = scanner.nextLine(); <END> logger.info(MorphaStemmer.stem(line)); } }</code><technical_language>main(), STDOUT</technical_language>

Target:
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(MorphaStemmer.stem(line)); } }
Source:
<code>public void shutdown(final String taskId) { if (!started) { <START> log.info("This TaskRunner is stopped. Ignorning shutdown command for task: %s", taskId); <END> } else if (pendingTasks.remove(taskId) != null) { log.info("Removed task from pending queue: %s", taskId); } else if (completeTasks.containsKey(taskId)) { cleanup(completeTasks.get(taskId).getWorker().getHost(), taskId); } else { final ZkWorker zkWorker = findWorkerRunningTask(taskId); if (zkWorker == null) { log.info("Can't shutdown! No worker running task %s", taskId); return; } try { final URL url = makeWorkerURL(zkWorker.getWorker(), String.format("/task/%s/shutdown", taskId)); final StatusResponseHolder response = httpClient.post(url) .go(RESPONSE_HANDLER) .get(); log.info( "Sent shutdown message to worker: %s, status %s, response: %s", zkWorker.getWorker().getHost(), response.getStatus(), response.getContent() ); if (!response.getStatus().equals(HttpResponseStatus.ACCEPTED)) { log.error("Shutdown failed for %s! Are you sure the task was running?", taskId); } } catch (Exception e) { throw Throwables.propagate(e); } } }</code><technical_language>Ignoring</technical_language>

Target:
public void shutdown(final String taskId) { if (!started) { log.info("This TaskRunner is stopped. Ignoring shutdown command for task: %s", taskId); } else if (pendingTasks.remove(taskId) != null) { pendingTaskPayloads.remove(taskId); log.info("Removed task from pending queue: %s", taskId); } else if (completeTasks.containsKey(taskId)) { cleanup(completeTasks.get(taskId).getWorker().getHost(), taskId); } else { final ZkWorker zkWorker = findWorkerRunningTask(taskId); if (zkWorker == null) { log.info("Can't shutdown! No worker running task %s", taskId); return; } try { final URL url = makeWorkerURL(zkWorker.getWorker(), String.format("/task/%s/shutdown", taskId)); final StatusResponseHolder response = httpClient.post(url) .go(RESPONSE_HANDLER) .get(); log.info( "Sent shutdown message to worker: %s, status %s, response: %s", zkWorker.getWorker().getHost(), response.getStatus(), response.getContent() ); if (!response.getStatus().equals(HttpResponseStatus.ACCEPTED)) { log.error("Shutdown failed for %s! Are you sure the task was running?", taskId); } } catch (Exception e) { throw Throwables.propagate(e); } } }
Source:
<code>public synchronized int getLast() { <START> if (data.isEmpty()) { <END> return -1; } return data.get(data.size() - 1); }</code><technical_language>I prefer a one-liner a ternary operator</technical_language>

Target:
public synchronized int getLast() { return data.isEmpty() ? -1 : data.get(data.size() - 1); }
Source:
<code>public void setId(String id) throws FormatException, IOException { super.setId(id); <START> if(zarrService == null) { <END> try { ServiceFactory factory = new ServiceFactory(); zarrService = factory.getInstance(ZarrService.class); } catch (DependencyException e) { throw new FormatException(ZarrServiceImpl.NO_ZARR_MSG, e); } } if(zarrService != null) { if (!zarrService.isOpen() && zarrService.getID() != id) { MetadataRetrieve meta = getMetadataRetrieve(); MetadataTools.verifyMinimumPopulated(meta, series); int x = meta.getPixelsSizeX(series).getValue().intValue(); int y = meta.getPixelsSizeY(series).getValue().intValue(); int z = meta.getPixelsSizeZ(series).getValue().intValue(); int c = meta.getPixelsSizeC(series).getValue().intValue(); int t = meta.getPixelsSizeT(series).getValue().intValue(); int shape = {x, y, z, c, t}; int chunkX = getTileSizeX(); int chunkY = getTileSizeY(); boolean usingTiling = chunkX > 0 && chunkY > 0; if (!usingTiling) { chunkX = CHUNK_DEFAULT; chunkY = CHUNK_DEFAULT; } int chunks = {chunkX, chunkY, 1, 1, 1}; int pixelType = FormatTools.pixelTypeFromString( meta.getPixelsType(series).toString()); zarrService.create(id, shape, chunks, pixelType, !meta.getPixelsBigEndian(series)); } } }</code><technical_language>space if ( consistent</technical_language>

Target:
public void setId(String id) throws FormatException, IOException { super.setId(id); if(zarrService == null) { zarrService = new ZarrServiceImpl(); } if(zarrService != null) { if (!zarrService.isOpen() && zarrService.getID() != id) { MetadataRetrieve meta = getMetadataRetrieve(); MetadataTools.verifyMinimumPopulated(meta, series); int x = meta.getPixelsSizeX(series).getValue().intValue(); int y = meta.getPixelsSizeY(series).getValue().intValue(); int z = meta.getPixelsSizeZ(series).getValue().intValue(); int c = meta.getPixelsSizeC(series).getValue().intValue(); int t = meta.getPixelsSizeT(series).getValue().intValue(); int shape = {x, y, z, c, t}; int chunkX = getTileSizeX(); int chunkY = getTileSizeY(); boolean usingTiling = chunkX > 0 && chunkY > 0; if (!usingTiling) { chunkX = CHUNK_DEFAULT; chunkY = CHUNK_DEFAULT; } int chunks = {chunkX, chunkY, 1, 1, 1}; int pixelType = FormatTools.pixelTypeFromString( meta.getPixelsType(series).toString()); zarrService.create(id, shape, chunks, pixelType, !meta.getPixelsBigEndian(series)); } } }
Source:
<code>public void testSuccessWithIncludeOptionalMetadataTrue() throws Exception { Response<InstitutionsGetByIdResponse> response = client().service().institutionsGetById( new InstitutionsGetByIdRequest(TARTAN_BANK_INSTITUTION_ID).withIncludeOptionalMetadata(true)) .execute(); assertSuccessResponse(response); Institution institution = response.body().getInstitution(); assertFalse(institution.getCredentials().isEmpty()); for (Institution.Credential c : institution.getCredentials()) { assertNotNull(c.getLabel()); assertNotNull(c.getType()); assertNotNull(c.getName()); } assertIsValidInstitution(institution); assertEquals("<LINK_0>", institution.getUrl()); <START> assertEquals("#174e7c", institution.getPrimaryColor()); <END> }</code><technical_language>this removed</technical_language>

Target:
public void testSuccessWithIncludeOptionalMetadataTrue() throws Exception { Response<InstitutionsGetByIdResponse> response = client().service().institutionsGetById( new InstitutionsGetByIdRequest(TARTAN_BANK_INSTITUTION_ID).withIncludeOptionalMetadata(true)) .execute(); assertSuccessResponse(response); Institution institution = response.body().getInstitution(); assertFalse(institution.getCredentials().isEmpty()); for (Institution.Credential c : institution.getCredentials()) { assertNotNull(c.getLabel()); assertNotNull(c.getType()); assertNotNull(c.getName()); } assertIsValidInstitution(institution); assertEquals("<LINK_0>", institution.getUrl()); assertNotNull(institution.getLogo()); assertEquals("#174e7c", institution.getPrimaryColor()); }
Source:
<code>public void testInvalidConfig() throws Exception { XMLParser.Config config = new XMLParser.Config("body", "UTF-8", "category://book/@category,title://book/title," + "year:/bookstore/book[price>35.00]/year,price:/bookstore/book[price>35.00]/price,subcategory://book/subcategory", "category:,title:string,price:double,year:int,subcategory:string", "Exit on error"); MockPipelineConfigurer configurer = new MockPipelineConfigurer(INPUT); String caughtMessage = ""; try { new XMLParser(config).configurePipeline(configurer); Assert.fail(); } catch (Exception e) { caughtMessage = e.getMessage(); } <START> Assert.assertEquals(validationExceptionMessage, caughtMessage); <END> FailureCollector collector = configurer.getStageConfigurer().getFailureCollector(); Assert.assertEquals(1, collector.getValidationFailures().size()); Assert.assertEquals(1, collector.getValidationFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute(stage, mockStage); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, "fieldTypeMapping"); expectedCause.addAttribute(CauseAttributes.CONFIG_ELEMENT, "category:"); Assert.assertEquals(expectedCause, collector.getValidationFailures().get(0).getCauses().get(0)); }</code><technical_language>check exception message</technical_language>

Target:
public void testInvalidConfig() throws Exception { XMLParser.Config config = new XMLParser.Config("body", "UTF-8", "category://book/@category,title://book/title," + "year:/bookstore/book[price>35.00]/year,price:/bookstore/book[price>35.00]/price,subcategory://book/subcategory", "category:,title:string,price:double,year:int,subcategory:string", "Exit on error"); MockPipelineConfigurer configurer = new MockPipelineConfigurer(INPUT); try { new XMLParser(config).configurePipeline(configurer); Assert.fail(); } catch (ValidationException e) { Assert.assertEquals(1, e.getFailures().size()); Assert.assertEquals(1, e.getFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute("stage", "mockstage"); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, XMLParser.Config.FIELD_TYPE_MAPPING); expectedCause.addAttribute(CauseAttributes.CONFIG_ELEMENT, "category:"); Assert.assertEquals(expectedCause, e.getFailures().get(0).getCauses().get(0)); } }
Source:
<code>private void handleEditorImage(Intent data) { String newFilePath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT); boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false); if (isImageEdit) { } else { newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH); <START> ; <END> } Log.d("image is edit", isImageEdit + ""); LoadImageTask loadTask = new LoadImageTask(); loadTask.execute(newFilePath); }</code><technical_language>is extra semicolon here? Also, try refactor code is absolutely required</technical_language>

Target:
private void handleEditorImage(Intent data) { String newFilePath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT); boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false); if (isImageEdit) { } else { newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH); } Log.d("image is edit", isImageEdit + ""); LoadImageTask loadTask = new LoadImageTask(); loadTask.execute(newFilePath); }