auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static String retrieveNodeExecutableFromConfig(@Nullable Configuration configuration) throws NodeCommandException { if (configuration != null && (configuration.hasKey(NODE_EXECUTABLE_PROPERTY) || configuration.hasKey(NODE_EXECUTABLE_PROPERTY_TS))) { String nodeExecutable = ""; String usedProperty = ""; if (configuration.hasKey(NODE_EXECUTABLE_PROPERTY_TS)) { LOG.warn("The use of " + NODE_EXECUTABLE_PROPERTY_TS + " is deprecated, use " + NODE_EXECUTABLE_PROPERTY + " instead."); usedProperty = NODE_EXECUTABLE_PROPERTY_TS; nodeExecutable = configuration.get(NODE_EXECUTABLE_PROPERTY_TS).get(); } if (configuration.hasKey(NODE_EXECUTABLE_PROPERTY)) { usedProperty = NODE_EXECUTABLE_PROPERTY; nodeExecutable = configuration.get(NODE_EXECUTABLE_PROPERTY).get(); } File file = new File(nodeExecutable); if (file.exists()) { LOG.info("Using Node.js executable from property {}.", file.getAbsoluteFile(), usedProperty); return nodeExecutable; } else { <START> LOG.error("Provided Node.js executable file does not exist. Property '{}' was to '{}'", NODE_EXECUTABLE_PROPERTY, nodeExecutable); <END> throw new NodeCommandException("Provided Node.js executable file does not exist."); } } LOG.debug("Using default Node.js executable: '{}'.", NODE_EXECUTABLE_DEFAULT); return NODE_EXECUTABLE_DEFAULT; }</code><technical_language>replace NODE_EXECUTABLE_PROPERTY usedProperty ? If yes, is a test needs updated</technical_language>

Target:
private static String retrieveNodeExecutableFromConfig(@Nullable Configuration configuration) throws NodeCommandException { if (configuration != null && (configuration.hasKey(NODE_EXECUTABLE_PROPERTY) || configuration.hasKey(NODE_EXECUTABLE_PROPERTY_TS))) { String nodeExecutable = ""; String usedProperty = ""; if (configuration.hasKey(NODE_EXECUTABLE_PROPERTY_TS)) { LOG.warn("The use of " + NODE_EXECUTABLE_PROPERTY_TS + " is deprecated, use " + NODE_EXECUTABLE_PROPERTY + " instead."); usedProperty = NODE_EXECUTABLE_PROPERTY_TS; nodeExecutable = configuration.get(NODE_EXECUTABLE_PROPERTY_TS).get(); } if (configuration.hasKey(NODE_EXECUTABLE_PROPERTY)) { usedProperty = NODE_EXECUTABLE_PROPERTY; nodeExecutable = configuration.get(NODE_EXECUTABLE_PROPERTY).get(); } File file = new File(nodeExecutable); if (file.exists()) { LOG.info("Using Node.js executable from property {}.", file.getAbsoluteFile(), usedProperty); return nodeExecutable; } else { LOG.error("Provided Node.js executable file does not exist. Property '{}' was to '{}'", usedProperty, nodeExecutable); throw new NodeCommandException("Provided Node.js executable file does not exist."); } } LOG.debug("Using default Node.js executable: '{}'.", NODE_EXECUTABLE_DEFAULT); return NODE_EXECUTABLE_DEFAULT; }
Source:
<code>private void autoIgnoreDerivedResources(IProject project, IProgressMonitor monitor) throws CoreException { if (!Activator.autoIgnoreDerived()) { return; } List<IPath> paths = findDerivedResources(project); if (paths.size() > 0) { IgnoreOperation ignoreOp = new IgnoreOperation(paths); IProgressMonitor subMonitor = new <START> SubProgressMonitor(monitor, <END> 1); ignoreOp.execute(subMonitor); } }</code><technical_language>this? pass 'monitor'</technical_language>

Target:
private void autoIgnoreDerivedResources(IProject project, IProgressMonitor monitor) throws CoreException { if (!Activator.autoIgnoreDerived()) { return; } List<IPath> paths = findDerivedResources(project); if (paths.size() > 0) { IgnoreOperation ignoreOp = new IgnoreOperation(paths); ignoreOp.execute(monitor); } }
Source:
<code>private void showOrHideButtons() { if (playQueue == null) return; <START> if (playQueue.getIndex() == 0) playPreviousButton.setVisibility(View.INVISIBLE); else playPreviousButton.setVisibility(View.VISIBLE); if (playQueue.getIndex() + 1 == playQueue.getStreams().size()) playNextButton.setVisibility(View.INVISIBLE); else playNextButton.setVisibility(View.VISIBLE); if (playQueue.getStreams().size() <= 1 || popupPlayerSelected()) queueButton.setVisibility(View.GONE); else queueButton.setVisibility(View.VISIBLE); <END> }</code><technical_language>?: suggestion playPreviousButton.setVisibility(playQueue.getIndex() == 0 ? View.INVISIBLE : View.VISIBLE); playNextButton.setVisibility(playQueue.getIndex() + 1 == playQueue.getStreams().size() ? View.INVISIBLE : View.VISIBLE); queueButton.setVisibility(playQueue.getStreams().size() <= 1 || popupPlayerSelected() ? View.GONE : View.VISIBLE);</technical_language>

Target:
private void showOrHideButtons() { if (playQueue == null) { return; } playPreviousButton.setVisibility(playQueue.getIndex() == 0 ? View.INVISIBLE : View.VISIBLE); playNextButton.setVisibility(playQueue.getIndex() + 1 == playQueue.getStreams().size() ? View.INVISIBLE : View.VISIBLE); queueButton.setVisibility(playQueue.getStreams().size() <= 1 || popupPlayerSelected() ? View.GONE : View.VISIBLE); }
Source:
<code>private String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table, String simpleName) { logger.debug("JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}", filter.toString(), numberDecimalcount, table, simpleName); <START> SimpleDateFormat jdbcDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); <END> String filterString = ""; if (filter.getBeginDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME>'" + jdbcDateFormat.format(filter.getBeginDate()) + "'"; } if (filter.getEndDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME<'" + jdbcDateFormat.format(filter.getEndDate().getTime()) + "'"; } filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC "; if (filter.getPageSize() != 0x7fffffff) { filterString += " LIMIT " + filter.getPageNumber() * filter.getPageSize() + "," + filter.getPageSize(); } String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1 ? "SELECT time, ROUND(value," + numberDecimalcount + ") FROM " + table : "SELECT time, value FROM " + table; if (!filterString.isEmpty()) { queryString += filterString; } logger.debug("JDBC::query queryString = {}", queryString); return queryString; }</code><technical_language>This DateFormat object changes. static final in class scope save a bit of performance</technical_language>

Target:
private String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table, String simpleName) { logger.debug( "JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}", filter.toString(), numberDecimalcount, table, simpleName); String filterString = ""; if (filter.getBeginDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME>'" + jdbcDateFormat.print(new DateTime(filter.getBeginDate().getTime())) + "'"; } if (filter.getEndDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME<'" + jdbcDateFormat.print(new DateTime(filter.getEndDate().getTime())) + "'"; } filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC "; if (filter.getPageSize() != 0x7fffffff) { filterString += " LIMIT " + filter.getPageNumber() * filter.getPageSize() + "," + filter.getPageSize(); } String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1 ? "SELECT time, ROUND(value," + numberDecimalcount + ") FROM " + table : "SELECT time, value FROM " + table; if (!filterString.isEmpty()) { queryString += filterString; } logger.debug("JDBC::query queryString = {}", queryString); return queryString; }
Source:
<code>public <V> V getService(Class<V> serviceClass, String filter) { ServiceReference<V> serviceRef = getServiceReference(serviceClass, filter); if (serviceRef == null) { return null; } else { if <START> (fServices.containsKey(serviceRef)) <END> { @SuppressWarnings("unchecked") V service = (V)fServices.get(serviceRef); return service; } else { V service = fBundleContext.getService(serviceRef); fServices.put(serviceRef, service); return service; } } }</code><technical_language>Redundant double checking of key</technical_language>

Target:
public <V> V getService(Class<V> serviceClass, String filter) { ServiceReference<V> serviceRef = getServiceReference(serviceClass, filter); if (serviceRef == null) { return null; } @SuppressWarnings("unchecked") V service = (V)fServices.get(serviceRef); if (service == null) { if (fServices.containsKey(serviceRef) == false) { service = fBundleContext.getService(serviceRef); fServices.put(serviceRef, service); } } return service; }
Source:
<code>public void onBindViewHolder(RandoViewHolder holder, Cursor cursor) { recycle(holder); holder.rando = RandoDAO.cursorToRando(cursor); holder.position = cursor.getPosition(); <START> holder.timestamp.setText(dateFormat.format(holder.rando.date).toUpperCase()); <END> setRatingIcon(holder, false); loadImages(holder.randoItemLayout.getContext(), holder, holder.rando); if (holder.rando.isUnwanted()) { holder.unwantedRandoView = new UnwantedRandoView(holder.randoItemLayout.getContext()); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(imageSize, imageSize); holder.randoItemLayout.addView(holder.unwantedRandoView, layoutParams); } else { if (holder.rando.isToUpload()) { holder.uploadingProgress = new RoundProgress(holder.randoItemLayout.getContext(), (float) (imageSize / 2.0) - 8); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(imageSize, imageSize); holder.randoItemLayout.addView(holder.uploadingProgress, layoutParams); } else { setAnimations(holder); } } }</code><technical_language>2 formatters: for current year for ones? need year for current</technical_language>

Target:
public void onBindViewHolder(RandoViewHolder holder, Cursor cursor) { recycle(holder); holder.rando = RandoDAO.cursorToRando(cursor); holder.position = cursor.getPosition(); String timestamp = holder.rando.date.after(nyDate) ? dateFormat.format(holder.rando.date) : dateYearFormat.format(holder.rando.date); holder.timestamp.setText(timestamp.toUpperCase()); setRatingIcon(holder, false); loadImages(holder.randoItemLayout.getContext(), holder, holder.rando); if (holder.rando.isUnwanted()) { holder.unwantedRandoView = new UnwantedRandoView(holder.randoItemLayout.getContext()); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(imageSize, imageSize); holder.randoItemLayout.addView(holder.unwantedRandoView, layoutParams); } else { if (holder.rando.isToUpload()) { holder.uploadingProgress = new RoundProgress(holder.randoItemLayout.getContext(), (float) (imageSize / 2.0) - 8); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(imageSize, imageSize); holder.randoItemLayout.addView(holder.uploadingProgress, layoutParams); } else { setAnimations(holder); } } }
Source:
<code>protected void setWorkflowImplServiceListener(WorkflowImplServiceListener workflowListener) { <START> if(workflowListener !=null) { <END> WorkflowImplServiceDataHolder.getInstance().getWorkflowListenerList() .add(workflowListener); } }</code><technical_language>Do need null check ? I register a service null object. formatting is wrong: != null</technical_language>

Target:
protected void setWorkflowImplServiceListener(WorkflowImplServiceListener workflowListener) { WorkflowImplServiceDataHolder.getInstance().getWorkflowListenerList().add(workflowListener); }
Source:
<code>public boolean performNextOperation(int completedChildCount) { <START> switch (getParameters().getCreateSnapshotStage()) { <END> case CREATE_VOLUME_FINISHED: getParameters().setCreateSnapshotStage(CreateSnapshotForVmParameters.CreateSnapshotStage.CREATE_SNAPSHOT_STARTED); Snapshot createdSnapshot = snapshotDao.get(getParameters().getCreatedSnapshotId()); getParameters().setTaskGroupSuccess(createdSnapshot != null && getParameters().getTaskGroupSuccess()); if (getParameters().getTaskGroupSuccess()) { getParameters().setLiveSnapshotRequired(shouldPerformLiveSnapshot(createdSnapshot)); if (getParameters().isLiveSnapshotRequired()) { getParameters().setLiveSnapshotSucceeded(performLiveSnapshot(createdSnapshot)); } else if (snapshotWithMemory(createdSnapshot)) { logMemorySavingFailed(); snapshotDao.removeMemoryFromSnapshot(createdSnapshot.getId()); removeMemoryVolumesOfSnapshot(createdSnapshot); } } getParameters().setCreateSnapshotStage(CreateSnapshotForVmParameters.CreateSnapshotStage.CREATE_SNAPSHOT_COMPLETED); break; default: return false; } persistCommandIfNeeded(); return true; }</code><technical_language>do need a switch statement for option? If is more elegant in case IMO</technical_language>

Target:
public boolean performNextOperation(int completedChildCount) { if (getParameters().getCreateSnapshotStage() == CreateSnapshotForVmParameters.CreateSnapshotStage.CREATE_VOLUME_FINISHED) { getParameters().setCreateSnapshotStage(CreateSnapshotForVmParameters.CreateSnapshotStage.CREATE_SNAPSHOT_STARTED); Snapshot createdSnapshot = snapshotDao.get(getParameters().getCreatedSnapshotId()); getParameters().setTaskGroupSuccess(createdSnapshot != null && getParameters().getTaskGroupSuccess()); if (getParameters().getTaskGroupSuccess()) { getParameters().setLiveSnapshotRequired(shouldPerformLiveSnapshot(createdSnapshot)); if (getParameters().isLiveSnapshotRequired()) { getParameters().setLiveSnapshotSucceeded(performLiveSnapshot(createdSnapshot)); } else if (snapshotWithMemory(createdSnapshot)) { logMemorySavingFailed(); snapshotDao.removeMemoryFromSnapshot(createdSnapshot.getId()); removeMemoryVolumesOfSnapshot(createdSnapshot); } } getParameters().setCreateSnapshotStage(CreateSnapshotForVmParameters.CreateSnapshotStage.CREATE_SNAPSHOT_COMPLETED); persistCommandIfNeeded(); return true; } return false; }
Source:
<code>void connect() throws Exception { webSocketConnection.connect(); verify(webSocketClient) .connectBlocking( <START> WebSocketConnection.DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); <END> }</code><technical_language>nitpicky, if gain verifying parameters of this test, this more flexible asserting arg is passed connect blocking</technical_language>

Target:
void connect() throws Exception { when(webSocketClient.connectBlocking(anyLong(), any())).thenReturn(true); webSocketConnection.connect(); verify(webSocketClient).connectBlocking(anyLong(), any()); }
Source:
<code><START> void close() { <END> if (running) { synchronized (this) { if (running) { try { LOG.info("Starting to close FeatureStateConsumer."); kafkaConsumer.wakeup(); shutdownLatch.await(); running = false; LOG.info("Successfully closed FeatureStateConsumer."); } catch (InterruptedException e) { LOG.error("An error occurred while closing FeatureStateConsumer.", e); } } else { LOG.info("FeatureStateConsumer has already been closed."); } } } else { LOG.info("FeatureStateConsumer has already been closed."); } }</code><technical_language>suggest private</technical_language>

Target:
private synchronized void close() { if (running) { try { LOG.debug("Starting to close FeatureStateConsumer."); kafkaConsumer.wakeup(); shutdownLatch.await(); LOG.debug("Successfully closed FeatureStateConsumer."); } catch (InterruptedException e) { LOG.warn("Closing of FeatureStateConsumer was interrupted.", e); currentThread().interrupt(); } } else { LOG.info("FeatureStateConsumer has already been closed."); } }
Source:
<code>default SaslServer createSaslServer(String mechanism, List<Principal> principals, String protocol, String serverName, Map<String, String> props) throws SaslException { <START> AuthorizingCallbackHandler callbackHandler = getCallbackHandler(mechanism, props); <END> if ("EXTERNAL".equals(mechanism)) { for(Principal principal : principals) { if (principal instanceof X500Principal) { ExternalSaslServerFactory factory = new ExternalSaslServerFactory((X500Principal) principal); SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, callbacks -> { if (callbackHandler != null) { callbackHandler.handle(callbacks); } }); return new SubjectSaslServer(saslServer, principals, callbackHandler); } } throw new IllegalStateException("EXTERNAL mech requires X500Principal"); } else { for (SaslServerFactory factory : SaslUtils.getSaslServerFactories()) { if (factory != null) { SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, callbacks -> { if (callbackHandler != null) { callbackHandler.handle(callbacks); } }); if (saslServer != null) { return new SubjectSaslServer(saslServer, principals, callbackHandler); } } } } return null; }</code><technical_language>add a ClassLoader param implement getCallbackHandler in EndpointServerAuthenticationProvider</technical_language>

Target:
default SaslServer createSaslServer(String mechanism, List<Principal> principals, String protocol, String serverName, Map<String, String> props) throws SaslException { AuthorizingCallbackHandler callbackHandler = getCallbackHandler(mechanism, props); if ("EXTERNAL".equals(mechanism)) { for(Principal principal : principals) { if (principal instanceof X500Principal) { ExternalSaslServerFactory factory = new ExternalSaslServerFactory((X500Principal) principal); SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, callbacks -> { if (callbackHandler != null) { callbackHandler.handle(callbacks); } }); return new SubjectSaslServer(saslServer, principals, callbackHandler); } } throw new IllegalStateException("EXTERNAL mech requires X500Principal"); } else { for (SaslServerFactory factory : SaslUtils.getSaslServerFactories(this.getClass().getClassLoader(), true)) { if (factory != null) { SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, callbacks -> { if (callbackHandler != null) { callbackHandler.handle(callbacks); } }); if (saslServer != null) { return new SubjectSaslServer(saslServer, principals, callbackHandler); } } } } return null; }
Source:
<code>private boolean isLocationEnabled() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); boolean gpsEnabled = false; boolean networkEnabled = false; try { gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); networkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); <START> } catch (Exception e) { <END> Toast.makeText(getApplicationContext(), R.string.gps_network_not_available, Toast.LENGTH_SHORT).show(); } if (gpsEnabled && networkEnabled) { return true; } else { return false; } }</code><technical_language>Catching generic exception is discouraged. throw other exception NullPointerException? check nullity of lm prior processing. <LINK_0></technical_language>

Target:
private boolean isLocationEnabled() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); boolean gpsEnabled = false; boolean networkEnabled = false; if (lm != null) { try { gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); networkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (NullPointerException e) { Toast.makeText(getApplicationContext(), R.string.gps_network_not_available, Toast.LENGTH_SHORT) .show(); } } else { Toast.makeText(getApplicationContext(), R.string.location_services_unavailable, Toast.LENGTH_SHORT) .show(); } return gpsEnabled && networkEnabled; }
Source:
<code>protected void replay(long windowId) throws SQLException { try { MutablePair<Integer, Integer> recoveredData = (MutablePair<Integer, Integer>)windowManager.load(operatorId, windowId); if (recoveredData != null && shouldReplayWindow(recoveredData)) { LOG.debug("[Recovering Window ID - for record range: {}, {}]", windowId, recoveredData.left, recoveredData.right); ps = store.getConnection().prepareStatement( <START> buildRangeQuery(rangeQueryPair.getKey(), (rangeQueryPair.getValue() - rangeQueryPair.getKey())), <END> TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); LOG.info("Query formed to recover data - {}", ps.toString()); emitReplayedTuples(ps); } if (currentWindowId == windowManager.getLargestRecoveryWindow()) { try { if (!isPollerPartition && rangeQueryPair.getValue() != null) { ps = store.getConnection().prepareStatement( buildRangeQuery(lastEmittedRecord, (rangeQueryPair.getValue() - lastEmittedRecord)), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); } else { Integer bound = null; if (lastEmittedRecord == null) { bound = rangeQueryPair.getKey(); } else { bound = lastEmittedRecord; } ps = store.getConnection().prepareStatement(buildRangeQuery(bound, Integer.MAX_VALUE), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); } scanService.scheduleAtFixedRate(new DBPoller(), 0, pollInterval, TimeUnit.MILLISECONDS); } catch (SQLException e) { throw new RuntimeException(e); } } } catch (IOException e) { throw new RuntimeException("replay", e); } }</code><technical_language>this fetch data recoveredData.left recoveredData.right</technical_language>

Target:
protected void replay(long windowId) throws SQLException { try { MutablePair<Integer, Integer> recoveredData = (MutablePair<Integer, Integer>)windowManager.load(operatorId, windowId); if (recoveredData != null && shouldReplayWindow(recoveredData)) { LOG.debug("[Recovering Window ID - for record range: {}, {}]", windowId, recoveredData.left, recoveredData.right); ps = store.getConnection().prepareStatement( buildRangeQuery(recoveredData.left, (recoveredData.right - recoveredData.left)), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); LOG.info("Query formed to recover data - {}", ps.toString()); emitReplayedTuples(ps); } if (currentWindowId == windowManager.getLargestRecoveryWindow()) { try { if (!isPollerPartition && rangeQueryPair.getValue() != null) { ps = store.getConnection().prepareStatement( buildRangeQuery(lastEmittedRow, (rangeQueryPair.getValue() - lastEmittedRow)), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); } else { Integer bound = null; if (lastEmittedRow == null) { bound = rangeQueryPair.getKey(); } else { bound = lastEmittedRow; } ps = store.getConnection().prepareStatement(buildRangeQuery(bound, Integer.MAX_VALUE), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); } scanService.scheduleAtFixedRate(new DBPoller(), 0, pollInterval, TimeUnit.MILLISECONDS); } catch (SQLException e) { throw new RuntimeException(e); } } } catch (IOException e) { throw new RuntimeException("Exception during replay of records.", e); } }
Source:
<code>public CollectionFuture<Boolean> asyncLopInsert(String key, int index, Object value, CollectionAttributes attributesForCreate) { <START> ListInsert<Object> listStore = new ListInsert<Object>(value, <END> (attributesForCreate != null), null, attributesForCreate); return asyncCollectionInsert(key, String.valueOf(index), listStore, collectionTranscoder); }</code><technical_language>listStore => listInsert</technical_language>

Target:
public CollectionFuture<Boolean> asyncLopInsert(String key, int index, Object value, CollectionAttributes attributesForCreate) { ListInsert<Object> listInsert = new ListInsert<Object>(value, (attributesForCreate != null), null, attributesForCreate); return asyncCollectionInsert(key, String.valueOf(index), listInsert, collectionTranscoder); }
Source:
<code><START> public Optional<T> getFirstResult() { <END> Collection<T> list = getResult(); Iterator<T> iterator = list.iterator(); if (iterator.hasNext()) { return Optional.of(iterator.next()); } return Optional.empty(); }</code><technical_language>getResult() unnecessary creates empty list. suggest writing if(result != null) { return result.stream().findFirst(); } return Optional.empty();</technical_language>

Target:
public Optional<T> getFirstResult() { if (result != null) { return result.stream().findFirst(); } return Optional.empty(); }
Source:
<code>protected void configureMoveCommand(String source, String destination) { Connection connection = getHandlerConnection(); command = new RemoteMoveFileCommand(); command.setConnectionConfiguration(connection.getConfiguration()); <START> ((RemoteCommand) command).setConnection(connection); <END> ((RemoteMoveFileCommand) command).setConfiguration(source, destination); ((RemoteMoveFileCommand) command).setMoveType(HANDLE_TYPE); }</code><technical_language>Type casting again</technical_language>

Target:
protected void configureMoveCommand(String source, String destination) { RemoteMoveFileCommand cmd = new RemoteMoveFileCommand(); cmd.setConfiguration(source, destination); cmd.setMoveType(HANDLE_TYPE); cmd.setPermissions(permissions); cmd.setConnectionConfiguration(connection.get().getConfiguration()); cmd.setConnection(connection.get()); command.set(cmd); }
Source:
<code>private static Meter getMeter(String name) { <START> return metricsManager.registerMeter(SnapshotTransaction.class, name); <END> }</code><technical_language>a scary this is calling "registerMeter", method renamed idempotent</technical_language>

Target:
private static Meter getMeter(String name) { return metricsManager.registerOrGetMeter(SnapshotTransaction.class, name); }
Source:
<code>private static String getAvaticaConnectionId(Map<String, Object> requestMap) throws IOException { Object connectionIdObj = requestMap.get("connectionId"); if (connectionIdObj == null) { throw new IAE("Received an Avatica request without a connectionId."); } if (!(connectionIdObj instanceof String)) { throw new IAE("Received an Avatica request with a non-String connectionId."); } <START> return (String) requestMap.get("connectionId"); <END> }</code><technical_language>nit: return (String) connectionIdObj;</technical_language>

Target:
private static String getAvaticaConnectionId(Map<String, Object> requestMap) throws IOException { Object connectionIdObj = requestMap.get("connectionId"); if (connectionIdObj == null) { throw new IAE("Received an Avatica request without a connectionId."); } if (!(connectionIdObj instanceof String)) { throw new IAE("Received an Avatica request with a non-String connectionId."); } return (String) connectionIdObj; }
Source:
<code>public static String generateHtmlSnippet(String id, URI baseUri) { <START> StringBuilder sb = new StringBuilder(); <END> Formatter formatter = new Formatter(sb); formatter.format("<script type=\"text/javascript\" language=\"javascript\" " + "src=\"%1$s/factory/resources/embed.js?%2$s\"></script>", UriBuilder.fromUri(baseUri).replacePath("").build(), id); return sb.toString(); }</code><technical_language>useless string builder, default constructor</technical_language>

Target:
public static String generateHtmlSnippet(String id, URI baseUri) { Formatter formatter = new Formatter(); formatter.format("<script type=\"text/javascript\" language=\"javascript\" " + "src=\"%1$s/factory/resources/embed.js?%2$s\"></script>", UriBuilder.fromUri(baseUri).replacePath("").build().toString(), id); return formatter.toString(); }
Source:
<code>private Tracing newTracing(String serviceName) { return Tracing.newBuilder() .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder() <START> .addScopeDecorator(MDCScopeDecorator.create()).build()) <END> .localServiceName(serviceName) .sampler(Sampler.create(rate)) .spanReporter(spanReporter).build(); }</code><technical_language>add option turn on|off this MDC scope decorator</technical_language>

Target:
private Tracing newTracing(String serviceName) { Tracing brave = null; if (camelContext.isUseMDCLogging()) { brave = Tracing.newBuilder() .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder() .addScopeDecorator(MDCScopeDecorator.create()).build()) .localServiceName(serviceName) .sampler(Sampler.create(rate)) .spanReporter(spanReporter).build(); } else { brave = Tracing.newBuilder() .localServiceName(serviceName) .sampler(Sampler.create(rate)) .spanReporter(spanReporter).build(); } return brave; }
Source:
<code>public boolean setZoneTemperatureControlValues(String sessionToken, Integer zoneID, String zoneName, List<Object[]> controlValues) { if (checkRequiredZone(zoneID, zoneName)) { try { if (checkRequiredZone(zoneID, zoneName)) { if (controlValues != null) { SimpleRequestBuilder builder = SimpleRequestBuilder.buildNewRequest(InterfaceKeys.JSON) .addRequestClass(ClassKeys.ZONE) .addFunction(FunctionKeys.SET_TEMEPERATURE_CONTROL_VALUE) .addParameter(ParameterKeys.TOKEN, sessionToken) .addParameter(ParameterKeys.ID, convertIntegerToString(zoneID)) .addParameter(ParameterKeys.NAME, zoneName); for (Object[] objAry : controlValues) { if (objAry.length == 2 && objAry[0] instanceof String && objAry[1] instanceof Integer) { builder.addParameter((String) objAry[0], convertIntegerToString((Integer) objAry[1])); } else { builder.buildRequestString(); <START> throw new IllegalArgumentException( <END> "The first field of the object array have to be a String and the second have to be a Integer."); } } String response = transport.execute(builder.buildRequestString()); return JSONResponseHandler.checkResponse(JSONResponseHandler.toJsonObject(response)); } } } catch (Exception e) { logger.debug("An exception occurred", e); } } return false; }</code><technical_language>Do catch this Exception somewhere</technical_language>

Target:
public boolean setZoneTemperatureControlValues(String sessionToken, Integer zoneID, String zoneName, List<Object[]> controlValues) { if (checkRequiredZone(zoneID, zoneName)) { if (checkRequiredZone(zoneID, zoneName)) { if (controlValues != null) { SimpleRequestBuilder builder = SimpleRequestBuilder.buildNewRequest(InterfaceKeys.JSON) .addRequestClass(ClassKeys.ZONE).addFunction(FunctionKeys.SET_TEMEPERATURE_CONTROL_VALUE) .addDefaultZoneParameter(sessionToken, zoneID, zoneName); for (Object[] objAry : controlValues) { if (objAry.length == 2 && objAry[0] instanceof String && objAry[1] instanceof Integer) { builder.addParameter((String) objAry[0], SimpleRequestBuilder.objectToString(objAry[1])); } else { builder.buildRequestString(); throw new IllegalArgumentException( "The first field of the object array have to be a String and the second have to be a Integer."); } } String response = transport.execute(builder.buildRequestString()); return JSONResponseHandler.checkResponse(JSONResponseHandler.toJsonObject(response)); } } } return false; }
Source:
<code>public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); IdSiteController controller = new LogoutIdSiteController(); controller.setServerUriResolver(serverUriResolver); controller.setCallbackUri(idSiteResultUri); controller.setIdSiteOrganizationResolver(idSiteOrganizationResolver); controller.setAlreadyLoggedInUri(nextUri); controller.init(); this.idSiteController = controller; <START> } <END></code><technical_language>removing this? LogoutController#init() //If sub-classess override this method CALL super.init() some point insider custom implementation. Removing existing explicit invocation a method in a parent class uncaught errors if doing. Please add in solve new issue this cause</technical_language>

Target:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); IdSiteController controller = new LogoutIdSiteController(); controller.setServerUriResolver(serverUriResolver); controller.setCallbackUri(idSiteResultUri); controller.setIdSiteOrganizationResolver(idSiteOrganizationResolver); controller.setAlreadyLoggedInUri(nextUri); controller.init(); this.idSiteController = controller; super.init(); }
Source:
<code>public Certificate getCertificateForGateway() throws KeystoreServiceException, KeyStoreException { Certificate cert = null; <START> readLock.lock(); <END> try { KeyStore ks = getKeystoreForGateway(); if (ks != null) { cert = ks.getCertificate(config.getIdentityKeyAlias()); } return cert; } finally { readLock.unlock(); } }</code><technical_language>a minor note: getKeystoreForGateway applies read lock; do need lock here? I critical step is fetch ks instance is guarded readLock</technical_language>

Target:
public Certificate getCertificateForGateway() throws KeystoreServiceException, KeyStoreException { KeyStore ks = getKeystoreForGateway(); return (ks == null) ? null : ks.getCertificate(config.getIdentityKeyAlias()); }
Source:
<code>public void findAllTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community Two") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Collection col2 = CollectionBuilder.createCollection(context, child2).withName("Collection 2").build(); getClient().perform(get("/api/core/collections") <START> .param("embed", CollectionMatcher.getFullEmbedsParameter())) <END> .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$._embedded.collections", Matchers.containsInAnyOrder( CollectionMatcher.matchCollectionEntryFullProjection(col1.getName(), col1.getID(), col1.getHandle()), CollectionMatcher.matchCollectionEntryFullProjection(col2.getName(), col2.getID(), col2.getHandle()) ))); }</code><technical_language>check if needed <LINK_0> if needed I recommend create a copy of current failing test flag report in a JIRA ticket</technical_language>

Target:
public void findAllTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community Two") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Collection col2 = CollectionBuilder.createCollection(context, child2).withName("Collection 2").build(); getClient().perform(get("/api/core/collections") .param("embed", CollectionMatcher.getEmbedsParameter())) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$._embedded.collections", Matchers.containsInAnyOrder( CollectionMatcher.matchCollectionEntrySpecificEmbedProjection(col1.getName(), col1.getID(), col1.getHandle()), CollectionMatcher.matchCollectionEntrySpecificEmbedProjection(col2.getName(), col2.getID(), col2.getHandle()) ))); }
Source:
<code>protected final void check() { checkArgument(!password().equals(""), "password cannot be empty"); <START> } <END></code><technical_language>sorry, missed this time through, I want error if URI contains empty string, a check for somehow</technical_language>

Target:
protected final void check() { Preconditions.checkArgument(!uri().equals(URI.create("")), "uri cannot be empty"); Preconditions.checkArgument(!password().equals(""), "password cannot be empty"); }
Source:
<code>public void deleteSupplementaryFolder() { IFolder supplFolder = getTraceSupplementaryFolder(getResourceName()); if (supplFolder.exists()) { try { supplFolder.delete(true, new NullProgressMonitor()); } catch (CoreException e) { <START> Activator.getDefault().logError("Error deleting supplementary folder " + supplFolder, e); END> } } }</code><technical_language>externalize</technical_language>

Target:
public void deleteSupplementaryFolder() { IFolder supplFolder = getTraceSupplementaryFolder(getResourceName()); if (supplFolder.exists()) { try { supplFolder.delete(true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().logError(Messages.TmfCommonProjectElement_ErrorDeletingSF + supplFolder, e); } } }
Source:
<code>public void makeUnDiscoverablePatchTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .withSubject("ExtraEntry") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); <START> ReplaceOperation replaceOperation = new ReplaceOperation("/discoverable", "false"); <END> ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/core/items/" + item.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(false))); getClient(token).perform(get("/api/core/items/" + item.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(false))); }</code><technical_language>official true instead "true"</technical_language>

Target:
public void makeUnDiscoverablePatchTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .withSubject("ExtraEntry") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/discoverable", false); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/core/items/" + item.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(false))); getClient(token).perform(get("/api/core/items/" + item.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(false))); }
Source:
<code>public Optional<String> getETag() { <START> return Optional.ofNullable(_eTag); <END> }</code><technical_language>This Optional<...> member convention instead of wrapping access. I realize this is IDEA advice</technical_language>

Target:
public Optional<String> getETag() { return _eTag; }
Source:
<code>protected HistoryEvent getHistoricTaskInstance(CommandContext commandContext) { String historicTaskInstanceId = authorization.getResourceId(); <START> if (historicTaskInstanceId == null) { <END> return null; } return commandContext.getHistoricTaskInstanceManager() .findHistoricTaskInstanceById(historicTaskInstanceId); }</code><technical_language>skip query if resourceId is *</technical_language>

Target:
protected HistoryEvent getHistoricTaskInstance(CommandContext commandContext) { String historicTaskInstanceId = authorization.getResourceId(); if (historicTaskInstanceId == null || isAny(historicTaskInstanceId)) { return null; } return commandContext.getHistoricTaskInstanceManager() .findHistoricTaskInstanceById(historicTaskInstanceId); }
Source:
<code>protected TimeEvent createTimeEvent(TimeGraphEntry entry, ITimeGraphState state) { if (state.getValue() == Integer.MIN_VALUE) { return new NullTimeEvent(entry, state.getStartTime(), state.getDuration(), <START> state.getActiveProperties()); <END> } String label = state.getLabel(); if (label != null) { return new NamedTimeEvent(entry, state.getStartTime(), state.getDuration(), state.getValue(), label, state.getActiveProperties()); } return new TimeEvent(entry, state.getStartTime(), state.getDuration(), state.getValue(), state.getActiveProperties()); }</code><technical_language>NullTimeEvent need properties..</technical_language>

Target:
protected TimeEvent createTimeEvent(TimeGraphEntry entry, ITimeGraphState state) { if (state.getValue() == Integer.MIN_VALUE) { return new NullTimeEvent(entry, state.getStartTime(), state.getDuration()); } String label = state.getLabel(); if (label != null) { return new NamedTimeEvent(entry, state.getStartTime(), state.getDuration(), state.getValue(), label, state.getActiveProperties()); } return new TimeEvent(entry, state.getStartTime(), state.getDuration(), state.getValue(), state.getActiveProperties()); }
Source:
<code>public void shouldReturnOnlyTestUnitsForClassesWithinReach() throws IOException { when( this.extractor.extractCallDependenciesForPackages( eq(this.aTestUnit.getDescription().getFirstTestClass()), isNull())).thenReturn(Arrays.asList("foo")); when( this.extractor.extractCallDependenciesForPackages( eq(this.anotherTestUnit.getDescription().getFirstTestClass()), <START> isNull())).thenReturn(Collections.<String> emptyList()); <END> assertEquals(Arrays.asList(this.aTestUnit), this.testee.filterTestsByDependencyAnalysis(this.tus)); }</code><technical_language>This null happen lead a NPE in DependencyExtractor. I mock Predicate<String> (used constructor paramter)</technical_language>

Target:
public void shouldReturnOnlyTestUnitsForClassesWithinReach() throws IOException { when( this.extractor.extractCallDependenciesForPackages( eq(this.aTestUnit.getDescription().getFirstTestClass()), any(Predicate.class))).thenReturn(Arrays.asList("foo")); when( this.extractor.extractCallDependenciesForPackages( eq(this.anotherTestUnit.getDescription().getFirstTestClass()), any(Predicate.class))).thenReturn(Collections.<String> emptyList()); assertEquals(Arrays.asList(this.aTestUnit), this.testee.filterTestsByDependencyAnalysis(this.tus)); }
Source:
<code>private void loadGalleryItem() { updateProgressBar(true, true, 0); new GalleryItemFetchTask(app.getAPIForSite(imageTitle.getWikiSite()), imageTitle.getWikiSite(), imageTitle, FileUtil.isVideo(mimeType)) { @Override public void onFinish(Map<PageTitle, GalleryItem> result) { if (!isAdded()) { return; } if (result.size() > 0) { galleryItem = (GalleryItem) result.values().toArray()[0]; parentActivity.getGalleryCache().put((PageTitle) result.keySet().toArray()[0], galleryItem); loadMedia(); } else { updateProgressBar(false, true, 0); parentActivity.showError(null, true); } } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } updateProgressBar(false, true, 0); parentActivity.showError(caught, true); <START> L.e("caught " + caught.getMessage()); <END> } }.execute(); }</code><technical_language>I recommend L.e(Throwable) a good reason to</technical_language>

Target:
private void loadGalleryItem() { updateProgressBar(true, true, 0); new GalleryItemFetchTask(app.getAPIForSite(imageTitle.getWikiSite()), imageTitle.getWikiSite(), imageTitle, FileUtil.isVideo(mimeType)) { @Override public void onFinish(Map<PageTitle, GalleryItem> result) { if (!isAdded()) { return; } if (result.size() > 0) { galleryItem = (GalleryItem) result.values().toArray()[0]; parentActivity.getGalleryCache().put((PageTitle) result.keySet().toArray()[0], galleryItem); loadMedia(); } else { updateProgressBar(false, true, 0); parentActivity.showError(null, true); } } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } updateProgressBar(false, true, 0); parentActivity.showError(caught, true); L.e(caught); } }.execute(); }
Source:
<code><START> public KeyEncryptionKeyClientBuilder credential(TokenCredential credential) { <END> Objects.requireNonNull(credential); this.credential = credential; return this; }</code><technical_language>discussed, call super inheritDoc. this class simple possible</technical_language>

Target:
public KeyEncryptionKeyClientBuilder credential(TokenCredential credential) { super.credential(credential); return this; }
Source:
<code>protected boolean isRegisteredStudent(){ <START> if(student != null){ <END> return student.googleId != null && !student.googleId.isEmpty(); }else{ return false; } }</code><technical_language>This is cleaner: return (student != null) && (student.googleId != null) && (!student.googleId.isEmpty())</technical_language>

Target:
protected boolean isRegisteredStudent(){ return (student != null) && (student.googleId != null) && (!student.googleId.isEmpty()); }
Source:
<code>protected static void checkNonNull(Object thing) { <START> if(thing == null) { <END> throw new NullPointerException(); } }</code><technical_language>leverage Java 8 constructs for these</technical_language>

Target:
protected static void checkNonNull(Object thing) { Objects.requireNonNull(thing); }
Source:
<code>public DataStoreIT() { <START> goodUser = new User(new Principal() { @Override public String getName() { return "1"; } }); <END> badUser = new User(new Principal() { @Override public String getName() { return "-1"; } }); mapper = new ObjectMapper(); Map<String, Class<? extends Check>> checks = new HashMap(TestCheckMappings.MAPPINGS); checks.put("filterCheck", Filtered.FilterCheck.class); checks.put("filterCheck3", Filtered.FilterCheck3.class); elide = new Elide(new ElideSettingsBuilder(dataStore) .withAuditLogger(new TestAuditLogger()) .withEntityDictionary(new EntityDictionary(checks)) .build()); }</code><technical_language>suggestion goodUser = new User(() -> "1");</technical_language>

Target:
public DataStoreIT() { goodUser = new User(() -> "1"); badUser = new User(() -> "-1"); mapper = new ObjectMapper(); Map<String, Class<? extends Check>> checks = new HashMap(TestCheckMappings.MAPPINGS); checks.put("filterCheck", Filtered.FilterCheck.class); checks.put("filterCheck3", Filtered.FilterCheck3.class); elide = new Elide(new ElideSettingsBuilder(dataStore) .withAuditLogger(new TestAuditLogger()) .withEntityDictionary(new EntityDictionary(checks)) .build()); }
Source:
<code>public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(this.scalar); bits = 31 * bits + ((this.vector == null) ? 0 : this.vector.hashCode()); final int b = (int) bits; <START> return b; <END> }</code><technical_language>b ^ (b >> 31) is missed here</technical_language>

Target:
public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(this.scalar); bits = 31 * bits + ((this.vector == null) ? 0 : this.vector.hashCode()); final int b = (int) bits; return b ^ (b >> 31); }
Source:
<code>public void shouldBlockUntilCancellation() throws Exception { AtomicReference<Exception> testThreadException = new AtomicReference<>(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); runSeparateTestThread(() -> { try { testCallback.waitForGet(); testCallback.cancel(true); } catch (Exception e) { testThreadException.compareAndSet(null, e); } }); assertFalse(testCallback.isDone()); testCallback.get(); <START> if (testThreadException.get() != null) { <END> throw testThreadException.get(); } }</code><technical_language>get() canceled throw CancellationException above? code executed</technical_language>

Target:
public void shouldBlockUntilCancellation() throws Exception { AtomicReference<Exception> testThreadException = new AtomicReference<>(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); executor.submit(() -> { try { testCallback.waitForGet(); testCallback.cancel(true); } catch (Exception e) { testThreadException.compareAndSet(null, e); } }); assertFalse(testCallback.isDone()); testCallback.get(); if (testThreadException.get() != null) { throw testThreadException.get(); } }