auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void RTEDisabledEditorEntryDefaultPreferredTests_001_CreatePageEntry() { String articleName = PageContent.articleNamePrefix + base.getTimeStamp(); ArticlePageObject article = <START> base.openArticleByName(wikiURL, articleName); <END> VisualEditorPageObject ve = article.createArticleInVEUsingDropdown(articleName); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); ve.logOut(wikiURL); }</code><technical_language>fit in line</technical_language>

Target:
public void RTEDisabledEditorEntryDefaultPreferredTests_001_CreatePageEntry() { String articleName = PageContent.articleNamePrefix + base.getTimeStamp(); ArticlePageObject article = base.openArticleByName(wikiURL, articleName); VisualEditorPageObject ve = article.createArticleInVEUsingDropdown(articleName); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); }
Source:
<code>public boolean isActive(FeatureState featureState, FeatureUser user) { ApplicationContext applicationContext = ContextClassLoaderApplicationContextHolder.get(); if (applicationContext == null) { <START> return false; <END> } List<String> activeProfiles = Arrays.asList(applicationContext.getEnvironment().getActiveProfiles()); List<String> profiles = Strings.splitAndTrim(featureState.getParameter(PARAM_PROFILES), "[\\s,]+"); for (String profile : profiles) { if (activeProfiles.contains(profile)) { return true; } } return false; }</code><technical_language>treating this a fatal error. 100% this. thoughts in other PR</technical_language>

Target:
public boolean isActive(FeatureState featureState, FeatureUser user) { ApplicationContext applicationContext = ContextClassLoaderApplicationContextHolder.get(); if (applicationContext == null) { throw new IllegalStateException("ApplicationContext could not be found, which can occur if there is no bean for " + "TogglzApplicationContextBinderApplicationListener when TogglzAutoConfiguration is not being used"); } List<String> activeProfileNames = getActiveProfileNames(applicationContext); List<Profile> profiles = parseProfiles(featureState); for (Profile profile : profiles) { if (activeProfileNames.contains(profile.name) != profile.negated) { return true; } } return false; }
Source:
<code>protected void ExecuteVmCommand() { if (getVm().getstatus() == VMStatus.Up) { performPlugCommnad(getPlugAction(), diskImage, oldVmDevice); } <START> oldVmDevice.setIsPlugged(!oldVmDevice.getIsPlugged()); <END> getVmDeviceDao().update(oldVmDevice); VmHandler.updateDisksFromDb(getVm()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { VmDeviceUtils.updateBootOrderInVmDevice(getVm().getStaticData()); return null; } }); setSucceeded(true); }</code><technical_language>I u start transaction line 72</technical_language>

Target:
protected void ExecuteVmCommand() { if (getVm().getstatus() == VMStatus.Up) { performPlugCommnad(getPlugAction(), diskImage, oldVmDevice); } oldVmDevice.setIsPlugged(!oldVmDevice.getIsPlugged()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getVmDeviceDao().update(oldVmDevice); VmHandler.updateDisksFromDb(getVm()); VmDeviceUtils.updateBootOrderInVmDevice(getVm().getStaticData()); return null; } }); setSucceeded(true); }
Source:
<code>private static PathElement counterElement(ModelNode operation) <START> throws OperationFailedException { <END> final PathAddress address = pathAddress(operation.require(OP_ADDR)); final PathElement counterElement = address.getElement(address.size() - 1); return counterElement; }</code><technical_language>OperationFailedException thrown removed</technical_language>

Target:
private static PathElement counterElement(ModelNode operation) { final PathAddress address = pathAddress(operation.require(OP_ADDR)); final PathElement counterElement = address.getElement(address.size() - 1); return counterElement; }
Source:
<code>RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { for (;;) { final RevCommit c = pending.next(); if (c == null) return null; if (c.inDegree > 0) { c.flags |= TOPO_DELAY; continue; } for (int i = 0; i < c.parents.length; i++) { <START> if (i > 0 && firstParent) { <END> break; } RevCommit p = c.parents[i]; if (--p.inDegree == 0 && (p.flags & TOPO_DELAY) != 0) { p.flags &= ~TOPO_DELAY; pending.unpop(p); } } return c; } }</code><technical_language>Order of tests in if: other "ifs" do "firstParent && i > 0"</technical_language>

Target:
RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { for (;;) { final RevCommit c = pending.next(); if (c == null) return null; if (c.inDegree > 0) { c.flags |= TOPO_DELAY; continue; } for (int i = 0; i < c.parents.length; i++) { if (firstParent && i > 0) { break; } RevCommit p = c.parents[i]; if (--p.inDegree == 0 && (p.flags & TOPO_DELAY) != 0) { p.flags &= ~TOPO_DELAY; pending.unpop(p); } } return c; } }
Source:
<code>public void testConfiguredConfigEnabled() { CallOptionsConfig config = new CallOptionsConfig.Builder().setUseTimeout(true).build(); CallOptionsFactory factory = new CallOptionsFactory.ConfiguredCallOptionsFactory(config); Assert.assertEquals( <START> (double) config.getShortRpcTimeoutMs(), <END> getDeadlineMs(factory, MutateRowRequest.getDefaultInstance()), 100.0 ); Assert.assertEquals( (double) config.getLongRpcTimeoutMs(), (double) getDeadlineMs(factory, MutateRowsRequest.getDefaultInstance()), 100.0 ); }</code><technical_language>explicitly set ShortRpcTimeoutMs? is easier understand this is coming from</technical_language>

Target:
public void testConfiguredConfigEnabled() { CallOptionsConfig config = new CallOptionsConfig.Builder().setUseTimeout(true).build(); CallOptionsFactory factory = new CallOptionsFactory.ConfiguredCallOptionsFactory(config); assertEqualsDeadlines( config.getShortRpcTimeoutMs(), getDeadlineMs(factory, MutateRowRequest.getDefaultInstance()) ); assertEqualsDeadlines( config.getLongRpcTimeoutMs(), getDeadlineMs(factory, MutateRowsRequest.getDefaultInstance()) ); }
Source:
<code>public int hashCode() { <START> return Objects.hash(pointer, ownerName, owner, readers, writers); <END> }</code><technical_language>neat</technical_language>

Target:
public int hashCode() { return Objects.hash(pointer, ownerName); }
Source:
<code>private Contentlet createContentlet(final ContentType contentType) { final ContentletDataGen contentletDataGen = new ContentletDataGen(contentType.id()); Contentlet contentlet = contentletDataGen.next(); contentlet.setStringProperty("widgetTitle", "New YouTube Content"); contentlet.setStringProperty("url", "new-youtube-content"); contentlet = contentletDataGen.persist(contentlet); <START> return contentlet; <END> }</code><technical_language>do this in line return final Contentlet contentlet = new ContentletDataGen(contentType.id()).setStringProperty("widgetTitle", "New YouTube Content").setStringProperty("url", "new-youtube-content").nextPersisted();</technical_language>

Target:
private Contentlet createContentlet(final ContentType contentType) { return new ContentletDataGen(contentType.id()) .setProperty("widgetTitle", "New YouTube Content") .setProperty("url", "new-youtube-content").nextPersisted(); }
Source:
<code>public void testFiltersByDate() throws Exception { FeatureSource fs = dataStore.getFeatureSource( tname("dates") ); FilterFactory ff = dataStore.getFilterFactory(); DateFormat df = new SimpleDateFormat("yyyy-dd-MM"); df.setTimeZone( TimeZone.getTimeZone("PST")); <START> Filter f = ff.lessOrEqual( ff.property( aname("d") ), ff.literal("2009-06-28") ); <END> assertEquals( 2, fs.getCount( new DefaultQuery(tname("dates"),f ) ) ); f = ff.lessOrEqual( ff.property( aname("d") ), ff.literal( df.parse("2009-28-06") ) ); assertEquals( 2, fs.getCount( new DefaultQuery(tname("dates"),f ) ) ); }</code><technical_language>this test is testing - a literal string actual date (in PST)</technical_language>

Target:
public void testFiltersByDate() throws Exception { FeatureSource fs = dataStore.getFeatureSource( tname("dates") ); FilterFactory ff = dataStore.getFilterFactory(); DateFormat df = new SimpleDateFormat("yyyy-dd-MM"); df.setTimeZone( TimeZone.getTimeZone("PST")); Filter f = ff.lessOrEqual( ff.property( aname("d") ), ff.literal( df.parse("2009-28-06") ) ); assertEquals( 2, fs.getCount( new DefaultQuery(tname("dates"),f ) ) ); f = ff.lessOrEqual( ff.property( aname("d") ),ff.literal( df.parse("2009-28-06") ) ); assertEquals( 2, fs.getCount( new DefaultQuery(tname("dates"),f ) ) ); }
Source:
<code><START> public static Collection<Object> getSatisfiedAuthenticationMethods(final Authentication authentication) { <END> if (authentication.getAttributes().containsKey(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD)) { final Object methods = authentication.getAttributes().get( MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD); if (methods != null) { return MultiFactorUtils.convertValueToCollection(methods); } } return Collections.emptyList(); }</code><technical_language>this more specific nature of Collection? in, this a Set, right, is expressed is set of fulfilled authentication methods? A authentication method is fulfilled (appears in set) authentication methods order relationship</technical_language>

Target:
public static Set<String> getSatisfiedAuthenticationMethods(final Authentication authentication) { if (authentication.getAttributes().containsKey(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD)) { final Object methods = authentication.getAttributes().get( MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD); if (methods != null) { final Set<Object> valuesAsACollection = convertValueToCollection(methods); return new HashSet<String>(Arrays.asList(valuesAsACollection.toArray(new String[] {}))); } } return Collections.emptySet(); }
Source:
<code>public void canReadItemJustWritten() throws BufferIOException { CircularBuffer<Integer> buffer = new CircularBuffer<>(1); buffer.write(1); <START> assertEquals((int) buffer.read(), 1); <END> }</code><technical_language>do need this cast</technical_language>

Target:
public void canReadItemJustWritten() throws BufferIOException { CircularBuffer<Integer> buffer = new CircularBuffer<>(1); buffer.write(1); assertThat(buffer.read(), is(1)); }
Source:
<code>private boolean shouldRedraw(AnyObjectId headId, AnyObjectId fetchHeadId, List<FilterPath> paths) { boolean pathChanged = pathChanged(pathFilters, paths); boolean headChanged = headId == null || !headId.equals(currentHeadId); boolean allBranchesChanged = currentShowAllBranches != store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_ALL_BRANCHES); currentShowAllBranches = store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_ALL_BRANCHES); boolean firstParentOnlyChanged = currentShowFirstParentOnly != <START> isShowFirstParentOnly(); <END> currentShowFirstParentOnly = isShowFirstParentOnly(); boolean additionalRefsChange = currentShowAdditionalRefs != store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_ADDITIONAL_REFS); currentShowAdditionalRefs = store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_ADDITIONAL_REFS); boolean fetchHeadChanged = currentShowAdditionalRefs && fetchHeadId != null && !fetchHeadId.equals(currentFetchHeadId); boolean showNotesChanged = currentShowNotes != store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_NOTES); currentShowNotes = store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_NOTES); boolean followRenamesChanged = currentFollowRenames != getFollowRenames(); currentFollowRenames = getFollowRenames(); return pathChanged || headChanged || fetchHeadChanged || allBranchesChanged || firstParentOnlyChanged || additionalRefsChange || showNotesChanged || followRenamesChanged; }</code><technical_language>I extract this a variable</technical_language>

Target:
private boolean shouldRedraw(AnyObjectId headId, AnyObjectId fetchHeadId, List<FilterPath> paths) { boolean pathChanged = pathChanged(pathFilters, paths); boolean headChanged = headId == null || !headId.equals(currentHeadId); boolean allBranchesChanged = currentShowAllBranches != store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_ALL_BRANCHES); currentShowAllBranches = store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_ALL_BRANCHES); boolean isShowFirstParentOnly = isShowFirstParentOnly(); boolean firstParentOnlyChanged = currentShowFirstParentOnly != isShowFirstParentOnly; currentShowFirstParentOnly = isShowFirstParentOnly; boolean additionalRefsChange = currentShowAdditionalRefs != store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_ADDITIONAL_REFS); currentShowAdditionalRefs = store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_ADDITIONAL_REFS); boolean fetchHeadChanged = currentShowAdditionalRefs && fetchHeadId != null && !fetchHeadId.equals(currentFetchHeadId); boolean showNotesChanged = currentShowNotes != store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_NOTES); currentShowNotes = store .getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_NOTES); boolean followRenamesChanged = currentFollowRenames != getFollowRenames(); currentFollowRenames = getFollowRenames(); return pathChanged || headChanged || fetchHeadChanged || allBranchesChanged || firstParentOnlyChanged || additionalRefsChange || showNotesChanged || followRenamesChanged; }
Source:
<code>public void testAttachContainerToNetwork() { api().connectContainerToNetwork(network.id(), container.id()); Container foundContainer = api.getContainerApi().inspectContainer(container.id()); <START> assertNotNull(Iterables.tryFind(foundContainer.networkSettings().networks().keySet(), Predicates.equalTo(network.name())).orNull()); <END> }</code><technical_language>more readable assertTrue(Iterables.any(...)</technical_language>

Target:
public void testAttachContainerToNetwork() { api().connectContainerToNetwork(network.id(), container.id()); container = api.getContainerApi().inspectContainer(container.id()); assertTrue(Iterables.any(container.networkSettings().networks().keySet(), Predicates.equalTo(network.name()))); }
Source:
<code>public Version toOSGIVersion() { <START> return new Version(toString()); <END> }</code><technical_language>this return null if version is a valid OSGI version</technical_language>

Target:
final public Version toOSGIVersion() { try { return new Version(toString()); } catch (IllegalArgumentException e) { return null; } }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if (!FiltersHelper.isAuthenticated(req) || !FiltersHelper.isSessionValid((HttpServletRequest) request, (HttpServletResponse) response)) { authenticateWithSSO(req, (HttpServletResponse) response); } <START> chain.doFilter(request, response); <END> }</code><technical_language>again, this be, unconditional chaining... nego able stop chaining, please current implementation of nego</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; if (FiltersHelper.isAuthenticated(req) && FiltersHelper.isSessionValid((HttpServletRequest) request, (HttpServletResponse) response)) { chain.doFilter(request, response); } else { try { req.setAttribute(FiltersHelper.Constants.REQUEST_SCHEMES_KEY, schemes); HttpSession session = req.getSession(false); Deque<AuthenticationProfile> stack = null; if (session != null) { stack = (Deque<AuthenticationProfile>) session.getAttribute(STACK_ATTR); } if (stack == null) { stack = new ArrayDeque<>(); stack.addAll(profiles); } String username = doAuth(req, resp, stack); if (!stack.isEmpty()) { req.getSession(true).setAttribute(STACK_ATTR, stack); } else { if (session != null) { session.removeAttribute(STACK_ATTR); } if (StringUtils.isNotEmpty(username)) { Map<String, Object> jsonResponse = SSOOAuthServiceUtils.loginOnBehalf(resp, username, scope); FiltersHelper.isStatusOk(jsonResponse); SSOUtils.createUserSession(req, FiltersHelper.getPayloadForToken(resp, (String) jsonResponse.get("access_token")), false); } chain.doFilter(req, resp); } } catch (Exception e) { log.error("Cannot authenticate using External Authentication: {}", e.getMessage()); log.debug("Cannot authenticate using External Authentication", e); } } }
Source:
<code>private void setupController() { try{ if (player != null) { View f = getView(); if (f != null) { ViewGroup container = (ViewGroup) f .findViewById(R.id.preview_container); PlayerController controller = new PlayerController( getActivity()); controller.setAnchorView(container); controller.setAutoHide(true); controller.setPrevNextListeners(nextListner, prevListner); player.setController(controller); player.setShareVideoListener(this); reAttachPlayEventListener(); <START> <END> } else { } } else { } }catch(Exception e){ logger.error(e); } }</code><technical_language>extra line useless else blocks (x2)</technical_language>

Target:
private void setupController() { if (null == player) { return; } try { View f = getView(); if (f == null) { return; } final ViewGroup container = (ViewGroup) f .findViewById(R.id.preview_container); final PlayerController controller = new PlayerController( getActivity()); controller.setAnchorView(container); controller.setAutoHide(true); controller.setNextPreviousListeners(nextListner, prevListner); player.setController(controller); player.setShareVideoListener(this); reAttachPlayEventListener(); } catch(Exception e) { logger.error(e); } }
Source:
<code>public void start(ComponentContext context) { super.start(context); <START> List<BatchHandlerDescriptor> descriptors = getDescriptors(EP_BATCH_HANDLER); <END> descriptors.forEach(d -> { try { BatchHandler handler = d.klass.newInstance(); handler.initialize(d.name, d.properties); handlers.put(d.name, handler); } catch (ReflectiveOperationException e) { getLog().error(e); } }); }</code><technical_language>introduce a convention for extension point ? I XP_sth</technical_language>

Target:
public void start(ComponentContext context) { super.start(context); List<BatchHandlerDescriptor> descriptors = getDescriptors(XP_BATCH_HANDLER); descriptors.forEach(d -> { try { BatchHandler handler = d.klass.newInstance(); handler.initialize(d.name, d.properties); handlers.put(d.name, handler); } catch (ReflectiveOperationException e) { getLog().error(e,e); } }); }
Source:
<code>public void testHighWaterMark() throws Exception { try (Scenario scenario = new Scenario(0, 2)) { TFuture<RawResponse> future1 = scenario.sendRequest(100); TFuture<RawResponse> future2 = scenario.sendRequest(100); <START> scenario.releaseResponses(2); <END> int success = 0; if (ResponseCode.OK.equals(future1.get().getResponseCode())) { success += 1; assertEquals(ErrorType.Timeout, future2.get().getError().getErrorType()); } if (ResponseCode.OK.equals(future2.get().getResponseCode())) { success += 1; assertEquals(ErrorType.Timeout, future1.get().getError().getErrorType()); } assertEquals(1, success); } }</code><technical_language>If I understand code/test scenario correctly, message through, triggers high watermark. If time message is read, time out</technical_language>

Target:
public void testHighWaterMark() throws Exception { try (Scenario scenario = new Scenario(0, 2)) { ArrayList<TFuture<RawResponse>> futures = new ArrayList<>(); futures.add(scenario.sendRequest(1000)); Thread.sleep(100); futures.add(scenario.sendRequest(1000)); Thread.sleep(100); futures.add(scenario.sendRequest(1000)); Thread.sleep(100); assertEquals(2, scenario.responseGate.getQueueLength()); scenario.releaseResponses(futures.size()); for (TFuture<RawResponse> future : futures) { assertEquals(ResponseCode.OK, future.get().getResponseCode()); } } }
Source:
<code>protected void initiateLoginAttempt(boolean restoreSession) { LoginMode loginMode = uiController.getLoginMode(); <START> if (uiController.getEnteredPasswordOrPin().equals("") && <END> loginMode != LoginMode.PRIMED) { if (loginMode == LoginMode.PASSWORD) { raiseLoginMessage(StockMessages.Auth_EmptyPassword, false); return; } else { raiseLoginMessage(StockMessages.Auth_EmptyPin, false); return; } } uiController.clearErrorMessage(); ViewUtil.hideVirtualKeyboard(LoginActivity.this); if (loginMode == LoginMode.PASSWORD) { DevSessionRestorer.tryAutoLoginPasswordSave(uiController.getEnteredPasswordOrPin()); } if (ResourceInstallUtils.isUpdateReadyToInstall()) { installPendingUpdate(); } else { localLoginOrPullAndLogin(restoreSession); } }</code><technical_language>I generally equals call hard-coded string ("") if avoid potential for a null pointer exception</technical_language>

Target:
protected void initiateLoginAttempt(boolean restoreSession) { LoginMode loginMode = uiController.getLoginMode(); if ("".equals(uiController.getEnteredPasswordOrPin()) && loginMode != LoginMode.PRIMED) { if (loginMode == LoginMode.PASSWORD) { raiseLoginMessage(StockMessages.Auth_EmptyPassword, false); } else { raiseLoginMessage(StockMessages.Auth_EmptyPin, false); } return; } uiController.clearErrorMessage(); ViewUtil.hideVirtualKeyboard(LoginActivity.this); if (loginMode == LoginMode.PASSWORD) { DevSessionRestorer.tryAutoLoginPasswordSave(uiController.getEnteredPasswordOrPin()); } if (ResourceInstallUtils.isUpdateReadyToInstall()) { installPendingUpdate(); } else { localLoginOrPullAndLogin(restoreSession); } }
Source:
<code><START> public void testReadOnlySlow() throws IOException { <END> ByteBuffer msg = createMsg("@ReadOnlySlow", "select * from a"); ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn); assertNull(resp); ArgumentCaptor<LocalObjectMessage> captor = ArgumentCaptor.forClass(LocalObjectMessage.class); verify(m_messenger).send(eq(32L), captor.capture()); assertTrue(captor.getValue().payload instanceof AdHocPlannerWork); String payloadString = captor.getValue().payload.toString(); assertTrue(payloadString.contains("user partitioning: none")); }</code><technical_language>Comparing this testAdHoc, I replicated MP invocation test SP invocation test. me. SP work? MP work</technical_language>

Target:
public void testReadOnlySlow() throws IOException { ByteBuffer msg = createMsg("@ReadOnlySlow", "select * from a"); ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn); assertNull(resp); ArgumentCaptor<LocalObjectMessage> captor = ArgumentCaptor.forClass(LocalObjectMessage.class); verify(m_messenger).send(eq(32L), captor.capture()); assertTrue(captor.getValue().payload instanceof AdHocPlannerWork); String payloadString = captor.getValue().payload.toString(); assertTrue(payloadString.contains("user partitioning: none")); reset(m_messenger); msg = createMsg("@ReadOnlySlow", "select * from a where i = 3", 3); resp = m_ci.handleRead(msg, m_handler, m_cxn); assertNull(resp); verify(m_messenger).send(eq(32L), captor.capture()); assertTrue(captor.getValue().payload instanceof AdHocPlannerWork); payloadString = captor.getValue().payload.toString(); assertTrue(payloadString.contains("user param[1]: 3")); assertTrue(payloadString.contains("user partitioning: none")); }
Source:
<code>public Object set(final int index, final Object element) { Object prev = null; if (checkString(index)) prev = table.getStringValue(col, index); else prev = table.getValueAsDouble(col, index); if (element instanceof String) table.setValue(col, index, (String) element); else if (element instanceof Number) table.setValue(col, index, ((Number) element).doubleValue()); <START> else throw new IllegalArgumentException("element must be String or Double"); <END> return prev; }</code><technical_language>draconian be: java if (element instanceof Number) table.setValue(col, index, ((Number) element).doubleValue()); else if (element != null) table.setValue(col, index, element.toString()); else ... // do null... NPE thrown..</technical_language>

Target:
public Object set(final int index, final Object element) { Object prev = null; if (checkString(index)) prev = table.getStringValue(col, index); else prev = table.getValueAsDouble(col, index); if (element instanceof Number) table.setValue(col, index, ((Number) element) .doubleValue()); else if (element != null) table.setValue(col, index, element.toString()); else throw new NullPointerException(); return prev; }
Source:
<code>private void handleError(Map action) { String msg = (String) action.get("msg"); <START> if (msg != null) { <END> _collector.reportError(new Exception("Shell Process Exception: " + msg)); } }</code><technical_language>do check for null here</technical_language>

Target:
private void handleError(Map action) { String msg = (String) action.get("msg"); _collector.reportError(new Exception("Shell Process Exception: " + msg)); }
Source:
<code>public Object createModelObject(Class<?> model, OpenEngSBModelEntry... entries) throws IllegalArgumentException { LOGGER.debug("createModelObject for model interface called", model.getName()); boolean valid = false; for (Class<?> i : model.getInterfaces()) { <START> if (i.equals(OpenEngSBModel.class)) { <END> valid = true; break; } } if (!valid) { throw new IllegalArgumentException("the model class is not an interface of OpenEngSBModel"); } return generateProxy(model, entries); }</code><technical_language>I CollectionUtils a contains-method for arrays</technical_language>

Target:
private Object createModelObject(Class<?> model, OpenEngSBModelEntry... entries) { ClassLoader classLoader = model.getClassLoader(); Class<?>[] classes = new Class<?>[]{ OpenEngSBModel.class, model }; InvocationHandler handler = makeHandler(model, entries); return Proxy.newProxyInstance(classLoader, classes, handler); }
Source:
<code>public void onActivityResult(final int requestCode, int resultCode, final Intent intent) { if (mRequestQuestionId == null || resultCode != RESULT_OK) { mRequestQuestionId = null; return; } mAdapter.setOnTabLoadedListener(new SurveyTabAdapter.OnTabLoadedListener() { @Override <START> public void OnTabLoaded() { <END> switch (requestCode) { case ConstantUtil.PHOTO_ACTIVITY_REQUEST: onImageTaken(); break; case ConstantUtil.VIDEO_ACTIVITY_REQUEST: onVideoTaken(intent.getData()); break; case ConstantUtil.GET_PHOTO_ACTIVITY_REQUEST: onImageAcquired(intent.getData()); break; case ConstantUtil.GET_VIDEO_ACTIVITY_REQUEST: onVideoAcquired(intent.getData()); break; case ConstantUtil.CADDISFLY_REQUEST: case ConstantUtil.SCAN_ACTIVITY_REQUEST: case ConstantUtil.PLOTTING_REQUEST: case ConstantUtil.SIGNATURE_REQUEST: default: mAdapter.onQuestionResultReceived(mRequestQuestionId, intent.getExtras()); break; } mAdapter.setOnTabLoadedListener(null); mRequestQuestionId = null; } }); }</code><technical_language>suggestion public void onTabLoaded() {</technical_language>

Target:
public void onActivityResult(final int requestCode, int resultCode, final Intent intent) { if (mRequestQuestionId == null || resultCode != RESULT_OK) { mRequestQuestionId = null; return; } if (mAdapter.getQuestionView(mRequestQuestionId) == null) { mAdapter.setOnTabLoadedListener(new SurveyTabAdapter.OnTabLoadedListener() { @Override public void onTabLoaded() { setResult(requestCode, intent, mRequestQuestionId); mAdapter.setOnTabLoadedListener(null); } }); } else { setResult(requestCode, intent, mRequestQuestionId); } }
Source:
<code>public LuceneCollectors build() { TopDocsCollector<?> topDocsCollector = null; LuceneScoreDocPostProcessor scoreDocPostProcessor = null; if ( requireTopDocs && maxDocs > 0 ) { if ( sort == null ) { topDocsCollector = TopScoreDocCollector.create( maxDocs, Integer.MAX_VALUE ); } else { if ( requireScore ) { SortField[] sortFields = sort.getSort(); for ( int i = 0; i < sortFields.length; i++ ) { SortField sortField = sortFields[i]; if ( sortField.getType() == SortField.Type.SCORE ) { <START> scoreDocPostProcessor = new LuceneTopFieldCollectorScoreSortPostProcessor( i ); <END> break; } } scoreDocPostProcessor = new LuceneTopFieldCollectorRescoringPostProcessor(); } topDocsCollector = TopFieldCollector.create( sort, maxDocs, Integer.MAX_VALUE ); } luceneCollectors.add( topDocsCollector ); } Collector compositeCollector; if ( luceneCollectors.size() == 1 ) { compositeCollector = luceneCollectors.get( 0 ); } else { compositeCollector = MultiCollector.wrap( luceneCollectors ); } return new LuceneCollectors( topDocsCollector, totalHitCountCollector, compositeCollector, scoreDocPostProcessor ); }</code><technical_language>I this assignment overridden other line 90</technical_language>

Target:
public LuceneCollectors build() { TopDocsCollector<?> topDocsCollector = null; Integer scoreSortFieldIndexForRescoring = null; boolean requireFieldDocRescoring = false; if ( requireTopDocs && maxDocs > 0 ) { if ( sort == null ) { topDocsCollector = TopScoreDocCollector.create( maxDocs, Integer.MAX_VALUE ); } else { if ( requireScore ) { requireFieldDocRescoring = true; SortField[] sortFields = sort.getSort(); for ( int i = 0; i < sortFields.length; i++ ) { SortField sortField = sortFields[i]; if ( sortField.getType() == SortField.Type.SCORE ) { scoreSortFieldIndexForRescoring = i; break; } } } topDocsCollector = TopFieldCollector.create( sort, maxDocs, Integer.MAX_VALUE ); } luceneCollectors.add( topDocsCollector ); } Collector compositeCollector; if ( luceneCollectors.size() == 1 ) { compositeCollector = luceneCollectors.get( 0 ); } else { compositeCollector = MultiCollector.wrap( luceneCollectors ); } return new LuceneCollectors( topDocsCollector, totalHitCountCollector, compositeCollector, requireFieldDocRescoring, scoreSortFieldIndexForRescoring ); }
Source:
<code>static Stream<Arguments> filePositionFromQuery() { return Stream.of( <START> Arguments.of(null, -1, -1), END> Arguments.of("?!", -1, -1), Arguments.of("line=ZZ", -1, -1), Arguments.of("line=42", 42, -1), Arguments.of("line=42&line=24", 24, -1), Arguments.of("line=42&column=99", 42, 99), Arguments.of("line=42&column=ZZ", 42, -1) ); }</code><technical_language>Arguments.of --> arguments (via static import )</technical_language>

Target:
static Stream<Arguments> filePositionFromQuery() { return Stream.of( arguments(null, -1, -1), arguments("?!", -1, -1), arguments("line=ZZ", -1, -1), arguments("line=42", 42, -1), arguments("line=42&line=24", 24, -1), arguments("line=42&column=99", 42, 99), arguments("line=42&column=ZZ", 42, -1) ); }
Source:
<code>private void doAsyncCreate(final String path, final byte[] data, final CreateMode mode, final long startT, final ZkAsyncCallbacks.CreateCallbackHandler cb, final String expectedSessionId) { retryUntilConnected(() -> { <START> final ZooKeeper zk; try { zk = getExpectedZookeeper(expectedSessionId); } catch (ZkSessionMismatchedException e) { cb.processResult(KeeperException.Code.BADARGUMENTS.intValue(), path, new ZkAsyncCallMonitorContext(_monitor, startT, 0, false), null); throw e; } zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, mode, cb, new ZkAsyncRetryCallContext(_asyncCallRetryThread, cb, _monitor, startT, 0, false) { @Override protected void doRetry() { doAsyncCreate(path, data, mode, System.currentTimeMillis(), cb, expectedSessionId); <END> } }); return null; }); }</code><technical_language>need cancel in doRetry()</technical_language>

Target:
private void doAsyncCreate(final String path, final byte[] data, final CreateMode mode, final long startT, final ZkAsyncCallbacks.CreateCallbackHandler cb, final String expectedSessionId) { try { retryUntilConnected(() -> { getExpectedZookeeper(expectedSessionId) .create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, mode, cb, new ZkAsyncRetryCallContext(_asyncCallRetryThread, cb, _monitor, startT, 0, false) { @Override protected void doRetry() { doAsyncCreate(path, data, mode, System.currentTimeMillis(), cb, expectedSessionId); } }); return null; }); } catch (RuntimeException e) { cb.processResult(ZkAsyncCallbacks.UNKNOWN_RET_CODE, path, new ZkAsyncCallMonitorContext(_monitor, startT, 0, false), null); throw e; } }
Source:
<code>public void close() { LOG.info("Closing crutch consumer and removing ip address change listener"); super.close(); <START> this.kafkaLocationManager.removeIpAddressChangeListener(brokerIpAddressChangeListener); <END> }</code><technical_language>try finally {}</technical_language>

Target:
public void close() { this.kafkaLocationManager.removeIpAddressChangeListener(brokerIpAddressChangeListener); super.close(); }
Source:
<code>public void setNull(long columnIndex) { parent.checkImmutable(); <START> getTable().checkNullValueIsLegal(columnIndex, getIndex()); <END> nativeSetNull(nativePointer, columnIndex); }</code><technical_language>this check done JNI</technical_language>

Target:
public void setNull(long columnIndex) { parent.checkImmutable(); getTable().checkDuplicatedNullForPrimaryKeyValue(columnIndex, getIndex()); nativeSetNull(nativePointer, columnIndex); }
Source:
<code>public MessageContext receive() { if (isAlive()) { try { GetResponse delivery = channel.basicGet(queueName, false); if (delivery != null) { <START> StorableMessage storableMessage = deserializeMessage(channel, delivery); <END> org.apache.axis2.context.MessageContext axis2Mc = store.newAxis2Mc(); MessageContext synapseMc = store.newSynapseMc(axis2Mc); synapseMc = MessageConverter.toMessageContext(storableMessage, axis2Mc, synapseMc); updateCache(delivery, delivery.getProps().getMessageId()); log.info(getId() + " Received MessageId: " + delivery.getProps().getMessageId()); if (log.isDebugEnabled()) { log.debug(getId() + " Received MessageId: " + delivery.getProps().getMessageId()); } return synapseMc; } } catch (ShutdownSignalException | IOException e) { log.error(getId() + " connection error when receiving messages." + e); } } else { cleanup(); setConnection(store.createConnection()); setChannel(store.createChannel(connection)); } return null; }</code><technical_language>delivery null? handle situation</technical_language>

Target:
public MessageContext receive() { if (isAlive()) { GetResponse delivery = null; try { delivery = channel.basicGet(queueName, false); if (delivery != null) { StorableMessage storableMessage = deserializeMessage(delivery); org.apache.axis2.context.MessageContext axis2Mc = store.newAxis2Mc(); MessageContext synapseMc = store.newSynapseMc(axis2Mc); synapseMc = MessageConverter.toMessageContext(storableMessage, axis2Mc, synapseMc); updateCache(delivery, delivery.getProps().getMessageId()); if (log.isDebugEnabled()) { log.debug(getId() + " Received MessageId: " + delivery.getProps().getMessageId()); } return synapseMc; } } catch (ShutdownSignalException | IOException e) { log.error(getId() + " connection error when receiving messages.", e); cleanup(); } catch (ClassNotFoundException e) { log.error(getId() + "unable to read the stored message.", e); try { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } catch (IOException ex) { log.error(getId() + "unable to acknowledge the stored message.", e); } } } else { log.warn("The connection and channel to the RabbitMQ broker are unhealthy."); cleanup(); setConnection(store.createConnection()); setChannel(store.createChannel(connection)); } return null; }
Source:
<code>public void edgeCaseTest() throws Exception { AsyncRequestResponseHandler requestResponseHandler; RequestResponseHandlerMetrics metrics; try { requestResponseHandler = getAsyncRequestResponseHandler(-1); fail("Setting request workers < 0 should have thrown exception"); } catch (IllegalArgumentException e) { } try { requestResponseHandler = getAsyncRequestResponseHandler(-1); <START> fail("Setting request workers < 0 should have thrown exception"); <END> } catch (IllegalArgumentException e) { } try { RestRequestService restRequestService = new MockRestRequestService(verifiableProperties, router); metrics = new RequestResponseHandlerMetrics(new MetricRegistry()); new AsyncRequestResponseHandler(metrics, 1, null); fail("Setting RestRequestService to null should have thrown exception"); } catch (IllegalArgumentException e) { } }</code><technical_language>difference line 165 line 173 test cases</technical_language>

Target:
public void edgeCaseTest() throws Exception { AsyncRequestResponseHandler requestResponseHandler; RequestResponseHandlerMetrics metrics; try { requestResponseHandler = getAsyncRequestResponseHandler(-1); fail("Setting request workers < 0 should have thrown exception"); } catch (IllegalArgumentException e) { } try { RestRequestService restRequestService = new MockRestRequestService(verifiableProperties, router); metrics = new RequestResponseHandlerMetrics(new MetricRegistry()); new AsyncRequestResponseHandler(metrics, 1, null); fail("Setting RestRequestService to null should have thrown exception"); } catch (IllegalArgumentException e) { } }
Source:
<code>public void tint (Color tint) { final float floatTint = tint.toFloatBits(); if (textChanged || oldTint != floatTint) { textChanged = false; oldTint = floatTint; <START> markdown.tint(this, tint, floatTint); <END> } }</code><technical_language>Please run [eclipse formatter](<LINK_0></technical_language>

Target:
public void tint (Color tint) { final float floatTint = tint.toFloatBits(); if (textChanged || oldTint != floatTint) { textChanged = false; oldTint = floatTint; markup.tint(this, tint); } }
Source:
<code><START> handleOfflineReservationsWillExpire(Event event, List<TicketReservationInfo> reservations) { <END> Map<String, Object> payload = new HashMap<>(); payload.put("reservations", reservations); asyncCall(ExtensionEvent.OFFLINE_RESERVATIONS_WILL_EXPIRE, event, payload); }</code><technical_language>new line</technical_language>

Target:
void handleOfflineReservationsWillExpire(Event event, List<TicketReservationInfo> reservations) { Map<String, Object> payload = new HashMap<>(); payload.put("reservations", reservations); asyncCall(ExtensionEvent.OFFLINE_RESERVATIONS_WILL_EXPIRE, event, payload); }
Source:
<code>private void createMarriedWallet() throws BlockStoreException { wallet = new Wallet(params); blockStore = new MemoryBlockStore(params); chain = new BlockChain(params, wallet, blockStore); final DeterministicKeyChain keyChain = new DeterministicKeyChain(new SecureRandom()); DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, keyChain.getWatchingKey().serializePubB58()); CustomTransactionSigner signer = new CustomTransactionSigner() { @Override <START> public byte[] serialize() { <END> return new byte[0]; } @Override protected SignatureAndKey getSignature(Sha256Hash sighash, List<ChildNumber> derivationPath) { ImmutableList<ChildNumber> keyPath = ImmutableList.copyOf(derivationPath); DeterministicKey key = keyChain.getKeyByPath(keyPath, true); return new SignatureAndKey(key.sign(sighash), key.getPubOnly()); } }; wallet.addTransactionSigner(signer); wallet.addFollowingAccountKeys(ImmutableList.of(partnerKey)); }</code><technical_language>CustomTransactionSigner is a StatelessTransactionSigner I this override is unnecessary</technical_language>

Target:
private void createMarriedWallet() throws BlockStoreException { wallet = new Wallet(params); blockStore = new MemoryBlockStore(params); chain = new BlockChain(params, wallet, blockStore); final DeterministicKeyChain keyChain = new DeterministicKeyChain(new SecureRandom()); DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, keyChain.getWatchingKey().serializePubB58()); CustomTransactionSigner signer = new CustomTransactionSigner() { @Override protected SignatureAndKey getSignature(Sha256Hash sighash, List<ChildNumber> derivationPath) { ImmutableList<ChildNumber> keyPath = ImmutableList.copyOf(derivationPath); DeterministicKey key = keyChain.getKeyByPath(keyPath, true); return new SignatureAndKey(key.sign(sighash), key.getPubOnly()); } }; wallet.addTransactionSigner(signer); wallet.addFollowingAccountKeys(ImmutableList.of(partnerKey)); }
Source:
<code>private void initOwner() { final VerticalPanel ownerPanel = new VerticalPanel(); ownerPanel.setStyleName(Gerrit.RESOURCES.css().groupOwnerPanel()); ownerPanel.add(new SmallHeading(Util.C.headingOwner())); ownerTxtBox = new NpTextBox(); ownerTxtBox.setVisibleLength(60); final AccountGroupSuggestOracle accountGroupOracle = new AccountGroupSuggestOracle(); ownerTxt = new SuggestBox(new RPCSuggestOracle( accountGroupOracle), ownerTxtBox); ownerTxt.setStyleName(Gerrit.RESOURCES.css().groupOwnerTextBox()); ownerPanel.add(ownerTxt); saveOwner = new Button(Util.C.buttonChangeGroupOwner()); saveOwner.setEnabled(false); saveOwner.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { final String newOwner = ownerTxt.getText().trim(); if (newOwner.length() > 0) { AccountGroup.UUID ownerUuid = accountGroupOracle.getUUID(newOwner); <START> GroupApi.setGroupOwner(getGroupUUID(), ownerUuid.get(), <END> new GerritCallback<GroupInfo>() { public void onSuccess(final GroupInfo result) { updateOwnerGroup(result); saveOwner.setEnabled(false); } }); } } }); ownerPanel.add(saveOwner); add(ownerPanel); new OnEditEnabler(saveOwner, ownerTxtBox); }</code><technical_language>If user provides invalid group name accountGroupOracle.getUUID(newOwner) return null, results in NPE. This NPE prevents displaying of proper 'Group Found' error message. s/ownerUuid.get()/ownerUuid != null ? ownerUuid.get() : newOwner</technical_language>

Target:
private void initOwner() { final VerticalPanel ownerPanel = new VerticalPanel(); ownerPanel.setStyleName(Gerrit.RESOURCES.css().groupOwnerPanel()); ownerPanel.add(new SmallHeading(Util.C.headingOwner())); ownerTxtBox = new NpTextBox(); ownerTxtBox.setVisibleLength(60); final AccountGroupSuggestOracle accountGroupOracle = new AccountGroupSuggestOracle(); ownerTxt = new SuggestBox(new RPCSuggestOracle( accountGroupOracle), ownerTxtBox); ownerTxt.setStyleName(Gerrit.RESOURCES.css().groupOwnerTextBox()); ownerPanel.add(ownerTxt); saveOwner = new Button(Util.C.buttonChangeGroupOwner()); saveOwner.setEnabled(false); saveOwner.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { final String newOwner = ownerTxt.getText().trim(); if (newOwner.length() > 0) { AccountGroup.UUID ownerUuid = accountGroupOracle.getUUID(newOwner); String ownerId = ownerUuid != null ? ownerUuid.get() : newOwner; GroupApi.setGroupOwner(getGroupUUID(), ownerId, new GerritCallback<GroupInfo>() { public void onSuccess(final GroupInfo result) { updateOwnerGroup(result); saveOwner.setEnabled(false); } }); } } }); ownerPanel.add(saveOwner); add(ownerPanel); new OnEditEnabler(saveOwner, ownerTxtBox); }
Source:
<code>private void innerVerifyJobActive(final UUID jobId) throws IOException, JobRecoveryNotActiveException { try { client.getActiveJobSpectraS3(new GetActiveJobSpectraS3Request(jobId)); <START> } catch (final FailedRequestException e) { <END> throw new JobRecoveryNotActiveException(jobId, e.getMessage()); } }</code><technical_language>I create a exception if request returns a 404, otherwise, I catch this exception</technical_language>

Target:
private void innerVerifyJobActive(final UUID jobId) throws IOException, JobRecoveryNotActiveException { try { client.getActiveJobSpectraS3(new GetActiveJobSpectraS3Request(jobId)); } catch (final FailedRequestException e) { if (e.getStatusCode() == 404) { throw new JobRecoveryNotActiveException(jobId, e); } throw e; } }
Source:
<code>public OptionalLong metadataDelete(ConnectorSession session, ConnectorTableHandle tableHandle, ConnectorTableLayoutHandle tableLayoutHandle) { HiveTableHandle handle = (HiveTableHandle) tableHandle; HiveTableLayoutHandle layoutHandle = (HiveTableLayoutHandle) tableLayoutHandle; Optional<Table> table = metastore.getTable(handle.getSchemaName(), handle.getTableName()); if (!table.isPresent()) { throw new TableNotFoundException(handle.getSchemaTableName()); } List<ColumnHandle> partitionColumns = layoutHandle.getPartitionColumns(); if (!layoutHandle.getEffectivePredicate().getDomains() <START> .map(domains -> Maps.filterKeys(domains, not(Predicates.in(partitionColumns)))) <END> .orElse(ImmutableMap.of()).isEmpty()) { throw new PrestoException(NOT_SUPPORTED, "This connector only supports delete where one or more partitions are deleted entirely"); } if (table.get().getPartitionColumns().isEmpty()) { metastore.truncateUnpartitionedTable(session, handle.getSchemaName(), handle.getTableName()); } else { for (HivePartition hivePartition : getOrComputePartitions(layoutHandle, session, tableHandle)) { metastore.dropPartition(session, handle.getSchemaName(), handle.getTableName(), toPartitionValues(hivePartition.getPartitionId())); } } return OptionalLong.empty(); }</code><technical_language>this easier read if written imperatively, if consistently statically imported things: .map(domains -> filterKeys(domains, not(in(partitionColumns))))</technical_language>

Target:
public OptionalLong metadataDelete(ConnectorSession session, ConnectorTableHandle tableHandle, ConnectorTableLayoutHandle tableLayoutHandle) { HiveTableHandle handle = (HiveTableHandle) tableHandle; HiveTableLayoutHandle layoutHandle = (HiveTableLayoutHandle) tableLayoutHandle; Optional<Table> table = metastore.getTable(handle.getSchemaName(), handle.getTableName()); if (!table.isPresent()) { throw new TableNotFoundException(handle.getSchemaTableName()); } List<ColumnHandle> partitionColumns = layoutHandle.getPartitionColumns(); if (!layoutHandle.getEffectivePredicate().getDomains() .map(domains -> filterKeys(domains, not(in(partitionColumns)))) .orElse(ImmutableMap.of()).isEmpty()) { throw new PrestoException(NOT_SUPPORTED, "This connector only supports delete where one or more partitions are deleted entirely"); } if (table.get().getPartitionColumns().isEmpty()) { metastore.truncateUnpartitionedTable(session, handle.getSchemaName(), handle.getTableName()); } else { for (HivePartition hivePartition : getOrComputePartitions(layoutHandle, session, tableHandle)) { metastore.dropPartition(session, handle.getSchemaName(), handle.getTableName(), toPartitionValues(hivePartition.getPartitionId())); } } return OptionalLong.empty(); }