auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected CompletableFuture<ClientCoordinationResponseBody> handleRequest( @Nonnull HandlerRequest<ClientCoordinationRequestBody, ClientCoordinationMessageParameters> request, @Nonnull RestfulGateway gateway) throws RestHandlerException { JobID jobId = request.getPathParameter(JobIDPathParameter.class); OperatorID operatorId = request.getPathParameter(OperatorIDPathParameter.class); SerializedValue<CoordinationRequest> serializedRequest = request.getRequestBody().getSerializedCoordinationRequest(); CompletableFuture<CoordinationResponse> responseFuture = gateway.deliverCoordinationRequestToCoordinator(jobId, operatorId, serializedRequest, timeout); return responseFuture.thenApply( coordinationResponse -> { try { return new ClientCoordinationResponseBody(new SerializedValue<>(coordinationResponse)); } catch (IOException e) { <START> throw new RuntimeException("Failed to construct response body", e); <END> } }); }</code><technical_language>throw RestHandlerException instead? RuntimeException crash rest server</technical_language>

Target:
protected CompletableFuture<ClientCoordinationResponseBody> handleRequest( @Nonnull HandlerRequest<ClientCoordinationRequestBody, ClientCoordinationMessageParameters> request, @Nonnull RestfulGateway gateway) throws RestHandlerException { JobID jobId = request.getPathParameter(JobIDPathParameter.class); OperatorID operatorId = request.getPathParameter(OperatorIDPathParameter.class); SerializedValue<CoordinationRequest> serializedRequest = request.getRequestBody().getSerializedCoordinationRequest(); CompletableFuture<CoordinationResponse> responseFuture = gateway.deliverCoordinationRequestToCoordinator(jobId, operatorId, serializedRequest, timeout); return responseFuture.thenApply( coordinationResponse -> { try { return new ClientCoordinationResponseBody(new SerializedValue<>(coordinationResponse)); } catch (IOException e) { throw new CompletionException( new RestHandlerException( "Failed to serialize coordination response", HttpResponseStatus.INTERNAL_SERVER_ERROR, e)); } }); }
Source:
<code>private static String getHeaderValue(String urlBase, String filter, int page, int perPage, boolean showArchived, long totalRecords, String orderBy, OrderDirection direction) { <START> List<String> links = new ArrayList<>(); <END> links.add(StringUtil.format(LINK_TEMPLATE, map( "URL", getUrl(urlBase, filter, FIRST_PAGE_INDEX, perPage, showArchived, orderBy, direction), "relValue", FIRST_REL_VALUE ))); int lastPage = (int) (Math.ceil((double) totalRecords/perPage)); links.add(StringUtil.format(LINK_TEMPLATE, map( "URL", getUrl(urlBase, filter, lastPage, perPage, showArchived, orderBy, direction), "relValue", LAST_REL_VALUE ))); links.add(StringUtil.format(LINK_TEMPLATE, map( "URL", getUrl(urlBase, filter, -1, perPage, showArchived, orderBy, direction), "relValue", PAGE_REL_VALUE ))); int next = page + 1; if (next <= lastPage){ links.add(StringUtil.format(LINK_TEMPLATE, map( "URL", getUrl(urlBase, filter, next, perPage, showArchived, orderBy, direction), "relValue", NEXT_REL_VALUE ))); } int prev = page - 1; if (prev > 0){ links.add(StringUtil.format(LINK_TEMPLATE, map( "URL", getUrl(urlBase, filter, prev, perPage, showArchived, orderBy, direction), "relValue", PREV_REL_VALUE ))); } return String.join(",", links); }</code><technical_language>immutable</technical_language>

Target:
private static String getHeaderValue(String urlBase, String filter, int page, int perPage, boolean showArchived, long totalRecords, String orderBy, OrderDirection direction) { final List<String> links = new ArrayList<>(); links.add(StringUtil.format(LINK_TEMPLATE, map( "URL", getUrl(urlBase, filter, FIRST_PAGE_INDEX, perPage, showArchived, orderBy, direction), "relValue", FIRST_REL_VALUE ))); int lastPage = (int) (Math.ceil((double) totalRecords/perPage)); links.add(StringUtil.format(LINK_TEMPLATE, map( "URL", getUrl(urlBase, filter, lastPage, perPage, showArchived, orderBy, direction), "relValue", LAST_REL_VALUE ))); links.add(StringUtil.format(LINK_TEMPLATE, map( "URL", getUrl(urlBase, filter, -1, perPage, showArchived, orderBy, direction), "relValue", PAGE_REL_VALUE ))); int next = page + 1; if (next <= lastPage){ links.add(StringUtil.format(LINK_TEMPLATE, map( "URL", getUrl(urlBase, filter, next, perPage, showArchived, orderBy, direction), "relValue", NEXT_REL_VALUE ))); } int prev = page - 1; if (prev > 0){ links.add(StringUtil.format(LINK_TEMPLATE, map( "URL", getUrl(urlBase, filter, prev, perPage, showArchived, orderBy, direction), "relValue", PREV_REL_VALUE ))); } return String.join(",", links); }
Source:
<code>private String getLocalised(Map<String, Object> source, String fieldName, String lang) { final Map<String, String> map = (Map<String, String>) source.get(fieldName); if (map == null) return null; if (map.get(lang) != null) { return map.get(lang); } if (!map.containsKey("default")) { <START> return map.get(map.keySet().toArray()[0]); END> } return map.get("default"); }</code><technical_language>define order here. Right get a random localized name, if I understand code right. I suggest: housename, int, loc, reg, alt, Also, note NAME other names default localised ones. a special handling of name a good idea</technical_language>

Target:
private String getLocalised(Map<String, Object> source, String fieldName, String lang) { final Map<String, String> map = (Map<String, String>) source.get(fieldName); if (map == null) return null; if (map.get(lang) != null) { return map.get(lang); } if (fieldName.equals("name")) { for (String key : NAME_PRECEDENCE) { if (map.containsKey(key)) return map.get(key); } } return map.get("default"); }
Source:
<code>private String formatPrefix(Factory formatFactory, ConfigOption<String> formatOption) { String identifier = formatFactory.factoryIdentifier(); <START> if (formatOption.key().equals(FORMAT_KEY) || formatOption.equals(KEY_FORMAT) || formatOption.equals(VALUE_FORMAT)) { <END> return identifier + "."; } else if (formatOption.key().endsWith(FORMAT_SUFFIX)) { String keyPrefix = formatOption.key().substring(0, formatOption.key().length() - FORMAT_SUFFIX.length()); return keyPrefix + "." + identifier + "."; } else { throw new ValidationException( "Format identifier key should be 'format' or suffix with '.format', " + "don't support format identifier key '" + formatOption.key() + "'."); } }</code><technical_language>need add this condition. This handled condition. If format key is prefixed key. value., format options prefixed key. value.. 'value.format' = 'csv', 'value.csv.ignore-parse-error' = 'true'</technical_language>

Target:
private String formatPrefix(Factory formatFactory, ConfigOption<String> formatOption) { String identifier = formatFactory.factoryIdentifier(); if (formatOption.key().equals(FORMAT.key())) { return identifier + "."; } else if (formatOption.key().endsWith(FORMAT_SUFFIX)) { String keyPrefix = formatOption.key().substring(0, formatOption.key().length() - FORMAT_SUFFIX.length()); return keyPrefix + "." + identifier + "."; } else { throw new ValidationException( "Format identifier key should be 'format' or suffix with '.format', " + "don't support format identifier key '" + formatOption.key() + "'."); } }
Source:
<code>public int compareTo(Object o) { <START> if (!(o instanceof FileEntry)) <END> throw new ClassCastException(); if (this == o) return 0; FileEntry fe = (FileEntry) o; int diff = size - fe.size; return (diff != 0) ? diff : offset > fe.offset ? 1 : -1; }</code><technical_language>cast result a bit faster :-) FileEntry fe = (FileEntry) o;</technical_language>

Target:
public int compareTo(Object o) { FileEntry fe = (FileEntry) o; if (this == fe) return 0; int diff = size - fe.size; return (diff != 0) ? diff : offset > fe.offset ? 1 : -1; }
Source:
<code>private void checkClosingTag(Element element) { XmlTextRange startLocation = XmlFile.startLocation(element); XmlTextRange endLocation = XmlFile.endLocation(element); if (!isSelfClosing(element) && startLocation.getEndLine() != endLocation.getStartLine()) { if (!needToCheckIndentation(element)) { return; <START> } <END> int startIndent = startIndent(element.getPreviousSibling()); int endIndent = startIndent(element.getLastChild()); if (startIndent != endIndent) { reportIssue(endLocation, startIndent); } } }</code><technical_language>In order ease reading, I early return if a self-closing node: java if (isSelfClosing(element)) { return; } XmlTextRange startLocation = XmlFile.startLocation(element); XmlTextRange endLocation = XmlFile.endLocation(element); if (startLocation.getEndLine() != endLocation.getStartLine()) { // ..</technical_language>

Target:
private void checkClosingTag(Element element) { if (isSelfClosing(element)) { return; } XmlTextRange startLocation = XmlFile.startLocation(element); XmlTextRange endLocation = XmlFile.endLocation(element); if (startLocation.getEndLine() != endLocation.getStartLine()) { if (!needToCheckIndentation(element)) { return; } int startIndent = startIndent(element.getPreviousSibling()); int endIndent = startIndent(element.getLastChild()); if (startIndent != endIndent) { reportIssue(endLocation, startIndent); } } }
Source:
<code><START> public static Location getContextStartLocation(ParserRuleContext ctx) { <END> return new Location(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine() + 1); }</code><technical_language>static methods</technical_language>

Target:
Location getContextStartLocation(ParserRuleContext ctx) { return new Location(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine() + 1); }
Source:
<code>public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException { super.processBindingConfiguration(context, item, bindingConfig); TACmiBindingConfig config = new TACmiBindingConfig(); logger.debug("Processing binding configuration: '{}'", bindingConfig); final String[] configParts = bindingConfig.split("#"); switch (configParts.length) { case 3: config.canNode = configParts[0]; config.portType = configParts[1]; config.portNumber = Integer.parseInt(configParts[2]); break; case 4: config.canNode = configParts[0]; config.portType = configParts[1]; config.portNumber = Integer.parseInt(configParts[2]); config.measureType = TACmiMeasureType.fromString(configParts[3]); break; default: throw new BindingConfigParseException( "A TACmi binding configuration must consist of three or four parts - please verify your *.items file"); } config.configurationString = bindingConfig; <START> logger.debug("Adding binding: {}", config); <END> addBindingConfig(item, config); }</code><technical_language>"Adding Binding configuration"</technical_language>

Target:
public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException { super.processBindingConfiguration(context, item, bindingConfig); TACmiBindingConfig config = new TACmiBindingConfig(); logger.debug("Processing binding configuration: '{}'", bindingConfig); final String[] configParts = bindingConfig.split("#"); switch (configParts.length) { case 3: config.canNode = configParts[0]; config.portType = configParts[1]; config.portNumber = Integer.parseInt(configParts[2]); break; case 4: config.canNode = configParts[0]; config.portType = configParts[1]; config.portNumber = Integer.parseInt(configParts[2]); config.measureType = TACmiMeasureType.fromString(configParts[3]); break; default: throw new BindingConfigParseException( "A TACmi binding configuration must consist of three or four parts - please verify your *.items file"); } config.configurationString = bindingConfig; logger.debug("Adding Binding configuration: {}", config); addBindingConfig(item, config); }
Source:
<code>public DependencyTypesMapper() { <START> jsonDepsReader = new PomJsonReader(getClass().getClassLoader().getResourceAsStream(JSON_POM_DEPS)); <END> mapping = jsonDepsReader.readDeps(); }</code><technical_language>Nice improvement. 1 objection this impl: do need store jsonDepsReader in instance field, if in constructor initialize map? abou removing private PomJsonReader jsonDepsReader declaring reader locally in constructor PomJsonReader jsonDepsReader = new ...</technical_language>

Target:
public DependencyTypesMapper() { PomJsonReaderDefault jsonDepsReader = new PomJsonReaderDefault(getClass().getClassLoader().getResourceAsStream(JSON_POM_DEPS)); mapping = jsonDepsReader.readDeps(); }
Source:
<code>public boolean isEmpty() { if (restoring.isEmpty() && !restoringByPartition.isEmpty()) { log.error("Assigned stream tasks in an inconsistent state: the set of restoring tasks is empty but the " + "restoring by partitions map contained {}", restoringByPartition); <START> return false; <END> } else { return super.isEmpty() && restoring.isEmpty() && restoringByPartition.isEmpty() && restoredPartitions.isEmpty() && suspended.isEmpty(); } }</code><technical_language>is save return false? throw IllegalStateException</technical_language>

Target:
public boolean isEmpty() throws IllegalStateException { if (restoring.isEmpty() && !restoringByPartition.isEmpty()) { log.error("Assigned stream tasks in an inconsistent state: the set of restoring tasks is empty but the " + "restoring by partitions map contained {}", restoringByPartition); throw new IllegalStateException("Found inconsistent state: no tasks restoring but nonempty restoringByPartition"); } else { return super.isEmpty() && restoring.isEmpty() && restoringByPartition.isEmpty() && restoredPartitions.isEmpty() && suspended.isEmpty(); } }
Source:
<code>public okhttp3.Request authenticate(Route route, okhttp3.Response response) throws IOException { this.userSessionInfoProvider.removeSession(userSession); this.userSession = null; if (tryCount >= MAX_TRIES) { LOG.info("Maximum retries reached"); this.tryCount = 0; return null; } tryCount++; try { userSession = userSessionInfoProvider.retrieveSession(signIn); } catch (ConsentRequiredException e) { <START> LOG.debug("Ignoring 412 during auto-authentication"); <END> } return addBridgeHeaders(response.request()); }</code><technical_language>I this throw. unexpected unusual, calls fail..</technical_language>

Target:
public okhttp3.Request authenticate(Route route, okhttp3.Response response) throws IOException { this.userSessionInfoProvider.removeSession(userSession); this.userSession = null; if (tryCount >= MAX_TRIES) { LOG.info("Maximum retries reached"); this.tryCount = 0; return null; } tryCount++; userSession = userSessionInfoProvider.retrieveSession(signIn); return addBridgeHeaders(response.request()); }
Source:
<code>public ApplicationStatus status(StreamApplication app) { try { boolean finished = false; boolean unsuccessfulFinish = false; ProcessorGraph processorGraph = getExecutionPlan(app); for (ProcessorNode processor : processorGraph.getProcessorNodes()) { Config processorConfig = processor.generateConfig(); JobRunner runner = new JobRunner(processorConfig); ApplicationStatus status = runner.status(); log.debug("Status is for processor with config {}", new Object[]{status, processor.getId(), processorConfig}); switch (status) { case Running: return ApplicationStatus.Running; case UnsuccessfulFinish: <START> unsuccessfulFinish = true; <END> case SuccessfulFinish: finished = true; break; default: } } if (unsuccessfulFinish) { return ApplicationStatus.UnsuccessfulFinish; } else if (finished) { return ApplicationStatus.SuccessfulFinish; } return ApplicationStatus.New; } catch (Throwable t) { throw new SamzaException("Failed to get status for application", t); } }</code><technical_language>IIUC, cleaner return ApplicationStatus.UnsuccessfulFinish immediately here. need unsuccessfulFinish boolean way</technical_language>

Target:
public ApplicationStatus status(StreamApplication app) { try { boolean finished = false; boolean unsuccessfulFinish = false; ProcessorGraph processorGraph = getExecutionPlan(app); for (ProcessorNode processor : processorGraph.getProcessorNodes()) { Config processorConfig = processor.generateConfig(); JobRunner runner = new JobRunner(processorConfig); ApplicationStatus status = runner.status(); log.debug("Status is for processor {}", new Object[]{status, processor.getId()}); switch (status) { case Running: return ApplicationStatus.Running; case UnsuccessfulFinish: unsuccessfulFinish = true; case SuccessfulFinish: finished = true; break; default: } } if (unsuccessfulFinish) { return ApplicationStatus.UnsuccessfulFinish; } else if (finished) { return ApplicationStatus.SuccessfulFinish; } return ApplicationStatus.New; } catch (Throwable t) { throw new SamzaException("Failed to get status for application", t); } }
Source:
<code>public <L> void receivedEvent(AvailEvent<L> event) { MonitoredEndpoint<EndpointConfiguration> endpoint = event.getSamplingService().getMonitoredEndpoint(); String endpointTenantId = endpoint.getEndpointConfiguration().getTenantId(); String tenantId = (null != endpointTenantId) ? endpointTenantId : storageAdapter.getStorageAdapterConfiguration().getTenantId(); event.getChanged().keySet().stream() .filter(mi -> mi.getResource().getResourceType().getNotifications().contains(NotificationType.AVAIL_CHANGE)) .forEach(mi -> { CanonicalPath cp = CanonicalPath.of() .tenant(tenantId) .feed(feedId) .resource(mi.getResource().getID().getIDString()) .get(); try { NotificationPayloadBuilder b = storageAdapter.createNotificationPayloadBuilder(); b.addNotificationType(NotificationType.AVAIL_CHANGE); b.addProperty("resourceType", mi.getResource().getResourceType().getName().getNameString()); b.addProperty("resourcePath", cp.toString()); b.addProperty("availType", mi.getType().getName().getNameString()); b.addProperty("newAvail", event.getChanged().get(mi).name()); storageAdapter.store(b, 0); } catch (Exception e) { <START> <END> } }); }</code><technical_language>log error message silently ignore it</technical_language>

Target:
public <L> void receivedEvent(AvailEvent<L> event) { MonitoredEndpoint<EndpointConfiguration> endpoint = event.getSamplingService().getMonitoredEndpoint(); String endpointTenantId = endpoint.getEndpointConfiguration().getTenantId(); String tenantId = (null != endpointTenantId) ? endpointTenantId : storageAdapter.getStorageAdapterConfiguration().getTenantId(); processAvailEvents(event.getChanged(), NotificationType.AVAIL_CHANGE, tenantId); processAvailEvents(event.getStarted(), NotificationType.AVAIL_STARTING, tenantId); }
Source:
<code><START> public void exposeHostPort(int hostPort, int containerPort) { <END> if (exposedPorts.add(hostPort)) { getSshConnection().requestRemotePortForwarding("", containerPort, "localhost", hostPort); } }</code><technical_language>exposeHostPort(int port) delegate this method</technical_language>

Target:
public void exposeHostPort(int hostPort, int containerPort) { if (exposedPorts.add(new AbstractMap.SimpleEntry<>(hostPort, containerPort))) { getSshConnection().requestRemotePortForwarding("", containerPort, "localhost", hostPort); } }
Source:
<code>public void checkSpecificAccessControl() { if (!userInfo.isInstructor) { throw new UnauthorizedAccessException("Instructor privilege is required to access this resource."); } <START> String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); <END> InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.id); gateKeeper.verifyAccessible( instructor, logic.getCourse(courseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); }</code><technical_language>this getNonNullRequestParamValue</technical_language>

Target:
public void checkSpecificAccessControl() { if (!userInfo.isInstructor) { throw new UnauthorizedAccessException("Instructor privilege is required to access this resource."); } String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.id); gateKeeper.verifyAccessible( instructor, logic.getCourse(courseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); }
Source:
<code><START> public Map<K, V> getEntries() { <END> return (Map<K, V>) entries; }</code><technical_language>Change unneeded. unchecked removed well</technical_language>

Target:
public Map<? extends K, ? extends V> getEntries() { return entries; }
Source:
<code>public void testMenuNoMarkerSet() { SWTBotRootMenu viewMenu = fViewBot.viewMenu(); List<String> menuItems = viewMenu.menu("Marker Set").menuItems(); <START> assertEquals("number of items", 3, menuItems.size()); <END> assertArrayEquals("menu items, no marker set", MENU_ITEMS_NO_MARKERS_SET, menuItems.toArray()); }</code><technical_language>assertArrayEquals check length</technical_language>

Target:
public void testMenuNoMarkerSet() { SWTBotRootMenu viewMenu = fViewBot.viewMenu(); List<String> menuItems = viewMenu.menu("Marker Set").menuItems(); assertArrayEquals("menu items, no marker set", MENU_ITEMS_NO_MARKERS_SET, menuItems.toArray()); }
Source:
<code>public static boolean isConstant(Expr expr) { <START> return expr instanceof DoubleExpr || expr instanceof LongExpr || expr instanceof StringExpr; <END> }</code><technical_language>is this instanceof ConstantExpr? is point "ConstantExpr" interface if figure out if is a constant not</technical_language>

Target:
public static boolean isConstant(Expr expr) { return expr instanceof ConstantExpr; }
Source:
<code>private void logRenamedEntity() { if (this instanceof RenamedEntityInfoProvider) { <START> String entity="UNKNOWN"; <END> String oldName=""; String newName=""; try { entity = ReflectionUtils.getMethodValue(this, "getEntityName").toString(); oldName = ReflectionUtils.getMethodValue(this, "getOldName").toString(); newName = ReflectionUtils.getMethodValue(this, "getNewName").toString(); if (!oldName.equals(newName)) { AuditLogableBase logable = new AuditLogableBase(); logable.AddCustomValue("EntityName", entity); logable.AddCustomValue("OldName", oldName); logable.AddCustomValue("NewName", newName); Class<AuditLogableBase> partypes[] = new Class[1]; partypes[0] = AuditLogableBase.class; Object arglist[] = new Object[1]; arglist[0] = logable; ReflectionUtils.callMethod(this, "setId", partypes, arglist); AuditLogDirector.log(logable, AuditLogType.ENTITY_RENAMED); } } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }</code><technical_language>is need initialize entity, oldName newName overridden straightafterward in try-catch block. I move declaration try block. e.g.: try { String entity = ReflectionUtils.getMethodValue(this, "getEntityName").toString(); ... } Yair suggested: try { if (this instanceof RenamedEntityProvider) { RenamedEntityProvider renameable = (RenamedEntityProvider)this; String entity = renameable.getEntityName(); ... renameable.setId(logable); } ... }</technical_language>

Target:
private void logRenamedEntity() { try { if (this instanceof RenamedEntityInfoProvider) { String oldEntityName; String newEntityName; RenamedEntityInfoProvider renameable = (RenamedEntityInfoProvider) this; String entityType = renameable.getEntityType(); oldEntityName = renameable.getEntityOldName(); newEntityName = renameable.getEntityNewName(); if (!oldEntityName.equals(newEntityName)) { AuditLogableBase logable = new AuditLogableBase(); logable.AddCustomValue("EntityType", entityType); logable.AddCustomValue("OldEntityName", oldEntityName); logable.AddCustomValue("NewEntityName", newEntityName); renameable.setEntityId(logable); AuditLogDirector.log(logable, AuditLogType.ENTITY_RENAMED); } } } catch (Exception e) { log.error(e.getMessage()); log.debug("Failed to log entity rename operation.", e); } }
Source:
<code>private static Properties loadLibraryProperties(@Nonnull InputVFS vfs) throws NotJackLibraryException { Properties libraryProperties = new Properties(); try { InputVFile libProp = vfs.getRootInputVDir().getInputVFile(JackLibrary.LIBRARY_PROPERTIES_VPATH); InputStream inputStream = null; try { inputStream = libProp.getInputStream(); libraryProperties.load(inputStream); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { logger.log( Level.WARNING, "Failed to close ''{0}''", libProp.getLocation().getDescription()); } } } } catch (NotFileOrDirectoryException | NoSuchFileException | WrongPermissionException e) { throw new NotJackLibraryException(vfs.getLocation()); } <START> catch (IOException e) { throw new NotJackLibraryException(vfs.getLocation()); } <END> return libraryProperties; }</code><technical_language>Multi-catch</technical_language>

Target:
private static Properties loadLibraryProperties(@Nonnull InputVFS vfs) throws NotJackLibraryException { Properties libraryProperties = new Properties(); try { InputVFile libProp = vfs.getRootInputVDir().getInputVFile(JackLibrary.LIBRARY_PROPERTIES_VPATH); InputStream inputStream = null; try { inputStream = libProp.getInputStream(); libraryProperties.load(inputStream); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { logger.log( Level.WARNING, "Failed to close ''{0}''", libProp.getLocation().getDescription()); } } } } catch (IOException | NotFileOrDirectoryException | NoSuchFileException | WrongPermissionException e) { throw new NotJackLibraryException(vfs.getLocation()); } return libraryProperties; }
Source:
<code>public boolean rewrite(File f) throws InvalidKeyException, IOException { AtomicFileWriter w = new AtomicFileWriter(f, "UTF-8"); try { boolean modified = false; try (PrintWriter out = new PrintWriter(new BufferedWriter(w)); InputStream fin = Files.newInputStream(f.toPath()); BufferedReader r = new BufferedReader(new InputStreamReader(fin, StandardCharsets.UTF_8))) { String line; StringBuilder buf = new StringBuilder(); while ((line = r.readLine()) != null) { int copied = 0; buf.setLength(0); while (true) { int sidx = line.indexOf('>', copied); if (sidx < 0) break; int eidx = line.indexOf('<', sidx); if (eidx < 0) break; String elementText = line.substring(sidx + 1, eidx); String replacement = tryRewrite(elementText); if (!replacement.equals(elementText)) modified = true; buf.append(line, copied, sidx + 1); buf.append(replacement); copied = eidx; } buf.append(line.substring(copied)); out.println(buf.toString()); } <START> } catch (InvalidPathException e) { <END> throw new IOException(e); } if (modified) { w.commit(); } return modified; } finally { w.abort(); } }</code><technical_language>Util.fileToPath() FTW</technical_language>

Target:
public boolean rewrite(File f) throws InvalidKeyException, IOException { AtomicFileWriter w = new AtomicFileWriter(f, "UTF-8"); try { boolean modified = false; try (PrintWriter out = new PrintWriter(new BufferedWriter(w)); InputStream fin = Files.newInputStream(Util.fileToPath(f)); BufferedReader r = new BufferedReader(new InputStreamReader(fin, StandardCharsets.UTF_8))) { String line; StringBuilder buf = new StringBuilder(); while ((line = r.readLine()) != null) { int copied = 0; buf.setLength(0); while (true) { int sidx = line.indexOf('>', copied); if (sidx < 0) break; int eidx = line.indexOf('<', sidx); if (eidx < 0) break; String elementText = line.substring(sidx + 1, eidx); String replacement = tryRewrite(elementText); if (!replacement.equals(elementText)) modified = true; buf.append(line, copied, sidx + 1); buf.append(replacement); copied = eidx; } buf.append(line.substring(copied)); out.println(buf.toString()); } } if (modified) { w.commit(); } return modified; } finally { w.abort(); } }
Source:
<code>private void storeEvent(Map<String, Object> event, Date timestamp) { try { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); ObjectMapper m = new ObjectMapper(); StringWriter w = new StringWriter(); m.writeValue(w, event); Entity entity = new Entity("EventQueue"); entity.setProperty("createdDateTime", timestamp); entity.setProperty("lastUpdateDateTime", timestamp); String payload = w.toString(); if (payload.length() > Constants.MAX_LENGTH) { entity.setProperty("payloadText", new Text(payload)); } else { <START> entity.setProperty("payload", w.toString()); <END> } datastore.put(entity); notifyLog(); } catch (Exception e) { logger.log(Level.SEVERE, "could not store " + event.get("eventType") + " event. Error: " + e.toString(), e); } }</code><technical_language>calling w.toString() 2 times, payload local variable String value, apologies for catching earlier</technical_language>

Target:
private void storeEvent(Map<String, Object> event, Date timestamp) { try { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); ObjectMapper m = new ObjectMapper(); StringWriter w = new StringWriter(); m.writeValue(w, event); Entity entity = new Entity("EventQueue"); entity.setProperty("createdDateTime", timestamp); entity.setProperty("lastUpdateDateTime", timestamp); String payload = w.toString(); if (payload.length() > Constants.MAX_LENGTH) { entity.setProperty("payloadText", new Text(payload)); } else { entity.setProperty("payload", payload); } datastore.put(entity); notifyLog(); } catch (Exception e) { logger.log(Level.SEVERE, "could not store " + event.get("eventType") + " event. Error: " + e.toString(), e); } }
Source:
<code>public void prompt(PrintStream out) { int maxLength = String.valueOf(mChoices.length).length(); out.println(CliUtils.pad("", maxLength + 1) + mHeader); out.println("=============================================================================================="); <START> int i; <END> for (i = 0; i < mChoices.length; ++i) { String d = rows[i]; out.println(CliUtils.pad(String.valueOf(i), maxLength) + ")" + d); } if(mAction != null) { out.println(); out.println("action) " + mAction.getDisplay().evaluate().getName()); } }</code><technical_language>is int i declaration of loop header</technical_language>

Target:
public void prompt(PrintStream out) { int maxLength = String.valueOf(mChoices.length).length(); out.println(CliUtils.pad("", maxLength + 1) + mHeader); out.println("=============================================================================================="); for (int i = 0; i < mChoices.length; ++i) { String d = rows[i]; out.println(CliUtils.pad(String.valueOf(i), maxLength) + ")" + d); } if(mAction != null) { out.println(); out.println("action) " + mAction.getDisplay().evaluate().getName()); } }
Source:
<code>public void removeTask(@NotNull final String taskId, Protos.TaskStatus status) { List<CassandraNode> nodes = clusterState.nodes(); List<CassandraNode> newNodes = new ArrayList<>(nodes.size()); boolean changed = false; for (CassandraNode cassandraNode : nodes) { CassandraNodeTask nodeTask = CassandraFrameworkProtosUtils.getTaskForNode(cassandraNode, taskId); if (nodeTask == null) { newNodes.add(cassandraNode); continue; } CassandraNode.Builder builder = CassandraFrameworkProtosUtils.removeTask(cassandraNode, nodeTask); changed = true; switch (nodeTask.getTaskType()) { case METADATA: removeExecutorMetadata(nodeTask.getExecutorId()); builder.clearTasks(); break; <START> case SERVER: <END> changed = true; break; } newNodes.add(builder.build()); } if (changed) clusterState.nodes(newNodes); ClusterJobStatus clusterJob = getCurrentClusterJob(); if (clusterJob != null) { if (clusterJob.hasCurrentNode() && clusterJob.getCurrentNode().getTaskId().equals(taskId)) { jobsState.removeTaskForCurrentNode(status, clusterJob); } } }</code><technical_language>redundant switch branch, changed is set true switch begins</technical_language>

Target:
public void removeTask(@NotNull final String taskId, Protos.TaskStatus status) { List<CassandraNode> nodes = clusterState.nodes(); List<CassandraNode> newNodes = new ArrayList<>(nodes.size()); boolean changed = false; for (CassandraNode cassandraNode : nodes) { CassandraNodeTask nodeTask = CassandraFrameworkProtosUtils.getTaskForNode(cassandraNode, taskId); if (nodeTask == null) { newNodes.add(cassandraNode); continue; } CassandraNode.Builder builder = CassandraFrameworkProtosUtils.removeTask(cassandraNode, nodeTask); changed = true; switch (nodeTask.getTaskType()) { case METADATA: removeExecutorMetadata(nodeTask.getExecutorId()); builder.clearTasks(); break; case SERVER: builder.clearCassandraDaemonPid(); break; } newNodes.add(builder.build()); } if (changed) { clusterState.nodes(newNodes); } ClusterJobStatus clusterJob = getCurrentClusterJob(); if (clusterJob != null) { if (clusterJob.hasCurrentNode() && clusterJob.getCurrentNode().getTaskId().equals(taskId)) { jobsState.removeTaskForCurrentNode(status, clusterJob); } } }
Source:
<code>public boolean containsPoint(float x, float y) { <START> return x >= this.minX && y >= this.minY && x <= this.maxX && y <= this.maxY; <END> }</code><technical_language>I upper bounds be: x < this.maxX y < this.maxY current this is inconsistent int version of this method, yielding for exact integer coordinates false int version true for float version (for float-representable integers)</technical_language>

Target:
public boolean containsPoint(float x, float y) { return x > this.minX && y > this.minY && x < this.maxX && y < this.maxY; }
Source:
<code>public Map<String, String> getCoordinates() { <START> return new HashMap<>(coordinates); <END> }</code><technical_language>a big fan of HashMap HashSet, guarantee order of elements in them. Is a reason this instead of LinkedHashMap? If is reason, mind replacing this (I've a other places in changed code HashMap HashSet). If missing reason, please elaborate</technical_language>

Target:
public Map<String, String> getCoordinates() { return new LinkedHashMap<>(coordinates); }
Source:
<code>private static boolean isNestingBroken(ConditionalExpressionTree conditionalExpression) { Tree parent = ((JavaScriptTree) conditionalExpression).getParent(); while (!parent.is(Kind.CONDITIONAL_EXPRESSION)) { if (breaksRecursion(parent)) { return true; } <START> parent = ((JavaScriptTree) parent).getParent(); <END> } return false; }</code><technical_language>@ivandalbosco CheckUtils.parent(parent) avoid cast</technical_language>

Target:
private static boolean isNestingBroken(ConditionalExpressionTree conditionalExpression) { Tree parent = ((JavaScriptTree) conditionalExpression).getParent(); while (!parent.is(Kind.CONDITIONAL_EXPRESSION)) { if (breaksNesting(parent)) { return true; } parent = CheckUtils.parent(parent); } return false; }
Source:
<code>public void onApplicationEvent(ScalingEvent event) { Set<BaseAlert> alerts = event.getAlerts(); Long clusterId = alerts.stream().findFirst().map(ma -> ma.getCluster().getId()).orElseThrow(); Cluster cluster = clusterService.findById(clusterId); MDCBuilder.buildMdcContext(cluster); if (isCooldownElapsed(cluster)) { <START> alerts.forEach(alert -> scale(cluster, alert.getScalingPolicy())); <END> } }</code><technical_language>Do want trigger multiple scaling actions time</technical_language>

Target:
public void onApplicationEvent(ScalingEvent event) { List<BaseAlert> alerts = event.getAlerts(); Long clusterId = alerts.stream().findFirst().map(ma -> ma.getCluster().getId()).orElseThrow(); Cluster cluster = clusterService.findById(clusterId); MDCBuilder.buildMdcContext(cluster); alerts.forEach(alert -> { if (scalingHandlerUtil.isCooldownElapsed(cluster)) { scalingHandlerUtil.scaleIfNeed(cluster, alert); } }); }
Source:
<code><START> private JacksonIterator(Type type, ObjectMapper mapper, Response response, Reader reader) <END> throws IOException { this.response = response; this.parser = mapper.getFactory().createParser(reader); this.objectReader = mapper.reader().forType(mapper.constructType(type)); }</code><technical_language>notice in other feign code is infrequently private access modifiers bloat bytecode sharing packages supported feign anyway. if feel strongly hiding things, making type private default modifiers ctor symbols accomplishes same</technical_language>

Target:
JacksonIterator(Type type, ObjectMapper mapper, Response response, Reader reader) throws IOException { this.response = response; this.parser = mapper.getFactory().createParser(reader); this.objectReader = mapper.reader().forType(mapper.constructType(type)); }
Source:
<code><START> public static Context setSpanName(String spanName, Context context) { <END> if (TRACER == null) { return context; } return TRACER.setSpanName(spanName, context); }</code><technical_language>this API return Context? inconsistent setAttribute() API returns a void. Or, setAttribute() return Context start() is returning Context</technical_language>

Target:
public static Context setSpanName(String spanName, Context context) { if (tracer == null) { return context; } return tracer.setSpanName(spanName, context); }
Source:
<code>public void testNonBlockingConnectionManagerInstantiationBadInputs() { try { connectionManager = new NonBlockingConnectionManager(null, networkConfig, routerConfig.routerMaxConnectionsPerPortPlainText, routerConfig.routerMaxConnectionsPerPortSsl, time); <START> Assert.fail(); <END> } catch (IllegalArgumentException e) { } try { connectionManager = new NonBlockingConnectionManager(selector, null, routerConfig.routerMaxConnectionsPerPortPlainText, routerConfig.routerMaxConnectionsPerPortSsl, time); Assert.fail(); } catch (IllegalArgumentException e) { } }</code><technical_language>message</technical_language>

Target:
public void testNonBlockingConnectionManagerInstantiationBadInputs() { try { connectionManager = new NonBlockingConnectionManager(null, networkConfig, routerConfig.routerScalingUnitMaxConnectionsPerPortPlainText, routerConfig.routerScalingUnitMaxConnectionsPerPortSsl, time); Assert.fail("NonBlockingConnectionManager should not get constructed with a null Selector"); } catch (IllegalArgumentException e) { } try { connectionManager = new NonBlockingConnectionManager(selector, null, routerConfig.routerScalingUnitMaxConnectionsPerPortPlainText, routerConfig.routerScalingUnitMaxConnectionsPerPortSsl, time); Assert.fail("NonBlockingConnectionManager should not get constructed with a null NetworkConfig"); } catch (IllegalArgumentException e) { } }
Source:
<code>private static boolean isSupportedSpatialFunction(FunctionCall functionCall) { String functionName = functionCall.getName().getSuffix(); <START> for (FullyQualifiedName allowedName : ALLOWED_SPATIAL_JOIN_FUNCTIONS) { <END> if (functionName.equalsIgnoreCase(allowedName.getSuffix())) { return true; } } return false; }</code><technical_language>this loop is slow; convert ALLOWED_SPATIAL_JOIN_FUNCTIONS a set of lowercase function names, Set.contains(functionName.toLower())</technical_language>

Target:
private static boolean isSupportedSpatialFunction(FunctionCall functionCall) { String functionName = functionCall.getName().getSuffix().toLowerCase(ENGLISH); return ALLOWED_SPATIAL_JOIN_FUNCTIONS.contains(functionName); }
Source:
<code>private KeyStore loadKeyStore(String keyStorePath, char[] keyStorePassword) throws SecureVaultException { Path keyStoreFileLocation; if (SecureVaultDataHolder.getInstance().getBundleContext().isPresent()) { keyStoreFileLocation = Paths.get(SecureVaultUtils.getCarbonHome().get().toString(), <START> keyStorePath); <END> } else { keyStoreFileLocation = Paths.get(keyStorePath); } try (BufferedInputStream bufferedInputStream = new BufferedInputStream( new FileInputStream(keyStoreFileLocation.toString()))) { KeyStore keyStore; try { keyStore = KeyStore.getInstance(JKS); keyStore.load(bufferedInputStream, keyStorePassword); logger.debug("Keystore at path : '{}', loaded successfully.", keyStorePath); return keyStore; } catch (CertificateException e) { throw new SecureVaultException("Failed to load certificates from keystore : '" + keyStorePath + "'", e); } catch (NoSuchAlgorithmException e) { throw new SecureVaultException("Failed to load keystore algorithm at : '" + keyStorePath + "'", e); } catch (KeyStoreException e) { throw new SecureVaultException("Failed to initialize keystore at : '" + keyStorePath + "'", e); } } catch (IOException e) { throw new SecureVaultException("Unable to find keystore at '" + keyStorePath + "'", e); } }</code><technical_language>move this upper line, right</technical_language>

Target:
private KeyStore loadKeyStore(String keyStorePath, char[] keyStorePassword) throws SecureVaultException { Path keyStoreFileLocation; if (SecureVaultUtils.isOSGIEnv()) { keyStoreFileLocation = Paths.get(SecureVaultUtils.getCarbonHome().get().toString(), keyStorePath); } else { keyStoreFileLocation = Paths.get(keyStorePath); } try (BufferedInputStream bufferedInputStream = new BufferedInputStream( new FileInputStream(keyStoreFileLocation.toString()))) { KeyStore keyStore; try { keyStore = KeyStore.getInstance(JKS); keyStore.load(bufferedInputStream, keyStorePassword); logger.debug("Keystore at path : '{}', loaded successfully.", keyStorePath); return keyStore; } catch (CertificateException e) { throw new SecureVaultException("Failed to load certificates from keystore : '" + keyStorePath + "'", e); } catch (NoSuchAlgorithmException e) { throw new SecureVaultException("Failed to load keystore algorithm at : '" + keyStorePath + "'", e); } catch (KeyStoreException e) { throw new SecureVaultException("Failed to initialize keystore at : '" + keyStorePath + "'", e); } } catch (IOException e) { throw new SecureVaultException("Unable to find keystore at '" + keyStorePath + "'", e); } }
Source:
<code>private void simpleScanAsPomFile(File file, Document document) { MavenProject project = MavenParser.parseXML(file); <START> MavenFileScannerContext mavenContext = new MavenFileScannerContextImpl(project, document, file, sonarComponents); <END> if (project != null) { for (MavenFileScanner mavenFileScanner : mavenFileScanners) { mavenFileScanner.scanFile(mavenContext); } } }</code><technical_language>This line if next line</technical_language>

Target:
private void simpleScanAsPomFile(File file, Document document) { MavenProject project = PomParser.parseXML(file); if (project != null) { PomCheckContext context = new PomCheckContextImpl(project, document, file, sonarComponents); for (PomCheck check : pomChecks) { check.scanFile(context); } } }
Source:
<code>public void testChangingCurrentThreadCLINotification() throws Throwable { ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<MIStoppedEvent>(fMultiRunControl.getSession(), MIStoppedEvent.class); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint("36", false); SyncUtil.resumeAll(); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); <START> <END> for (int i = 0; i < 2; i++) { assertEquals("2",switchThreadAndCaptureThreadSwitchedEvent("2")); assertEquals("3",switchThreadAndCaptureThreadSwitchedEvent("3")); assertEquals("4",switchThreadAndCaptureThreadSwitchedEvent("4")); assertEquals("5",switchThreadAndCaptureThreadSwitchedEvent("5")); assertEquals("1",switchThreadAndCaptureThreadSwitchedEvent("1")); assertEquals("1",switchThreadAndCaptureThreadSwitchedEvent("1")); } }</code><technical_language>massageTimeout instead,</technical_language>

Target:
public void testChangingCurrentThreadCLINotification() throws Throwable { ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<MIStoppedEvent>(fMultiRunControl.getSession(), MIStoppedEvent.class); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint("36", false); SyncUtil.resumeAll(); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); for (int i = 0; i < 2; i++) { assertEquals("2",switchThreadAndCaptureThreadSwitchedEvent("2")); assertEquals("3",switchThreadAndCaptureThreadSwitchedEvent("3")); assertEquals("4",switchThreadAndCaptureThreadSwitchedEvent("4")); assertEquals("5",switchThreadAndCaptureThreadSwitchedEvent("5")); assertEquals("1",switchThreadAndCaptureThreadSwitchedEvent("1")); assertEquals("1",switchThreadAndCaptureThreadSwitchedEvent("1")); } }
Source:
<code>private void refreshView() { try { String[] headers = new String[shortSelect.getFields().length]; for (int i = 0; i < headers.length; ++i) { headers[i] = shortSelect.getFields()[i].getHeader().evaluate(); if ("address".equals(shortSelect.getFields()[i].getTemplateForm())) { this.mMappingEnabled = true; } } header.removeAllViews(); if (!shortSelect.usesGridView()) { EntityView v = new EntityView(this, shortSelect, headers); header.addView(v); } if (adapter == null) { <START> loadEntities(); <END> } else { startTimer(); } } catch (RuntimeException re) { createErrorDialog(re.getMessage(), true); } }</code><technical_language>Good call</technical_language>

Target:
private void refreshView() { try { String[] headers = new String[shortSelect.getFields().length]; for (int i = 0; i < headers.length; ++i) { headers[i] = shortSelect.getFields()[i].getHeader().evaluate(); if ("address".equals(shortSelect.getFields()[i].getTemplateForm())) { this.mMappingEnabled = true; } } header.removeAllViews(); if (!shortSelect.usesGridView()) { EntityView v = EntityView.buildHeadersEntityView(this, shortSelect, headers); header.addView(v); } if (adapter == null) { loadEntities(); } else { startTimer(); } } catch (RuntimeException re) { createErrorDialog(re.getMessage(), true); } }
Source:
<code>private void processGeneratedExpressionColumn(Reference reference, Input<?> expressionInput) { toInject.put(reference, expressionInput); final ColumnIdent ident = reference.column(); if (!ident.isTopLevel()) { List<Reference> references = nestedReferenceByTopLevelColumnName.getOrDefault( ident.name(), <START> new ArrayList<>()); <END> references.add(reference); nestedReferenceByTopLevelColumnName.put(ident.name(), references); } }</code><technical_language>I a manual .get() if (.. null) more efficient right new ArrayList<>() is evaluated, is element found</technical_language>

Target:
private void processGeneratedExpressionColumn(Reference reference, Input<?> expressionInput) { toInject.put(reference, expressionInput); final ColumnIdent ident = reference.column(); if (!ident.isTopLevel()) { List<Reference> references = nestedReferenceByTopLevelColumnName.get(ident.name()); if (references == null) { references = new ArrayList<>(); } references.add(reference); nestedReferenceByTopLevelColumnName.put(ident.name(), references); } }
Source:
<code>public void draw (Batch batch, float parentAlpha) { currentBackground.draw(batch, getX(), getY(), getWidth(), getHeight()); <START> layout = new GlyphLayout(style.font, model.getValue().toString()); <END> style.font.draw(batch, model.getValue().toString() + "", getX() + style.background.getLeftWidth(), getY() + (getHeight() + layout.height) / 2); }</code><technical_language>Please allocate heavy objects in draw() (and getPrefWidth/Height - while allocations of a deal, avoid them)</technical_language>

Target:
public void draw (Batch batch, float parentAlpha) { currentBackground.draw(batch, getX(), getY(), getWidth(), getHeight()); style.font.draw(batch, model.getDisplayValue() + "", getX() + style.background.getLeftWidth(), getY() + (getHeight() + layout.height) / 2); }
Source:
<code>public boolean isAutomaticProvisioningEnabled () { <START> return AutomaticProvisioningStatus.ENABLED.equals(getAutomaticProvisioning()) ? true : false; <END> }</code><technical_language>simplified AutomaticProvisioningStatus.ENABLED.equals(getAutomaticProvisioning());</technical_language>

Target:
public boolean isAutomaticProvisioningEnabled () { return AutomaticProvisioningStatus.ENABLED.equals(getAutomaticProvisioning()); }