auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setValues(SolrDocument document) { super.setValues(document); <START> this.firstName = Objects.toString(document.getFieldValue("first_name")); <END> this.lastName = Objects.toString(document.getFieldValue("last_name")); nameVariants = new ArrayList<String>(); Collection<Object> document_name_variant = document.getFieldValues("name_variant"); if (document_name_variant != null) { for (Object name_variants : document_name_variant) { addNameVariant(String.valueOf(name_variants)); } } if (document.getFieldValue("institution") != null) { this.institution = String.valueOf(document.getFieldValue("institution")); } Collection<Object> emails = document.getFieldValues("email"); if (emails != null) { for (Object email : emails) { addEmail(String.valueOf(email)); } } }</code><technical_language>ObjectUtils.toString(null) returns "" while Objects.toString(null) returns "null. OK? If not, Objects.toString(thing, "") exact replacement</technical_language>

Target:
public void setValues(SolrDocument document) { super.setValues(document); this.firstName = Objects.toString(document.getFieldValue("first_name"), ""); this.lastName = Objects.toString(document.getFieldValue("last_name"), ""); nameVariants = new ArrayList<String>(); Collection<Object> document_name_variant = document.getFieldValues("name_variant"); if (document_name_variant != null) { for (Object name_variants : document_name_variant) { addNameVariant(String.valueOf(name_variants)); } } if (document.getFieldValue("institution") != null) { this.institution = String.valueOf(document.getFieldValue("institution")); } Collection<Object> emails = document.getFieldValues("email"); if (emails != null) { for (Object email : emails) { addEmail(String.valueOf(email)); } } }
Source:
<code>public static ValueIndexItem property(@NonNull String property) { if(property == null) { throw new IllegalArgumentException("property is null"); <START> } <END> return new ValueIndexItem(Expression.property(property)); }</code><technical_language>Summary: 1. Removed @throws IllegalArgumentException alias is null. is required declare throwing a runtime exception. declared this in other places e.g. Database class well. 2. Remove extra empty line if(<variable> == null) {. 3. Add a space if (. if (<variable> == null). 4. Add . (full stop) end of "... is null" -> ... is null. 5. Do for other methods</technical_language>

Target:
public static ValueIndexItem property(@NonNull String property) { if (property == null) { throw new IllegalArgumentException("property is null."); } return new ValueIndexItem(Expression.property(property)); }
Source:
<code>public static ZombieType toNative(org.spongepowered.api.data.type.ZombieType type, @Nullable Profession profession) { if(type == ZombieTypes.NORMAL) { return ZombieType.NORMAL; } else if(type == ZombieTypes.HUSK) { return ZombieType.HUSK; } else { <START> return ZOMBIE_TYPE_MAP.get(profession); <END> } }</code><technical_language>this getOrDefault avoid null returns</technical_language>

Target:
public static ZombieType toNative(org.spongepowered.api.data.type.ZombieType type, @Nullable Profession profession) { if (type == ZombieTypes.NORMAL) { return ZombieType.NORMAL; } else if (type == ZombieTypes.HUSK) { return ZombieType.HUSK; } else { return ZOMBIE_TYPE_MAP.getOrDefault(profession, ZombieType.NORMAL); } }
Source:
<code>public static void main(String[] args) { if (args.length < 1 || !"encryption".equals(args[0]) || !"decryption".equals(args[0] )){ LOG.error("Expect encryption/decryption action parameter"); <START> return; <END> } boolean encrypt = "encryption".equals(args[0]); SensitiveDataEncryption sensitiveDataEncryption = null; try { Injector injector = Guice.createInjector(new EncryptionHelperControllerModule(), new EncryptionHelperAuditModule(), new LdapModule()); sensitiveDataEncryption = injector.getInstance(SensitiveDataEncryption.class); sensitiveDataEncryption.startPersistenceService(); AmbariManagementController ambariManagementController = injector.getInstance(AmbariManagementController.class); Encryptor<Config> configEncryptor = injector.getInstance(ConfigPropertiesEncryptor.class); Clusters clusters = ambariManagementController.getClusters(); if (clusters != null) { Map<String, Cluster> clusterMap = clusters.getClusters(); if (clusterMap != null && !clusterMap.isEmpty()) { for (final Cluster cluster : clusterMap.values()) { Collection<Config> configs = cluster.getAllConfigs(); for (Config config : configs) { if (encrypt) { config.encryptSensitiveDataAndSave(configEncryptor); } else { config.decryptSensitiveDataAndSave(configEncryptor); } } } } } } catch (Throwable e) { LOG.error("Exception occurred during config encryption/decryption:", e); } finally { if (sensitiveDataEncryption != null) { sensitiveDataEncryption.stopPersistenceService(); } } }</code><technical_language>exit -1</technical_language>

Target:
public static void main(String[] args) { if (args.length < 1 || (!"encryption".equals(args[0]) && !"decryption".equals(args[0] ))){ LOG.error("The action parameter (\"encryption\" or \"decryption\") is required"); System.exit(-1); } boolean encrypt = "encryption".equals(args[0]); SensitiveDataEncryption sensitiveDataEncryption = null; try { Injector injector = Guice.createInjector(new EncryptionHelperControllerModule(), new EncryptionHelperAuditModule(), new LdapModule()); sensitiveDataEncryption = injector.getInstance(SensitiveDataEncryption.class); sensitiveDataEncryption.startPersistenceService(); sensitiveDataEncryption.doEncryption(encrypt); } catch (Throwable e) { LOG.error("Exception occurred during config encryption/decryption:", e); } finally { if (sensitiveDataEncryption != null) { sensitiveDataEncryption.stopPersistenceService(); } } }
Source:
<code>public Response doImport(Action action) { validateParameters(action, "cluster.id|name"); Guid destStorageDomainId = getDestStorageDomainId(action); ImportVmTemplateParameters params = new ImportVmTemplateParameters(parent.getDataCenterId(destStorageDomainId), parent.getStorageDomainId(), destStorageDomainId, getClusterId(action), getEntity()); params.setImageToDestinationDomainMap(getDiskToDestinationMap(action)); <START> params.setForceOverride(action.isSetForce() ? action.isForce() : false); <END> if (action.isSetClone()){ params.setImportAsNewEntity(action.isClone()); if(action.isSetTemplate() && action.getTemplate().isSetName()) { params.getVmTemplate().setname(action.getTemplate().getName()); } } return doAction(VdcActionType.ImportVmTemplate, params, action); }</code><technical_language>in /export action action.isExclusive(), please do here</technical_language>

Target:
public Response doImport(Action action) { validateParameters(action, "cluster.id|name"); Guid destStorageDomainId = getDestStorageDomainId(action); ImportVmTemplateParameters params = new ImportVmTemplateParameters(parent.getDataCenterId(destStorageDomainId), parent.getStorageDomainId(), destStorageDomainId, getClusterId(action), getEntity()); params.setImageToDestinationDomainMap(getDiskToDestinationMap(action)); params.setForceOverride(action.isSetExclusive() ? action.isExclusive() : false); if (action.isSetClone()){ params.setImportAsNewEntity(action.isClone()); if(action.isSetTemplate() && action.getTemplate().isSetName()) { params.getVmTemplate().setname(action.getTemplate().getName()); } } return doAction(VdcActionType.ImportVmTemplate, params, action); }
Source:
<code>private void resetTabsValidity() { setIsGeneralTabValid(true); setIsSystemTabValid(true); setIsFirstRunTabValid(true); setIsDisplayTabValid(true); setIsHostTabValid(true); setIsAllocationTabValid(true); setIsBootSequenceTabValid(true); setRngTabValid(true); <START> setIsCustomPropertiesTabValid(true); <END> }</code><technical_language>reset isValid entity well, a separate call in a lot of places</technical_language>

Target:
private void resetTabsValidity() { setIsGeneralTabValid(true); setIsSystemTabValid(true); setIsFirstRunTabValid(true); setIsDisplayTabValid(true); setIsHostTabValid(true); setIsAllocationTabValid(true); setIsBootSequenceTabValid(true); setRngTabValid(true); setIsCustomPropertiesTabValid(true); getValid().setEntity(true); }
Source:
<code>private void initSwagger() { final Info info = new Info() .version(OpenmrsConstants.OPENMRS_VERSION_SHORT) .title("OpenMRS API Docs") .description("OpenMRS RESTful API documentation generated by Swagger") <START> .contact(new Contact().name("OpenMRS Talk").url("<LINK_2>")) <END> .license(new License().name("MPL-2.0 w/ HD").url("<LINK_0>")); this.swagger .info(info) .scheme(Scheme.HTTP) .securityDefinition("basic_auth", new BasicAuthDefinition()) .security(new SecurityRequirement().requirement("basic_auth")) .consumes("application/json") .produces("application/json"); String host = baseUrl.split("/")[0]; String basePath = baseUrl.substring(baseUrl.indexOf("/")) + "/v1"; this.swagger .host(host) .basePath(basePath); }</code><technical_language>is reason replacing openmrs.org talk.openmrs.org</technical_language>

Target:
private void initSwagger() { final Info info = new Info() .version(OpenmrsConstants.OPENMRS_VERSION_SHORT) .title("OpenMRS API Docs") .description("OpenMRS RESTful API specification") .contact(new Contact().url("<LINK_1>")) .license(new License().name("MPL-2.0 w/ HD").url("<LINK_0>")); this.swagger .info(info) .scheme(Scheme.HTTP) .securityDefinition("basic_auth", new BasicAuthDefinition()) .security(new SecurityRequirement().requirement("basic_auth")) .consumes("application/json") .produces("application/json"); String host = baseUrl.split("/")[0]; String basePath = baseUrl.substring(baseUrl.indexOf("/")) + "/v1"; this.swagger .host(host) .basePath(basePath); }
Source:
<code>public void testGetSelectedNodeWhenNotSelected() { selectedItems.clear(); assertEquals(null, ClientUtils.getSelectedNode(diagram, viewerSession)); <START> assertEquals(null, ClientUtils.getSelectedNode(diagram, editorSession)); <END> }</code><technical_language>assertNull instead</technical_language>

Target:
public void testGetSelectedNodeWhenNotSelected() { selectedItems.clear(); assertNull(ClientUtils.getSelectedNode(diagram, viewerSession)); assertNull(ClientUtils.getSelectedNode(diagram, editorSession)); }
Source:
<code>private static ExpressionTree mostLeft(ExpressionTree arg) { ExpressionTree res = arg; <START> while (res.is(Tree.Kind.PLUS)) { <END> res = ((BinaryExpressionTree) res).leftOperand(); } return res; }</code><technical_language>skipping parenthesis, raise issue for following: conn.setRequestProperty("Authorization", ("Basic " + encoding + encoding))</technical_language>

Target:
private static ExpressionTree mostLeft(ExpressionTree arg) { ExpressionTree res = ExpressionUtils.skipParentheses(arg); while (res.is(Tree.Kind.PLUS)) { res = ExpressionUtils.skipParentheses(((BinaryExpressionTree) res).leftOperand()); } return res; }
Source:
<code>public void refresh() { <START> ChannelBindingAdapter adapter = binderAdapter(); <END> adapter.setOutputChannels(getOutputChannels()); adapter.setInputChannels(getInputChannels()); }</code><technical_language>nitpick: bindingAdapter</technical_language>

Target:
public void refresh() { ChannelBindingAdapter adapter = bindingAdapter(); adapter.setOutputChannels(getOutputChannels()); adapter.setInputChannels(getInputChannels()); }
Source:
<code>public QuestionsBlock getQuestionsBlockByUserId(String userID, String appointmentId) throws QuestionsBlockNotFound, InterviewNotFoundException, HttpRequestException, WrongCriteriaException { questionsBlocks = interviewService.getInterviewByAppointmentID(appointmentId).getQuestionsBlocks(); for (QuestionsBlock questionsBlock1 : questionsBlocks){ try{ if (questionsBlock1.getUser().getId().equals(userID)) return questionsBlock1; } <START> catch(NullPointerException e){} <END> } throw new QuestionsBlockNotFound("Wrong userID or appointmentId"); }</code><technical_language>Empty catch block wrong logic</technical_language>

Target:
public QuestionsBlock getQuestionsBlockByUserId(String userID, String appointmentId) throws QuestionsBlockNotFound, InterviewNotFoundException, HttpRequestException, WrongCriteriaException { questionsBlocks = interviewService.getInterviewByAppointmentID(appointmentId).getQuestionsBlocks(); for (QuestionsBlock questionsBlock1 : questionsBlocks){ if (questionsBlock1.getUser() != null && questionsBlock1.getUser().getId().equals(userID)) return questionsBlock1; } throw new QuestionsBlockNotFound("Wrong userID or appointmentId"); }
Source:
<code>private Map<Integer, List<CommitItem>> getSeverityItems() { Map<Integer, List<CommitItem>> result = new HashMap<>(); for (final CommitItem item : items) { if (item.getProblemSeverity() >= IMarker.SEVERITY_WARNING) { if (result.get(item.getProblemSeverity()) == null) { result.put(item.getProblemSeverity(), <START> new ArrayList<CommitItem>() { <END> { add(item); } }); } else { result.get(item.getProblemSeverity()).add(item); } } } return result; }</code><technical_language>I create anonymous class add item. done more "standard" code</technical_language>

Target:
private Map<Integer, List<CommitItem>> getSeverityItems() { Map<Integer, List<CommitItem>> result = new HashMap<>(); for (final CommitItem item : items) { if (item.getProblemSeverity() >= IMarker.SEVERITY_WARNING) { if (result.get(item.getProblemSeverity()) == null) { List<CommitItem> itemsList = new ArrayList<>(); itemsList.add(item); result.put(item.getProblemSeverity(), itemsList); } else { result.get(item.getProblemSeverity()).add(item); } } } return result; }
Source:
<code>public String getProcessForm(String containerId, String processId, String language) { if( config.isRest() ) { Map<String, Object> valuesMap = new HashMap<String, Object>(); valuesMap.put(RestURI.CONTAINER_ID, containerId); valuesMap.put(RestURI.PROCESS_ID, processId); return makeHttpGetRequestAndCreateRawResponse( <START> build(loadBalancer.getUrl(), FORM_URI + "/" + PROCESS_FORM_GET_URI, valuesMap) + "?lang=" + language); <END> } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new DescriptorCommand( "FormService", "getFormDisplayProcess", new Object[]{containerId, processId, language, true} )) ); ServiceResponse<String> response = (ServiceResponse<String>) executeJmsCommand( script, DescriptorCommand.class.getName(), "BPM-UI", containerId ).getResponses().get(0); throwExceptionOnFailure(response); return response.getResult(); } }</code><technical_language>is missing "filter" parameter</technical_language>

Target:
public String getProcessForm(String containerId, String processId, String language) { if( config.isRest() ) { Map<String, Object> valuesMap = new HashMap<String, Object>(); valuesMap.put(RestURI.CONTAINER_ID, containerId); valuesMap.put(RestURI.PROCESS_ID, processId); return makeHttpGetRequestAndCreateRawResponse( build(loadBalancer.getUrl(), FORM_URI + "/" + PROCESS_FORM_GET_URI, valuesMap) + "?lang=" + language + "&filter=true"); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new DescriptorCommand( "FormService", "getFormDisplayProcess", new Object[]{containerId, processId, language, true} )) ); ServiceResponse<String> response = (ServiceResponse<String>) executeJmsCommand( script, DescriptorCommand.class.getName(), "BPM-UI", containerId ).getResponses().get(0); throwExceptionOnFailure(response); return response.getResult(); } }
Source:
<code>public String addCustomer(final String name) { if (LOG.isTraceEnabled()) { LOG.trace("CustomerManager.addCustomer(name=" + name + ")"); } <START> beginTransaction(); <END> try { final Customer customer = new Customer(customerDAO.getNextId(), name); customerDAO.insert(customer); commitTransaction(); return "customerAdded"; } catch (Exception e) { LOG.warn(e.getMessage(), e); rollbackTransaction(); return "customerDuplicate"; } }</code><technical_language>Personally, I feel putting this code in a beginTransaction method spoils readability of code, especially beginTransaction is called here, for commitTransaction rollbackTransaction, wdyt</technical_language>

Target:
public String addCustomer(final String name) throws SystemException, NotSupportedException, RollbackException { if (LOG.isTraceEnabled()) { LOG.trace("CustomerManager.addCustomer(name=" + name + ")"); } final TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); transactionManager.begin(); transactionManager.getTransaction().enlistResource(new DummyXAResource()); try { final Customer customer = new Customer(customerDAO.getNextId(), name); customerDAO.insert(customer); transactionManager.commit(); return "customerAdded"; } catch (Exception e) { LOG.warn(e.getMessage(), e); transactionManager.rollback(); return "customerDuplicate"; } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display_points); mapButton = (Button) findViewById(R.id.mapButton); nextScenarioButton = (Button) findViewById(R.id.nextScenarioButton); Integer currentPointsValue = getIntent().getExtras().getInt(getString(R.string.current_points_key)); currentPointsTextView = (TextView) findViewById(R.id.current_points_text); totalPointsTextView = (TextView) findViewById(R.id.total_points_text); currentPointsTextView.setText(currentPointsValue.toString()); Integer totalPointsValue = SessionHistory.totalPoints; <START> totalPointsTextView.setText(totalPointsValue.toString()); <END> mapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(Activity.RESULT_CANCELED, new Intent()); finish(); } }); nextScenarioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(Activity.RESULT_OK, new Intent()); finish(); } }); }</code><technical_language>need declare this variable here. do setText(new Integer(SessionHistory.totalPoints) instead</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display_points); mapButton = (Button) findViewById(R.id.mapButton); nextScenarioButton = (Button) findViewById(R.id.nextScenarioButton); Integer currentPointsValue = getIntent().getExtras().getInt(Keys.currentPointsKey); currentPointsTextView = (TextView) findViewById(R.id.current_points_text); totalPointsTextView = (TextView) findViewById(R.id.total_points_text); currentPointsTextView.setText(currentPointsValue.toString()); totalPointsTextView.setText(new Integer(SessionHistory.totalPoints).toString()); mapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(Activity.RESULT_CANCELED, new Intent()); finish(); } }); nextScenarioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(Activity.RESULT_OK, new Intent()); finish(); } }); }
Source:
<code>private String convertFipsPoCountryOptionToFipsCountryCode(String poCountryOption) { <START> if (StringUtils.isNotBlank(poCountryOption) <END> && StringUtils.equalsIgnoreCase(poCountryOption, PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.UNITED_STATES.getPmwCountryOptionAsString())) { return PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.UNITED_STATES.getFipsCountryCode(); } else if (StringUtils.isNotBlank(poCountryOption) && StringUtils.equalsIgnoreCase(poCountryOption, PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.CANADA.getPmwCountryOptionAsString())) { return PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.CANADA.getFipsCountryCode(); } else if (StringUtils.isNotBlank(poCountryOption) && StringUtils.equalsIgnoreCase(poCountryOption, PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.AUSTRALIA.getPmwCountryOptionAsString())) { return PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.AUSTRALIA.getFipsCountryCode(); } else if (StringUtils.isNotBlank(poCountryOption) && StringUtils.equalsIgnoreCase(poCountryOption, PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.OTHER.getPmwCountryOptionAsString())) { return PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.OTHER.getFipsCountryCode(); } return KFSConstants.EMPTY_STRING; }</code><technical_language>StringUtils.isNotBlank() check is duplicated in "if" "else if" condition. I recommend adding some short-circuit logic in event of a blank country option. Also, StringUtils.equalsIgnoreCase() null-safe, simplifying this</technical_language>

Target:
private String convertFipsPoCountryOptionToFipsCountryCode(String poCountryOption) { if (StringUtils.isBlank(poCountryOption)) { return KFSConstants.EMPTY_STRING; } else if (StringUtils.equalsIgnoreCase(poCountryOption, PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.UNITED_STATES.getPmwCountryOptionAsString())) { return PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.UNITED_STATES.getFipsCountryCode(); } else if (StringUtils.equalsIgnoreCase(poCountryOption, PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.CANADA.getPmwCountryOptionAsString())) { return PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.CANADA.getFipsCountryCode(); } else if (StringUtils.equalsIgnoreCase(poCountryOption, PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.AUSTRALIA.getPmwCountryOptionAsString())) { return PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.AUSTRALIA.getFipsCountryCode(); } else if (StringUtils.equalsIgnoreCase(poCountryOption, PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.OTHER.getPmwCountryOptionAsString())) { return PaymentWorksConstants.PaymentWorksPurchaseOrderCountryFipsOption.OTHER.getFipsCountryCode(); } return KFSConstants.EMPTY_STRING; }
Source:
<code><START> public void testChildPredicate() throws Exception { <END> final Predicate<Edge> predicate = CaseManagementCommandUtil.childPredicate(); final Edge edge = mock(Edge.class); when(edge.getContent()).thenReturn(mock(Child.class)); assertTrue(predicate.test(edge)); }</code><technical_language>Exception is thrown</technical_language>

Target:
public void testChildPredicate() { final Predicate<Edge> predicate = CaseManagementCommandUtil.childPredicate(); final Edge edge = mock(Edge.class); when(edge.getContent()).thenReturn(mock(Child.class)); assertTrue(predicate.test(edge)); }
Source:
<code>public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); System.out.println("Usage: MatrixVectorMul [--output <path>] [--dimension <dimension> --data-size <data_size>] [--resource-name <resource_name>]"); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.getConfig().setGlobalJobParameters(params); int dimension; if (params.has("dimension")) { <START> dimension = params.getInt("dimension"); <END> } else { System.out.println(String.format("Executing MatrixVectorMul example with default vector dimension %d.\nUse --dimension to specify dimension of input vector.", DEFAULT_DIM)); dimension = DEFAULT_DIM; } int dataSize; if (params.has("data-size")) { dataSize = params.getInt("data-size"); } else { System.out.println(String.format("Executing MatrixVectorMul example with default data size %d.\nUse --data-size to specify size of the vector stream.", DEFAULT_DATA_SIZE)); dataSize = DEFAULT_DATA_SIZE; } String resourceName; if (params.has("resource-name")) { resourceName = params.get("resource-name"); } else { System.out.println(String.format("Executing MatrixVectorMul example with default resource name %s.\nUse --resource-name to specify resource name of GPU.", DEFAULT_RESOURCE_NAME)); resourceName = DEFAULT_RESOURCE_NAME; } DataStream<List<Float>> result = env.addSource(new RandomVectorSource(dimension, dataSize)) .map(new Multiplier(dimension, resourceName)); if (params.has("output")) { result.addSink(StreamingFileSink.forRowFormat(new Path(params.get("output")), new SimpleStringEncoder<List<Float>>()).build()); } else { System.out.println("Printing result to stdout. Use --output to specify output path."); result.print(); } env.execute("Matrix-Vector Multiplication"); }</code><technical_language>params.getInt("dimension", DEFAULT_DIM)</technical_language>

Target:
public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); System.out.println("Usage: MatrixVectorMul [--output <path>] [--dimension <dimension> --data-size <data_size>] [--resource-name <resource_name>]"); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.getConfig().setGlobalJobParameters(params); final int dimension = params.getInt("dimension", DEFAULT_DIM); final int dataSize = params.getInt("data-size", DEFAULT_DATA_SIZE); final String resourceName = params.get("resource-name", DEFAULT_RESOURCE_NAME); DataStream<List<Float>> result = env.addSource(new RandomVectorSource(dimension, dataSize)) .map(new Multiplier(dimension, resourceName)); if (params.has("output")) { result.addSink(StreamingFileSink.forRowFormat(new Path(params.get("output")), new SimpleStringEncoder<List<Float>>()).build()); } else { System.out.println("Printing result to stdout. Use --output to specify output path."); result.print(); } env.execute("Matrix-Vector Multiplication"); }
Source:
<code>void shutdown() throws InterruptedException, StoreException, IOException { long startTimeInMs = time.milliseconds(); try { if (enabled.get()) { logger.info("Hard delete shutdown initiated for store ", dataDir); enabled.set(false); hardDeleteLock.lock(); if (awaitingAfterCaughtUp) { logger.info("HardDelete is awaiting after caught up for store ", dataDir); } else { logger.info("HardDelete in progress for store ", dataDir); } try { pauseCondition.signal(); } finally { hardDeleteLock.unlock(); } shutdownLatch.await(); logger.info("Hard delete shutdown complete for store ", dataDir); <START> } } finally { <END> metrics.hardDeleteShutdownTimeInMs.update(time.milliseconds() - startTimeInMs); } }</code><technical_language>here, remove StoreException, IOException in method signature</technical_language>

Target:
void shutdown() throws InterruptedException { long startTimeInMs = time.milliseconds(); try { if (enabled.get()) { logger.info("Hard delete shutdown initiated for store ", dataDir); enabled.set(false); hardDeleteLock.lock(); if (awaitingAfterCaughtUp) { logger.info("HardDelete is awaiting after caught up for store ", dataDir); } else { logger.info("HardDelete in progress for store ", dataDir); } try { pauseCondition.signal(); } finally { hardDeleteLock.unlock(); } shutdownLatch.await(); logger.info("Hard delete shutdown complete for store ", dataDir); } } finally { metrics.hardDeleteShutdownTimeInMs.update(time.milliseconds() - startTimeInMs); } }
Source:
<code>public static Supplier<Connection> buildEphemeralSqlite() { HikariConfig config = new HikariConfig(); config.setDriverClassName("org.sqlite.JDBC"); config.setJdbcUrl("jdbc:sqlite::memory:"); config.setConnectionTestQuery("SELECT 1"); config.setMaxLifetime(60000); config.setIdleTimeout(45000); <START> config.setMaximumPoolSize(50); END> HikariDataSource ds = new HikariDataSource(config); return () -> { try { return ds.getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } }; }</code><technical_language>50 1. Is intended</technical_language>

Target:
public static Supplier<Connection> buildEphemeralSqlite() { try { Connection memory = Sqlite.build(":memory:"); Connection instance = new Sqlite.UncloseableConnection(memory); return () -> instance; } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
<code>public void init(PinotConfiguration config) { Preconditions.checkArgument(!isNullOrEmpty(config.getProperty(REGION))); String region = config.getProperty(REGION); <START> disableAcl = config.getProperty(DISABLE_ACL, true); <END> AwsCredentialsProvider awsCredentialsProvider; try { if (!isNullOrEmpty(config.getProperty(ACCESS_KEY)) && !isNullOrEmpty(config.getProperty(SECRET_KEY))) { String accessKey = config.getProperty(ACCESS_KEY); String secretKey = config.getProperty(SECRET_KEY); AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create(accessKey, secretKey); awsCredentialsProvider = StaticCredentialsProvider.create(awsBasicCredentials); } else { awsCredentialsProvider = DefaultCredentialsProvider.create(); } S3ClientBuilder s3ClientBuilder = S3Client.builder().region(Region.of(region)).credentialsProvider(awsCredentialsProvider); if (!isNullOrEmpty(config.getProperty(ENDPOINT))) { String endpoint = config.getProperty(ENDPOINT); try { s3ClientBuilder.endpointOverride(new URI(endpoint)); } catch (URISyntaxException e) { throw new RuntimeException(e); } } _s3Client = s3ClientBuilder.build(); } catch (S3Exception e) { throw new RuntimeException("Could not initialize S3PinotFS", e); } }</code><technical_language>Create constant DEFAULT_DISABLE_ACL=true here</technical_language>

Target:
public void init(PinotConfiguration config) { Preconditions.checkArgument(!isNullOrEmpty(config.getProperty(REGION))); String region = config.getProperty(REGION); disableAcl = config.getProperty(DISABLE_ACL_CONFIG_KEY, DEFAULT_DISABLE_ACL); AwsCredentialsProvider awsCredentialsProvider; try { if (!isNullOrEmpty(config.getProperty(ACCESS_KEY)) && !isNullOrEmpty(config.getProperty(SECRET_KEY))) { String accessKey = config.getProperty(ACCESS_KEY); String secretKey = config.getProperty(SECRET_KEY); AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create(accessKey, secretKey); awsCredentialsProvider = StaticCredentialsProvider.create(awsBasicCredentials); } else { awsCredentialsProvider = DefaultCredentialsProvider.create(); } S3ClientBuilder s3ClientBuilder = S3Client.builder().region(Region.of(region)).credentialsProvider(awsCredentialsProvider); if (!isNullOrEmpty(config.getProperty(ENDPOINT))) { String endpoint = config.getProperty(ENDPOINT); try { s3ClientBuilder.endpointOverride(new URI(endpoint)); } catch (URISyntaxException e) { throw new RuntimeException(e); } } _s3Client = s3ClientBuilder.build(); } catch (S3Exception e) { throw new RuntimeException("Could not initialize S3PinotFS", e); } }
Source:
<code>DiskIOScheduler(Map<String, Throttler> throttlers) { if (throttlers != null) { <START> this.throttlers.putAll(throttlers); <END> } }</code><technical_language>minor: currently, i concurrent map instance in this class is required (might in future if allow injecting of throttlers). For now, this.throttlers = throttlers do</technical_language>

Target:
DiskIOScheduler(Map<String, Throttler> throttlers) { this.throttlers = throttlers != null ? throttlers : new HashMap<String, Throttler>(); }
Source:
<code>public void run() { try { scheduler.freeze(); while (!noOtherTaskIsRunning()) { Thread.sleep(10000); } removeOldBackups(); performBackup(); } catch (IOException | InterruptedException e) { <START> LOGGER.error(e); <END> } finally { scheduler.resume(); } }</code><technical_language>LOGGER.error("", e) exception message is printed is empty</technical_language>

Target:
public void run() { try { scheduler.freeze(); while (!noOtherTaskIsRunning()) { Thread.sleep(10000); } removeOldBackups(); performBackup(); } catch (IOException | InterruptedException e) { LOGGER.error("", e); } finally { scheduler.resume(); } }
Source:
<code>public void updateWith(Talk item, Room row, Date start, Date end, boolean isPlaceholder) { super.updateWith(item, row, start, end, isPlaceholder); <START> ((TalkView) itemView).updateWith(item); <END> }</code><technical_language>This is difficult understand is visibility of itemView. Is _safe_ cast TalkView? easy decide based this class. is a smell is amiss - if itemView is owned parent class, modifying direcrtly a subclass</technical_language>

Target:
public void updateWith(Talk item, Room row, Date start, Date end, boolean isPlaceholder) { super.updateWith(item, row, start, end, isPlaceholder); talkView.updateWith(item); }
Source:
<code>public Session toSession(SessionPropertyManager sessionPropertyManager) { return new Session( new QueryId(queryId), transactionId, clientTransactionSupport, <START> new Identity(user, InternalPrincipal.createPrincipal(getPrincipal())), <END> source, catalog, schema, timeZoneKey, locale, remoteUserAddress, userAgent, clientInfo, clientTags, startTime, systemProperties, catalogProperties, ImmutableMap.of(), sessionPropertyManager, preparedStatements); }</code><technical_language>instance method suggest principal field instead of getter. Also, this is rest of method does</technical_language>

Target:
public Session toSession(SessionPropertyManager sessionPropertyManager) { return new Session( new QueryId(queryId), transactionId, clientTransactionSupport, new Identity(user, InternalPrincipal.createPrincipal(principal)), source, catalog, schema, timeZoneKey, locale, remoteUserAddress, userAgent, clientInfo, clientTags, startTime, systemProperties, catalogProperties, ImmutableMap.of(), sessionPropertyManager, preparedStatements); }
Source:
<code><START> public static void main(String[] args) { <END> IllinoisLemmatizer lem = new IllinoisLemmatizer(); logger.info("Getting lemma for 'media': "); String lemma = lem.getLemma("media", "NNS"); logger.info(lemma); logger.info("Getting lemma for 'men': "); lemma = lem.getLemma("men", "NNS"); logger.info(lemma); logger.info("Getting lemmas for 'retakes': "); lemma = lem.getLemma("retakes", "VBZ"); logger.info(lemma); logger.info("Getting lemmas for 'putting': "); lemma = lem.getLemma("putting", "VBG"); logger.info(lemma); }</code><technical_language>main(), STDOUT</technical_language>

Target:
public static void main(String[] args) { IllinoisLemmatizer lem = new IllinoisLemmatizer(); System.out.println("Getting lemma for 'media': "); String lemma = lem.getLemma("media", "NNS"); System.out.println(lemma); System.out.println("Getting lemma for 'men': "); lemma = lem.getLemma("men", "NNS"); System.out.println(lemma); System.out.println("Getting lemmas for 'retakes': "); lemma = lem.getLemma("retakes", "VBZ"); System.out.println(lemma); System.out.println("Getting lemmas for 'putting': "); lemma = lem.getLemma("putting", "VBG"); System.out.println(lemma); }
Source:
<code>public double computeWithResultOption(MetricKey<O> key, T node, MetricVersion version, ResultOption option) { <START> checkKeyNotNull(key); <END> if (option == null) { throw new IllegalArgumentException("The result option may not be null"); } MetricVersion safeVersion = (version == null) ? Version.STANDARD : version; return getLanguageSpecificComputer().computeWithResultOption(key, node, false, safeVersion, option, getLanguageSpecificProjectMirror()); }</code><technical_language>for null checks (key + option) utility method java.util.Objects.requireNonNull, e.g. Objects.requireNonNull(key, "The metric key null"); Objects.requireNonNull(option, "The result option null");</technical_language>

Target:
public double computeWithResultOption(MetricKey<O> key, T node, MetricVersion version, ResultOption option) { Objects.requireNonNull(key, "The metric key must not be null"); Objects.requireNonNull(option, "The result option must not be null"); MetricVersion safeVersion = (version == null) ? Version.STANDARD : version; return getLanguageSpecificComputer().computeWithResultOption(key, node, false, safeVersion, option, getLanguageSpecificProjectMirror()); }
Source:
<code>protected List<OvfEntityData> getEntitiesFromStorageOvfDisk() { List<OvfEntityData> ovfEntitiesFromTar = Collections.emptyList(); boolean isUnregisteredDisksRetrieved = false; List<Disk> unregisteredDisks = getBackend().runInternalQuery(VdcQueryType.GetUnregisteredDisks, new GetUnregisteredDisksQueryParameters(getParameters().getStorageDomainId(), getVds().getStoragePoolId())).getReturnValue(); if (!unregisteredDisks.isEmpty()) { Pair<DiskImage, Long> ovfDiskAndSize = getLatestOVFDisk(unregisteredDisks); DiskImage ovfDisk = ovfDiskAndSize.getFirst(); if (ovfDisk != null) { try { VDSReturnValue retrievedByteData = runVdsCommand(VDSCommandType.RetrieveImageData, new ImageHttpAccessVDSCommandParameters(getVdsId(), getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), ovfDisk.getId(), ovfDisk.getImage().getId(), ovfDiskAndSize.getSecond())); if (retrievedByteData.getSucceeded()) { ovfEntitiesFromTar = OvfUtils.getOvfEntities((byte[]) retrievedByteData.getReturnValue(), getParameters().getStorageDomainId()); isUnregisteredDisksRetrieved = true; } <START> } catch (VdcBLLException e) { <END> log.errorFormat("Image data could not be retrieved for disk id {0} in storage domain id {1}", ovfDisk.getId(), getParameters().getStorageDomainId()); } } } if (!isUnregisteredDisksRetrieved) { AuditLogDirector.log(this, AuditLogType.RETRIEVE_OVF_STORE_FAILED); } return ovfEntitiesFromTar; }</code><technical_language>this separated runtime exception</technical_language>

Target:
protected List<OvfEntityData> getEntitiesFromStorageOvfDisk() { List<OvfEntityData> ovfEntitiesFromTar = Collections.emptyList(); boolean isOvfDataRetirieved = false; List<Disk> unregisteredDisks = getBackend().runInternalQuery(VdcQueryType.GetUnregisteredDisks, new GetUnregisteredDisksQueryParameters(getParameters().getStorageDomainId(), getVds().getStoragePoolId())).getReturnValue(); if (!unregisteredDisks.isEmpty()) { Pair<DiskImage, Long> ovfDiskAndSize = getLatestOVFDisk(unregisteredDisks); DiskImage ovfDisk = ovfDiskAndSize.getFirst(); if (ovfDisk != null) { try { VDSReturnValue retrievedByteData = runVdsCommand(VDSCommandType.RetrieveImageData, new ImageHttpAccessVDSCommandParameters(getVdsId(), getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), ovfDisk.getId(), ovfDisk.getImage().getId(), ovfDiskAndSize.getSecond())); if (retrievedByteData.getSucceeded()) { ovfEntitiesFromTar = OvfUtils.getOvfEntities((byte[]) retrievedByteData.getReturnValue(), getParameters().getStorageDomainId()); isOvfDataRetirieved = true; } } catch (RuntimeException e) { log.errorFormat("Image data could not be retrieved for disk id {0} in storage domain id {1}. Error: {2}", ovfDisk.getId(), getParameters().getStorageDomainId(), e); } } } if (!isOvfDataRetirieved) { AuditLogDirector.log(this, AuditLogType.RETRIEVE_OVF_STORE_FAILED); } return ovfEntitiesFromTar; }
Source:
<code>public void register(FContext context, FAsyncCallback callback) throws TException { if (context.getOpId() == 0) { context.setOpId(NEXT_OP_ID.incrementAndGet()); } <START> if (handlers.containsKey(context.getOpId())) { <END> throw new FException("context already registered"); } handlers.put(context.getOpId(), callback); }</code><technical_language>I case? I this thread client thread is calling operation generated client, guaranteed thread. processor thread is responsible for reading frames, writing</technical_language>

Target:
public void register(FContext context, FAsyncCallback callback) throws TException { if (handlers.containsKey(context.getOpId())) { throw new FException("context already registered"); } long opId = NEXT_OP_ID.incrementAndGet(); context.setOpId(opId); handlers.put(opId, Pair.of(callback, Thread.currentThread())); }
Source:
<code>public static long getFormIdForPath(File path) { long formId = -1; Cursor cursor = null; try { cursor = OdkXformSyncTask.getCursorForFormFile( path, new String[] { BaseColumns._ID }); if(cursor.getCount() >= 1) { if (cursor.getCount() > 1) { Log.e(TAG, "More than one form in database with the same id. This indicates an " + "error occurred on insert (probably a race condition) and should be " + "fixed. However, the app should still function correctly"); } <START> Preconditions.checkArgument(cursor.getColumnCount() == 1); <END> cursor.moveToNext(); formId = cursor.getLong(0); } } finally { if (cursor != null) { cursor.close(); } } return formId; }</code><technical_language>This check is redundant; projection in query is 10 lines column</technical_language>

Target:
public static long getFormIdForPath(File path) { long formId = -1; Cursor cursor = null; try { cursor = OdkXformSyncTask.getCursorForFormFile( path, new String[] { BaseColumns._ID }); if(cursor.getCount() >= 1) { if (cursor.getCount() > 1) { Log.e(TAG, "More than one form in database with the same id. This indicates an " + "error occurred on insert (probably a race condition) and should be " + "fixed. However, the app should still function correctly"); } cursor.moveToNext(); formId = cursor.getLong(0); } } finally { if (cursor != null) { cursor.close(); } } return formId; }
Source:
<code><START> private void calculateTurn() <END></code><technical_language><LINK_0> if issues managing adding items project</technical_language>

Target:
private void calculateTurn() { setupDiffusionMaps(); }
Source:
<code>public Set<Executor> getAllActiveExecutors() { <START> return activeExecutors; <END> }</code><technical_language>guess returning a copy of list a idea in memory list is "data of truth", want list messed caller</technical_language>

Target:
public Collection<Executor> getAllActiveExecutors() { return Collections.unmodifiableCollection(activeExecutors); }
Source:
<code>private RefactoringStatus checkAbstractMembersInDestinationClasses(IMember[] membersToPushDown, IType[] destinationClassesForAbstract) throws JavaModelException { RefactoringStatus result= new RefactoringStatus(); IMember[] abstractMembersToPushDown= getAbstractMembers(membersToPushDown); for (IType <START> t : <END> destinationClassesForAbstract) { result.merge(MemberCheckUtil.checkMembersInDestinationType(abstractMembersToPushDown, t)); } return result; }</code><technical_language>rename type</technical_language>

Target:
private RefactoringStatus checkAbstractMembersInDestinationClasses(IMember[] membersToPushDown, IType[] destinationClassesForAbstract) throws JavaModelException { RefactoringStatus result= new RefactoringStatus(); IMember[] abstractMembersToPushDown= getAbstractMembers(membersToPushDown); for (IType type : destinationClassesForAbstract) { result.merge(MemberCheckUtil.checkMembersInDestinationType(abstractMembersToPushDown, type)); } return result; }
Source:
<code>public void addResourceSelfServiceGroup(PerunSession sess, Resource resource, Group group) throws InternalErrorException, PrivilegeException, AlreadyAdminException { Utils.checkPerunSession(sess); Vo vo; Facility facility; try { facility = sess.getPerun().getFacilitiesManager().getFacilityById(sess, resource.getFacilityId()); } catch (FacilityNotExistsException e) { throw new InternalErrorException("Failed to find facility for given resource."); } try { vo = sess.getPerun().getVosManager().getVoById(sess, resource.getVoId()); } catch (VoNotExistsException e) { throw new InternalErrorException("Failed to find vo for given resource."); } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) && !AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { <START> throw new PrivilegeException(sess, "addResourceSelfServiceUser"); <END> } getResourcesManagerBl().addResourceSelfServiceGroup(sess, resource, group); }</code><technical_language>parameter "addResourceSelfServiceGroup"</technical_language>

Target:
public void addResourceSelfServiceGroup(PerunSession sess, Resource resource, Group group) throws InternalErrorException, PrivilegeException, AlreadyAdminException { Utils.checkPerunSession(sess); Vo vo; Facility facility; try { facility = sess.getPerun().getFacilitiesManager().getFacilityById(sess, resource.getFacilityId()); } catch (FacilityNotExistsException e) { throw new InternalErrorException("Failed to find facility for given resource."); } try { vo = sess.getPerun().getVosManager().getVoById(sess, resource.getVoId()); } catch (VoNotExistsException e) { throw new InternalErrorException("Failed to find vo for given resource."); } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) && !AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { throw new PrivilegeException(sess, "addResourceSelfServiceGroup"); } getResourcesManagerBl().addResourceSelfServiceGroup(sess, resource, group); }
Source:
<code>static boolean needsCompaction(@Nullable Long targetCompactionSizeBytes, List<DataSegment> candidates) { if (targetCompactionSizeBytes == null) { return true; } final double minAllowedSize = targetCompactionSizeBytes * (1 - ALLOWED_ERROR_OF_SEGMENT_SIZE); final double maxAllowedSize = targetCompactionSizeBytes * (1 + ALLOWED_ERROR_OF_SEGMENT_SIZE); return candidates .stream() .filter(segment -> segment.getSize() < minAllowedSize || segment.getSize() > maxAllowedSize) <START> .count() > 1; <END> }</code><technical_language>~nit: I this anyMatch instead of filter + count materialize entire set reaching match~</technical_language>

Target:
static boolean needsCompaction(@Nullable Long targetCompactionSizeBytes, List<DataSegment> candidates) { if (targetCompactionSizeBytes == null) { return true; } final double minTargetThreshold = targetCompactionSizeBytes * (1 - ALLOWED_ERROR_OF_SEGMENT_SIZE); final double maxTargetThreshold = targetCompactionSizeBytes * (1 + ALLOWED_ERROR_OF_SEGMENT_SIZE); return candidates .stream() .filter(segment -> segment.getSize() < minTargetThreshold || segment.getSize() > maxTargetThreshold) .count() > 1; }
Source:
<code>private static <T extends VmBase> void addImportedInterfaces(T entity, List<VmDevice> vmDeviceToUpdate) { final Guid id = entity.getId(); for (VmNetworkInterface iface : entity.getInterfaces()) { Guid deviceId = iface.getId(); VmDevice vmDevice = addManagedDevice(new VmDeviceId(deviceId, id), VmDeviceType.INTERFACE, VmDeviceType.BRIDGE, null, <START> true, <END> false, getAddress(entity, id)); updateVmDevice(entity, vmDevice, deviceId, vmDeviceToUpdate, iface); } }</code><technical_language>send plugged field determine plugged not, instead of updating afterwards</technical_language>

Target:
private static <T extends VmBase> void addImportedInterfaces(T entity, List<VmDevice> vmDeviceToUpdate) { final Guid id = entity.getId(); for (VmNetworkInterface iface : entity.getInterfaces()) { Guid deviceId = iface.getId(); VmDevice vmDevice = addManagedDevice(new VmDeviceId(deviceId, id), VmDeviceType.INTERFACE, VmDeviceType.BRIDGE, null, true, false, getAddress(entity, id)); VmDevice exportedDevice = entity.getManagedDeviceMap().get(deviceId); if (exportedDevice == null) { entity.getManagedDeviceMap().put(deviceId, vmDevice); exportedDevice = vmDevice; } exportedDevice.setIsPlugged(exportedDevice.getIsPlugged() && canPlugInterface(iface)); updateVmDevice(entity, vmDevice, deviceId, vmDeviceToUpdate); } }
Source:
<code>public ComponentWsRequest setComponentKey(@Nullable String componentKey) { return setComponent(componentKey); <START> } <END></code><technical_language>![INFO](<LINK_0> 'Severity: INFO') Do forget remove this deprecated code someday. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public ComponentWsRequest setComponentKey(@Nullable String componentKey) { this.componentKey = componentKey; return this; }