auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testLaunchJobTwiceWhereMakeUniqueIsFalse() { logger.info("Launch batch job (makeUnique=false) twice"); executeJobCreate(MY_JOB, JOB_WITH_PARAMETERS_DESCRIPTOR + " --makeUnique=false"); checkForJobInList(MY_JOB, JOB_WITH_PARAMETERS_DESCRIPTOR + " --makeUnique=false", true); executeJobLaunch(MY_JOB); CommandResult result = executeCommandExpectingFailure("job launch --name " + MY_JOB); <START> System.out.println("*************************" + result.getException().getMessage()); <END> assertThat( result.getException().getMessage(), containsString("A job instance already exists and is complete for parameters={}. If you want to run this job again, change the parameters.")); }</code><technical_language>I assume this meant removed</technical_language>

Target:
public void testLaunchJobTwiceWhereMakeUniqueIsFalse() { logger.info("Launch batch job (makeUnique=false) twice"); executeJobCreate(MY_JOB, JOB_WITH_PARAMETERS_DESCRIPTOR + " --makeUnique=false"); checkForJobInList(MY_JOB, JOB_WITH_PARAMETERS_DESCRIPTOR + " --makeUnique=false", true); executeJobLaunch(MY_JOB); CommandResult result = executeCommandExpectingFailure("job launch --name " + MY_JOB); assertThat( result.getException().getMessage(), containsString("A job instance already exists and is complete for parameters={}. If you want to run this job again, change the parameters.")); }
Source:
<code>public List<GenericVertex> resolve(GraphService graphService, SearchCriteria searchCriteria) { <START> GenericGraph graph = graphService.getGraph(searchCriteria.getNamespace()); <END> return graph.getVertices() .stream() .map(ApplicationVertex::new) .filter(v -> filter(v, searchCriteria.getCriteria())) .map(ApplicationVertex::asGenericVertex) .collect(Collectors.toList()); }</code><technical_language>do do, if result is null</technical_language>

Target:
public List<GenericVertex> resolve(GraphService graphService, SearchCriteria searchCriteria) { return getVerticesOfGraph(graphService, searchCriteria.getNamespace()) .stream() .map(ApplicationVertex::new) .filter(v -> filter(v, searchCriteria.getCriteria())) .map(ApplicationVertex::asGenericVertex) .collect(Collectors.toList()); }
Source:
<code>protected Location manageRecursive(Location loc, final ManagementTransitionMode initialMode) { AccessController.Response access = managementContext.getAccessController().canManageLocation(loc); if (!access.isAllowed()) { throw new IllegalStateException("Access controller forbids management of "+loc+": "+access.getMsg()); } if (log.isDebugEnabled()) { String msg = "Managing location " + loc + " ("+initialMode+"), from " + Tasks.current()+" / "+Entitlements.getEntitlementContext(); <START> long count = LOCATION_CNT.incrementAndGet(); <END> if (count % 100 == 0) { log.debug(msg, new Exception("Informational stack trace of call to manage location "+loc+" ("+count+" calls; "+getLocations().size()+" currently managed)")); } else { log.debug(msg); } } recursively(loc, new Predicate<AbstractLocation>() { public boolean apply(AbstractLocation it) { ManagementTransitionMode mode = getLastManagementTransitionMode(it.getId()); if (mode==null) { setManagementTransitionMode(it, mode = initialMode); } if (it.isManaged()) { if (mode==ManagementTransitionMode.CREATING) { return false; } else { } } boolean result = manageNonRecursive(it, null); if (result) { it.setManagementContext(managementContext); if (!mode.isReadOnly()) { it.onManagementStarted(); recordLocationEvent(it, Lifecycle.CREATED); } managementContext.getRebindManager().getChangeListener().onManaged(it); } return result; } }); return loc; }</code><technical_language>do increment of if (log.isDebugEnabled). call is cheap, if log level changed on-the-fly debug want message accurate call count</technical_language>

Target:
protected Location manageRecursive(Location loc, final ManagementTransitionMode initialMode) { AccessController.Response access = managementContext.getAccessController().canManageLocation(loc); if (!access.isAllowed()) { throw new IllegalStateException("Access controller forbids management of "+loc+": "+access.getMsg()); } long count = LOCATION_CNT.incrementAndGet(); if (log.isDebugEnabled()) { String msg = "Managing location " + loc + " ("+initialMode+"), from " + Tasks.current()+" / "+Entitlements.getEntitlementContext(); if (count % 100 == 0) { log.debug(msg, new Exception("Informational stack trace of call to manage location "+loc+" ("+count+" calls; "+getLocations().size()+" currently managed)")); } else { log.debug(msg); } } recursively(loc, new Predicate<AbstractLocation>() { public boolean apply(AbstractLocation it) { ManagementTransitionMode mode = getLastManagementTransitionMode(it.getId()); if (mode==null) { setManagementTransitionMode(it, mode = initialMode); } if (it.isManaged()) { if (mode==ManagementTransitionMode.CREATING) { return false; } else { } } boolean result = manageNonRecursive(it, null); if (result) { it.setManagementContext(managementContext); if (!mode.isReadOnly()) { it.onManagementStarted(); recordLocationEvent(it, Lifecycle.CREATED); } managementContext.getRebindManager().getChangeListener().onManaged(it); } return result; } }); return loc; }
Source:
<code>void start(int slot) { mSlot = slot; int error = isValid(); if (error == SUCCESS) { Log.d(TAG, "Starting keepalive " + mSlot + " on " + mNai.name()); switch (mType) { case TYPE_NATT: mNai.asyncChannel .sendMessage(CMD_START_SOCKET_KEEPALIVE, slot, mInterval, mPacket); break; case TYPE_TCP: mTcpController.startSocketMonitor(mFd, this, mSlot); mNai.asyncChannel .sendMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER, slot, 0 , mPacket); mNai.asyncChannel .sendMessage(CMD_START_SOCKET_KEEPALIVE, slot, mInterval, mPacket); break; default: Log.wtf(TAG, "Starting keepalive with unknown type: " + <START> mType); <END> } mStartedState = STARTING; } else { handleStopKeepalive(mNai, mSlot, error); return; } }</code><technical_language>Return early enter STARTING state? Call handleStopKeepalive ERROR_INVALID_PACKET</technical_language>

Target:
void start(int slot) { mSlot = slot; int error = isValid(); if (error == SUCCESS) { Log.d(TAG, "Starting keepalive " + mSlot + " on " + mNai.name()); switch (mType) { case TYPE_NATT: mNai.asyncChannel .sendMessage(CMD_START_SOCKET_KEEPALIVE, slot, mInterval, mPacket); break; case TYPE_TCP: mTcpController.startSocketMonitor(mFd, this, mSlot); mNai.asyncChannel .sendMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER, slot, 0 , mPacket); mNai.asyncChannel .sendMessage(CMD_START_SOCKET_KEEPALIVE, slot, mInterval, mPacket); break; default: Log.wtf(TAG, "Starting keepalive with unknown type: " + mType); handleStopKeepalive(mNai, mSlot, error); return; } mStartedState = STARTING; } else { handleStopKeepalive(mNai, mSlot, error); return; } }
Source:
<code>public NewTmfViewAction(TmfView view) { super(MessageFormat.format(Messages.TmfView_NewTmfViewNameText, <START> view.getTitle().toLowerCase()), <END> IAction.AS_PUSH_BUTTON); setToolTipText(MessageFormat.format(Messages.TmfView_NewTmfViewToolTipText, view.getTitle())); }</code><technical_language>I display view names capitalized users</technical_language>

Target:
public NewTmfViewAction(TmfView view) { super(MessageFormat.format(Messages.TmfView_NewTmfViewNameText, view.getTitle()), IAction.AS_PUSH_BUTTON); setToolTipText(MessageFormat.format(Messages.TmfView_NewTmfViewToolTipText, view.getTitle())); fViewId = checkNotNull(view.getViewId()); }
Source:
<code>public ChangeInfo apply(RevisionResource rsrc, Input input) throws BadRequestException, ResourceConflictException, EmailException, OrmException, ResourceNotFoundException, IOException { if (Strings.isNullOrEmpty(input.message)) { throw new BadRequestException("message must be non-empty"); } final Repository git; try { git = gitManager.openRepository(rsrc.getChange().getProject()); } catch (RepositoryNotFoundException e) { <START> throw new ResourceNotFoundException(); <END> } try { return json.format(ChangeUtil.editCommitMessage( rsrc.getPatchSet().getId(), rsrc.getControl().getRefControl(), (IdentifiedUser) rsrc.getControl().getCurrentUser(), input.message, dbProvider.get(), commitMessageEditedSenderFactory, git, myIdent, patchSetInserterFactory)); } catch (InvalidChangeOperationException e) { throw new BadRequestException(e.getMessage()); } catch (MissingObjectException e) { throw new ResourceConflictException(e.getMessage()); } catch (IncorrectObjectTypeException e) { throw new ResourceConflictException(e.getMessage()); } catch (PatchSetInfoNotAvailableException e) { throw new ResourceConflictException(e.getMessage()); } catch (NoSuchChangeException e) { throw new ResourceNotFoundException(); } finally { git.close(); } }</code><technical_language>Unrelated change. in a separate commit</technical_language>

Target:
public ChangeInfo apply(RevisionResource rsrc, Input input) throws BadRequestException, ResourceConflictException, EmailException, OrmException, ResourceNotFoundException, IOException { if (Strings.isNullOrEmpty(input.message)) { throw new BadRequestException("message must be non-empty"); } final Repository git; try { git = gitManager.openRepository(rsrc.getChange().getProject()); } catch (RepositoryNotFoundException e) { throw new ResourceNotFoundException(e.getMessage()); } try { return json.format(ChangeUtil.editCommitMessage( rsrc.getPatchSet().getId(), rsrc.getControl().getRefControl(), (IdentifiedUser) rsrc.getControl().getCurrentUser(), input.message, dbProvider.get(), commitMessageEditedSenderFactory, git, myIdent, patchSetInserterFactory)); } catch (InvalidChangeOperationException e) { throw new BadRequestException(e.getMessage()); } catch (MissingObjectException e) { throw new ResourceConflictException(e.getMessage()); } catch (IncorrectObjectTypeException e) { throw new ResourceConflictException(e.getMessage()); } catch (PatchSetInfoNotAvailableException e) { throw new ResourceConflictException(e.getMessage()); } catch (NoSuchChangeException e) { throw new ResourceNotFoundException(); } finally { git.close(); } }
Source:
<code>public void testBlogPosting() { onView(withText("Log In")) .perform(click()); <START> onView(withId(R.id.input)) <END> .perform(replaceText(mUserEmail), closeSoftKeyboard()); onView(withText("Next")) .perform(click()); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } onView(withId(R.id.login_enter_password)) .perform(click()); onView(withId(R.id.input)) .perform(replaceText(mUserPassword), closeSoftKeyboard()); onView(withText("Next")) .perform(click()); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } onView(withText("Continue")) .perform(click()); onView(withId(R.id.viewpager_main)) .perform(ViewPagerActions.scrollToFirst()); onView(withId(R.id.fab_button)) .perform(click()); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } onView(withId(R.id.title)) .perform(replaceText("Hello"), closeSoftKeyboard()); onView(withId(R.id.aztec)) .perform(replaceText("World"), closeSoftKeyboard()); onView(withId(R.id.menu_save_post)) .perform(click()); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } onView(withId(R.id.promo_dialog_button_positive)) .perform(click()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } onView(withText(R.string.uploading_post)).inRoot(new ToastMatcher()) .check(matches(isDisplayed())); }</code><technical_language>This fail test SmartLock for Passwords pops dialog for selecting a saved email/pass combination</technical_language>

Target:
public void testBlogPosting() { new LoginRobot() .selectLoginOption() .typeUsername(USERNAME) .tapNextButton() .tapToEnterPasswordInstead() .typePassword(PASSWORD) .tapNextButton() .tapToContinueOnSiteSelection(); new NavigationRobot() .selectMyWordpressSites(); MySitesMenuRobot mySitesMenu = new MySitesMenuRobot(); mySitesMenu.tapToWriteNewPost(); new ComposePostRobot() .writeTitle("Hello") .writePost("World") .tapToPublish(); mySitesMenu.tapBlogPosts(); new BlogPostsRobot.ResultRobot() .hasTitleAndTextAtPosition("Hello", "World", 0); }
Source:
<code>public void placeOnTop(Node pNode) { assert pNode != null; <START> if( aType == DiagramType.SEQUENCE && pNode.getClass() == CallNode.class ) <END> { return; } if( pNode.hasParent() ) { Node parent = pNode.getParent(); parent.placeLast(pNode); placeOnTop(parent); } else if( containsAsRoot(pNode) ) { removeRootNode(pNode); addRootNode(pNode); } }</code><technical_language>CallNode present in sequence diagrams, I recommend eliminating (presumed defensive) clause aType == DiagramType.SEQUENCE of potential confusion if cause</technical_language>

Target:
public void placeOnTop(Node pNode) { assert pNode != null; if( pNode.getClass() == CallNode.class ) { return; } if( pNode.hasParent() ) { Node parent = pNode.getParent(); parent.placeLast(pNode); placeOnTop(parent); } else if( containsAsRoot(pNode) ) { removeRootNode(pNode); addRootNode(pNode); } }
Source:
<code>public int[] downloadSetupConfigurationTemplate(String uuid){ int[] result = new int[2]; try { SetupConfigurationTemplate setupConfigurationTemplate = setupConfigurationController.downloadSetupConfigurationTemplate(uuid); result[0] = SyncStatusConstants.SUCCESS; if(setupConfigurationTemplate != null) { result[1] = 1; } <START> System.out.println("MuzimaSyncService: "+setupConfigurationTemplate.getConfigJson()); <END> setupConfigurationController.saveSetupConfigurationTemplate(setupConfigurationTemplate); } catch (SetupConfigurationController.SetupConfigurationDownloadException e){ Log.e(TAG, "Exception when trying to download setup configs"); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; } catch (SetupConfigurationController.SetupConfigurationSaveException e){ Log.e(TAG, "Exception when trying to save setup configs"); result[0] = SyncStatusConstants.SAVE_ERROR; } return result; }</code><technical_language>Replace logger</technical_language>

Target:
public int[] downloadSetupConfigurationTemplate(String uuid){ int[] result = new int[2]; try { SetupConfigurationTemplate setupConfigurationTemplate = setupConfigurationController.downloadSetupConfigurationTemplate(uuid); result[0] = SyncStatusConstants.SUCCESS; if(setupConfigurationTemplate != null) { result[1] = 1; } setupConfigurationController.saveSetupConfigurationTemplate(setupConfigurationTemplate); } catch (SetupConfigurationController.SetupConfigurationDownloadException e){ Log.e(TAG, "Exception when trying to download setup configs"); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; } catch (SetupConfigurationController.SetupConfigurationSaveException e){ Log.e(TAG, "Exception when trying to save setup configs"); result[0] = SyncStatusConstants.SAVE_ERROR; } return result; }
Source:
<code>public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (orientation != newConfig.orientation) { try { orientation = newConfig.orientation; getFragmentManager().beginTransaction().remove(this).commit(); getFragmentManager().beginTransaction() .replace(R.id.cover_fragment_container, CoverFragment.class.newInstance()) <START> .commitAllowingStateLoss(); <END> } catch (Exception e) { Log.e(TAG, "onConfigurationChanged " + e.toString()); } } }</code><technical_language>I this is pretty strange. returning a FrameLayout in onCreateView re-inflating content in onConfigurationChanged</technical_language>

Target:
public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); CoverFragment next; if (orientation != newConfig.orientation) { try { Log.d(TAG, "onConfigurationChanged " + newConfig.orientation); orientation = newConfig.orientation; if (_prev == null) { next = CoverFragment.class.newInstance(); } else { next = _prev; } _prev = this; getParentFragmentManager().beginTransaction() .remove(_prev) .add(R.id.cover_fragment_container, next) .commitAllowingStateLoss(); } catch (Exception e) { Log.e(TAG, "onConfigurationChanged " + e.toString()); } } }
Source:
<code>protected void serviceStart() throws Exception { super.serviceStart(); if (UserGroupInformation.isSecurityEnabled()) { delegationTokenManager.startThreads(); } InetSocketAddress connectAddress = NetUtils.getConnectAddress(this.heartbeatListener.getAddress()); URI connectUri = RecoverableRpcProxy.toConnectURI(connectAddress); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), getConfig()); recoveryHandler.writeConnectUri(connectUri.toString()); try { org.mortbay.log.Log.setLog(null); } catch (Throwable throwable) { } try { Configuration config = getConfig(); if (SecurityUtils.isStramWebSecurityEnabled()) { config = new Configuration(config); config.set("hadoop.http.filter.initializers", StramWSFilterInitializer.class.getCanonicalName()); } addSSLConfigResource(config); WebApp webApp = WebApps.$for("stram", StramAppContext.class, appContext, "ws").with(config).start(new StramWebApp(this.dnmgr)); LOG.info("Started web service at port: " + webApp.port()); <START> appMasterTrackingUrl = NetUtils.getConnectAddress(webApp.getListenerAddress()).getAddress().getCanonicalHostName() + ":" + webApp.port(); <END> if (ConfigUtils.isSSLEnabled(config)) { appMasterTrackingUrl = "https://" + appMasterTrackingUrl; } LOG.info("Setting tracking URL to: " + appMasterTrackingUrl); } catch (Exception e) { LOG.error("Webapps failed to start. Ignoring for now:", e); } }</code><technical_language>Sounds a workaround for host misconfiguration issue</technical_language>

Target:
protected void serviceStart() throws Exception { super.serviceStart(); if (UserGroupInformation.isSecurityEnabled()) { delegationTokenManager.startThreads(); } InetSocketAddress connectAddress = NetUtils.getConnectAddress(this.heartbeatListener.getAddress()); URI connectUri = RecoverableRpcProxy.toConnectURI(connectAddress); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), getConfig()); recoveryHandler.writeConnectUri(connectUri.toString()); try { org.mortbay.log.Log.setLog(null); } catch (Throwable throwable) { } try { Configuration config = SecurityUtils.configureWebAppSecurity(getConfig(), dag.getValue(Context.DAGContext.SSL_CONFIG)); WebApp webApp = WebApps.$for("stram", StramAppContext.class, appContext, "ws").with(config).start(new StramWebApp(this.dnmgr)); LOG.info("Started web service at port: " + webApp.port()); connectAddress = NetUtils.getConnectAddress(webApp.getListenerAddress()); String hostname = connectAddress.getAddress().getCanonicalHostName(); if (hostname.equals(connectAddress.getAddress().getHostAddress())) { hostname = connectAddress.getHostName(); } appMasterTrackingUrl = hostname + ":" + webApp.port(); if (ConfigUtils.isSSLEnabled(config)) { appMasterTrackingUrl = "https://" + appMasterTrackingUrl; } LOG.info("Setting tracking URL to: " + appMasterTrackingUrl); } catch (Exception e) { LOG.error("Webapps failed to start. Ignoring for now:", e); } }
Source:
<code>protected void executeVdsBrokerCommand() { String storageDomainId = getParameters().getStorageDomainId().toString(); List<String> deviceList = getParameters().getDeviceList(); String[] deviceArray = deviceList.toArray(new String[deviceList.size()]); boolean isForce = getParameters().isForce(); boolean supportForceCreateVG = Config.<Boolean> getValue( ConfigValues.SupportForceCreateVG, getVds().getVdsGroupCompatibilityVersion().toString()); <START> _result = supportForceCreateVG ? <END> getBroker().createVG(storageDomainId, deviceArray, isForce) : getBroker().createVG(storageDomainId, deviceArray); proceedProxyReturnValue(); setReturnValue(_result.uuid); }</code><technical_language>please rename _result</technical_language>

Target:
protected void executeVdsBrokerCommand() { String storageDomainId = getParameters().getStorageDomainId().toString(); List<String> deviceList = getParameters().getDeviceList(); String[] deviceArray = deviceList.toArray(new String[deviceList.size()]); boolean isForce = getParameters().isForce(); boolean supportForceCreateVG = Config.<Boolean> getValue( ConfigValues.SupportForceCreateVG, getVds().getVdsGroupCompatibilityVersion().toString()); result = supportForceCreateVG ? getBroker().createVG(storageDomainId, deviceArray, isForce) : getBroker().createVG(storageDomainId, deviceArray); proceedProxyReturnValue(); setReturnValue(result.uuid); }
Source:
<code>public boolean addNextEvent(final MistEvent event, final Direction direction) { <START> if (operatorChainManager != null && queue.isEmpty()) { <END> operatorChainManager.insert(this); } return queue.add(new Tuple<>(event, direction)); }</code><technical_language>I good perform this logic in OutputEmitter</technical_language>

Target:
public boolean addNextEvent(final MistEvent event, final Direction direction) { final boolean isAdded; synchronized (this) { if (operatorChainManager != null && queue.isEmpty()) { isAdded = queue.add(new Tuple<>(event, direction)); operatorChainManager.insert(this); } else { isAdded = queue.add(new Tuple<>(event, direction)); } } return isAdded; }
Source:
<code>public void freeUnderlyingResources() { int spi = mSpi.getSpi(); try { mSrvConfig .getNetdInstance() .ipSecDeleteSecurityAssociation( <START> 0, <END> mConfig.getSourceAddress(), mConfig.getDestinationAddress(), spi, 0, mConfig.getMarkMask()); } catch (RemoteException | ServiceSpecificException e) { Log.e(TAG, "Failed to delete SA with ID: " + mResourceId, e); } getResourceTracker().give(); }</code><technical_language>prefer call this DEFAULT_REQUEST_ID. easier read easier change if decide zero number (which I suggest number non-unique other users of API)</technical_language>

Target:
public void freeUnderlyingResources() { int spi = mSpi.getSpi(); try { mSrvConfig .getNetdInstance() .ipSecDeleteSecurityAssociation( uid, mConfig.getSourceAddress(), mConfig.getDestinationAddress(), spi, 0, mConfig.getMarkMask()); } catch (RemoteException | ServiceSpecificException e) { Log.e(TAG, "Failed to delete SA with ID: " + mResourceId, e); } getResourceTracker().give(); }
Source:
<code>public void execute() { final Setting setting = getActionContext().getSetting(); final EObject eObject = setting.getEObject(); final EStructuralFeature eStructuralFeature = setting.getEStructuralFeature(); final List<?> containments = (List<?>) eObject.eGet(eStructuralFeature, true); final List<?> moveUpList = Arrays.asList( ((IStructuredSelection) getTableViewer().getSelection()).toArray()); sortSelectionBasedOnIndex(moveUpList, containments); final EditingDomain editingDomain = getActionContext().getEditingDomain(); for (final Object moveUpObject : moveUpList) { final int currentIndex = containments.indexOf(moveUpObject); if (currentIndex <= 0) { return; } editingDomain.getCommandStack() .execute( new MoveCommand( editingDomain, eObject, eStructuralFeature, currentIndex, currentIndex - 1)); } <START> } <END></code><technical_language>check in canExecute reached start of list</technical_language>

Target:
public void execute() { final List<?> containments = getContainments(); final List<?> moveUpList = Arrays.asList( ((IStructuredSelection) getTableViewer().getSelection()).toArray()); sortSelectionBasedOnIndex(moveUpList, containments); final EditingDomain editingDomain = getActionContext().getEditingDomain(); final Setting setting = getActionContext().getSetting(); final EObject eObject = setting.getEObject(); final EStructuralFeature eStructuralFeature = setting.getEStructuralFeature(); for (final Object moveUpObject : moveUpList) { final int currentIndex = containments.indexOf(moveUpObject); if (currentIndex <= 0) { return; } editingDomain.getCommandStack() .execute( new MoveCommand( editingDomain, eObject, eStructuralFeature, currentIndex, currentIndex - 1)); } }
Source:
<code>protected Array createArrayOf(String typeName, Object[] array) { Connection connection = null; try { connection = getJdbcTemplate().getDataSource().getConnection(); return connection.createArrayOf(typeName, array); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (connection != null) { <START> try { connection.close();} catch (SQLException e) <END> } } }</code><technical_language>use: try (Connection connection = getJdbcTemplate().getDataSource().getConnection()) { return connection.createArrayOf(typeName, array); } catch(SQLException ex) { throw new RuntimeException(e); }</technical_language>

Target:
protected Array createArrayOf(String typeName, Object[] array) { try (Connection connection = getJdbcTemplate().getDataSource().getConnection()) { return connection.createArrayOf(typeName, array); } catch (SQLException ex) { throw new RuntimeException(ex); } }
Source:
<code>public byte[] serialize() { <START> ByteBuffer buffer = ByteBuffer.allocate(9); <END> buffer.put(TYPE_LONG); buffer.putLong(value); return buffer.array(); }</code><technical_language>magic number</technical_language>

Target:
public byte[] serialize() { ByteBuffer buffer = ByteBuffer.allocate(Byte.BYTES + Long.BYTES); buffer.put(getType().getByte()); buffer.putLong(value); return buffer.array(); }
Source:
<code>public ServiceReference[] getServiceReferences(String clazz, String filter) { ServiceReference[] refs = null; try { if (bundleContext != null) { refs = bundleContext.getServiceReferences(clazz, filter); } } catch (InvalidSyntaxException e) { <START> if (log.isLoggable(Level.SEVERE)) { <END> log.log(Level.SEVERE, e.getMessage(), e); } } return refs; }</code><technical_language>I prefer exception re-thrown a typed exception (e.g. PlatformServicesException) handled caller eating exception here</technical_language>

Target:
public ServiceReference[] getServiceReferences(String clazz, String filter) throws PlatformServicesException { ServiceReference[] refs = null; try { if (bundleContext != null) { refs = bundleContext.getServiceReferences(clazz, filter); } } catch (InvalidSyntaxException e) { throw new PlatformServicesException(e); } return refs; }
Source:
<code>private boolean execute(final IProcessDMContext processDmc, final IDebugCommandRequest request) { try { fExecutor.execute(new DsfRunnable() { @Override public void run() { IProcesses procService = fTracker.getService(IProcesses.class); if (procService != null) { procService.terminate(processDmc, new ImmediateRequestMonitor() { @Override protected void handleCompleted() { <START> if (!getStatus().isOK()) { <END> request.setStatus(getStatus()); request.done(); } else { WaitForTerminationJob job = new WaitForTerminationJob(fSession.getId(), request); job.schedule(); } }; }); } else { request.done(); } } }); } catch (RejectedExecutionException e) { request.done(); } return false; }</code><technical_language>RequestMonitor.isSuccess(). Is a reason IStatus directly</technical_language>

Target:
private boolean execute(final IProcessDMContext processDmc, final IDebugCommandRequest request) { try { fExecutor.execute(new DsfRunnable() { @Override public void run() { IProcesses procService = fTracker.getService(IProcesses.class); if (procService != null) { procService.terminate(processDmc, new ImmediateRequestMonitor() { @Override protected void handleCompleted() { if (!isSuccess()) { request.setStatus(getStatus()); request.done(); } else { WaitForTerminationJob job = new WaitForTerminationJob(fSession.getId(), request); job.schedule(); } }; }); } else { request.done(); } } }); } catch (RejectedExecutionException e) { request.done(); } return false; }
Source:
<code>void deleteProperty(AccumuloElement element, Property property, Authorizations authorizations) { <START> if (!element.getFetchHints().isIncludeAllProperties()) { <END> throw new VertexiumMissingFetchHintException(element.getFetchHints(), "All Properties"); } if (!element.getFetchHints().isIncludeAllPropertyMetadata()) { throw new VertexiumMissingFetchHintException(element.getFetchHints(), "All Property Metadata"); } Mutation m = new Mutation(element.getId()); elementMutationBuilder.addPropertyDeleteToMutation(m, property); addMutations(element, m); getSearchIndex().deleteProperty( this, element, PropertyDescriptor.fromProperty(property), authorizations ); if (hasEventListeners()) { queueEvent(new DeletePropertyEvent(this, element, property)); } }</code><technical_language>Is reason isIncludeAllProperties of search index? need loaded</technical_language>

Target:
void deleteProperty(AccumuloElement element, Property property, Authorizations authorizations) { if (!element.getFetchHints().isIncludePropertyAndMetadata(property.getName())) { throw new VertexiumMissingFetchHintException(element.getFetchHints(), "Property " + property.getName() + " needs to be included with metadata"); } Mutation m = new Mutation(element.getId()); elementMutationBuilder.addPropertyDeleteToMutation(m, property); addMutations(element, m); getSearchIndex().deleteProperty( this, element, PropertyDescriptor.fromProperty(property), authorizations ); if (hasEventListeners()) { queueEvent(new DeletePropertyEvent(this, element, property)); } }
Source:
<code>public List<ExperimentSpotDesignReadSpec> list() { <START> List expmts = this.getHibernateTemplate().find("from ExperimentSpotDesignReadSpec as readSpec order by readSpec.experimentSpotDesignReadSpecId asc" END> ); return expmts; }</code><technical_language>this need ordered synthetic primary key</technical_language>

Target:
public List<ExperimentSpotDesignReadSpec> list() { List expmts = this.getHibernateTemplate().find("from ExperimentSpotDesignReadSpec as readSpec" ); return expmts; }
Source:
<code><START> public void testToFlowElement_autostart() throws Exception { <END> final ReusableSubprocess definition = new ReusableSubprocess(); definition.getExecutionSet().setAdHocAutostart(new AdHocAutostart(true)); final View<BaseReusableSubprocess> view = new ViewImpl<>(definition, Bounds.create()); final Node<View<BaseReusableSubprocess>, ?> node = new NodeImpl<>(java.util.UUID.randomUUID().toString()); node.setContent(view); final PropertyWriter propertyWriter = tested.toFlowElement(node); assertTrue(CallActivityPropertyWriter.class.isInstance(propertyWriter)); assertTrue(CustomElement.autoStart.of(propertyWriter.getFlowElement()).get()); }</code><technical_language>Exception is thrown</technical_language>

Target:
public void testToFlowElement_autostart() { final ReusableSubprocess definition = new ReusableSubprocess(); definition.getExecutionSet().setAdHocAutostart(new AdHocAutostart(true)); final View<BaseReusableSubprocess> view = new ViewImpl<>(definition, Bounds.create()); final Node<View<BaseReusableSubprocess>, ?> node = new NodeImpl<>(java.util.UUID.randomUUID().toString()); node.setContent(view); final PropertyWriter propertyWriter = tested.toFlowElement(node); assertTrue(CallActivityPropertyWriter.class.isInstance(propertyWriter)); assertTrue(CustomElement.autoStart.of(propertyWriter.getFlowElement()).get()); }
Source:
<code>public static Date parseDate(String date, String format) { <START> return parseDate(date, new SimpleDateFormat(format, Locale.getDefault())); <END> }</code><technical_language>Is a null check for passed in "date" required for safety</technical_language>

Target:
public static Date parseDate(String date, String format) { if (date == null) { return null; } return parseDate(date, new SimpleDateFormat(format, Locale.getDefault())); }
Source:
<code>public boolean equals(Object that) { if (this == that) { return true; } if (that instanceof Rating) { Rating other = (Rating) that; <START> return type.equals(other.type) && value == other.value && numberOfVotes.equals(other.numberOfVotes); <END> } return false; }</code><technical_language>numberOfVotes null replace this Objects.equals(numberOfVotes, other.numberOfVotes)</technical_language>

Target:
public boolean equals(Object that) { if (this == that) { return true; } if (that instanceof Rating) { Rating other = (Rating) that; return type.equals(other.type) && value == other.value && Objects.equals(numberOfVotes, other.numberOfVotes); } return false; }
Source:
<code>public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout) throws IOException { if (socket == null || endpoint == null || timeout < 0) { throw new IllegalArgumentException("Illegal argument for connect()"); } SocketChannel ch = socket.getChannel(); if (localAddr != null) { Class localClass = localAddr.getClass(); Class remoteClass = endpoint.getClass(); Preconditions.checkArgument(localClass.equals(remoteClass), "Local address %s must be of same family as remote address %s.", localAddr, endpoint); socket.bind(localAddr); } try { if (ch == null) { socket.connect(endpoint, timeout); } else { SocketIOWithTimeout.connect(ch, endpoint, timeout); } } catch (SocketTimeoutException ste) { throw new ConnectTimeoutException(ste.getMessage()); <START> } catch (UnresolvedAddressException ue) { <END> throw new UnknownHostException(ue.getMessage()); } if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) { LOG.info("Detected a loopback TCP socket, disconnecting it"); socket.close(); throw new ConnectException( "Localhost targeted connection resulted in a loopback. " + "No daemon is listening on the target port."); } }</code><technical_language>nit: call uae</technical_language>

Target:
public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout) throws IOException { if (socket == null || endpoint == null || timeout < 0) { throw new IllegalArgumentException("Illegal argument for connect()"); } SocketChannel ch = socket.getChannel(); if (localAddr != null) { Class localClass = localAddr.getClass(); Class remoteClass = endpoint.getClass(); Preconditions.checkArgument(localClass.equals(remoteClass), "Local address %s must be of same family as remote address %s.", localAddr, endpoint); socket.bind(localAddr); } try { if (ch == null) { socket.connect(endpoint, timeout); } else { SocketIOWithTimeout.connect(ch, endpoint, timeout); } } catch (SocketTimeoutException ste) { throw new ConnectTimeoutException(ste.getMessage()); } catch (UnresolvedAddressException uae) { throw new UnknownHostException(uae.getMessage()); } if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) { LOG.info("Detected a loopback TCP socket, disconnecting it"); socket.close(); throw new ConnectException( "Localhost targeted connection resulted in a loopback. " + "No daemon is listening on the target port."); } }
Source:
<code>public void testReviewForm() throws ParseException { final DeliveryReviewView view = getDeliveryReviewView(); final DeliveryReviewView.DeliveryForm deliveryForm = view.getDelivery(); deliveryForm.setGrade("4.0"); <START> deliveryForm.setState("Rejected"); <END> deliveryForm.setCommentary("Hello World!"); assertTrue(deliveryForm.getGrade() == 4.0D); assertEquals(Delivery.State.REJECTED, deliveryForm.getSelectedState()); assertEquals("Hello World!", deliveryForm.getCommentary()); }</code><technical_language>WordUtils.capitalize(Delivery.State.REJECTED) test is more stable (will compilation errors) if some point change Delivery API</technical_language>

Target:
public void testReviewForm() throws ParseException { final DeliveryReviewView view = getDeliveryReviewView(); final DeliveryReviewView.DeliveryForm deliveryForm = view.getDelivery(); deliveryForm.setGrade(INSUFFICIENT_GRADE); deliveryForm.setState(State.REJECTED); deliveryForm.setCommentary(DELIVERY_COMMENTARY); assertEquals(INSUFFICIENT_GRADE, deliveryForm.getGrade(), 1e-4); assertEquals(Delivery.State.REJECTED, deliveryForm.getSelectedState()); assertEquals(DELIVERY_COMMENTARY, deliveryForm.getCommentary()); }
Source:
<code>private static void addRequestParameter(SOAPFactory soapFactory, OMElement bodyFirstChild, OMNamespace ns, String key, Object parameter) { if (parameter instanceof DataHandler) { DataHandler dataHandler = (DataHandler)parameter; OMText dataText = bodyFirstChild.getOMFactory().createOMText( dataHandler, true); OMElement omElement = soapFactory.createOMElement(key, ns, bodyFirstChild); omElement.addChild(dataText); omElement.addAttribute("filename",((DataHandler) parameter).getDataSource().getName(),ns); <START> omElement.addAttribute("filename", ((DataHandler) parameter).getDataSource().getName(), ns); <END> } else { String textValue = parameter.toString(); soapFactory.createOMElement(key, ns, bodyFirstChild).setText( textValue); } }</code><technical_language>repeating code line</technical_language>

Target:
private static void addRequestParameter(SOAPFactory soapFactory, OMElement bodyFirstChild, OMNamespace ns, String key, Object parameter) { if (parameter instanceof DataHandler) { DataHandler dataHandler = (DataHandler)parameter; OMText dataText = bodyFirstChild.getOMFactory().createOMText( dataHandler, true); OMElement omElement = soapFactory.createOMElement(key, ns, bodyFirstChild); omElement.addChild(dataText); omElement.addAttribute("filename", ((DataHandler) parameter).getDataSource().getName(), ns); } else { String textValue = parameter.toString(); soapFactory.createOMElement(key, ns, bodyFirstChild).setText( textValue); } }
Source:
<code>public Future<Void> executeFailed(Stage stage, Class<?> executingClass, ConsumerRecord<byte[], byte[]> consumerRecord, Throwable error) { <START> if (!withinToleranceLimits()) { <END> errorHandlingMetrics.recordFailure(); markAsFailed(); throw new ConnectException("Tolerance exceeded in the errant record reporter", error); } context.consumerRecord(consumerRecord); context.currentContext(stage, executingClass); context.error(error); errorHandlingMetrics.recordError(); return context.report(); }</code><technical_language>if attempt operation fails, recordFailure incremented, recordError tracks cases encounter a problem framework retry skip. In case, able retry skip record. In executeFailed scenario, recordFailure() time, recordError fail task</technical_language>

Target:
public Future<Void> executeFailed(Stage stage, Class<?> executingClass, ConsumerRecord<byte[], byte[]> consumerRecord, Throwable error) { markAsFailed(); context.consumerRecord(consumerRecord); context.currentContext(stage, executingClass); context.error(error); errorHandlingMetrics.recordFailure(); Future<Void> errantRecordFuture = context.report(); if (!withinToleranceLimits()) { errorHandlingMetrics.recordError(); throw new ConnectException("Tolerance exceeded in error handler", error); } return errantRecordFuture; }
Source:
<code>public OutputWriter createOutputWriter() { if (file.exists()) { ExcelDatastore datastore = new ExcelDatastore(file.getName(), new FileResource(file), file.getAbsolutePath()); try (final UpdateableDatastoreConnection connection = datastore.openConnection()) { final DataContext dataContext = connection.getDataContext(); final Schema[] schemas = dataContext.getSchemas(); if (schemas.length >= 1) { <START> final String[] tableNames = schemas[1].getTableNames(); <END> for (int i = 0; i < tableNames.length; i++) { if (tableNames[i].equals(sheetName)) { if (overwriteSheetIfExists) { final Table tableSheet = dataContext.getTableByQualifiedLabel(sheetName); final UpdateableDataContext updateableDataContext = connection .getUpdateableDataContext(); updateableDataContext.executeUpdate(new UpdateScript() { @Override public void run(UpdateCallback callback) { callback.dropTable(tableSheet).execute(); ; } }); } } } } } } String[] headers = new String[columns.length]; for (int i = 0; i < headers.length; i++) { headers[i] = columns[i].getName(); } return ExcelOutputWriterFactory.getWriter(file.getPath(), sheetName, columns); }</code><technical_language>get proper schema is dataContext.getDefaultSchema() ... schemas[1] is guaranteed work schemas sorted alphabetically rely filename (which is schema name) sorted "information_schema" :-)</technical_language>

Target:
public OutputWriter createOutputWriter() { if (file.exists()) { ExcelDatastore datastore = new ExcelDatastore(file.getName(), new FileResource(file), file.getAbsolutePath()); try (final UpdateableDatastoreConnection connection = datastore.openConnection()) { final DataContext dataContext = connection.getDataContext(); final String[] tableNames = dataContext.getDefaultSchema().getTableNames(); for (int i = 0; i < tableNames.length; i++) { if (tableNames[i].equals(sheetName)) { if (overwriteSheetIfExists) { final Table tableSheet = dataContext.getTableByQualifiedLabel(sheetName); final UpdateableDataContext updateableDataContext = connection.getUpdateableDataContext(); updateableDataContext.executeUpdate(new DropTable(tableSheet)); } } } } } String[] headers = new String[columns.length]; for (int i = 0; i < headers.length; i++) { headers[i] = columns[i].getName(); } return ExcelOutputWriterFactory.getWriter(file.getPath(), sheetName, columns); }
Source:
<code>public boolean isQueryCacheable(Query query) { <START> return !query.isDescending() && !unCacheable.contains(query.getType()); <END> }</code><technical_language>reason for disabling cache for descending order queries</technical_language>

Target:
public boolean isQueryCacheable(Query query) { return !unCacheable.contains(query.getType()); }
Source:
<code>public void testBacktickEscapedIdentifier() { assertTrue(CharFormatUtil.unescapeIdentifier("``").isEmpty()); assertTrue(CharFormatUtil.unescapeIdentifier("").isEmpty()); assertTrue(CharFormatUtil.unescapeIdentifier("`s`").equals("s")); assertTrue(CharFormatUtil.unescapeIdentifier("`self`").equals("self")); <START> assertFalse(CharFormatUtil.unescapeIdentifier("`self").equals("self")); <END> assertFalse(CharFormatUtil.unescapeIdentifier("self`").equals("self")); assertFalse(CharFormatUtil.unescapeIdentifier("``self`").equals("self")); }</code><technical_language>assertFalse is kind of weird (it's expect self). change this assertEqual (and assertFalse(s) well)</technical_language>

Target:
public void testBacktickEscapedIdentifier() { assertTrue(CharFormatUtil.unescapeIdentifier("``").isEmpty()); assertTrue(CharFormatUtil.unescapeIdentifier("").isEmpty()); assertEquals("self", CharFormatUtil.unescapeIdentifier("`self`")); assertEquals("s",CharFormatUtil.unescapeIdentifier("`s`")); assertEquals("self",CharFormatUtil.unescapeIdentifier("`self`")); assertEquals("`self", CharFormatUtil.unescapeIdentifier("`self")); assertEquals("self`", CharFormatUtil.unescapeIdentifier("self`")); assertEquals("`self", CharFormatUtil.unescapeIdentifier("``self`")); }
Source:
<code>protected void validateAuthenticationState(HttpClient httpClient) throws GerritLoginException { Optional<Cookie> cookie = findCookieWithName(LOGIN_COOKIE_NAME, httpClient); cookie.ifPresent(this::setXsrfCookie); <START> if (!cookie.isPresent()) { <END> if (CoreUtil.TEST_MODE) { System.err.println(" Authentication failed: " + httpClient.getState()); } throw new GerritLoginException(); } }</code><technical_language>mixture of functional non-functional programming right, I works,</technical_language>

Target:
protected void validateAuthenticationState(HttpClient httpClient) throws GerritLoginException { Optional<Cookie> cookie = findCookieWithName(LOGIN_COOKIE_NAME, httpClient); setXsrfCookie(nonNullOrThrow(cookie, () -> new GerritLoginException(), httpClient).get()); }
Source:
<code>private void testGetForDeletedBlobWithoutIncludeExpiredOption(List<BlobId> blobIds) { try { store.get(blobIds, EnumSet.noneOf(StoreGetOptions.class)); assertTrue( "get should fail for a expired blob, if StoreGetOptions.Store_Include_Expired is not set in get options", false); } catch (StoreException e) { <START> assertTrue( <END> "get for expired blob with with StoreGetOptions.Store_Include_Expired not set in get options should throw exception with " + StoreErrorCodes.TTL_Expired + " error code.", e.getErrorCode().equals(StoreErrorCodes.TTL_Expired)); } }</code><technical_language>assertEquals remove expected message string</technical_language>

Target:
private void testGetForDeletedBlobWithoutIncludeExpiredOption(List<BlobId> blobIds) { try { store.get(blobIds, EnumSet.noneOf(StoreGetOptions.class)); fail("get should fail for a expired blob, if StoreGetOptions.Store_Include_Expired is not set in get options"); } catch (StoreException e) { assertEquals( "get for expired blob with with StoreGetOptions.Store_Include_Expired not set in get options, should throw exception with " + StoreErrorCodes.TTL_Expired + " error code.", e.getErrorCode(), StoreErrorCodes.TTL_Expired); } }
Source:
<code>public Publisher<Integer> createFailedPublisher() { <START> return null; <END> }</code><technical_language>provide</technical_language>

Target:
public Publisher<Integer> createFailedPublisher() { final SubmissionPublisher<Integer> sp = new SubmissionPublisher<Integer>(); sp.closeExceptionally(new IOException()); return ReactiveStreamsFlowBridge.toReactiveStreams(sp); }
Source:
<code>public String name() { <START> return Json.createReader(new StringReader(this.obj)) <END> .readObject() .getString("name"); }</code><technical_language>a duplication me. this.json().getString("name")</technical_language>

Target:
public String name() { return this.json().getString("name"); }
Source:
<code>protected FieldBase(String name, DataType dataType) { if (CoreUtils.isNullOrEmpty(name)) { <START> throw logger.logExceptionAsError(new IllegalArgumentException("The name of field cannot be null")); <END> } this.name = name; this.dataType = dataType; }</code><technical_language>validate DataType != null</technical_language>

Target:
protected FieldBase(String name, DataType dataType) { if (CoreUtils.isNullOrEmpty(name)) { throw logger.logExceptionAsError(new IllegalArgumentException("The name of the field cannot be null")); } this.dataType = Objects.requireNonNull(dataType, "'dataType' cannot be null."); this.name = name; }
Source:
<code>public Map<?, ?> read() { final Yaml yaml = new Yaml(); final Map<String, String> properties = new HashMap<>(); <START> try (InputStream in = inputStream) { <END> yaml.loadAll(in).forEach((Object obj) -> this.loadValue(properties, "", obj)); return properties; } catch (IOException e) { throw new IllegalStateException("Cannot load environment", e); } }</code><technical_language>I need close this InputStream some point</technical_language>

Target:
public Map<?, ?> read() { final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); try (InputStream in = inputStream) { yaml.setResources(new InputStreamResource(inputStream)); return yaml.getObject(); } catch (IOException e) { throw new IllegalStateException("Cannot load environment", e); } }
Source:
<code>private static String createOrUpdateAccountsAndWait(Collection<Account> accounts) throws Exception { String jsonFilePath = tempDirPath + File.separator + UUID.randomUUID().toString() + ".json"; <START> writeAccountsToFile(accounts, jsonFilePath); <END> int numOfAccounts = AccountUpdater.createOrUpdate(jsonFilePath, ZK_SERVER_ADDRESS, HELIX_STORE_ROOT_PATH, null, null); Thread.sleep(100); return numOfAccounts == -1 ? null : jsonFilePath; }</code><technical_language>do clean files exit? root level dir is deleted exit</technical_language>

Target:
private static void createOrUpdateAccountsAndWait(Collection<Account> accounts) throws Exception { String jsonFilePath = tempDirPath + File.separator + UUID.randomUUID().toString() + ".json"; writeAccountsToFile(accounts, jsonFilePath); AccountUpdateTool.updateAccount(jsonFilePath, ZK_SERVER_ADDRESS, HELIX_STORE_ROOT_PATH, 2000, 2000); Thread.sleep(100); }
Source:
<code>private Integer extractCount(HttpServletRequest request) { Integer count = Integer.valueOf(getParameter(request, "count")); <START> checkArgument(COUNT_RANGE.contains(count), "'count' must be in range %s, was %s", COUNT_RANGE, count); <END> return count; }</code><technical_language>"in range" providing a range; "'count' %s"? Also, %d</technical_language>

Target:
private Integer extractCount(HttpServletRequest request) { Integer count = Integer.valueOf(getParameter(request, COUNT_PARAM)); checkArgument(COUNT_RANGE.contains(count), "'count' must be between %s and %s, was %s", COUNT_RANGE.lowerEndpoint(), COUNT_RANGE.upperEndpoint(), count); return count; }
Source:
<code>private void dismissToast() { try { toast.cancel(); <START> } catch (NullPointerException e) { <END> ZLog.logException(e); } }</code><technical_language>hear i handle this error gracefully if (toast != null) check send traceback crashylytics Zlog.logException(e)</technical_language>

Target:
private void dismissToast() { if (toast != null) { toast.cancel(); } }