auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private int getCorrectedMimeSpecificity(MimeType mimeType) { final int ret; final String mimeTypeStr = mimeType.toString(); if (mimeTypeStr.equals("application/octet-stream")) { <START> ret = -1; <END> } else if (mimeTypeStr.equals("text/plain")) { ret = 0; } else { ret = mimeType.getSpecificity(); } return ret; }</code><technical_language>early return: if (mimeTypeStr.equals("...") { return -1; } else if (...) { return 0; } return mimeType.getSpecificity(); a lines shorter matches other cases Gerrit this style works</technical_language>

Target:
private int getCorrectedMimeSpecificity(MimeType mimeType) { final String mimeTypeStr = mimeType.toString(); if (mimeTypeStr.equals("application/octet-stream")) { return -1; } if (mimeTypeStr.equals("text/plain")) { return 0; } return mimeType.getSpecificity(); }
Source:
<code>public Response getPropertyByPath(@PathParam("clusterId") String clusterId, @PathParam("path") String path) { path = "/" + path; if (!isPathValid(path)) { <START> LOG.error("The path is mis-inputted for cluster {}", path, clusterId); <END> throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity( "Invalid path string. Valid path strings use slash as the directory separator and names the location of ZNode") .build()); } String propertyStoreRootPath = PropertyPathBuilder.propertyStore(clusterId); HelixPropertyStore<ZNRecord> propertyStore = new ZkHelixPropertyStore<>( (ZkBaseDataAccessor<ZNRecord>) getDataAccssor(clusterId).getBaseDataAccessor(), propertyStoreRootPath, Collections.emptyList()); ZNRecord record = propertyStore.get(path, null, AccessOption.PERSISTENT); return JSONRepresentation(record); }</code><technical_language>I this sounds better: "This propertyStore path is invalid for cluster {}"..</technical_language>

Target:
public Response getPropertyByPath(@PathParam("clusterId") String clusterId, @PathParam("path") String path) { path = "/" + path; if (!isPathValid(path)) { LOG.info("The propertyStore path is invalid for cluster {}", path, clusterId); return badRequest( "Invalid path string. Valid path strings use slash as the directory separator and names the location of ZNode"); } final String recordPath = PropertyPathBuilder.propertyStore(clusterId) + path; ZkBaseDataAccessor<byte[]> propertyStoreDataAccessor = getByteArrayDataAccessor(); if (propertyStoreDataAccessor.exists(recordPath, AccessOption.PERSISTENT)) { byte[] bytes = propertyStoreDataAccessor.get(recordPath, null, AccessOption.PERSISTENT); ZNRecord znRecord = (ZNRecord) ZN_RECORD_SERIALIZER.deserialize(bytes); if (znRecord == null) { ObjectNode jsonNode = OBJECT_MAPPER.createObjectNode(); jsonNode.put(CONTENT_KEY, new String(bytes)); return JSONRepresentation(jsonNode); } return JSONRepresentation(znRecord); } else { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity(String.format("The property store path %s doesn't exist", recordPath)).build()); } }
Source:
<code>@Override public void write(DataOutput output) throws IOException { WritableUtils.writeVInt(output, this.viewInfoTrackerList.size()); for (ViewInfoWritable viewInfoWritable : this.viewInfoTrackerList) { <START> ViewInfoTracker viewInfoTracker = (ViewInfoTracker)viewInfoWritable; <END> viewInfoTracker.write(output); } }</code><technical_language>u add a check for instance type, is future proof</technical_language>

Target:
@Override public void write(DataOutput output) throws IOException { WritableUtils.writeVInt(output, this.viewInfoTrackerList.size()); for (ViewInfoWritable viewInfoWritable : this.viewInfoTrackerList) { if (viewInfoWritable instanceof ViewInfoTracker) { viewInfoWritable.write(output); } } }
Source:
<code>public TransactorCache(Configuration config) { <START> timeoutCache = CacheBuilder.newBuilder().maximumWeight(1000000).weigher(new Weigher<Long,Long>() { <END> @Override public int weigh(Long key, Long value) { return 8 + 8; } }).concurrencyLevel(10).build(); this.config = config; cache = new PathChildrenCache(config.getSharedResources().getCurator(), TransactorID.getNodeRoot(config), true); try { cache.start(StartMode.BUILD_INITIAL_CACHE); status = TcStatus.OPEN; } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>maximumSize() maximumWeight() item in cache weight? Also, timed based expiration sense too</technical_language>

Target:
public TransactorCache(Configuration config) { timeoutCache = CacheBuilder.newBuilder().maximumSize(1 << 15).expireAfterAccess(TxInfoCache.CACHE_TIMEOUT_MIN, TimeUnit.MINUTES).concurrencyLevel(10) .build(); this.config = config; cache = new PathChildrenCache(config.getSharedResources().getCurator(), TransactorID.getNodeRoot(config), true); try { cache.start(StartMode.BUILD_INITIAL_CACHE); status = TcStatus.OPEN; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>private Matcher<DockerContainer> fileExists(final String path) { <START> return new Matcher<DockerContainer>("container with file '%s' in it", path) { <END> @Override public boolean matchesSafely(DockerContainer dock) { try { int exit = Docker.cmd("exec", dock.getCid(), "test", "-e", path).system(); if (exit == 0) return true; if (exit == 1) return false; throw new Error("Unexpected return code while checking for file existence: " + exit); } catch (IOException|InterruptedException e) { throw new Error("Failed testing for file existence in the container", e); } } }; }</code><technical_language>message sense</technical_language>

Target:
private Matcher<DockerContainer> fileExists(final String path) { return new Matcher<DockerContainer>("container with file/directory '%s' in it", path) { @Override public boolean matchesSafely(DockerContainer dock) { try { int exit = Docker.cmd("exec", dock.getCid(), "test", "-e", path).system(); if (exit == 0) return true; if (exit == 1) return false; throw new Error("Unexpected return code while checking for file existence: " + exit); } catch (IOException|InterruptedException e) { throw new Error("Failed testing for file existence in the container", e); } } }; }
Source:
<code>private boolean noConflictingNetwork() { if (networkExists()) { <START> addCanDoActionMessage(VdcBllMessages.NETWORK_ALREADY_ATTACHED_TO_CLUSTER); <END> return false; } return true; }</code><technical_language>write more simply as: return failCanDoAction(VdcBllMessages.NETWORK_ALREADY_ATTACHED_TO_CLUSTER);</technical_language>

Target:
private boolean noConflictingNetwork() { if (networkExists()) { return failCanDoAction(VdcBllMessages.NETWORK_ALREADY_ATTACHED_TO_CLUSTER); } return true; }
Source:
<code><START> public boolean equals(Object obj) { <END> if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } RepositoryVersion other = (RepositoryVersion) obj; if (major == null) { if (other.major != null) { return false; } } else if (!major.equals(other.major)) { return false; } if (micro == null) { if (other.micro != null) { return false; } } else if (!micro.equals(other.micro)) { return false; } if (minor == null) { if (other.minor != null) { return false; } } else if (!minor.equals(other.minor)) { return false; } if (qualifier == null) { if (other.qualifier != null) { return false; } } else if (!qualifier.equals(other.qualifier)) { return false; } return true; }</code><technical_language>treat 4.5.0 equal 4.05.0, v4.5.0? I if compare orgVersions. do think</technical_language>

Target:
public boolean equals(Object obj) { boolean result; if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } RepositoryVersion other = (RepositoryVersion) obj; result = ObjectUtils.equals(major, other.major); if (result) { result = ObjectUtils.equals(minor, other.minor); if (result) { result = ObjectUtils.equals(minor, other.minor); if (result) { result = ObjectUtils.equals(qualifier, other.qualifier); } } } return result; }
Source:
<code>public Blog createBlog(Blog blog) throws ClientServicesException { if (null == blog){ throw new ClientServicesException(null,"null blog"); } Response result = null; try { BaseBlogTransformer transformer = new BaseBlogTransformer(blog); Object payload = transformer.transform(blog.getFieldsMap()); Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/atom+xml"); String createBlogUrl = BlogUrls.MY_BLOGS.format(this, BlogUrlParts.blogHandle.get(defaultHomepageHandle)); result = createData(createBlogUrl, null, headers, payload); blog = getBlogFeedHandler().createEntity(result); <START> } catch (Exception e) { <END> throw new ClientServicesException(e, "error creating blog post"); } return blog; }</code><technical_language>catch IOException exception wrapped ClientServicesException is more specific? Do in other instances this happens, well, please</technical_language>

Target:
public Blog createBlog(Blog blog) throws ClientServicesException { if (null == blog){ throw new ClientServicesException(null,"null blog"); } Response result = null; try { BaseBlogTransformer transformer = new BaseBlogTransformer(blog); Object payload = transformer.transform(blog.getFieldsMap()); Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/atom+xml"); String createBlogUrl = BlogUrls.MY_BLOGS.format(this, BlogUrlParts.blogHandle.get(defaultHomepageHandle)); result = createData(createBlogUrl, null, headers, payload); blog = getBlogFeedHandler().createEntity(result); } catch (IOException e) { throw new ClientServicesException(e, "error creating blog"); } catch (TransformerException e) { throw new ClientServicesException(e, "error creating blog"); } return blog; }
Source:
<code>@Override protected void afterTest() throws Exception { stopAllGrids(); cleanPersistenceDir(); <START> super.afterTest(); <END> }</code><technical_language>change sane me. Call super some additional validation sence stopped grid</technical_language>

Target:
@Override protected void afterTest() throws Exception { super.afterTest(); stopAllGrids(); cleanPersistenceDir(); }
Source:
<code>private boolean storageContainsImage(AzureClient client, String resourceGroupName, String storageName, String image) { List<ListBlobItem> listBlobItems = client.listBlobInStorage(resourceGroupName, storageName, IMAGES_CONTAINER); for (ListBlobItem listBlobItem : listBlobItems) { <START> if (getNameFromConnectionString(listBlobItem.getUri().getPath()).equals(image.split("/")[image.split("/").length - 1])) { <END> return true; } } return false; }</code><technical_language>getNameFromConnectionString for image,</technical_language>

Target:
private boolean storageContainsImage(AzureClient client, String resourceGroupName, String storageName, String image) { List<ListBlobItem> listBlobItems = client.listBlobInStorage(resourceGroupName, storageName, IMAGES_CONTAINER); for (ListBlobItem listBlobItem : listBlobItems) { if (getNameFromConnectionString(listBlobItem.getUri().getPath()).equals(getNameFromConnectionString(image))) { return true; } } return false; }
Source:
<code>public Rule CriteriaOnlyFindQuery() { return Sequence( !builder.isCliQuery(), JsonObject() , builder.setOperation( Operation.FIND ), builder.setCriteria( match() ) <START> ); <END> }</code><technical_language>please put ); line one</technical_language>

Target:
public Rule CriteriaOnlyFindQuery() { return Sequence( !peek().isCliQuery(), JsonParameter( JsonObject() ) , peek().setOperation( Operation.FIND ), peek().setCriteria( match() ) ); }
Source:
<code>protected String getPath(String filename) throws IOException { return super.getPath("checks" + File.separator + "whitespace" + File.separator <START> + "TypecastParenPad" + File.separator <END> + filename); }</code><technical_language>I folder names in lowercase other package names</technical_language>

Target:
protected String getPath(String filename) throws IOException { return super.getPath("checks" + File.separator + "whitespace" + File.separator + "typecastparenpad" + File.separator + filename); }
Source:
<code>protected static SpringApplicationBuilder embedApp( ConfigurableApplicationContext parentContext, String namespace, Class<?> app) { return new SpringApplicationBuilder(new Object[]{app, EmbeddedServletContainerAutoConfiguration.class, EndpointWebMvcManagementContextConfiguration.class, WebMvcAutoConfiguration.EnableWebMvcConfiguration.class, ServerPropertiesAutoConfiguration.class}) .web(true).main(app) .bannerMode(Mode.OFF) .properties("spring.jmx.default-domain=" + namespace) .properties( InternalPropertyNames.NAMESPACE_PROPERTY_NAME + "=" + namespace) <START> .properties("server.port=-1") <END> .registerShutdownHook(false).parent(parentContext); }</code><technical_language>this is OK (also web(true) bit above). If starting web server child application is get this done, drop idea altogether support embedding of web apps</technical_language>

Target:
protected static SpringApplicationBuilder embedApp( ConfigurableApplicationContext parentContext, String namespace, Class<?> app) { return new SpringApplicationBuilder(new Object[] { app, RequestMappingConfiguration.class }) .web(false) .bannerMode(Mode.OFF) .properties("spring.jmx.default-domain=" + namespace) .properties( InternalPropertyNames.NAMESPACE_PROPERTY_NAME + "=" + namespace) .registerShutdownHook(false).parent(parentContext); }
Source:
<code>protected boolean canDoAction() { final VM vm = getVm(); if (vm == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); addCanDoActionMessage(VdcBllMessages.VAR__ACTION__SET); <START> addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_TICKET); <END> return false; } final VMStatus status = vm.getstatus(); if (status != VMStatus.Up && status != VMStatus.Paused && status != VMStatus.PoweringUp && status != VMStatus.PoweringDown && status != VMStatus.RebootInProgress) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL); addCanDoActionMessage(VdcBllMessages.VAR__ACTION__SET); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_TICKET); return false; } return canConnectToConsole(); }</code><technical_language>extract 2 lines override a method setActionMessageParameters instead of this times</technical_language>

Target:
protected boolean canDoAction() { final VM vm = getVm(); if (vm == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); return false; } final VMStatus status = vm.getstatus(); if (status != VMStatus.Up && status != VMStatus.Paused && status != VMStatus.PoweringUp && status != VMStatus.PoweringDown && status != VMStatus.RebootInProgress) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL); return false; } return canConnectToConsole(); }
Source:
<code><START> public static final int compare(String lhs, String rhs) <END> { Version lhsVersion = new Version(lhs); Version rhsVersion = new Version(rhs); int n = Math.max(lhsVersion.size(), rhsVersion.size()); for (int i = 0; i < n; i++) { int lhsComponent = lhsVersion.component(i); int rhsComponent = rhsVersion.component(i); if (lhsComponent < rhsComponent) return -1; else if (lhsComponent > rhsComponent) return 1; } return 0; }</code><technical_language>I idiomatic of this in Java is override compareTo for class</technical_language>

Target:
public static final int compare(String lhs, String rhs) { Version lhsVersion = new Version(lhs); Version rhsVersion = new Version(rhs); return lhsVersion.compareTo(rhsVersion); }
Source:
<code>public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { <START> {false, "sample"}, {true, "sample:branch"} <END> }); }</code><technical_language>interesting test a key ":" is remains of branch parsing key</technical_language>

Target:
public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { {false, "sample"}, {true, "sample:branch"}, {false, "sample:project"} }); }
Source:
<code><START> @Override public boolean equals(Object o) { <END> if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AffinityRulesEnforcementPerCluster that = (AffinityRulesEnforcementPerCluster) o; return new EqualsBuilder().append(clusterId, that.getClusterId()).isEquals(); }</code><technical_language>Please following: 1. Put method annotations separate line 2. recommended conditions in equals() Effective Java 2nd ed. 3. for blocks (even for 1 line blocks) 4. java.utils.Objects.equals() for objects comparisons method look: @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(obj instanceof AffinityRulesEnforcementPerCluster)) { return false; } AffinityRulesEnforcementPerCluster = (AffinityRulesEnforcementPerCluster) o; return Objects.equals(clusterId, that.getClusterId); }</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AffinityRulesEnforcementPerCluster)) { return false; } AffinityRulesEnforcementPerCluster that = (AffinityRulesEnforcementPerCluster) o; return Objects.equals(clusterId, that.getClusterId()); }
Source:
<code>public ResponseEntity setServerSettings(@RequestBody ServerSettingsForm serverSettingsForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { <START> validateServerSettingsForm(serverSettingsForm, bindingResult); <END> if (bindingResult.hasErrors()) { throw new RequestBodyValidationException(FAILED_SAVE_SERVER_SETTINGS, bindingResult); } configurationManagementService.setBaseUrl(serverSettingsForm.getBaseUrl()); configurationManagementService.setPort(serverSettingsForm.getPort()); configurationManagementService.setInstanceName(serverSettingsForm.getInstanceName()); if (serverSettingsForm.getCorsConfigurationForm() != null) { configurationManagementService.setCorsAllowedOrigins( serverSettingsForm.getCorsConfigurationForm().getAllowedOrigins() ); } if (serverSettingsForm.getSmtpConfigurationForm() != null) { configurationManagementService.setSmtpSettings( serverSettingsForm.getSmtpConfigurationForm().getMutableSmtpConfiguration() ); } if (serverSettingsForm.getProxyConfigurationForm() != null) { configurationManagementService.setProxyConfiguration( null, null, serverSettingsForm.getProxyConfigurationForm().getMutableProxyConfiguration() ); } return getSuccessfulResponseEntity(SUCCESSFUL_SAVE_SERVER_SETTINGS, acceptHeader); }</code><technical_language>Check message in validateServerSettingsForm method</technical_language>

Target:
public ResponseEntity setServerSettings(@RequestBody ServerSettingsForm serverSettingsForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { if (serverSettingsForm == null) { return getBadRequestResponseEntity(FAILED_EMPTY_FORM, acceptHeader); } validateServerSettingsForm(serverSettingsForm, bindingResult); if (bindingResult.hasErrors()) { throw new RequestBodyValidationException(FAILED_SAVE_SERVER_SETTINGS, bindingResult); } configurationManagementService.setBaseUrl(serverSettingsForm.getBaseUrl()); configurationManagementService.setPort(serverSettingsForm.getPort()); configurationManagementService.setInstanceName(serverSettingsForm.getInstanceName()); if (serverSettingsForm.getCorsConfigurationForm() != null) { configurationManagementService.setCorsAllowedOrigins( serverSettingsForm.getCorsConfigurationForm().getAllowedOrigins() ); } if (serverSettingsForm.getSmtpConfigurationForm() != null) { configurationManagementService.setSmtpSettings( serverSettingsForm.getSmtpConfigurationForm().getMutableSmtpConfiguration() ); } if (serverSettingsForm.getProxyConfigurationForm() != null) { configurationManagementService.setProxyConfiguration( null, null, serverSettingsForm.getProxyConfigurationForm().getMutableProxyConfiguration() ); } return getSuccessfulResponseEntity(SUCCESSFUL_SAVE_SERVER_SETTINGS, acceptHeader); }
Source:
<code>public void testGetCallbackWhenIsValid() { final DataType dataType = mock(DataType.class); final Command onSuccess = mock(Command.class); validator.getCallback(dataType, onSuccess).callback(true); <START> verify(onSuccess).execute(); <END> }</code><technical_language>please add assertion: verify(flashMessageEvent, never()).fire(any(DataTypeFlashMessage.class));</technical_language>

Target:
public void testGetCallbackWhenIsValid() { final DataType dataType = mock(DataType.class); final Command onSuccess = mock(Command.class); final DataTypeFlashMessage flashMessage = mock(DataTypeFlashMessage.class); when(nameIsInvalidErrorMessage.getFlashMessage(dataType)).thenReturn(flashMessage); validator.getCallback(dataType, onSuccess).callback(true); verify(onSuccess).execute(); verify(flashMessageEvent, never()).fire(flashMessage); }
Source:
<code>public final Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { Map<String, List<String>> tagQueries = new HashMap<>(); Long timestamp = null; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (timestampParts[1].contains(queryTimeSpanDelimiter)) { <START> return Status.NOT_IMPLEMENTED; <END> } timestamp = Long.valueOf(timestampParts[1]); } else { String[] queryParts = field.split(tagPairDelimiter); tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } return read(table, timestamp, tagQueries); }</code><technical_language>~~We start stop timestamps for read() method pass it. more complex queries dealing timestamps want focus common features in TSDs querying a time-range is common case.~~ Ah mind, right if a read, for a data point. In case want throw a DBException range queries allowed for a read</technical_language>

Target:
public final Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { Map<String, List<String>> tagQueries = new HashMap<>(); Long timestamp = null; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (timestampParts[1].contains(queryTimeSpanDelimiter)) { return Status.BAD_REQUEST; } timestamp = Long.valueOf(timestampParts[1]); } else { String[] queryParts = field.split(tagPairDelimiter); tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } if (timestamp == null) { return Status.BAD_REQUEST; } return read(table, timestamp, tagQueries); }
Source:
<code>private DataFetchingEnvironmentImpl(Builder builder) { this.source = builder.source; this.arguments = builder.arguments == null ? Collections::emptyMap : builder.arguments; this.context = builder.context; this.localContext = builder.localContext; this.root = builder.root; this.fieldDefinition = builder.fieldDefinition; this.mergedField = builder.mergedField; this.fieldType = builder.fieldType; this.parentType = builder.parentType; this.graphQLSchema = builder.graphQLSchema; this.fragmentsByName = builder.fragmentsByName == null ? CollectionsUtil.emptyMap() : builder.fragmentsByName; this.executionId = builder.executionId; this.selectionSet = builder.selectionSet; this.executionStepInfo = builder.executionStepInfo; this.dataLoaderRegistry = builder.dataLoaderRegistry; this.cacheControl = builder.cacheControl; this.locale = builder.locale; this.operationDefinition = builder.operationDefinition; this.document = builder.document; <START> this.variables = builder.variables == null ? ImmutableMapWithNullValues.empty() : builder.variables; <END> this.queryDirectives = builder.queryDirectives; }</code><technical_language>renamed ImmutableMapWithNullValues.empty() =to ImmutableMapWithNullValues.emptyMap() - this clearer in book static import this.variables = builder.variables == null ? emptyMap() : builder.variables;</technical_language>

Target:
private DataFetchingEnvironmentImpl(Builder builder) { this.source = builder.source; this.arguments = builder.arguments == null ? Collections::emptyMap : builder.arguments; this.context = builder.context; this.localContext = builder.localContext; this.root = builder.root; this.fieldDefinition = builder.fieldDefinition; this.mergedField = builder.mergedField; this.fieldType = builder.fieldType; this.parentType = builder.parentType; this.graphQLSchema = builder.graphQLSchema; this.fragmentsByName = builder.fragmentsByName == null ? ImmutableKit.emptyMap() : builder.fragmentsByName; this.executionId = builder.executionId; this.selectionSet = builder.selectionSet; this.executionStepInfo = builder.executionStepInfo; this.dataLoaderRegistry = builder.dataLoaderRegistry; this.cacheControl = builder.cacheControl; this.locale = builder.locale; this.operationDefinition = builder.operationDefinition; this.document = builder.document; this.variables = builder.variables == null ? ImmutableMapWithNullValues.emptyMap() : builder.variables; this.queryDirectives = builder.queryDirectives; }
Source:
<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String reportsUrl = Config.<String> getValue(ConfigValues.RedirectServletReportsPage); OutputStream out = response.getOutputStream(); try { if (StringUtils.isEmpty(reportsUrl)) { out.write(REPORTS_WEBAPP_NOT_DEPLOYED_MSG.getBytes(Charset.forName("UTF-8"))); } else { copy(new URL(reportsUrl + "/reports.xml").openStream(), out); } } catch (IOException ex) { <START> out.write(REPORTS_WEBAPP_NOT_DEPLOYED_MSG.getBytes(Charset.forName("UTF-8"))); <END> } finally { out.flush(); out.close(); } }</code><technical_language>I this reflected some return status, error message</technical_language>

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String reportsUrl = Config.<String> getValue(ConfigValues.RedirectServletReportsPage); OutputStream out = response.getOutputStream(); try { if (StringUtils.isEmpty(reportsUrl)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { copy(new URL(reportsUrl + "/reports.xml").openStream(), out); } } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } finally { out.flush(); out.close(); } }
Source:
<code>@Override public boolean canHandleSource(BufferedSource source) { try { <START> SVG.getFromInputStream(source.peek().inputStream()); <END> return true; } catch (SVGParseException e) { return false; } }</code><technical_language>is sufficient check for xml header bytes</technical_language>

Target:
@Override public boolean canHandleSource(BufferedSource source) { try { SVG.getFromInputStream(source.inputStream()); return true; } catch (SVGParseException e) { return false; } }
Source:
<code><START> private boolean isElasticAgent(String elasticAgentId, String elasticPluginId) { <END> return isNotBlank(elasticAgentId) || isNotBlank(elasticPluginId); }</code><technical_language>Move this AgentConfig</technical_language>

Target:
private boolean isElasticAgent(String elasticAgentId, String elasticPluginId) { return isNotBlank(elasticAgentId) && isNotBlank(elasticPluginId); }
Source:
<code>public void setUp() throws Exception { super.setUp(); dao = dbFacade.getStorageServerConnectionLunMapDao(); StorageServerConnectionDao storageServerConnectionDao = dbFacade.getStorageServerConnectionDao(); StorageServerConnections existingConnection = storageServerConnectionDao.get("0cc146e8-e5ed-482c-8814-270bc48c297e"); StorageServerConnections <START> newServerConnection = <END> new StorageServerConnections(); newServerConnection.setid("0cc146e8-e5ed-482c-8814-270bc48c2980"); newServerConnection.setconnection(EXISTING_DOMAIN_STORAGE_NAME); existingLUNStorageMap = dao.get(new LUNStorageServerConnectionMapId("1IET_00180001", existingConnection.getid())); newLUNStorageMap = new LUNStorageServerConnectionMap(FREE_LUN_ID, existingConnection.getid()); }</code><technical_language>newServerConnection completely redundant</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); dao = dbFacade.getStorageServerConnectionLunMapDao(); StorageServerConnectionDao storageServerConnectionDao = dbFacade.getStorageServerConnectionDao(); StorageServerConnections existingConnection = storageServerConnectionDao.get("0cc146e8-e5ed-482c-8814-270bc48c297e"); existingLUNStorageMap = dao.get(new LUNStorageServerConnectionMapId("1IET_00180001", existingConnection.getid())); newLUNStorageMap = new LUNStorageServerConnectionMap(FREE_LUN_ID, existingConnection.getid()); }
Source:
<code>public PdpFeedGroupEntry buildPdpFeedGroupEntry(ConcurStandardAccountingExtractDetailLine line) { PdpFeedGroupEntry currentGroup = new PdpFeedGroupEntry(); currentGroup.setPayeeName(buildPayeeName(line.getEmployeeLastName(), line.getEmployeeFirstName(), line.getEmployeeMiddleInitital())); currentGroup.setPayeeId(buildPayeeIdEntry(line)); currentGroup.setPaymentDate(formatDate(line.getBatchDate())); currentGroup.setCombineGroupInd(ConcurConstants.COMBINED_GROUP_INDICATOR); currentGroup.setBankCode(ConcurConstants.BANK_CODE); currentGroup.setCustomerInstitutionIdentifier(StringUtils.EMPTY); <START> addAddressesToGroup(line, currentGroup); <END> return currentGroup; }</code><technical_language>PDP files import other PDP customers do address of payee. PDP imports address of of record for payee KFS. IMHO, I feel need continue follow model send addresses in PDP import files. need determine get data correctly populated normal/existing PDP processing based payee specified</technical_language>

Target:
public PdpFeedGroupEntry buildPdpFeedGroupEntry(ConcurStandardAccountingExtractDetailLine line) { PdpFeedGroupEntry currentGroup = new PdpFeedGroupEntry(); currentGroup.setPayeeName(buildPayeeName(line.getEmployeeLastName(), line.getEmployeeFirstName(), line.getEmployeeMiddleInitital())); currentGroup.setPayeeId(buildPayeeIdEntry(line)); currentGroup.setPaymentDate(formatDate(line.getBatchDate())); currentGroup.setCombineGroupInd(ConcurConstants.COMBINED_GROUP_INDICATOR); currentGroup.setBankCode(ConcurConstants.BANK_CODE); currentGroup.setCustomerInstitutionIdentifier(StringUtils.EMPTY); return currentGroup; }
Source:
<code><START> public void checkpoint(final Checkpoint checkpoint) throws IOException { <END> memTable.flush(this, checkpoint); super.checkpoint(checkpoint); }</code><technical_language>1) do need this method? actual caller of this method is SortedLedgerStorage.onSizeLimitReached..in method "memTable.flush(SortedLedgerStorage.this);" is called 'checkpoint'. I dont need of calling memTable.flush(this, checkpoint); here. 2) remove this method SortedLedgerStorage class remove argument - 'checkpoint' for LedgerStorage.checkpoint method</technical_language>

Target:
public void checkpoint(final Checkpoint checkpoint) throws IOException { long numBytesFlushed = memTable.flush(this, checkpoint); if (numBytesFlushed > 0) { entryLogger.rollLog(); } super.checkpoint(checkpoint); }
Source:
<code>public void seek(long pos) throws IOException { checkIfClosed(); Preconditions.checkArgument(pos >= 0, PreconditionMessage.ERR_SEEK_NEGATIVE.toString(), pos); Preconditions .checkArgument(pos <= mLength, PreconditionMessage.ERR_SEEK_PAST_END_OF_REGION.toString(), mId); if (pos == mPos) { return; } if (pos < mPos) { mEOF = false; if (mDataReader instanceof NaiveSharedGrpcDataReader) { NaiveSharedGrpcDataReader reader = (NaiveSharedGrpcDataReader)mDataReader; reader.seek(pos); if (mCurrentChunk != null) { mCurrentChunk.release(); mCurrentChunk = null; } } else { closeDataReader(); } } else if (pos < mLength) { long curPos = mPos; while (mCurrentChunk != null && curPos < pos) { long nextPos = curPos + mCurrentChunk.readableBytes(); if (nextPos <= pos) { curPos = nextPos; mCurrentChunk.release(); mCurrentChunk = mDataReader.readChunkNoWait(); } else { int toRead = (int)(pos - curPos); final byte[] b = new byte[toRead]; mCurrentChunk.readBytes(b, 0, toRead); curPos = pos; } } <START> if (curPos < pos) { <END> closeDataReader(); } } else { closeDataReader(); } mPos = pos; }</code><technical_language>performance difference (rough numbers enough) in scenario compared original impl 1. single process Fuse read NaiveSharedGrpcDataReader 2. Single process Fuse read NaiveSharedGrpcDataReader 3. Multiple (four) processes Fuse read NaiveSharedGrpcDataReader 4. Multiple (four) processes Fuse read NaiveSharedGrpcDataReader</technical_language>

Target:
public void seek(long pos) throws IOException { checkIfClosed(); Preconditions.checkArgument(pos >= 0, PreconditionMessage.ERR_SEEK_NEGATIVE.toString(), pos); Preconditions .checkArgument(pos <= mLength, PreconditionMessage.ERR_SEEK_PAST_END_OF_REGION.toString(), mId); if (pos == mPos) { return; } if (!mContext.getClusterConf().getBoolean(PropertyKey.FUSE_SHARED_CACHING_READER_ENABLED)) { if (pos < mPos) { mEOF = false; } closeDataReader(); mPos = pos; return; } if (pos < mPos) { mEOF = false; if (mDataReader instanceof SharedGrpcDataReader) { SharedGrpcDataReader reader = (SharedGrpcDataReader) mDataReader; reader.seek(pos); if (mCurrentChunk != null) { mCurrentChunk.release(); mCurrentChunk = null; } } else { closeDataReader(); } } else { long curPos = mPos; while (mCurrentChunk != null && curPos < pos) { long nextPos = curPos + mCurrentChunk.readableBytes(); if (nextPos <= pos) { curPos = nextPos; mCurrentChunk.release(); mCurrentChunk = mDataReader.readChunkIfReady(); } else { int toRead = (int) (pos - curPos); final byte[] b = new byte[toRead]; mCurrentChunk.readBytes(b, 0, toRead); curPos = pos; } } if (curPos < pos) { closeDataReader(); } } mPos = pos; }
Source:
<code>private final String getConnectionUrl(){ <START> return "plocal:data/" + database; <END> }</code><technical_language>sure, if this is right place, I this is most-likely ConfigurationResourceResolver.getVaultDirectory() + "/db" for location of database</technical_language>

Target:
private String getConnectionUrl() { return "remote:" + host + ":" + port + "/" + database; }
Source:
<code>private SinkRecord convertAndTransformRecord(final ConsumerRecord<byte[], byte[]> msg) { SchemaAndValue keyAndSchema = retryWithToleranceOperator.execute(() -> keyConverter.toConnectData(msg.topic(), msg.headers(), msg.key()), Stage.KEY_CONVERTER, keyConverter.getClass()); SchemaAndValue valueAndSchema = retryWithToleranceOperator.execute(() -> valueConverter.toConnectData(msg.topic(), msg.headers(), msg.value()), Stage.VALUE_CONVERTER, valueConverter.getClass()); Headers headers = retryWithToleranceOperator.execute(() -> convertHeadersFor(msg), Stage.HEADER_CONVERTER, headerConverter.getClass()); if (retryWithToleranceOperator.failed()) { return null; } Long timestamp = ConnectUtils.checkAndConvertTimestamp(msg.timestamp()); SinkRecord origRecord = new SinkRecord(msg.topic(), msg.partition(), keyAndSchema.schema(), keyAndSchema.value(), valueAndSchema.schema(), valueAndSchema.value(), msg.offset(), timestamp, msg.timestampType(), headers); log.trace("{} Applying transformations to record in topic '{}' partition at offset and timestamp with key and value {}", this, msg.topic(), msg.partition(), msg.offset(), timestamp, keyAndSchema.value(), valueAndSchema.value()); <START> if (workerConfig.getBoolean(TOPIC_TRACKING_ENABLE_CONFIG)) { <END> recordActiveTopic(origRecord.topic()); } return transformationChain.apply(origRecord); }</code><technical_language>workerConfig.getBoolean(String) is cached, extra logic of tracking property used. this method is called record, worth speed this up. pulling this out a member variable in WorkerConfig adding a getter method return boolean value</technical_language>

Target:
private SinkRecord convertAndTransformRecord(final ConsumerRecord<byte[], byte[]> msg) { SchemaAndValue keyAndSchema = retryWithToleranceOperator.execute(() -> keyConverter.toConnectData(msg.topic(), msg.headers(), msg.key()), Stage.KEY_CONVERTER, keyConverter.getClass()); SchemaAndValue valueAndSchema = retryWithToleranceOperator.execute(() -> valueConverter.toConnectData(msg.topic(), msg.headers(), msg.value()), Stage.VALUE_CONVERTER, valueConverter.getClass()); Headers headers = retryWithToleranceOperator.execute(() -> convertHeadersFor(msg), Stage.HEADER_CONVERTER, headerConverter.getClass()); if (retryWithToleranceOperator.failed()) { return null; } Long timestamp = ConnectUtils.checkAndConvertTimestamp(msg.timestamp()); SinkRecord origRecord = new SinkRecord(msg.topic(), msg.partition(), keyAndSchema.schema(), keyAndSchema.value(), valueAndSchema.schema(), valueAndSchema.value(), msg.offset(), timestamp, msg.timestampType(), headers); log.trace("{} Applying transformations to record in topic '{}' partition at offset and timestamp with key and value {}", this, msg.topic(), msg.partition(), msg.offset(), timestamp, keyAndSchema.value(), valueAndSchema.value()); if (isTopicTrackingEnabled) { recordActiveTopic(origRecord.topic()); } return transformationChain.apply(origRecord); }
Source:
<code>public int getVisibility(IBinding member) { try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getAccessibility(member); } catch (CoreException e) { CCorePlugin.log(e); <START> throw new IllegalArgumentException(member.getName() + " is not a member of " + getName()); END> } }</code><technical_language>error is reported twice</technical_language>

Target:
public int getVisibility(IBinding member) { try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getVisibility(member); } catch (CoreException e) { CCorePlugin.log(e); throw new IllegalArgumentException(member.getName() + " is not a member of " + getName()); } }
Source:
<code>public MarketDataResult buildBaseMarketData( MarketDataRequirements requirements, BaseMarketData suppliedData) { ImmutableMap.Builder<MarketDataId<?>, Result<?>> failureBuilder = ImmutableMap.builder(); ImmutableMap.Builder<MarketDataId<?>, Result<?>> timeSeriesFailureBuilder = ImmutableMap.builder(); BaseMarketData builtData = suppliedData; MarketDataNode root = MarketDataNode.buildDependencyTree(requirements, suppliedData, builders); while (!root.isLeaf()) { Pair<MarketDataNode, MarketDataRequirements> pair = root.withLeavesRemoved(); <START> root = pair.getFirst(); <END> MarketDataRequirements leafRequirements = pair.getSecond(); BaseMarketDataBuilder dataBuilder = builtData.toBuilder(); leafRequirements.getTimeSeries().stream() .filter(not(builtData::containsTimeSeries)) .forEach(id -> addTimeSeries(dataBuilder, timeSeriesFailureBuilder, id)); Set<ObservableId> observableIds = leafRequirements.getObservables().stream() .filter(not(builtData::containsValue)) .collect(toImmutableSet()); buildObservableData(observableIds, dataBuilder, failureBuilder); BaseMarketData tmpData = builtData; leafRequirements.getNonObservables().stream() .filter(not(builtData::containsValue)) .forEach(id -> buildNonObservableData(id, tmpData, dataBuilder, failureBuilder)); builtData = dataBuilder.build(); } return MarketDataResult.builder() .marketData(builtData) .singleValueFailures(failureBuilder.build()) .timeSeriesFailures(timeSeriesFailureBuilder.build()) .build(); }</code><technical_language>read if this in loop. way, if current root loop, get original, new one</technical_language>

Target:
public MarketDataResult buildBaseMarketData( MarketDataRequirements requirements, BaseMarketData suppliedData) { ImmutableMap.Builder<MarketDataId<?>, Result<?>> failureBuilder = ImmutableMap.builder(); ImmutableMap.Builder<MarketDataId<?>, Result<?>> timeSeriesFailureBuilder = ImmutableMap.builder(); BaseMarketData builtData = suppliedData; MarketDataNode root = MarketDataNode.buildDependencyTree(requirements, suppliedData, builders); while (!root.isLeaf()) { Pair<MarketDataNode, MarketDataRequirements> pair = root.withLeavesRemoved(); MarketDataRequirements leafRequirements = pair.getSecond(); BaseMarketDataBuilder dataBuilder = builtData.toBuilder(); leafRequirements.getTimeSeries().stream() .filter(not(builtData::containsTimeSeries)) .forEach(id -> addTimeSeries(dataBuilder, timeSeriesFailureBuilder, id)); Set<ObservableId> observableIds = leafRequirements.getObservables().stream() .filter(not(builtData::containsValue)) .collect(toImmutableSet()); buildObservableData(observableIds, dataBuilder, failureBuilder); BaseMarketData tmpData = builtData; leafRequirements.getNonObservables().stream() .filter(not(builtData::containsValue)) .forEach(id -> buildNonObservableData(id, tmpData, dataBuilder, failureBuilder)); builtData = dataBuilder.build(); root = pair.getFirst(); } return MarketDataResult.builder() .marketData(builtData) .singleValueFailures(failureBuilder.build()) .timeSeriesFailures(timeSeriesFailureBuilder.build()) .build(); }
Source:
<code>public void onTraversalStart() { if (artifactModes.size() == 0) { artifactModes.add(DEFAULT_ARTIFACT_MODE); } <START> artifactModes.sort(null); <END> final MetricsFile<SequencingArtifactMetrics.PreAdapterDetailMetrics, Comparable<?>> mf = new MetricsFile<>(); try { mf.read(new FileReader(preAdapterMetricsFile)); } catch (final FileNotFoundException fnfe) { throw new UserException("Could not find file: " + preAdapterMetricsFile.getAbsolutePath()); } firstPassVariants = new ArrayList<>(); relevantArtifactModes = new TreeSet<>(); for (String artifactMode: artifactModes) { final String[] splitArtifactMode = artifactMode.split("/"); if (!isValidArtifactMode(splitArtifactMode)) { throw new UserException("Invalid artifact mode: " + String.join("/", splitArtifactMode)); } relevantArtifactModes.add(ArtifactMode.of(splitArtifactMode[0].charAt(0), splitArtifactMode[1].charAt(0))); } artifactModeToPreAdapterScoreMap = PreAdapterOrientationScorer.scoreOrientationBiasMetricsOverContext(mf.getMetrics()); logger.info("preAdapter scores:"); artifactModeToPreAdapterScoreMap.keySet().stream().forEach(k -> logger.info(k + ": " + artifactModeToPreAdapterScoreMap.get(k))); setupVCFWriter(); }</code><technical_language>Collections.sort(artifactModes)</technical_language>

Target:
public void onTraversalStart() { if (transitions.size() == 0) { transitions.add(DEFAULT_ARTIFACT_MODE); } transitions.sort(null); final MetricsFile<SequencingArtifactMetrics.PreAdapterDetailMetrics, Comparable<?>> mf = new MetricsFile<>(); try { mf.read(new FileReader(preAdapterMetricsFile)); } catch (final FileNotFoundException fnfe) { throw new UserException("Could not find file: " + preAdapterMetricsFile.getAbsolutePath()); } relevantTransitions.addAll(transitions.stream().map(s -> convertParameterToTransition(s)).collect(Collectors.toSet())); transitionToPreAdapterScoreMap = PreAdapterOrientationScorer.scoreOrientationBiasMetricsOverContext(mf.getMetrics()); logger.info("preAdapter scores:"); transitionToPreAdapterScoreMap.keySet().stream().forEach(k -> logger.info(k + ": " + transitionToPreAdapterScoreMap.get(k))); setupVCFWriter(); }
Source:
<code>public void before() throws Exception { DOWNLOAD_CACHE.before(); Path tmpPath = tmp.getRoot().toPath(); LOG.info("The current temporary path: {}", tmpPath); Path currentModulePath = Paths.get("").toAbsolutePath(); Path flinkHomePath = loadProjectRootDirectory(currentModulePath); <START> String hadoopClasspath = Paths.get(flinkHomePath.toString(), YARN_CLASSPATH).toString(); <END> File hadoopClasspathFile = new File(hadoopClasspath); if (!hadoopClasspathFile.exists()) { throw new FileNotFoundException(hadoopClasspath); } String classPathContent = FileUtils.readFileUtf8(hadoopClasspathFile); hadoopClasspathJars = Arrays.stream(classPathContent.split(":")) .map(jar -> Paths.get(jar)) .collect(Collectors.toList()); }</code><technical_language>Instead of re-using another modules classpath for convenience, please instead declare a set of hadop dependencies this test required, dependency-plugin generate a distinct classpath file</technical_language>

Target:
public void before() throws Exception { DOWNLOAD_CACHE.before(); Path tmpPath = tmp.getRoot().toPath(); LOG.info("The current temporary path: {}", tmpPath); File hadoopClasspathFile = new File(hadoopClasspath.toAbsolutePath().toString()); if (!hadoopClasspathFile.exists()) { throw new FileNotFoundException("File that contains hadoop classpath " + hadoopClasspath.toString() + " does not exist."); } String classPathContent = FileUtils.readFileUtf8(hadoopClasspathFile); hadoopClasspathJars = Arrays.stream(classPathContent.split(":")) .map(jar -> Paths.get(jar)) .collect(Collectors.toList()); }
Source:
<code>public FEELFnResult<Boolean> invoke(@ParameterName( "number" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot be null" ) ); } if ( number.remainder( BigDecimal.ONE ).signum() != 0 ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot have non-zero fractional part" ) ); } <START> return FEELFnResult.ofResult( BigInteger.ZERO.equals( number.toBigInteger().remainder(TWO) ) ); <END> }</code><technical_language>I 100% conversion BigInteger is needed here</technical_language>

Target:
public FEELFnResult<Boolean> invoke(@ParameterName( "number" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot be null" ) ); } if ( number.remainder( BigDecimal.ONE ).signum() != 0 ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot have non-zero fractional part" ) ); } return FEELFnResult.ofResult( BigDecimal.ZERO.compareTo( number.remainder(TWO) ) == 0); }
Source:
<code>public static org.ovirt.engine.api.model.VmPayload map(VmPayload entity, org.ovirt.engine.api.model.VmPayload template) { org.ovirt.engine.api.model.VmPayload model = template != null ? template : new org.ovirt.engine.api.model.VmPayload(); <START> model.setType(entity.getType().getName()); <END> VmPayloadFile file = new VmPayloadFile(); file.setName(entity.getFileName()); file.setContent(entity.getContent()); model.setFile(file); return model; }</code><technical_language>reason type null, safe add validation (if entity.getType()!=null)</technical_language>

Target:
public static org.ovirt.engine.api.model.VmPayload map(VmPayload entity, org.ovirt.engine.api.model.VmPayload template) { org.ovirt.engine.api.model.VmPayload model = template != null ? template : new org.ovirt.engine.api.model.VmPayload(); if (entity.getType() != null) { model.setType(entity.getType().getName()); } VmPayloadFile file = new VmPayloadFile(); file.setName(entity.getFileName()); file.setContent(entity.getContent()); model.setFile(file); return model; }
Source:
<code>AbstractStreamingCommitterOperator<CommT, GlobalCommT> createStreamingCommitterOperator() { return new GlobalStreamingCommitterOperator<>( sink.createGlobalCommitter() <START> .orElseThrow(() -> new IllegalArgumentException( <END> "Could not create global committer from the sink")), sink.getGlobalCommittableSerializer() .orElseThrow(() -> new IllegalArgumentException( "Could not create global committable serializer from the sink"))); }</code><technical_language>throw IllegalStateException instead of IllegalArgumentException. do @guoweiM</technical_language>

Target:
AbstractStreamingCommitterOperator<CommT, GlobalCommT> createStreamingCommitterOperator() { return new GlobalStreamingCommitterOperator<>( sink.createGlobalCommitter() .orElseThrow(() -> new IllegalStateException( "Could not create global committer from the sink")), sink.getGlobalCommittableSerializer() .orElseThrow(() -> new IllegalStateException( "Could not create global committable serializer from the sink"))); }