auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void createMessages(final ZulipApp app, final List<Message> messages) { try { TransactionManager.callInTransaction(app.getDatabaseHelper() .getConnectionSource(), new Callable<Void>() { public Void call() throws Exception { RuntimeExceptionDao<Message, Object> messageDao = app.getDao(Message.class); for (Message m : messages) { Person person = Person.getOrUpdate(app, m.getSenderEmail(), m.getSenderFullName(), m.getAvatarUrl()); m.setSender(person); Stream stream = Stream.getByName(app, m.getRecipients()); <START> m.setStream(stream); <END> messageDao.createOrUpdate(m); } return null; } }); } catch (SQLException e) { throw new RuntimeException(e); } }</code><technical_language>this work for messages individual a stream</technical_language>

Target:
public static void createMessages(final ZulipApp app, final List<Message> messages) { try { TransactionManager.callInTransaction(app.getDatabaseHelper() .getConnectionSource(), new Callable<Void>() { public Void call() throws Exception { RuntimeExceptionDao<Message, Object> messageDao = app.getDao(Message.class); for (Message m : messages) { Person person = Person.getOrUpdate(app, m.getSenderEmail(), m.getSenderFullName(), m.getAvatarUrl()); m.setSender(person); Stream stream = null; if (m.getType() == MessageType.STREAM_MESSAGE) { stream = Stream.getByName(app, m.getRecipients()); } m.setStream(stream); messageDao.createOrUpdate(m); } return null; } }); } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
<code>public static void parseQuestion(FormEntryPrompt prompt, JSONObject questionJson) { parseCaption(prompt, questionJson); questionJson.put("help", jsonNullIfNull(prompt.getHelpText())); questionJson.put("binding", jsonNullIfNull(prompt.getQuestion().getBind().getReference().toString())); questionJson.put("style", jsonNullIfNull(parseStyle(prompt))); questionJson.put("datatype", jsonNullIfNull(parseControlType(prompt))); questionJson.put("required", prompt.isRequired() ? 1 : 0); try { parseQuestionAnswer(questionJson, prompt); } catch (Exception e) { <START> e.printStackTrace(); <END> } questionJson.put("ix", jsonNullIfNull(prompt.getIndex())); if (prompt.getDataType() == Constants.DATATYPE_CHOICE || prompt.getDataType() == Constants.DATATYPE_CHOICE_LIST) { questionJson.put("choices", parseSelect(prompt)); } }</code><technical_language>failures is fine swallow</technical_language>

Target:
public static void parseQuestion(FormEntryPrompt prompt, JSONObject questionJson) { parseCaption(prompt, questionJson); questionJson.put("help", jsonNullIfNull(prompt.getHelpText())); questionJson.put("binding", jsonNullIfNull(prompt.getQuestion().getBind().getReference().toString())); questionJson.put("style", jsonNullIfNull(parseStyle(prompt))); questionJson.put("datatype", jsonNullIfNull(parseControlType(prompt))); questionJson.put("required", prompt.isRequired() ? 1 : 0); parseQuestionAnswer(questionJson, prompt); questionJson.put("ix", jsonNullIfNull(prompt.getIndex())); if (prompt.getDataType() == Constants.DATATYPE_CHOICE || prompt.getDataType() == Constants.DATATYPE_CHOICE_LIST) { questionJson.put("choices", parseSelect(prompt)); } }
Source:
<code>private void updateDisordersFromJSON(XWikiDocument doc, BaseObject data, XWikiContext context, JSONObject json) { try { JSONArray inputDisorders = json.optJSONArray(JSON_KEY_DISORDERS); if (inputDisorders != null) { this.disorders = new TreeSet<Disorder>(); List<String> disorderValues = new LinkedList<String>(); for (int i = 0; i < inputDisorders.length(); i++) { JSONObject disorderJSON = inputDisorders.optJSONObject(i); if (disorderJSON == null) { continue; } Disorder phenotipsDisorder = new PhenoTipsDisorder(disorderJSON); this.disorders.add(phenotipsDisorder); disorderValues.add(phenotipsDisorder.getValue()); } this.disorders = Collections.unmodifiableSet(this.disorders); <START> data.set(DISORDER_PROPERTIES_OMIMID, null, context); <END> data.set(DISORDER_PROPERTIES_OMIMID, disorderValues, context); context.getWiki().saveDocument(doc, "Updated disorders from JSON", true, context); } } catch (Exception ex) { this.logger.warn("Failed to update patient disorders from JSON [{}]: {}", ex.getMessage(), ex); } }</code><technical_language>do data.set(DISORDER_PROPERTIES_OMIMID, ...) neighbouring lines</technical_language>

Target:
private void updateDisordersFromJSON(XWikiDocument doc, BaseObject data, XWikiContext context, JSONObject json) { try { if (!json.has(JSON_KEY_DISORDERS)) { return; } JSONArray inputDisorders = json.optJSONArray(JSON_KEY_DISORDERS); if (inputDisorders != null) { this.disorders = new TreeSet<Disorder>(); List<String> disorderValues = new LinkedList<String>(); for (int i = 0; i < inputDisorders.length(); i++) { JSONObject disorderJSON = inputDisorders.optJSONObject(i); if (disorderJSON == null) { continue; } Disorder phenotipsDisorder = new PhenoTipsDisorder(disorderJSON); this.disorders.add(phenotipsDisorder); disorderValues.add(phenotipsDisorder.getValue()); } this.disorders = Collections.unmodifiableSet(this.disorders); data.set(DISORDER_PROPERTIES_OMIMID, null, context); data.set(DISORDER_PROPERTIES_OMIMID, disorderValues, context); context.getWiki().saveDocument(doc, "Updated disorders from JSON", true, context); } } catch (Exception ex) { this.logger.warn("Failed to update patient disorders from JSON [{}]: {}", ex.getMessage(), ex); } }
Source:
<code><START> private final void visit(ProjectState st, Set<Project.NameKey> seen) <END> { if (st == null) { order.add(allProjectsName); return; } Project pr = st.getProject(); if (pr == null) return; order.add(pr.getNameKey()); if (!seen.add(pr.getNameKey())) return; List<Project.NameKey> parents = pr.getParents(); if (parents == null || parents.size() < 1) { order.add(allProjectsName); return; } for (Project.NameKey parentKey : pr.getParents()) visit(cache.get(parentKey), seen); }</code><technical_language>style: methods declared constructors. Curly brace cuddles prior line</technical_language>

Target:
private final void visit(ProjectState st, Set<Project.NameKey> seen) { if (st == null) { order.add(allProjectsName); return; } Project pr = st.getProject(); if (pr == null) { return; } order.add(pr.getNameKey()); if (!seen.add(pr.getNameKey())) { return; } List<Project.NameKey> parents = pr.getParents(); if (parents == null || parents.size() < 1) { order.add(allProjectsName); return; } for (Project.NameKey parentKey : pr.getParents()) { visit(cache.get(parentKey), seen); } }
Source:
<code>private static boolean getExecutablePermission(int permission) { <START> return permission % 2 == 1; <END> }</code><technical_language>Similarly: java return permission & 1;</technical_language>

Target:
private static boolean getExecutablePermission(int permission) { return (permission & 1) == 1; }
Source:
<code>private Directory loadInstance(File file) { Properties configuration = new Properties(); InputStream in = null; <START> try { <END> in = new FileInputStream(file); configuration.load(in); } catch (IOException exception) { log.error( "Can't load directory configuration file \"" + file.getAbsolutePath() + "\".", exception ); return null; } finally { if (in != null) { try { in.close(); } catch (IOException exception) { log.warn( "Can't close directory configuration file \"" + file.getAbsolutePath() + "\".", exception ); } } } return loadInstance(file, configuration); }</code><technical_language>autoclosable syntax</technical_language>

Target:
private Directory loadInstance(File file) { Properties configuration = new Properties(); try (InputStream in = new FileInputStream(file)) { configuration.load(in); } catch (IOException exception) { log.error( "Can't load directory configuration file \"" + file.getAbsolutePath() + "\".", exception ); return null; } return loadInstance(file, configuration); }
Source:
<code>protected void handleGenericException(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException { sendErrorResponse(request, response, ex, "An Exception has occured", <START> HttpServletResponse.SC_INTERNAL_SERVER_ERROR); <END> }</code><technical_language>I this is root case of test failures. need account some exceptions custom response codes defined them. For example [PatchBadRequestException](<LINK_1> I change code in method for @ResponseStatus annotation (you [find example here](<LINK_0> If find it, response (field value). If annotation found, HttpServletResponse.SC_INTERNAL_SERVER_ERROR. I solve tests</technical_language>

Target:
protected void handleGenericException(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException { ResponseStatus responseStatusAnnotation = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class); int returnCode = 0; if (responseStatusAnnotation != null) { returnCode = responseStatusAnnotation.code().value(); } else { returnCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } sendErrorResponse(request, response, ex, "An Exception has occured", returnCode); }
Source:
<code>public void onBackPressed() { if (getFragment().onBackPressed()) { return; } <START> WikipediaApp.getInstance().getApplicationContext().startService(AnalyticsIntentService.getIntent(EventLoggingConfig.EXIT_PUSH)); <END> finish(); }</code><technical_language>A couple notes: - getApplicationContext() returns actual getInstance() call. - this onBackPressed() counter-intuitive. realm of possibility for a user press button leave app (e.g. pressing Home button). do this in onDestroy()</technical_language>

Target:
public void onBackPressed() { if (getFragment().onBackPressed()) { return; } finish(); }
Source:
<code>public void clickEnableMinRankOptions(int questionNumber) { WebElement minNumberOfOptionsToRankCheckbox = getMinOptionsToBeRankedCheckbox(questionNumber); <START> waitForPageToScroll(); <END> minNumberOfOptionsToRankCheckbox.click(); }</code><technical_language>method hide fact waits for scrolling clicking, mentioned earlier wait done here</technical_language>

Target:
public void clickEnableMinRankOptions(int questionNumber) { WebElement minNumberOfOptionsToRankCheckbox = getMinOptionsToBeRankedCheckbox(questionNumber); minNumberOfOptionsToRankCheckbox.click(); }
Source:
<code>private static void assertMethodSource(Method expectedMethod, TestDescriptor testDescriptor) { assertThat(testDescriptor.getSource()).containsInstanceOf(JavaMethodSource.class); <START> JavaMethodSource methodSource = (JavaMethodSource) testDescriptor.getSource().get(); <END> assertThat(methodSource.getMethodName()).isEqualTo(expectedMethod.getName()); assertThat(methodSource.getMethodParameterTypes()).isEqualTo( StringUtils.nullSafeToString(expectedMethod.getParameterTypes())); }</code><technical_language>a check for getClassName() now, there</technical_language>

Target:
private static void assertMethodSource(Method expectedMethod, TestDescriptor testDescriptor) { assertThat(testDescriptor.getSource()).containsInstanceOf(JavaMethodSource.class); JavaMethodSource methodSource = (JavaMethodSource) testDescriptor.getSource().get(); assertThat(methodSource.getClassName()).isEqualTo(expectedMethod.getDeclaringClass().getName()); assertThat(methodSource.getMethodName()).isEqualTo(expectedMethod.getName()); assertThat(methodSource.getMethodParameterTypes()).isEqualTo( StringUtils.nullSafeToString(expectedMethod.getParameterTypes())); }
Source:
<code>public void excecuteCommand() throws MojoExecutionException, MojoFailureException { <START> kieServerGateway.deploy(project, container); <END> }</code><technical_language>license header missing</technical_language>

Target:
public void excecuteCommand() throws MojoExecutionException, MojoFailureException { RuntimeStrategy strategy; try { strategy = RuntimeStrategy.valueOf(runtimeStrategy); } catch (IllegalArgumentException ex) { throw new MojoFailureException("Runtime Strategy Not Found: " + runtimeStrategy); } getLog().info("Runtime Strategy: " + runtimeStrategy); kieServerGateway.deploy(project, container, strategy); }
Source:
<code><START> private Map<String, VersionNumber> difference(Map<String, VersionNumber> base, Map<String, VersionNumber> toAdd) { <END> for (Map.Entry<String,VersionNumber> adding : toAdd.entrySet()) { if (!base.containsKey(adding.getKey())) { base.put(adding.getKey(), adding.getValue()); } } return base; }</code><technical_language>I find this method a bit confusing, I lack context. reading name I expect calculate difference maps passed, reading code I adds elements in if present in it. completely this is want modifying returning it. Is 'adding if present' desired behaviour</technical_language>

Target:
private Map<String, VersionNumber> difference(Map<String, VersionNumber> base, Map<String, VersionNumber> toAdd) { Map<String, VersionNumber> diff = new HashMap<String, VersionNumber>(); for (Map.Entry<String,VersionNumber> adding : toAdd.entrySet()) { if (!base.containsKey(adding.getKey())) { diff.put(adding.getKey(), adding.getValue()); } } return diff; }
Source:
<code>public AttributeDescriptor getAttributeDescriptor(String attributeName) { if (attributeName == null) { return null; } if (descriptors.size() != descriptorNameMap.size()) { <START> descriptorNameMap.clear(); <END> for (AttributeDescriptor descriptor : descriptors) { descriptorNameMap.put(descriptor.getName(), descriptor); } } return descriptorNameMap.get(attributeName); }</code><technical_language>Is size of map set match set's values keys in map</technical_language>

Target:
public AttributeDescriptor getAttributeDescriptor(String attributeName) { if (attributeName == null) { return null; } return descriptors.get(attributeName); }
Source:
<code>private void checkMultipleSubnetsCombinedWithUseData(Network network){ <START> if (_ntwkOfferingSrvcDao.listServicesForNetworkOffering(network.getNetworkOfferingId()).contains(Network.Service.UserData.getName()) && _vlanDao.listVlansByNetworkId(network.getId()).size() > 1) { <END> List<VlanVO> vlanVOs = _vlanDao.listVlansByNetworkId(network.getId()); for(VlanVO vlanVoItem : vlanVOs){ for(VlanVO VlanVoItem2 : vlanVOs){ if(!vlanVoItem.equals(VlanVoItem2) && !VlanVoItem2.getVlanGateway().equals(vlanVoItem.getVlanGateway())){ s_logger.error("NuageVsp provider does not support multiple subnets in combination with user data."); throw new UnsupportedServiceException("NuageVsp provider does not support multiple subnets in combination with user data."); } } } } }</code><technical_language>Please consider isEmpty a size check determine a list elements. is more idiomatic/expressive error-prone</technical_language>

Target:
private void checkMultipleSubnetsCombinedWithUseData(Network network) { if (_ntwkOfferingSrvcDao.listServicesForNetworkOffering(network.getNetworkOfferingId()).contains(Network.Service.UserData.getName())) { List<VlanVO> vlanVOs = _vlanDao.listVlansByNetworkId(network.getId()); if (vlanVOs.size() > 1) { VlanVO vlanVoItem = vlanVOs.get(0); for (VlanVO VlanVoItem2 : FluentIterable.from(vlanVOs).skip(1)) { if (!vlanVoItem.equals(VlanVoItem2) && !VlanVoItem2.getVlanGateway().equals(vlanVoItem.getVlanGateway())) { s_logger.error("NuageVsp provider does not support multiple subnets in combination with user data. Network: " + network + ", vlans: " + vlanVOs); throw new UnsupportedServiceException("NuageVsp provider does not support multiple subnets in combination with user data."); } } } } }
Source:
<code>protected void doGet( final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException { LOGGER.debug( "Loading verifier web worker" ); try { final String requestURI = request.getRequestURI(); final int indexOf = requestURI.indexOf( "/verifier" ); if ( indexOf >= 0 ) { final String fileName = requestURI.substring( indexOf ); if ( fileName.endsWith( "cache.js" ) ) { final byte[] bytes = loadResource( fileName ).getBytes(); <START> response.setHeader( "Content-Disposition", <END> format( "attachment; filename=\"%s\";", requestURI ) ); response.setContentType( "application/javascript" ); response.getOutputStream() .write( bytes, 0, bytes.length ); } } } catch ( final Exception e ) { LOGGER.error( "Failed to load verifier web worker." ); } }</code><technical_language>Wow, injected script "attachment" (or this for debugging?)</technical_language>

Target:
protected void doGet( final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException { LOGGER.debug( "Loading verifier web worker" ); try { final String requestURI = request.getRequestURI(); final int indexOf = requestURI.indexOf( "/verifier" ); if ( indexOf >= 0 ) { final String fileName = requestURI.substring( indexOf ); if ( fileName.endsWith( "cache.js" ) ) { final byte[] bytes = loadResource( fileName ).getBytes(); response.setContentType( "application/javascript" ); response.getOutputStream() .write( bytes, 0, bytes.length ); } } } catch ( final Exception e ) { LOGGER.error( "Failed to load verifier web worker." ); } }
Source:
<code>public AllowUsingTool(String name, Domain domain, IngredientRecipe ingredient) { super(name, domain, new String[] {AgentFactory.ClassName, ToolFactory.ClassName, ContainerFactory.ClassName} ,ingredient); <START> this.recipe = null; <END> }</code><technical_language>need set objects explicitly null</technical_language>

Target:
public AllowUsingTool(String name, Domain domain, IngredientRecipe ingredient) { super(name, domain, new String[] {AgentFactory.ClassName, ToolFactory.ClassName, ContainerFactory.ClassName} ,ingredient); }
Source:
<code>public String eval(NetworkAttachment networkAttachment) { final String networkName = networkAttachment.getNetworkName(); <START> return StringUtils.isEmpty(networkName) ? networkAttachment.getId().toString() : networkName; <END> }</code><technical_language>If 'networkName' is null 'networkId' 'id'</technical_language>

Target:
public String eval(NetworkAttachment networkAttachment) { final String networkName = networkAttachment.getNetworkName(); if (!StringUtils.isEmpty(networkName)) { return networkName; } final Guid networkId = networkAttachment.getNetworkId(); return networkId == null ? null : networkId.toString(); }
Source:
<code>public void testCacheDecreasesAfterGC() { generateJunkCacheEntries(); Long initialSize = Namespace.ID.cache.asMap().entrySet().stream().count(); Long postGCSize; System.out.println("Namespace.ID.cache.asMap().entrySet().stream().count() = " + initialSize); do { System.gc(); try { Thread.sleep(5000); } catch (InterruptedException e) { fail("Thread interrupted while waiting for GC"); } postGCSize = Namespace.ID.cache.asMap().entrySet().stream().count(); <START> System.out.println("After GC: Namespace.ID.cache.asMap().entrySet().stream().count() = " + postGCSize); <END> } while (postGCSize == initialSize); assertTrue("Cache did not decrease with GC.", Namespace.ID.cache.asMap().entrySet().stream().count() < initialSize); }</code><technical_language>logger remove debugging lines</technical_language>

Target:
public void testCacheDecreasesAfterGC() { Long initialSize = Namespace.ID.cache.asMap().entrySet().stream().count(); generateJunkCacheEntries(); Long postGCSize; do { System.gc(); try { Thread.sleep(500); } catch (InterruptedException e) { fail("Thread interrupted while waiting for GC"); } postGCSize = Namespace.ID.cache.asMap().entrySet().stream().count(); } while (postGCSize > initialSize); assertTrue("Cache did not decrease with GC.", Namespace.ID.cache.asMap().entrySet().stream().count() < initialSize); }
Source:
<code>public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { <START> return type.isAssignableFrom(SingleResultView.class) || type.isAssignableFrom(ListResultView.class); <END> }</code><technical_language>this is backwards. want SingleResultView.class.isAssignableFrom(type) ensure type is a subtype of SingleResultView</technical_language>

Target:
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return SingleResultView.class.isAssignableFrom(type) || ListResultView.class.isAssignableFrom(type); }
Source:
<code>public String getText(final Object element) { String text = "<UNKNOWN>"; if (element instanceof RefactorScope) { text = <START> element.toString(); <END> } return text; }</code><technical_language>This is all-capitals name of enumeration constant in code. human-readable name (from getName() method)</technical_language>

Target:
public String getText(final Object element) { String text = "<UNKNOWN>"; if (element instanceof RefactorScope) { text = ((RefactorScope) element).getName(); } return text; }
Source:
<code>public IdentityHashPartitionFunction( @JsonProperty(value = "index", required = true) final Integer index) { super(null); <START> this.index = java.util.Objects.requireNonNull(index, "missing property index"); <END> Preconditions.checkArgument(this.index >= 0, "IdentityHash field index cannot take negative value %s", this.index); }</code><technical_language>import Objects</technical_language>

Target:
public IdentityHashPartitionFunction( @JsonProperty(value = "index", required = true) final Integer index) { super(null); this.index = Objects.requireNonNull(index, "missing property index"); Preconditions.checkArgument(this.index >= 0, "IdentityHash field index cannot take negative value %s", this.index); }
Source:
<code>public boolean checkCode(String name, String code) { String savedCode = captchaCodes.get(name.toLowerCase()); if (savedCode != null && savedCode.equalsIgnoreCase(code)) { <START> captchaCodes.remove(name); <END> return true; } else { generateCode(name); } return false; }</code><technical_language>I this needs lowercase</technical_language>

Target:
public boolean checkCode(String name, String code) { String lowerCaseName = name.toLowerCase(); String savedCode = captchaCodes.get(lowerCaseName); if (savedCode != null && savedCode.equalsIgnoreCase(code)) { captchaCodes.remove(lowerCaseName); return true; } else { generateCode(name); } return false; }
Source:
<code>public Object[][] sortBundles(BundleDescription[] toSort) { List<Object[]> references = new ArrayList<>(toSort.length); for (BundleDescription <START> toSort1 : <END> toSort) { if (toSort1.isResolved()) { buildReferences(toSort1, references); } } Object[][] cycles = ComputeNodeOrder.computeNodeOrder(toSort, references.toArray(new Object[references.size()][])); if (cycles.length == 0) return cycles; for (Object[] cycle : cycles) { for (Object c : cycle) { BundleDescription fragment = (BundleDescription) c; if (fragment.getHost() == null) continue; BundleDescription host = (BundleDescription) fragment.getHost().getSupplier(); if (host == null) continue; fixFragmentOrder(host, fragment, toSort); } } return cycles; }</code><technical_language>name toAddReference</technical_language>

Target:
public Object[][] sortBundles(BundleDescription[] toSort) { List<Object[]> references = new ArrayList<>(toSort.length); for (BundleDescription toAddReference : toSort) { if (toAddReference.isResolved()) { buildReferences(toAddReference, references); } } Object[][] cycles = ComputeNodeOrder.computeNodeOrder(toSort, references.toArray(new Object[references.size()][])); if (cycles.length == 0) return cycles; for (Object[] cycle : cycles) { for (Object possibleFragment : cycle) { BundleDescription fragment = (BundleDescription) possibleFragment; if (fragment.getHost() == null) continue; BundleDescription host = (BundleDescription) fragment.getHost().getSupplier(); if (host == null) continue; fixFragmentOrder(host, fragment, toSort); } } return cycles; }
Source:
<code>private String _evtGetExtendedStatus(String query) { EVT_HANDLE handle = null; String result; try { handle = Wevtapi.INSTANCE.EvtQuery(null, "Application", query, Winevt.EVT_QUERY_FLAGS.EvtQueryChannelPath); result = WevtapiUtil.EvtGetExtendedStatus(); } finally { if (handle != null) { Wevtapi.INSTANCE.EvtClose(handle); } } <START> System.out.println(result); <END> return result; }</code><technical_language>This artifact debugging. I surprised I output place it. Please remove</technical_language>

Target:
private String _evtGetExtendedStatus(String query) { EVT_HANDLE handle = null; String result; try { handle = Wevtapi.INSTANCE.EvtQuery(null, "Application", query, Winevt.EVT_QUERY_FLAGS.EvtQueryChannelPath); result = WevtapiUtil.EvtGetExtendedStatus(); } finally { if (handle != null) { Wevtapi.INSTANCE.EvtClose(handle); } } return result; }
Source:
<code>public void contextDestroyed(ServletContextEvent event) { if (storage != null) { storage.close(); logger.debug("Template storage closed successfully", storage); } healthCheck.stop(); <START> executorService.shutdown(); <END> }</code><technical_language>more sense shutdownNow() wait for healthcheck stop itself</technical_language>

Target:
public void contextDestroyed(ServletContextEvent event) { if (storage != null) { storage.close(); logger.debug("Template storage closed successfully", storage); } healthCheck.stop(); executorService.shutdownNow(); }
Source:
<code>private GetSpecificAttributeValueResponse getSpecificAttributeValues(final Map<String, String> settings) throws WebServiceSecurityException, GeneralSecurityException, IOException { final GetSpecificAttributeValueRequest request = new GetSpecificAttributeValueRequest(); request.setClassId(BigInteger.valueOf(40L)); request.setObisCode(this.getObisCodeValues()); request.setAttribute(BigInteger.valueOf(3L)); request.setDeviceIdentification(settings.get(PlatformSmartmeteringKeys.KEY_DEVICE_IDENTIFICATION)); GetSpecificAttributeValueAsyncResponse asyncResponse; <START> asyncResponse = this.adHocRequestclient.doRequest(request); <END> final GetSpecificAttributeValueAsyncRequest asyncRequest = new GetSpecificAttributeValueAsyncRequest(); asyncRequest.setDeviceIdentification(asyncResponse.getDeviceIdentification()); asyncRequest.setCorrelationUid(asyncResponse.getCorrelationUid()); return this.adHocResponseClient.getResponse(asyncRequest); }</code><technical_language>combine statements: GetSpecificAttributeValueAsyncResponse asyncResponse = this.adHocRequestclient.doRequest(request);</technical_language>

Target:
private GetSpecificAttributeValueResponse getSpecificAttributeValues(final Map<String, String> settings) throws WebServiceSecurityException, GeneralSecurityException, IOException { final GetSpecificAttributeValueRequest request = new GetSpecificAttributeValueRequest(); request.setClassId(BigInteger.valueOf(40L)); request.setObisCode(this.getObisCodeValues()); request.setAttribute(BigInteger.valueOf(3L)); request.setDeviceIdentification(settings.get(PlatformSmartmeteringKeys.KEY_DEVICE_IDENTIFICATION)); final GetSpecificAttributeValueAsyncResponse asyncResponse = this.adHocRequestclient.doRequest(request); final GetSpecificAttributeValueAsyncRequest asyncRequest = new GetSpecificAttributeValueAsyncRequest(); asyncRequest.setDeviceIdentification(asyncResponse.getDeviceIdentification()); asyncRequest.setCorrelationUid(asyncResponse.getCorrelationUid()); return this.adHocResponseClient.getResponse(asyncRequest); }
Source:
<code>public void releaseTaskManager(ResourceID resourceId) { try { <START> supplyInMainThreadExecutor(() -> slotPool.releaseTaskManager(resourceId, new Exception("Test Exception"))); <END> } catch (Exception e) { throw new RuntimeException("Should not have happened.", e); } }</code><technical_language>Releasing TaskManager in SlotPool for tests</technical_language>

Target:
public void releaseTaskManager(ResourceID resourceId) { try { supplyInMainThreadExecutor( () -> slotPool.releaseTaskManager( resourceId, new Exception("Releasing TaskManager in SlotPool for tests"))); } catch (Exception e) { throw new RuntimeException("Should not have happened.", e); } }
Source:
<code>protected MessageGroupPreparedStatementSetter() { this.serializer = new SerializingConverter(); <START> this.lobHandler = new DefaultLobHandler(); <END> }</code><technical_language>Thanks, @meherzad , for update. Well, I want. I null add null checks setValues() method them. This implementor decide get some other logic for message store, e.g. convert simple string representation. This (s)he is able override setValues() count serializer/lobHandler. I nul checks minimize time for actions preparedStatement</technical_language>

Target:
protected MessageGroupPreparedStatementSetter() { this.serializer = null; this.lobHandler = null; }
Source:
<code>public <T> void reconcile(final String key, final long record, final T... values) { <START> reconcile(key, record, Lists.newArrayList(values)); <END> }</code><technical_language>pass in a Set instead of a List ultimately thrift method requires a Set</technical_language>

Target:
public <T> void reconcile(final String key, final long record, final T... values) { reconcile(key, record, Sets.newHashSet(values)); }
Source:
<code>public Map<SubpopulationGuid, ConsentStatus> withdrawAllConsents(Study study, StudyParticipant participant, CriteriaContext context, Withdrawal withdrawal, long withdrewOn) { checkNotNull(study); checkNotNull(context); checkNotNull(withdrawal); checkArgument(withdrewOn > 0); Account account = accountDao.getAccount(context.getAccountId()); for (SubpopulationGuid subpopGuid : account.getAllConsentSignatureHistories().keySet()) { withdrawSignatures(account, subpopGuid, withdrewOn); } account.setSharingScope(SharingScope.NO_SHARING); accountDao.updateAccount(account, false); for (SubpopulationGuid subpopGuid : account.getAllConsentSignatureHistories().keySet()) { Subpopulation subpop = subpopService.getSubpopulation(study.getStudyIdentifier(), subpopGuid); if (!subpop.isAutoSendConsentSuppressed()) { sendWithdrawEmail(study, participant.getExternalId(), account, withdrawal, withdrewOn); } <START> } <END> return getConsentStatuses(context, account); }</code><technical_language>This send email. sends email for subpop. This is intent. Incidentally, want a unit test case multiple subpops. (Both send send cases.)</technical_language>

Target:
public Map<SubpopulationGuid, ConsentStatus> withdrawAllConsents(Study study, StudyParticipant participant, CriteriaContext context, Withdrawal withdrawal, long withdrewOn) { checkNotNull(study); checkNotNull(context); checkNotNull(withdrawal); checkArgument(withdrewOn > 0); Account account = accountDao.getAccount(context.getAccountId()); for (SubpopulationGuid subpopGuid : account.getAllConsentSignatureHistories().keySet()) { withdrawSignatures(account, subpopGuid, withdrewOn); } account.setSharingScope(SharingScope.NO_SHARING); accountDao.updateAccount(account, false); sendWithdrawEmail(study, participant.getExternalId(), account, withdrawal, withdrewOn); return getConsentStatuses(context, account); }
Source:
<code>protected Void execute0(StatsCmd command, ResultCallback<Statistics> resultCallback) { WebTarget webTarget = getBaseResource().path("/containers/{id}/stats").resolveTemplate("id", command.getContainerId()); <START> if (isTrue(command.getNoStream())) { <END> webTarget = webTarget.queryParam("stream", "0"); } LOGGER.trace("GET: {}", webTarget); webTarget.request().get(new TypeReference<Statistics>() { }, resultCallback); return null; }</code><technical_language>I need BooleanUtils simply Boolean.TRUE.equals(command.getNoStream()) (null safe)</technical_language>

Target:
protected Void execute0(StatsCmd command, ResultCallback<Statistics> resultCallback) { WebTarget webTarget = getBaseResource().path("/containers/{id}/stats").resolveTemplate("id", command.getContainerId()); if (Boolean.TRUE.equals(command.hasNoStream())) { webTarget = webTarget.queryParam("stream", "0"); } LOGGER.trace("GET: {}", webTarget); webTarget.request().get(new TypeReference<Statistics>() { }, resultCallback); return null; }
Source:
<code>public List<PermissionSubject> getPermissionCheckSubjects() { if (permissionCheckSubjects == null) { permissionCheckSubjects = new ArrayList<PermissionSubject>(); <START> permissionCheckSubjects.addAll(super.getPermissionCheckSubjects()); <END> permissionCheckSubjects.add(new PermissionSubject( getParameters().getStorageDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); } return permissionCheckSubjects; }</code><technical_language>I this is right solution, this modify command inherited StorageDomainCommandBase require permission StoragePool, else override this method maintain current behaviour. For task/job description, override CommandBase.getJobMessageProperties() provide required properties for substitute place holder</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { return Collections.singletonList(new PermissionSubject(getParameters().getStorageDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); }
Source:
<code>protected void removeUnits(final IDelegateBridge bridge, final Predicate<Unit> unitMatch) { <START> final Collection<Unit> deadAttackers = <END> CollectionUtils.getMatches( battleState.getUnits(BattleState.Side.OFFENSE), unitMatch.and(Matches.unitIsSuicideOnAttack())); final Collection<Unit> deadDefenders = CollectionUtils.getMatches( battleState.getUnits(BattleState.Side.DEFENSE), unitMatch.and(Matches.unitIsSuicideOnDefense())); bridge .getDisplayChannelBroadcaster() .deadUnitNotification( battleState.getBattleId(), battleState.getAttacker(), deadAttackers, getDependents(deadAttackers)); bridge .getDisplayChannelBroadcaster() .deadUnitNotification( battleState.getBattleId(), battleState.getDefender(), deadDefenders, getDependents(deadDefenders)); final List<Unit> deadUnits = new ArrayList<>(deadAttackers); deadUnits.addAll(deadDefenders); battleActions.remove(deadUnits, bridge, battleState.getBattleSite(), null); }</code><technical_language>nit, suicideAttackers a bit more specified? 'deadAttackers' implies matching attackers casualties longer participating in battle (IE: removed in a previous battle step already)</technical_language>

Target:
protected void removeUnits(final IDelegateBridge bridge, final Predicate<Unit> unitMatch) { final Collection<Unit> suicideAttackers = CollectionUtils.getMatches( battleState.getUnits(BattleState.Side.OFFENSE), unitMatch.and(Matches.unitIsSuicideOnAttack())); final Collection<Unit> suicideDefenders = CollectionUtils.getMatches( battleState.getUnits(BattleState.Side.DEFENSE), unitMatch.and(Matches.unitIsSuicideOnDefense())); bridge .getDisplayChannelBroadcaster() .deadUnitNotification( battleState.getBattleId(), battleState.getAttacker(), suicideAttackers, getDependents(suicideAttackers)); bridge .getDisplayChannelBroadcaster() .deadUnitNotification( battleState.getBattleId(), battleState.getDefender(), suicideDefenders, getDependents(suicideDefenders)); final List<Unit> deadUnits = new ArrayList<>(suicideAttackers); deadUnits.addAll(suicideDefenders); battleActions.remove(deadUnits, bridge, battleState.getBattleSite(), null); }
Source:
<code>public void load() { <START> HdfsConfiguration.init(); <END> OptionBuilder<DatasetRepository> builder = new URIBuilder(); Registration.register( new URIPattern("file:/*path?absolute=true"), new URIPattern("file:/*path/:namespace/:dataset?absolute=true"), builder); Registration.register( new URIPattern("file:*path"), new URIPattern("file:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("hdfs:/*path?absolute=true"), new URIPattern("hdfs:/*path/:namespace/:dataset?absolute=true"), builder); Registration.register( new URIPattern("hdfs:*path"), new URIPattern("hdfs:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("webhdfs:/*path?absolute=true"), new URIPattern("webhdfs:/*path/:namespace/:dataset?absolute=true"), builder); }</code><technical_language>Is concern HdfsConfiguration is annotated @InterfaceAudience.Private</technical_language>

Target:
public void load() { try { FileSystem.getLocal(DefaultConfiguration.get()); } catch (IOException e) { throw new DatasetIOException("Cannot load default config", e); } OptionBuilder<DatasetRepository> builder = new URIBuilder(); Registration.register( new URIPattern("file:/*path?absolute=true"), new URIPattern("file:/*path/:namespace/:dataset?absolute=true"), builder); Registration.register( new URIPattern("file:*path"), new URIPattern("file:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("hdfs:/*path?absolute=true"), new URIPattern("hdfs:/*path/:namespace/:dataset?absolute=true"), builder); Registration.register( new URIPattern("hdfs:*path"), new URIPattern("hdfs:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("webhdfs:/*path?absolute=true"), new URIPattern("webhdfs:/*path/:namespace/:dataset?absolute=true"), builder); }
Source:
<code>public void testHangingFileExpires() throws Exception { System.setProperty("org.codice.ddf.catalog.content.monitor.expirationTime", "100"); doAnswer( (InvocationOnMock e) -> { <START> sleep(1000); <END> return null; }) .when(fileListener) .onFileCreate(any(File.class), any(Synchronization.class)); observer = new AsyncFileAlterationObserver(monitoredDirectory, store); observer.initialize(); observer.setListener(fileListener); observer.initializePeriodicProcessing(); File[] files = initFiles(1, monitoredDirectory, "file00"); observer.checkAndNotify(); verify(fileListener, times(files.length)) .onFileCreate(any(File.class), any(Synchronization.class)); assertThat(observer.expiredFiles.size(), is(1)); observer.checkAndNotify(); assertThat(observer.expiredFiles.size(), is(1)); }</code><technical_language>Do is right balance test time consistency? thinking potentially flakiness based sleep time</technical_language>

Target:
public void testHangingFileExpires() throws Exception { System.setProperty("org.codice.ddf.catalog.content.monitor.expirationTime", "100"); doAnswer( (InvocationOnMock e) -> { sleep(500); return null; }) .when(fileListener) .onFileCreate(any(File.class), any(Synchronization.class)); observer = new AsyncFileAlterationObserver(monitoredDirectory, store); observer.initialize(); observer.setListener(fileListener); observer.initializePeriodicProcessing(); File[] files = initFiles(1, monitoredDirectory, "file00"); observer.checkAndNotify(); verify(fileListener, times(files.length)) .onFileCreate(any(File.class), any(Synchronization.class)); assertThat(observer.expiredFiles.size(), is(1)); observer.checkAndNotify(); assertThat(observer.expiredFiles.size(), is(1)); }
Source:
<code>public List<String> getAllDatabases() { try { return retry() .stopOnIllegalExceptions() .run("getAllDatabases", stats.getGetAllDatabases().wrap(() -> <START> wrapHMSCallable((HiveMetastoreClient client, ThriftHiveMetastoreStats stat) -> stat.getGetAllDatabases().wrapCall(client::getAllDatabases)))); <END> } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); } }</code><technical_language>wrapMetastoreCallable</technical_language>

Target:
public List<String> getAllDatabases() { try { return retry() .stopOnIllegalExceptions() .run("getAllDatabases", stats.getGetAllDatabases().wrap(() -> wrapMetastoreCallable((HiveMetastoreClient client, ThriftHiveMetastoreStats stat) -> stat.getGetAllDatabases().wrapCall(client::getAllDatabases)))); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); } }
Source:
<code>public boolean hitEntity(ItemStack itemStack, EntityLivingBase target, EntityLivingBase attacker) { if (attacker instanceof EntityPlayer && attacker.getRNG().nextFloat() < .15) { if(!attacker.world.isRemote) { String[] options = new String[] {"Your blood shall fuel our machinations.", "They stir in your subconscious.", "Your suffering grants us strength.", "Our will is your will.", "It is done.", "You are a tool. A tool through which we we exert our conspiracies."}; Random rand = new Random(); <START> int num = rand.nextInt(5); <END> ITextComponent message = new TextComponentTranslation(options[num]); message.getStyle().setColor(TextFormatting.DARK_PURPLE); attacker.sendMessage(message); } attacker.addPotionEffect(new PotionEffect(MobEffects.WITHER, 100, 2)); } return super.hitEntity(itemStack, target, attacker); }</code><technical_language>6 able show messages, options.length instead</technical_language>

Target:
public boolean hitEntity(ItemStack itemStack, EntityLivingBase target, EntityLivingBase attacker) { if (attacker instanceof EntityPlayer && attacker.getRNG().nextFloat() < .15) { if(!attacker.world.isRemote) { String[] options = new String[] {"item.clawOfNrubyiglith.message.machinations", "item.clawOfNrubyiglith.message.stir", "item.clawOfNrubyiglith.message.suffering", "item.clawOfNrubyiglith.message.will", "item.clawOfNrubyiglith.message.done", "item.clawOfNrubyiglith.message.conspiracies"}; Random rand = new Random(); int num = rand.nextInt(options.length); ITextComponent message = new TextComponentTranslation(options[num]); message.getStyle().setColor(TextFormatting.DARK_PURPLE); attacker.sendMessage(message); } attacker.addPotionEffect(new PotionEffect(MobEffects.WITHER, 100, 2)); } return super.hitEntity(itemStack, target, attacker); }
Source:
<code>private Champ copyAndMigrateFromInlineToNode(final int bitpos, final Pair<Champ, Multihash> node) { final int oldIndex = index(dataMap, bitpos); final int newIndex = this.contents.length - 1 - index(nodeMap, bitpos); final HashPrefixPayload[] src = this.contents; final HashPrefixPayload[] dst = new HashPrefixPayload[src.length]; <START> assert oldIndex <= newIndex; <END> System.arraycopy(src, 0, dst, 0, oldIndex); System.arraycopy(src, oldIndex + 1, dst, oldIndex, newIndex - oldIndex); dst[newIndex] = new HashPrefixPayload(null, MaybeMultihash.of(node.right)); System.arraycopy(src, newIndex + 1, dst, newIndex + 1, src.length - newIndex - 1); BitSet newNodeMap = BitSet.valueOf(nodeMap.toByteArray()); newNodeMap.set(bitpos); BitSet newDataMap = BitSet.valueOf(dataMap.toByteArray()); newDataMap.set(bitpos, false); return new Champ(newDataMap, newNodeMap, dst); }</code><technical_language>this a full invariant raise a RuntimeException similar, asserts elided -ea javac flag</technical_language>

Target:
private Champ copyAndMigrateFromInlineToNode(final int bitpos, final Pair<Champ, Multihash> node) { final int oldIndex = getIndex(dataMap, bitpos); final int newIndex = this.contents.length - 1 - getIndex(nodeMap, bitpos); final HashPrefixPayload[] src = this.contents; final HashPrefixPayload[] dst = new HashPrefixPayload[src.length]; if (oldIndex > newIndex) throw new IllegalStateException("Invalid champ!"); System.arraycopy(src, 0, dst, 0, oldIndex); System.arraycopy(src, oldIndex + 1, dst, oldIndex, newIndex - oldIndex); dst[newIndex] = new HashPrefixPayload(MaybeMultihash.of(node.right)); System.arraycopy(src, newIndex + 1, dst, newIndex + 1, src.length - newIndex - 1); BitSet newNodeMap = BitSet.valueOf(nodeMap.toByteArray()); newNodeMap.set(bitpos); BitSet newDataMap = BitSet.valueOf(dataMap.toByteArray()); newDataMap.set(bitpos, false); return new Champ(newDataMap, newNodeMap, dst); }
Source:
<code>ListenableFuture<AnviltopServices.MutateRowResponse> issueDeleteRequest(Delete delete) { AnviltopData.RowMutation.Builder mutationBuilder = deleteAdapter.adapt(delete); AnviltopServices.MutateRowRequest.Builder requestBuilder = AnviltopServices.MutateRowRequest.newBuilder(); requestBuilder.setMutation(mutationBuilder); <START> AnviltopServices.MutateRowRequest request = <END> requestBuilder .setTableName(tableName.getQualifierAsString()) .setProjectId(options.getProjectId()) .build(); try { return client.mutateAtomicAsync(request); } catch (ServiceException e) { return Futures.immediateFailedFuture(e); } }</code><technical_language>is worth makeMutateRowRequest in AnvilTopTable? encapsulating try</technical_language>

Target:
ListenableFuture<AnviltopServices.MutateRowResponse> issueDeleteRequest(Delete delete) { AnviltopData.RowMutation.Builder mutationBuilder = deleteAdapter.adapt(delete); AnviltopServices.MutateRowRequest.Builder requestBuilder = makeMutateRowRequest(mutationBuilder); try { return client.mutateAtomicAsync(requestBuilder.build()); } catch (ServiceException e) { return Futures.immediateFailedFuture(e); } }
Source:
<code>private HTTPEndpointManager() { super(); internalInboundPort = ConfigurationLoader.getInternalInboundHttpPort(); internalInboundHttpsPort = ConfigurationLoader.getInternalInboundHttpsPort(); if (internalInboundPort != -1) { int portOffset = PersistenceUtils.getPortOffset(); <START> internalInboundPort += portOffset; <END> internalInboundHttpsPort += portOffset; ConfigurationLoader.loadInternalApis(Constants.INTERNAL_APIS_FILE); List<InternalAPI> httpInternalAPIList = ConfigurationLoader.getHttpInternalApis(); internalHttpAPIDispatcher = new InternalAPIDispatcher(httpInternalAPIList); internalHttpApiEnabled = !httpInternalAPIList.isEmpty(); List<InternalAPI> httpsInternalAPIList = ConfigurationLoader.getHttpsInternalApis(); internalHttpsAPIDispatcher = new InternalAPIDispatcher(httpsInternalAPIList); internalHttpsApiEnabled = !httpsInternalAPIList.isEmpty(); } }</code><technical_language>refactor internalInboundPort = internalInboundPort + portOffset for readability</technical_language>

Target:
private HTTPEndpointManager() { super(); if (ConfigurationLoader.isInternalApiEnabled()) { internalInboundHttpPort = ConfigurationLoader.getInternalInboundHttpPort(); internalInboundHttpsPort = ConfigurationLoader.getInternalInboundHttpsPort(); ConfigurationLoader.loadInternalApis(Constants.INTERNAL_APIS_FILE); List<InternalAPI> httpInternalAPIList = ConfigurationLoader.getHttpInternalApis(); internalHttpApiDispatcher = new InternalAPIDispatcher(httpInternalAPIList); internalHttpApiEnabled = !httpInternalAPIList.isEmpty(); List<InternalAPI> httpsInternalAPIList = ConfigurationLoader.getHttpsInternalApis(); internalHttpsApiDispatcher = new InternalAPIDispatcher(httpsInternalAPIList); internalHttpsApiEnabled = !httpsInternalAPIList.isEmpty(); } }
Source:
<code>public User(String userID) { <START> super.setId(userID); <END> }</code><technical_language>Missing new line method</technical_language>

Target:
public User(String userID) { super(userID); }
Source:
<code>public void run() { synchronized (_syncRoot) { if (_cancelled || _badEndPoints.get(_endPoint) != this) { return; } } HealthCheckResult result = checkHealth(_endPoint); synchronized (_syncRoot) { _count += 1; if (result.isHealthy()) { _badEndPoints.remove(_endPoint, this); this.cancel(false); } else { <START> long delayMillis = _healthCheckRetryPolicy.retry(_count, result); <END> if (_future != null) { _future.cancel(false); } _future = _healthCheckExecutor.schedule(this, Math.max(0, delayMillis), TimeUnit.MILLISECONDS); } } }</code><technical_language>reason worried this throwing exception</technical_language>

Target:
public void run() { synchronized (_syncRoot) { if (_cancelled || _badEndPoints.get(_endPoint) != this) { return; } } HealthCheckResult result = checkHealth(_endPoint); synchronized (_syncRoot) { _count += 1; if (result.isHealthy()) { _badEndPoints.remove(_endPoint, this); this.cancel(false); } else { long delayMillis = _healthCheckRetryDelay.getDelay(_count, result); if (_future != null) { _future.cancel(false); } _future = _healthCheckExecutor.schedule(this, Math.max(0, delayMillis), TimeUnit.MILLISECONDS); } } }
Source:
<code>public static Map<String, Set<XmlOutputElement>> getXmlOutputElements() { return <START> ImmutableMap.copyOf(XML_OUTPUT_ELEMENTS); <END> }</code><technical_language>copying map for module creation. cache ImmutableMultimap is built. improving performances a lot, more efficient</technical_language>

Target:
public static Multimap<String, XmlOutputElement> getXmlOutputElements() { return fCachedOutputElement; }