auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void parseArgs(String programName, String[] args, Object... others) { super.parseArgs(programName, args, others); if (legacyOpts != null || legacyOptsBoolean) { var errmsg = new StringBuilder(); for (String option : args) { <START> if (LEGACY_OPTION_MSG.keySet().contains(option)) { <END> errmsg.append("Option ").append(option).append(" has been dropped - ") .append(LEGACY_OPTION_MSG.get(option)).append("\n"); } } System.err.println(errmsg.append("See '-o' property override option").toString()); throw new IllegalArgumentException(errmsg.toString()); } if (getOverrides().size() > 0) { log.info("The following configuration was set on the command line:"); for (Map.Entry<String,String> entry : getOverrides().entrySet()) { String key = entry.getKey(); log.info(key + " = " + (Property.isSensitive(key) ? "<hidden>" : entry.getValue())); } } }</code><technical_language>a containsKey() method for this</technical_language>

Target:
public void parseArgs(String programName, String[] args, Object... others) { super.parseArgs(programName, args, others); if (legacyOpts != null || legacyOptsBoolean) { String errMsg = ""; for (String option : args) { if (LEGACY_OPTION_MSG.containsKey(option)) { errMsg += "Option " + option + " has been dropped - " + LEGACY_OPTION_MSG.get(option) + "\n"; } } errMsg += "See '-o' property override option"; System.err.println(errMsg); throw new IllegalArgumentException(errMsg); } if (getOverrides().size() > 0) { log.info("The following configuration was set on the command line:"); for (Map.Entry<String,String> entry : getOverrides().entrySet()) { String key = entry.getKey(); log.info(key + " = " + (Property.isSensitive(key) ? "<hidden>" : entry.getValue())); } } }
Source:
<code>public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (getArguments() != null && getArguments().getBoolean(ARGS_IS_PORTRAIT, false)) { <START> View header = getLayoutInflater(null) <END> .inflate(R.layout.header_list_special_event_series, (ViewGroup) getView(), false); TextView mDescription = ButterKnife.findById(header, R.id.special_description); ImageView mLogo = ButterKnife.findById(header, R.id.special_logo); mDescription.setText(mTaggedEventSeries.getDescriptionResId()); mLogo.setImageResource(mTaggedEventSeries.getLogoResId()); ListView list = (ListView) getListView(); list.addHeaderView(header, null, false); final Space space = new Space(getActivity()); space.setLayoutParams( new AbsListView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, Utils.dpToPx(getResources(), 16))); list.addHeaderView(space, null, false); } }</code><technical_language>encoding orientation right. handled in onConfigurationChanged</technical_language>

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ListView list = (ListView) getListView(); if (getArguments() != null && getArguments().getBoolean(ARGS_ADD_DESCRIPTION_AS_HEADER, false)) { View header = getLayoutInflater(null) .inflate(R.layout.header_list_special_event_series, (ViewGroup) getView(), false); TextView mDescription = ButterKnife.findById(header, R.id.special_description); mDescription.setText(mTaggedEventSeries.getDescriptionResId()); mDescription.setCompoundDrawablesWithIntrinsicBounds(0, mTaggedEventSeries.getLogoResId(), 0, 0); list.addHeaderView(header, null, false); } final ViewGroup.LayoutParams listLayoutParams = list.getLayoutParams(); if (getView() != null && listLayoutParams.width > getView().getWidth()) { listLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; } }
Source:
<code>private void injectPropertiesToEngine(String properties) throws ScriptException { <START> scriptEngine.eval("var " + PROPERTIES_OBJECT_NAME + "= " + properties); <END> }</code><technical_language>is good change '=' constants. this line formatting issue</technical_language>

Target:
private void injectPropertiesToEngine(String properties) throws ScriptException { scriptEngine.eval("var " + PROPERTIES_OBJECT_NAME + EQUALS_SIGN + properties); }
Source:
<code>protected void populateValueList(final StringBuilder buf, final int type, final String fieldType, final String value) { String workingValue = value.trim(); if (workingValue.startsWith("(")) { workingValue = workingValue.substring(1); } if (workingValue.endsWith(")")) { workingValue = workingValue.substring(0, workingValue.length() - 1); } <START> final String[] values = ListSplitter.split("\"",workingValue); <END> buf.append(" ( "); for (String v : values) { v = v.trim(); constraintValueBuilder.buildLHSFieldValue(buf, type, fieldType, v); buf.append(", "); } buf.delete(buf.length() - 2, buf.length()); buf.append(" )"); }</code><technical_language>formatting, please split method arguments space</technical_language>

Target:
protected void populateValueList(final StringBuilder buf, final int type, final String fieldType, final String value) { String workingValue = value.trim(); if (workingValue.startsWith("(")) { workingValue = workingValue.substring(1); } if (workingValue.endsWith(")")) { workingValue = workingValue.substring(0, workingValue.length() - 1); } final String[] values = ListSplitter.split("\"", true, workingValue); buf.append(" ( "); for (String v : values) { v = v.trim(); constraintValueBuilder.buildLHSFieldValue(buf, type, fieldType, v); buf.append(", "); } buf.delete(buf.length() - 2, buf.length()); buf.append(" )"); }
Source:
<code>public void addEmptyColumnReferencesForTable(AccessControl accessControl, Identity identity, QualifiedObjectName table) { AccessControlInfo accessControlInfo = new AccessControlInfo(accessControl, identity); <START> tableColumnReferences.putIfAbsent(accessControlInfo, new LinkedHashMap<>()); <END> tableColumnReferences.get(accessControlInfo).putIfAbsent(table, new HashSet<>()); }</code><technical_language>I write this java tableColumnReferences.computeIfAbsent(accessControlInfo, LinkedHashMap::new).computeIfAbsent(table, HashSet::new); This avoids creating empty maps exists</technical_language>

Target:
public void addEmptyColumnReferencesForTable(AccessControl accessControl, Identity identity, QualifiedObjectName table) { AccessControlInfo accessControlInfo = new AccessControlInfo(accessControl, identity); tableColumnReferences.computeIfAbsent(accessControlInfo, k -> new LinkedHashMap<>()).computeIfAbsent(table, k -> new HashSet<>()); }
Source:
<code>private Collection<String> getErrorParameterPackages() { return Stream .concat(Stream.of( <START> SpringRouteNotFoundError.class.getPackage().getName()), <END> Stream.concat( Stream.of(HasErrorParameter.class.getPackage() .getName()), getDefaultPackages().stream())) .collect(Collectors.toSet()); }</code><technical_language>add this new package this: Stream.of(HasErrorParameter.class.getPackage().getName(), SpringRouteNotFoundError.class.getPackage().getName())</technical_language>

Target:
private Collection<String> getErrorParameterPackages() { return Stream.concat( Stream.of(HasErrorParameter.class.getPackage().getName(), SpringRouteNotFoundError.class.getPackage().getName()), getDefaultPackages().stream()).collect(Collectors.toSet()); }
Source:
<code>public Component apply(ComponentDto dbComponent) { OrganizationDto organizationDto = organizationsByUuid.get(dbComponent.getOrganizationUuid()); <START> checkFound(organizationDto, "Organization with uuid '%s' not found", dbComponent.getOrganizationUuid()); <END> wsComponent .clear() .setOrganization(organizationDto.getKey()) .setId(dbComponent.uuid()) .setKey(dbComponent.key()) .setName(dbComponent.name()) .setVisibility(Visibility.getLabel(dbComponent.isPrivate())); wsComponent.getTagsBuilder().addAllTags(dbComponent.getTags()); SnapshotDto snapshotDto = analysisByProjectUuid.get(dbComponent.uuid()); if (snapshotDto != null) { if (request.getAdditionalFields().contains(ANALYSIS_DATE)) { wsComponent.setAnalysisDate(formatDateTime(snapshotDto.getCreatedAt())); } if (request.getAdditionalFields().contains(LEAK_PERIOD_DATE)) { setNullable(snapshotDto.getPeriodDate(), leakPeriodDate -> wsComponent.setLeakPeriodDate(formatDateTime(leakPeriodDate))); } } if (isUserLoggedIn) { wsComponent.setIsFavorite(favoriteProjectUuids.contains(dbComponent.uuid())); } return wsComponent.build(); }</code><technical_language>dbComponent.getOrganizationUuid() externalised a variable</technical_language>

Target:
public Component apply(ComponentDto dbComponent) { String organizationUuid = dbComponent.getOrganizationUuid(); OrganizationDto organizationDto = organizationsByUuid.get(organizationUuid); checkFound(organizationDto, "Organization with uuid '%s' not found", organizationUuid); wsComponent .clear() .setOrganization(organizationDto.getKey()) .setId(dbComponent.uuid()) .setKey(dbComponent.key()) .setName(dbComponent.name()) .setVisibility(Visibility.getLabel(dbComponent.isPrivate())); wsComponent.getTagsBuilder().addAllTags(dbComponent.getTags()); SnapshotDto snapshotDto = analysisByProjectUuid.get(dbComponent.uuid()); if (snapshotDto != null) { if (request.getAdditionalFields().contains(ANALYSIS_DATE)) { wsComponent.setAnalysisDate(formatDateTime(snapshotDto.getCreatedAt())); } if (request.getAdditionalFields().contains(LEAK_PERIOD_DATE)) { setNullable(snapshotDto.getPeriodDate(), leakPeriodDate -> wsComponent.setLeakPeriodDate(formatDateTime(leakPeriodDate))); } } if (isUserLoggedIn) { wsComponent.setIsFavorite(favoriteProjectUuids.contains(dbComponent.uuid())); } return wsComponent.build(); }
Source:
<code>private boolean subscribe(String eventName) { if (!subscribed) { getSubscriptionID(); } subscribed = connManager.getDigitalSTROMAPI().subscribeEvent(connManager.getSessionToken(), eventName, subscriptionID, config.getConnectionTimeout(), config.getReadTimeout()); if (subscribed) { logger.debug("subscribed event: to subscriptionID: {}", eventName, subscriptionID); } else { logger.error( <START> "Couldn't subscribe event ... maybe timeout because system is to busy ... event will subscribe later again ... "); <END> } return subscribed; }</code><technical_language>"system is busy" -> "system is busy" "event subscribe again" -> "event subscribe again"</technical_language>

Target:
private boolean subscribe(String eventName) { if (!subscribed) { getSubscriptionID(); } subscribed = connManager.getDigitalSTROMAPI().subscribeEvent(connManager.getSessionToken(), eventName, subscriptionID, config.getConnectionTimeout(), config.getReadTimeout()); if (subscribed) { logger.debug("subscribed event: to subscriptionID: {}", eventName, subscriptionID); } else { logger.error( "Couldn't subscribe event ... maybe timeout because system is too busy ... event will be tried to subscribe later again ... "); } return subscribed; }
Source:
<code>public void onItemClick(AdapterView<?> l, View v, int pos, long id) { PlayerSelectionOption selection = selectionMap.get(selectionAdapter.getItem(pos)); <START> Intent intent = new IntentBuilder(this) <END> .setActivity(selection.getActivity()) .setEmbedCode(selection.getEmbedCode()) .setPCode(selection.getPcode()) .setDomain(selection.getDomain()) .setAutoPlay(true) .build(); startActivity(intent); }</code><technical_language>Intent intent is redundant</technical_language>

Target:
public void onItemClick(AdapterView<?> l, View v, int pos, long id) { PlayerSelectionOption selection = selectionMap.get(selectionAdapter.getItem(pos)); Intent intent = new IntentBuilder() .setActivity(selection.getActivity()) .setEmbedCode(selection.getEmbedCode()) .setPCode(selection.getPcode()) .setDomain(selection.getDomain()) .setAutoPlay(true) .build(this); startActivity(intent); }
Source:
<code>public void testProcessImportsRnaseq() { <START> final String githubRepository = "nextflow-io/rnaseq-nf"; <END> WorkflowVersion workflowVersion = new WorkflowVersion(); workflowVersion.setName("master"); workflowVersion.setReference("master"); String mainDescriptorContents = sourceCodeRepoInterface.readFile(githubRepository, "nextflow.config", "master"); Map<String, SourceFile> stringSourceFileMap = sourceCodeRepoInterface .resolveImports(githubRepository, mainDescriptorContents, DescriptorLanguage.FileType.NEXTFLOW_CONFIG, workflowVersion, "/nextflow.config"); List<String> knownFileNames = Arrays.asList("main.nf", "/modules/index.nf", "/modules/multiqc.nf", "/modules/quant.nf", "/modules/fastqc.nf", "/modules/rnaseq.nf"); int size = knownFileNames.size(); checkAllSourceFiles(stringSourceFileMap, size); Assert.assertEquals(size, stringSourceFileMap.size()); knownFileNames.forEach(knownFile -> { SourceFile sourceFile = stringSourceFileMap.get(knownFile); checkSourceFile(sourceFile); }); }</code><technical_language>tests break if nextflow-io changes (or forked missing it?)</technical_language>

Target:
public void testProcessImportsRnaseq() { final String githubRepository = "dockstore-testing/rnaseq-nf"; WorkflowVersion workflowVersion = new WorkflowVersion(); workflowVersion.setName("2.0.1"); workflowVersion.setReference("2.0.1"); String mainDescriptorContents = sourceCodeRepoInterface.readFile(githubRepository, "nextflow.config", "master"); Map<String, SourceFile> stringSourceFileMap = sourceCodeRepoInterface .resolveImports(githubRepository, mainDescriptorContents, DescriptorLanguage.FileType.NEXTFLOW_CONFIG, workflowVersion, "/nextflow.config"); List<String> knownFileNames = Arrays.asList("main.nf", "/modules/index.nf", "/modules/multiqc.nf", "/modules/quant.nf", "/modules/fastqc.nf", "/modules/rnaseq.nf"); int size = knownFileNames.size(); checkAllSourceFiles(stringSourceFileMap, size); Assert.assertEquals(size, stringSourceFileMap.size()); knownFileNames.forEach(knownFile -> { SourceFile sourceFile = stringSourceFileMap.get(knownFile); checkSourceFile(sourceFile); }); }
Source:
<code>public Attribute fillAttribute(PerunSessionImpl perunSession, User user, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException { Attribute filledAttribute = new Attribute(attribute); <START> try { <END> Attribute a = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, user, CESNET_EDUROAM_NAMESPACE); if (a.getValue() != null) { filledAttribute.setValue(a.getValue()); return filledAttribute; } } catch (AttributeNotExistsException e) { throw new ConsistencyErrorException("Login namespace attribute for cesnet-eduroam must exists.", e); } Attribute idsCounter; try { idsCounter = perunSession.getPerunBl().getAttributesManagerBl().getEntitylessAttributeForUpdate(perunSession, cesnet_eduroam_key, CESNET_EDUROAM_IDS_COUNTER); } catch (AttributeNotExistsException e) { throw new ConsistencyErrorException("Attribute doesn't exists.", e); } Integer counterValue; if (idsCounter.getValue() == null) { counterValue = new Integer(1000); } else { counterValue = (Integer) idsCounter.getValue(); } filledAttribute.setValue(counterValue); try { perunSession.getPerunBl().getAttributesManagerBl().setAttribute(perunSession, user, filledAttribute); } catch (WrongAttributeValueException | WrongAttributeAssignmentException | WrongReferenceAttributeValueException e) { throw new InternalErrorException("Unable to store login to login-namespace:cesnet-eduroam attribute.", e); } counterValue++; try { idsCounter.setValue(counterValue); perunSession.getPerunBl().getAttributesManagerBl().setAttribute(perunSession, cesnet_eduroam_key, idsCounter); } catch (WrongAttributeValueException | WrongAttributeAssignmentException | WrongReferenceAttributeValueException ex) { throw new InternalErrorException(ex); } return filledAttribute; }</code><technical_language>I not, eduroam-vsup is filled existing vsup login-namespace. fill attribute itself. I say, wrong, fillAttribute() is called only, if is empty - filled anyway</technical_language>

Target:
public Attribute fillAttribute(PerunSessionImpl perunSession, User user, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException { Attribute filledAttribute = new Attribute(attribute); Attribute idsCounter; try { idsCounter = perunSession.getPerunBl().getAttributesManagerBl().getEntitylessAttributeForUpdate(perunSession, cesnet_eduroam_key, CESNET_EDUROAM_IDS_COUNTER); } catch (AttributeNotExistsException e) { throw new ConsistencyErrorException("Attribute doesn't exists.", e); } Integer counterValue; if (idsCounter.getValue() == null) { counterValue = new Integer(1000); } else { counterValue = (Integer) idsCounter.getValue(); } filledAttribute.setValue(counterValue); counterValue++; try { idsCounter.setValue(counterValue); perunSession.getPerunBl().getAttributesManagerBl().setAttribute(perunSession, cesnet_eduroam_key, idsCounter); } catch (WrongAttributeValueException | WrongAttributeAssignmentException | WrongReferenceAttributeValueException ex) { throw new InternalErrorException(ex); } return filledAttribute; }
Source:
<code><START> private ExponentialBackOffIntervalRetryScheduler(Builder builder) { <END> super(builder); builder.validate(); this.backoffFactor = builder.backoffFactor; }</code><technical_language>constructor protected users easily a wrapper for it</technical_language>

Target:
protected ExponentialBackOffIntervalRetryScheduler(Builder builder) { super(builder); this.backoffFactor = builder.backoffFactor; }
Source:
<code>private static Map<Class<?>, Class<?>> buildConvertableTypesMap() { Map<Class<?>, Class<?>> map = new HashMap<Class<?>, Class<?>>(); map.put(boolean.class, Boolean.class); map.put(byte.class, Byte.class); map.put(short.class, Short.class); map.put(char.class, Character.class); map.put(int.class, Integer.class); map.put(long.class, Long.class); map.put(float.class, Float.class); map.put(double.class, Double.class); <START> Iterable<Entry<Class<?>, Class<?>>> initialEntries = new HashSet<Entry<Class<?>, Class<?>>>(map.entrySet()); <END> for (Entry<Class<?>, Class<?>> entry : initialEntries) { map.put(entry.getValue(), entry.getKey()); } return Collections.unmodifiableMap(map); }</code><technical_language>simpler (and a more efficient) be: addSymmetrically(map, boolean.class, Boolean.class), addSymmetrically = map.put(a, b); map.put(b, a);</technical_language>

Target:
private static Map<Class<?>, Class<?>> buildConvertableTypesMap() { Map<Class<?>, Class<?>> map = new HashMap<Class<?>, Class<?>>(); putSymmetrically(map, boolean.class, Boolean.class); putSymmetrically(map, byte.class, Byte.class); putSymmetrically(map, short.class, Short.class); putSymmetrically(map, char.class, Character.class); putSymmetrically(map, int.class, Integer.class); putSymmetrically(map, long.class, Long.class); putSymmetrically(map, float.class, Float.class); putSymmetrically(map, double.class, Double.class); return Collections.unmodifiableMap(map); }
Source:
<code>public void testCheckConnectionWithValidUser() { DatabaseClient marklogic = DatabaseClientFactory.newClient("localhost", 8000, "unittest-nodeapi", new DatabaseClientFactory.DigestAuthContext( "admin", "admin")); ConnectionResult connResult = marklogic.checkConnection(); assertTrue(connResult.isConnected()); <START> assertTrue(connResult.getStatusCode() < 300); <END> }</code><technical_language>remove assertion line 133 if status code null in successful case</technical_language>

Target:
public void testCheckConnectionWithValidUser() { DatabaseClient marklogic = DatabaseClientFactory.newClient("localhost", 8000, "unittest-nodeapi", new DatabaseClientFactory.DigestAuthContext( "admin", "admin")); ConnectionResult connResult = marklogic.checkConnection(); assertTrue(connResult.isConnected()); }
Source:
<code>public void testMemoryMapping() { VDS vds = new VDS(); vds.setId(Guid.Empty); vds.setPhysicalMemMb(4000); Host host = HostMapper.map(vds, (Host) null); assertNotNull(host.getMemory()); <START> assertEquals(host.getMemory().longValue(), 4194304000L); <END> }</code><technical_language>potential NPE, host.getMemory() NULL instead please remove Long.valueOf() host.getMemory() Long 4194304000L</technical_language>

Target:
public void testMemoryMapping() { VDS vds = new VDS(); vds.setId(Guid.Empty); vds.setPhysicalMemMb(4000); Host host = HostMapper.map(vds, (Host) null); assertNotNull(host.getMemory()); assertEquals(host.getMemory(), Long.valueOf(4194304000L)); }
Source:
<code>public void configure(Binder binder) { binder.bind(ThriftConnector.class).in(Scopes.SINGLETON); thriftClientBinder(binder).bindThriftClient(PrestoThriftService.class); binder.bind(ThriftMetadata.class).in(Scopes.SINGLETON); binder.bind(ThriftSplitManager.class).in(Scopes.SINGLETON); binder.bind(ThriftPageSourceProvider.class).in(Scopes.SINGLETON); binder.bind(PrestoThriftServiceProvider.class).to(RetryingPrestoThriftServiceProvider.class).in(Scopes.SINGLETON); binder.bind(PrestoThriftServiceProvider.class).annotatedWith(NonRetrying.class).to(DefaultPrestoThriftServiceProvider.class).in(Scopes.SINGLETON); configBinder(binder).bindConfig(ThriftConnectorConfig.class); binder.bind(ThriftSessionProperties.class).in(Scopes.SINGLETON); binder.bind(ThriftIndexProvider.class).in(Scopes.SINGLETON); binder.bind(RetryingPrestoThriftServiceStats.class).in(Scopes.SINGLETON); newExporter(binder).export(RetryingPrestoThriftServiceStats.class) <START> .as(generatedNameOf(RetryingPrestoThriftServiceStats.class, connectorId)); <END> }</code><technical_language>This name RetryingPrestoThriftServiceStats for JMX bean. Is name</technical_language>

Target:
public void configure(Binder binder) { binder.bind(ThriftConnector.class).in(Scopes.SINGLETON); thriftClientBinder(binder).bindThriftClient(PrestoThriftService.class); binder.bind(ThriftMetadata.class).in(Scopes.SINGLETON); binder.bind(ThriftSplitManager.class).in(Scopes.SINGLETON); binder.bind(ThriftPageSourceProvider.class).in(Scopes.SINGLETON); binder.bind(PrestoThriftServiceProvider.class).to(RetryingPrestoThriftServiceProvider.class).in(Scopes.SINGLETON); binder.bind(PrestoThriftServiceProvider.class).annotatedWith(NonRetrying.class).to(DefaultPrestoThriftServiceProvider.class).in(Scopes.SINGLETON); configBinder(binder).bindConfig(ThriftConnectorConfig.class); binder.bind(ThriftSessionProperties.class).in(Scopes.SINGLETON); binder.bind(ThriftIndexProvider.class).in(Scopes.SINGLETON); newExporter(binder).export(PrestoThriftServiceProvider.class) .as(generatedNameOf(RetryingPrestoThriftServiceProvider.class, connectorId)); }
Source:
<code>void checkBundle(BlockingDeque<LauncherDiscoveryRequest> queue, Bundle bundle) { Bundle host = BundleUtils.getHost(bundle) .orElse(bundle); <START> if (host.getState() == Bundle.ACTIVE || host.getState() == Bundle.STARTING) { <END> String testcases = bundle.getHeaders() .get(aQute.bnd.osgi.Constants.TESTCASES); if (testcases != null) { trace("found active bundle with test cases %s : %s", bundle, testcases); queue.offerLast(buildRequest(bundle)); } } }</code><technical_language>Bundle state checks written bit mask tests. java if ((host.getState() & (Bundle.ACTIVE | Bundle.STARTING)) != 0) {</technical_language>

Target:
void checkBundle(BlockingDeque<LauncherDiscoveryRequest> queue, Bundle bundle) { Bundle host = BundleUtils.getHost(bundle) .orElse(bundle); if ((host.getState() & (Bundle.ACTIVE | Bundle.STARTING)) != 0) { String testcases = bundle.getHeaders() .get(aQute.bnd.osgi.Constants.TESTCASES); if (testcases != null) { trace("found active bundle with test cases %s : %s", bundle, testcases); queue.offerLast(buildRequest(bundle)); } } }
Source:
<code>public void correctSquareBrackets() { CtLocalVariableReference<Object> localVariableRef = new Launcher().getFactory().createLocalVariableReference(); <START> assertDoesNotThrow(() -> localVariableRef.setSimpleName("List<String>[]")); <END> }</code><technical_language>is a valid name for a local variable reference? a type reference instead</technical_language>

Target:
public void correctSquareBrackets() { CtTypeReference localVariableRef = new Launcher().getFactory().createTypeReference(); assertDoesNotThrow(() -> localVariableRef.setSimpleName("List<String>[]")); }
Source:
<code>public static boolean isRegistered(String serviceUniqueName) { Set<ProviderInvokerWrapper> providerInvokerWrapperSet = ProviderConsumerRegTable.getProviderInvoker(serviceUniqueName); <START> for (ProviderInvokerWrapper providerInvokerWrapper : providerInvokerWrapperSet) { <END> if (providerInvokerWrapper.isReg()) { return true; } } return false; }</code><technical_language>rewritten public static boolean isRegistered(String serviceUniqueName) { Set<ProviderInvokerWrapper> providerInvokerWrapperSet = ProviderConsumerRegTable.getProviderInvoker(serviceUniqueName); return providerInvokerWrapperSet.stream().anyMatch(ProviderInvokerWrapper::isReg); }</technical_language>

Target:
public static boolean isRegistered(String serviceUniqueName) { Set<ProviderInvokerWrapper> providerInvokerWrapperSet = ProviderConsumerRegTable.getProviderInvoker(serviceUniqueName); return providerInvokerWrapperSet.stream().anyMatch(ProviderInvokerWrapper::isReg); }
Source:
<code><START> protected boolean isAcceptableTx(Transaction tx) { <END> if (CasperTransactionExecutor.isCasperVote(tx, ((CasperProperties) config).getCasperAddress())) { return true; } return super.isAcceptableTx(tx); }</code><technical_language>turns need Tx validator sets managed Spring config instantiated for specific case. This BlockMiner PendingStateImpl clearer</technical_language>

Target:
protected boolean isAcceptableTx(Transaction tx) { if (casper.isVote(tx)) { return true; } return super.isAcceptableTx(tx); }
Source:
<code>public static StepType fromClassName(String className) { StepType type = UNKNOWN; <START> if(className != null) { <END> String name = className.trim(); for (StepType curType : values()) { if(curType.className.equals(name)) { type = curType; break; } } } return type; }</code><technical_language>possibly do assertion StringUtils.hasText() tighten a bit</technical_language>

Target:
public static StepType fromClassName(String className) { StepType type = UNKNOWN; if(StringUtils.hasText(className)) { String name = className.trim(); for (StepType curType : values()) { if(curType.className.equals(name)) { type = curType; break; } } } return type; }
Source:
<code><START> public Map<String, Object> getStats() throws IOException { <END> Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> documentMap = new HashMap<String, Object>(); DocumentReader<T> documentReader = getConnector().getDocumentReader(); documentMap.put("current", documentReader.getActiveDatabaseSize()); documentMap.put("throughput", 0); documentMap.put("archived", documentReader.getInactiveDatabaseSize()); documentMap.put("status", new HashMap<String, Long>()); map.put("documents", documentMap); Map<String, Object> stageMap = new HashMap<String, Object>(); map.put("groups", stageMap); PipelineReader pipelineReader = getConnector().getPipelineReader(); stageMap.put("active", getPipelineScanner().getStageConfigMap(pipelineReader.getPipeline())); stageMap.put("debug", getPipelineScanner().getStageConfigMap(pipelineReader.getDebugPipeline())); return map; }</code><technical_language>a caller possibly do IOException? Wrap more useful perhaps</technical_language>

Target:
public Map<String, Object> getStats() throws DatabaseException { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> documentMap = new HashMap<String, Object>(); DatabaseConnector<T> databaseConnector = null; PipelineScanner<T> scanner = null; try { databaseConnector = getConnector(); scanner = getPipelineScanner(); } catch (IOException e) { throw new DatabaseException("Failed to connect to database", e); } DocumentReader<T> documentReader = databaseConnector.getDocumentReader(); documentMap.put("current", documentReader.getActiveDatabaseSize()); documentMap.put("throughput", 0); documentMap.put("archived", documentReader.getInactiveDatabaseSize()); documentMap.put("status", new HashMap<String, Long>()); map.put("documents", documentMap); Map<String, Object> stageMap = new HashMap<String, Object>(); map.put("groups", stageMap); PipelineReader pipelineReader = databaseConnector.getPipelineReader(); stageMap.put("active", scanner.getStageConfigMap(pipelineReader.getPipeline())); stageMap.put("debug", scanner.getStageConfigMap(pipelineReader.getDebugPipeline())); return map; }
Source:
<code>public void testCookieAuthWithPath() throws Exception { MockWebServer mockWebServer = new MockWebServer(); <START> mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody("{\"ok\":true," + <END> "\"name\":\"root\",\"roles\":[\"_admin\"]}")); mockWebServer.enqueue(MockWebServerResources.JSON_OK); CloudantClient client = ClientBuilder.url(mockWebServer.url("/pathex").url()) .username("user") .password("password") .build(); client.database("test", true); assertThat("_session is the second element of the path", mockWebServer.takeRequest().getPath(), is("/pathex/_session")); }</code><technical_language>I a pre-canned OK cookie response in MockWebServerResources.OK_COOKIE</technical_language>

Target:
public void testCookieAuthWithPath() throws Exception { MockWebServer mockWebServer = new MockWebServer(); mockWebServer.enqueue(MockWebServerResources.OK_COOKIE); mockWebServer.enqueue(MockWebServerResources.JSON_OK); CloudantClient client = ClientBuilder.url(mockWebServer.url("/pathex").url()) .username("user") .password("password") .build(); client.database("test", true); assertThat("_session is the second element of the path", mockWebServer.takeRequest().getPath(), is("/pathex/_session")); }
Source:
<code>private void sendMail() { <START> String emailAddress = getString(R.string.mail_logger); <END> ArrayList<Uri> uris = new ArrayList<Uri>(); for (String file : Log_OC.getLogFileNames()) { File logFile = new File(mLogPath, file); if (logFile.exists()) { uris.add(Uri.fromFile(logFile)); } } Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE); intent.putExtra(Intent.EXTRA_EMAIL, emailAddress); intent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.log_send_mail_subject)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setType(MAIL_ATTACHMENT_TYPE); intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(this, getString(R.string.log_send_no_mail_app), Toast.LENGTH_LONG).show(); Log_OC.i(TAG, "Could not find app for sending log history."); } }</code><technical_language>Please, restore try - catch block. For moment need consider possibility setup.xml include "mail_logger" entry. This block prevents compilation fails in this case</technical_language>

Target:
private void sendMail() { String emailAddress; try { Class<?> stringClass = R.string.class; Field mailLoggerField = stringClass.getField("mail_logger"); int emailAddressId = (Integer) mailLoggerField.get(null); emailAddress = getString(emailAddressId); } catch (Exception e) { emailAddress = ""; } ArrayList<Uri> uris = new ArrayList<Uri>(); for (String file : Log_OC.getLogFileNames()) { File logFile = new File(mLogPath, file); if (logFile.exists()) { uris.add(Uri.fromFile(logFile)); } } Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE); intent.putExtra(Intent.EXTRA_EMAIL, emailAddress); String subject = String.format(getString(R.string.log_send_mail_subject), getString(R.string.app_name)); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setType(MAIL_ATTACHMENT_TYPE); intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(this, getString(R.string.log_send_no_mail_app), Toast.LENGTH_LONG).show(); Log_OC.i(TAG, "Could not find app for sending log history."); } }
Source:
<code>public Object loadConfiguration( File file ) throws IOException, ConfigurationIsCorruptedException { FileReader fr = null; org.sonatype.nexus.configuration.model.v2_2_0.Configuration conf = null; try { fr = new FileReader( file ); org.sonatype.nexus.configuration.model.v2_2_0.io.xpp3.NexusConfigurationXpp3Reader reader = new org.sonatype.nexus.configuration.model.v2_2_0.io.xpp3.NexusConfigurationXpp3Reader(); conf = reader.read( fr ); } catch ( XmlPullParserException e ) { throw new ConfigurationIsCorruptedException( file.getAbsolutePath(), e ); } finally { if ( fr != null ) { <START> fr.close(); <END> } } return conf; }</code><technical_language>Prefer call closeQuietly() if possible, eliminates null check</technical_language>

Target:
public Object loadConfiguration( File file ) throws IOException, ConfigurationIsCorruptedException { FileReader fr = null; org.sonatype.nexus.configuration.model.v2_2_0.Configuration conf = null; try { fr = new FileReader( file ); org.sonatype.nexus.configuration.model.v2_2_0.io.xpp3.NexusConfigurationXpp3Reader reader = new org.sonatype.nexus.configuration.model.v2_2_0.io.xpp3.NexusConfigurationXpp3Reader(); conf = reader.read( fr ); } catch ( XmlPullParserException e ) { throw new ConfigurationIsCorruptedException( file.getAbsolutePath(), e ); } finally { Closeables.closeQuietly( fr ); } return conf; }
Source:
<code>public SimpleCertificateResponseMessageType undoImportTruststore(ImportCertificateChainRequestMessageType request) { if (StringUtils.isBlank(request.getAlias()) || null == request.getRootCert() || CollectionUtils.isEmpty(request.getIntermediateList())) { <START> return buildSimpleResponse(false, "Undo import in Truststore required Alias, CA Root and CA Intermediate."); <END> } try { Map<String, Certificate> removeCerts = convertCertificateMap(request.getAlias(), request); removeCertificatesFrom(getTempTruststore(), removeCerts.values()); saveTempTruststore(); } catch (UtilException | KeyStoreException | CertificateManagerException ex) { LOG.error("Error occured on undo import in temporary TrustStore: {}", ex.getLocalizedMessage(), ex); return buildSimpleResponse(false, "Error occured on undo import in temporary TrustStore."); } return buildSimpleResponse(true, "Undo import in temporary TrustStore successful."); }</code><technical_language>"Undoing import requires Alias, CA Root, Intermediate certificates"</technical_language>

Target:
public SimpleCertificateResponseMessageType undoImportTruststore(ImportCertificateChainRequestMessageType request) { if (null == request.getRootCert() || CollectionUtils.isEmpty(request.getIntermediateList())) { return buildSimpleResponse(false, "Undoing an import requires the CA Root, and Intermediate certificates."); } try { Map<String, Certificate> removeCerts = convertCertificateMap("noalias", request); removeCertificatesFrom(getTempTruststore(), removeCerts.values()); saveTempTruststore(); } catch (UtilException | KeyStoreException | CertificateManagerException ex) { LOG.error("Error occured on undo import in temporary TrustStore: {}", ex.getLocalizedMessage(), ex); return buildSimpleResponse(false, "Error occured on undo import in temporary TrustStore."); } return buildSimpleResponse(true, "Undo import in temporary TrustStore successful."); }
Source:
<code>public boolean isRuntimeOnlyRegistrationValid() { <START> return processType.isServer(); <END> }</code><technical_language>Host Controller extensions</technical_language>

Target:
public boolean isRuntimeOnlyRegistrationValid() { if (processType.isServer()) { return true; } if (processType == ProcessType.HOST_CONTROLLER && extensionRegistryType == ExtensionRegistryType.HOST) { return true; } return false; }
Source:
<code>private void assertSuccess(ReadableStreamChannel readableStreamChannel, CountDownLatch readCompleteLatch, AtomicLong readCompleteResult, AtomicReference<Exception> readCompleteException) { try { ByteBufferAsyncWritableChannel asyncWritableChannel = new ByteBufferAsyncWritableChannel(); long written; Future<Long> readFuture = readableStreamChannel.readInto(asyncWritableChannel, null); int readBytes = 0; do { ByteBuffer buf = asyncWritableChannel.getNextChunk(); while (buf.hasRemaining()) { if (putContent[readBytes++] != buf.get()) { Exception e = new Exception("Content mismatch"); readCompleteException.set(e); asyncWritableChannel.resolveOldestChunk(e); return; } } asyncWritableChannel.resolveOldestChunk(null); } while (readBytes < blobSize); <START> written = readFuture.get(); <END> readCompleteResult.set(written); } catch (Exception e) { readCompleteException.set(e); } finally { readCompleteLatch.countDown(); } }</code><technical_language>incase more data in channel ? assert this</technical_language>

Target:
private void assertSuccess(ReadableStreamChannel readableStreamChannel, CountDownLatch readCompleteLatch, AtomicLong readCompleteResult, AtomicReference<Exception> readCompleteException) { try { ByteBufferAsyncWritableChannel asyncWritableChannel = new ByteBufferAsyncWritableChannel(); long written; Future<Long> readIntoFuture = readableStreamChannel.readInto(asyncWritableChannel, null); int readBytes = 0; do { ByteBuffer buf = asyncWritableChannel.getNextChunk(); int bufLength = buf.remaining(); Assert.assertTrue("total content read should not be greater than length of put content", readBytes + bufLength <= putContent.length); while (buf.hasRemaining()) { Assert.assertEquals("Get and Put blob content should match", putContent[readBytes++], buf.get()); } asyncWritableChannel.resolveOldestChunk(null); } while (readBytes < putContent.length); written = readIntoFuture.get(); Assert.assertEquals("the returned length in the future should be the length of data written", (long) readBytes, written); Assert.assertNull("There should be no more data in the channel", asyncWritableChannel.getNextChunk(0)); readCompleteResult.set(written); } catch (Exception e) { readCompleteException.set(e); } finally { readCompleteLatch.countDown(); } }
Source:
<code>public void testSetNoneDirectionAssociation() { <START> NonDirectionalAssociation directionalAssociation = new NonDirectionalAssociation(); <END> associationWriter.setDirectionAssociation(directionalAssociation); verify(association).setAssociationDirection(AssociationDirection.NONE); }</code><technical_language>change variable name nonDirectionalAssociation here</technical_language>

Target:
public void testSetNoneDirectionAssociation() { NonDirectionalAssociation nonDirectionalAssociation = new NonDirectionalAssociation(); associationWriter.setDirectionAssociation(nonDirectionalAssociation); verify(association).setAssociationDirection(AssociationDirection.NONE); }
Source:
<code>public void cleanup() throws Exception { context.turnOffAuthorisationSystem(); if (collection.getAdministrators() != null) { Group adminGroup = collection.getAdministrators(); collectionService.removeAdministrators(context, collection); <START> } <END> deleteWorkflowGroups(collection); delete(collection); }</code><technical_language>Please update this create Context, similar deleteWorkflowGroups(). run occasional Hibernate issues reusing global context for deletion of test data. practice is method in deleteWorkflowGroups() a try open a new context, deletes & completes</technical_language>

Target:
public void cleanup() throws Exception { deleteAdminGroup(); deleteDefaultReadGroups(collection); deleteWorkflowGroups(collection); delete(collection); }
Source:
<code>protected boolean checkConnection(ClientHelper p4) { p4.log("\nP4 Task: establishing connection."); if (!p4.isConnected()) { p4.log("P4: Server connection error: " + credential.getP4port()); <START> return false; <END> } p4.log("... server: " + credential.getP4port()); String host; try { host = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { host = "unknown"; } p4.log("... node: " + host); return true; }</code><technical_language>avoid NPE getCredential() catch exception</technical_language>

Target:
protected boolean checkConnection(ClientHelper p4) { p4.log("\nP4 Task: establishing connection."); if (!p4.isConnected()) { p4.log("P4: Server connection error: " + p4.getPort()); return false; } p4.log("... server: " + p4.getPort()); String host; try { host = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { host = "unknown"; } p4.log("... node: " + host); return true; }
Source:
<code><START> public JavaVersionImpl(int javaVersion) { <END> this.javaVersion = javaVersion; this.initialized = true; }</code><technical_language>deserve a @VisibleForTesting</technical_language>

Target:
public JavaVersionImpl(int javaVersion) { this.javaVersion = javaVersion; }
Source:
<code><START> public void setLocalityGroups(Map<String,Set<Text>> groups) { <END> LocalityGroupUtil.ensureNonOverlappingGroups(groups); localityProps = new HashMap<>(); for (Entry<String,Set<Text>> entry : groups.entrySet()) { Set<Text> colFams = entry.getValue(); String value = LocalityGroupUtil.encodeColumnFamilies(colFams); localityProps.put(Property.TABLE_LOCALITY_GROUP_PREFIX + entry.getKey(), value); } localityProps.put(Property.TABLE_LOCALITY_GROUPS.getKey(), groups.keySet().stream().collect(Collectors.joining(","))); }</code><technical_language>For consistency existing methods, nice return this</technical_language>

Target:
public NewTableConfiguration setLocalityGroups(Map<String,Set<Text>> groups) { LocalityGroupUtil.ensureNonOverlappingGroups(groups); Map<String,String> tmp = new HashMap<>(); for (Entry<String,Set<Text>> entry : groups.entrySet()) { Set<Text> colFams = entry.getValue(); String value = LocalityGroupUtil.encodeColumnFamilies(colFams); tmp.put(Property.TABLE_LOCALITY_GROUP_PREFIX + entry.getKey(), value); } tmp.put(Property.TABLE_LOCALITY_GROUPS.getKey(), groups.keySet().stream().collect(Collectors.joining(","))); checkDisjoint(properties, tmp, "locality groups"); localityProps = tmp; return this; }
Source:
<code>private ArtifactReadable findDispoArtifact(BranchId branch, String artId, IArtifactType type) { return getQuery() .fromBranch(branch) .andUuid(Long.valueOf(artId)) <START> .getResults().getOneOrNull(); <END> }</code><technical_language>this change requires of callers test for null, getExactlyOne throws exception, this change</technical_language>

Target:
private ArtifactReadable findDispoArtifact(BranchId branch, String artId, IArtifactType type) { return getQuery() .fromBranch(branch) .andUuid(Long.valueOf(artId)) .getResults().getExactlyOne(); }
Source:
<code>private void redraw(final IProgressMonitor statusMonitor, final long startTime, final long endTime, final List<ISegment> displayData) { fDisplayData = displayData; <START> fDirty.incrementAndGet(); <END> Display.getDefault().asyncExec(new Runnable() { @Override public void run() { updateData(startTime, endTime, displayData.size(), statusMonitor); fDirty.decrementAndGet(); } }); }</code><technical_language>increment redraw entry this is dirty</technical_language>

Target:
private void redraw(final IProgressMonitor statusMonitor, final long startTime, final long endTime, final List<ISegment> displayData) { fDisplayData = displayData; fDirty.incrementAndGet(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { updateData(startTime, endTime, displayData.size(), statusMonitor); } finally { fDirty.decrementAndGet(); } } }); }
Source:
<code>public void before() throws Exception { taskMetricStore = Mockito.mock(MetricStore.TaskMetricStore.class); MetricStore metricStore = Mockito.mock(MetricStore.class); Mockito.when(metricStore.getTaskMetricStore(TEST_JOB_ID.toString(), TEST_VERTEX_ID.toString())) .thenReturn(taskMetricStore); metricFetcher = Mockito.mock(MetricFetcher.class); Mockito.when(metricFetcher.getMetricStore()).thenReturn(metricStore); watermarkHandler = new JobVertexWatermarksHandler( Mockito.mock(LeaderGatewayRetriever.class), Time.seconds(1), Collections.emptyMap(), metricFetcher, <START> Mockito.mock(DefaultExecutionGraphCache.class), <END> Mockito.mock(Executor.class)); final Map<String, String> pathParameters = new HashMap<>(); pathParameters.put(JobIDPathParameter.KEY, TEST_JOB_ID.toString()); pathParameters.put(JobVertexIdPathParameter.KEY, TEST_VERTEX_ID.toString()); request = new HandlerRequest<>(EmptyRequestBody.getInstance(), new JobVertexMessageParameters(), pathParameters, Collections.emptyMap()); vertex = Mockito.mock(AccessExecutionJobVertex.class); Mockito.when(vertex.getJobVertexId()).thenReturn(TEST_VERTEX_ID); AccessExecutionVertex firstTask = Mockito.mock(AccessExecutionVertex.class); AccessExecutionVertex secondTask = Mockito.mock(AccessExecutionVertex.class); Mockito.when(firstTask.getParallelSubtaskIndex()).thenReturn(0); Mockito.when(secondTask.getParallelSubtaskIndex()).thenReturn(1); AccessExecutionVertex[] accessExecutionVertices = {firstTask, secondTask}; Mockito.when(vertex.getTaskVertices()).thenReturn(accessExecutionVertices); }</code><technical_language>noop cache instead</technical_language>

Target:
public void before() throws Exception { taskMetricStore = Mockito.mock(MetricStore.TaskMetricStore.class); MetricStore metricStore = Mockito.mock(MetricStore.class); Mockito.when(metricStore.getTaskMetricStore(TEST_JOB_ID.toString(), TEST_VERTEX_ID.toString())) .thenReturn(taskMetricStore); metricFetcher = Mockito.mock(MetricFetcher.class); Mockito.when(metricFetcher.getMetricStore()).thenReturn(metricStore); watermarkHandler = new JobVertexWatermarksHandler( Mockito.mock(LeaderGatewayRetriever.class), Time.seconds(1), Collections.emptyMap(), metricFetcher, NoOpExecutionGraphCache.INSTANCE, Mockito.mock(Executor.class)); final Map<String, String> pathParameters = new HashMap<>(); pathParameters.put(JobIDPathParameter.KEY, TEST_JOB_ID.toString()); pathParameters.put(JobVertexIdPathParameter.KEY, TEST_VERTEX_ID.toString()); request = new HandlerRequest<>(EmptyRequestBody.getInstance(), new JobVertexMessageParameters(), pathParameters, Collections.emptyMap()); vertex = Mockito.mock(AccessExecutionJobVertex.class); Mockito.when(vertex.getJobVertexId()).thenReturn(TEST_VERTEX_ID); AccessExecutionVertex firstTask = Mockito.mock(AccessExecutionVertex.class); AccessExecutionVertex secondTask = Mockito.mock(AccessExecutionVertex.class); Mockito.when(firstTask.getParallelSubtaskIndex()).thenReturn(0); Mockito.when(secondTask.getParallelSubtaskIndex()).thenReturn(1); AccessExecutionVertex[] accessExecutionVertices = {firstTask, secondTask}; Mockito.when(vertex.getTaskVertices()).thenReturn(accessExecutionVertices); }
Source:
<code>public boolean createIfNotExists(String tableName, NewTableConfiguration ntc) throws AccumuloException, AccumuloSecurityException { try { <START> if (!exists(tableName)) { <END> create(tableName, ntc); return true; } else { return false; } } catch (TableExistsException e) { throw new AssertionError(e); } }</code><technical_language>This code a race condition. another thread creates a table exists() create(). avoids race condition. java try{ create(tableName, ntc); return true; } catch (TableExistsException e) { return false }</technical_language>

Target:
public boolean createIfNotExists(String tableName, NewTableConfiguration ntc) throws AccumuloException, AccumuloSecurityException { try { create(tableName, ntc); return true; } catch (TableExistsException e) { return false; } }