auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List<Long> insertBucket(final Set<SequenceSegment> bucket, final Set<Sequence> visibleSequences) { List<Long> list = new ArrayList<>(4); list.add((long) 0); list.add((long) 0); list.add((long) 0); list.add((long) 0); <START> Map<Mutation, Integer> mutations = new HashMap<>(); <END> mutations.put(Mutation.INSERTION, 1); mutations.put(Mutation.DELETION, 2); mutations.put(Mutation.POLYMORPHISM, 3); for (SequenceSegment segment : bucket) { Set<Sequence> sources = new HashSet<>(segment.getSources()); if (visibleSequences != null) { sources.retainAll(visibleSequences); } long size = segment.getContent().getLength() * sources.size(); if (mutations.containsKey(segment.getMutation())) { int index = mutations.get(segment.getMutation()); list.set(index, list.get(index) + size); } list.set(0, list.get(0) + size); } return list; }</code><technical_language>Initialize HashMap 3</technical_language>

Target:
private List<Long> insertBucket(final Set<SequenceSegment> bucket, final Set<Sequence> visibleSequences) { List<Long> list = new ArrayList<>(NUMBER_OF_VALUES); for (int index = 0; index < NUMBER_OF_VALUES; index++) { list.add((long) 0); } Map<Mutation, Integer> mutations = new HashMap<>(3); mutations.put(Mutation.INSERTION, INSERTION_MAP); mutations.put(Mutation.DELETION, DELETION_MAP); mutations.put(Mutation.POLYMORPHISM, POLYMORPHISM_MAP); for (SequenceSegment segment : bucket) { Set<Sequence> sources = new HashSet<>(segment.getSources()); if (visibleSequences != null) { sources.retainAll(visibleSequences); } long size = segment.getContent().getLength() * sources.size(); if (mutations.containsKey(segment.getMutation())) { int index = mutations.get(segment.getMutation()); list.set(index, list.get(index) + size); } list.set(0, list.get(0) + size); } return list; }
Source:
<code>private HttpMessage sendRequest(HttpMessage msg, String param, String value) throws IOException { <START> msg = msg.cloneRequest(); <END> setParameter(msg, param, value); sendAndReceive(msg); return msg; }</code><technical_language>This getNewMessage() <LINK_0> (Might good review, build details out of date other parts good.)</technical_language>

Target:
private HttpMessage sendRequest(HttpMessage msg, String param, String value) throws IOException { msg = getNewMsg(); setParameter(msg, param, value); sendAndReceive(msg); requestsSent++; return msg; }
Source:
<code>boolean maybeResumeSuspendedTask(final TaskId taskId, final Set<TopicPartition> partitions) { if (suspended.containsKey(taskId)) { final StreamTask task = suspended.get(taskId); log.trace("Found suspended {}", taskTypeName, taskId); suspended.remove(taskId); if (task.partitions().equals(partitions)) { task.resume(); try { transitionToRunning(task); } catch (final TaskMigratedException e) { log.info("Failed to resume since it got migrated to another thread already. " + "Will trigger a new rebalance and close all tasks as zombies together.", taskTypeName, task.id()); throw e; } log.trace("Resuming suspended {}", taskTypeName, task.id()); return true; <START> } else { <END> log.warn("Couldn't resume task assigned partitions {}, task partitions {}", taskId, partitions, task.partitions()); task.closeSuspended(true, null); } } return false; }</code><technical_language>new diff contains closeZombieTask usages, of in AssignedStreamTasks firstException.compareAndSet(null, closeZombieTask(task)); prevActiveTasks.remove(id); standby tasks update some internal state closeRevokedStandbyTasks, disgard this function, is good enough encourage bugs people impression do more closing a task</technical_language>

Target:
boolean maybeResumeSuspendedTask(final TaskId taskId, final Set<TopicPartition> partitions) { if (suspended.containsKey(taskId)) { final StreamTask task = suspended.get(taskId); log.trace("Found suspended stream task {}", taskId); suspended.remove(taskId); if (task.partitions().equals(partitions)) { task.resume(); try { transitionToRunning(task); } catch (final TaskMigratedException e) { log.info("Failed to resume stream task since it got migrated to another thread already. " + "Will trigger a new rebalance and close all tasks as zombies together.", task.id()); throw e; } log.trace("Resuming the suspended stream task {}", task.id()); return true; } else { log.warn("Couldn't resume stream task assigned partitions {}, task partitions {}", taskId, partitions, task.partitions()); task.closeSuspended(true, null); } } return false; }
Source:
<code><START> private ExpressionTree getPackageName(CompilationUnitTree cut) { <END> return cut.packageDeclaration() != null ? cut.packageDeclaration().packageName() : null; }</code><technical_language>![MAJOR](<LINK_0> "getPackageName" a "static" method. [![rule](<LINK_2>](<LINK_1></technical_language>

Target:
private static ExpressionTree getPackageName(CompilationUnitTree cut) { return cut.packageDeclaration() != null ? cut.packageDeclaration().packageName() : null; }
Source:
<code>private Map <String, String> getQuota(Folder folder) { Map <String, String> map = new HashMap <String, String>(); try { if (folder.exists() && folder.getMessageCount() > 0) { <START> Quota[] quotas = ((IMAPFolder)folder).getQuota(); <END> for (Quota quota : quotas) { for (Quota.Resource resource : quota.resources) { String unit = " Mo"; int coef = 1000; if ((resource.limit/1000)>9999){ unit = " Go"; coef = 1000000; } String spaceUsed = new BigDecimal(String.valueOf(((double)(resource.usage*100)/(double)(resource.limit)))).setScale(2, BigDecimal.ROUND_DOWN).toString().concat("%"); map.put("userQuota", new BigDecimal(String.valueOf(((double)(resource.limit))/coef)).setScale(2, BigDecimal.ROUND_DOWN).toString().concat(unit)); map.put("spaceUsed", spaceUsed); } } } return map; } catch (MessagingException e) { log.error("Failed to connect or get quota for mail user "); map.put("userQuota", null); return map; } }</code><technical_language>@waymirec -- test this POP? Tweak work w/ POP</technical_language>

Target:
private EmailQuota getQuota(Folder folder) { if(!(folder instanceof IMAPFolder)) { return null; } try { if (folder.exists() && folder.getMessageCount() > 0) { Quota[] quotas = ((IMAPFolder)folder).getQuota(); for (Quota quota : quotas) { for (Quota.Resource resource : quota.resources) { if(resource.name.equals("STORAGE")) { return new EmailQuota(resource.limit,resource.usage); } } } } } catch (MessagingException e) { log.error("Failed to connect or get quota for mail user "); } return null; }
Source:
<code>protected void handleAnnotations(final DeploymentUnit deploymentUnit, final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final Class<?> componentClass, final EJBComponentDescription componentConfiguration) throws DeploymentUnitProcessingException { final EEModuleClassDescription clazz = applicationClasses.getClassByName(componentClass.getName()); if (clazz == null) { return; } final ClassAnnotationInformation<RunAs, String> runAs = clazz.getAnnotationInformation(RunAs.class); final ClassAnnotationInformation<RunAsPrincipal, String> runAsPrincipal = clazz .getAnnotationInformation(RunAsPrincipal.class); if (runAs == null) { if(runAsPrincipal != null) { <START> EjbLogger.DEPLOYMENT_LOGGER.warnf("@RunAs annotation is required when using @RunAsPrincipal on %s", componentClass.getName()); <END> } return; } if (!runAs.getClassLevelAnnotations().isEmpty()) { componentConfiguration.setRunAs(runAs.getClassLevelAnnotations().get(0)); } String principal = DEFAULT_RUN_AS_PRINCIPAL; if (runAsPrincipal != null) { if (!runAsPrincipal.getClassLevelAnnotations().isEmpty()) { principal = runAsPrincipal.getClassLevelAnnotations().get(0); } } componentConfiguration.setRunAsPrincipal(principal); }</code><technical_language>This a new method in EjbLogger</technical_language>

Target:
protected void handleAnnotations(final DeploymentUnit deploymentUnit, final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final Class<?> componentClass, final EJBComponentDescription componentConfiguration) throws DeploymentUnitProcessingException { final EEModuleClassDescription clazz = applicationClasses.getClassByName(componentClass.getName()); if (clazz == null) { return; } final ClassAnnotationInformation<RunAs, String> runAs = clazz.getAnnotationInformation(RunAs.class); final ClassAnnotationInformation<RunAsPrincipal, String> runAsPrincipal = clazz .getAnnotationInformation(RunAsPrincipal.class); if (runAs == null) { if(runAsPrincipal != null) { EjbLogger.DEPLOYMENT_LOGGER.missingRunAsAnnotation(componentClass.getName()); } return; } if (!runAs.getClassLevelAnnotations().isEmpty()) { componentConfiguration.setRunAs(runAs.getClassLevelAnnotations().get(0)); } String principal = DEFAULT_RUN_AS_PRINCIPAL; if (runAsPrincipal != null) { if (!runAsPrincipal.getClassLevelAnnotations().isEmpty()) { principal = runAsPrincipal.getClassLevelAnnotations().get(0); } } componentConfiguration.setRunAsPrincipal(principal); }
Source:
<code>public void initialize() { Configuration config = getThing().getConfiguration(); String ipAddress = (String) config.get(SonyAudioBindingConstants.HOST_PARAMETER); String path = (String) config.get(SonyAudioBindingConstants.SCALAR_PATH_PARAMETER); Object port_o = config.get(SonyAudioBindingConstants.SCALAR_PORT_PARAMETER); int port; if (port_o instanceof BigDecimal) { port = ((BigDecimal) port_o).intValue(); } else { port = (int) port_o; } Object refresh_o = config.get(SonyAudioBindingConstants.REFRESHINTERVAL); int refresh = 0; if (refresh_o instanceof BigDecimal) { refresh = ((BigDecimal) refresh_o).intValue(); } else if (refresh_o instanceof Integer) { refresh = (int) refresh_o; } try { connection = new SonyAudioConnection(ipAddress, port, path, this); connection.connect(scheduler); Runnable connectionChecker = new Runnable() { @Override public void run() { try { if (!connection.checkConnection()) { updateStatus(ThingStatus.OFFLINE); <START> } <END> } catch (Exception ex) { logger.warn("Exception in check connection to @{}. Cause: {}", connection.getConnectionName(), ex.getMessage()); } } }; connectionCheckerFuture = scheduler.scheduleWithFixedDelay(connectionChecker, 1, 10, TimeUnit.SECONDS); startAutomaticRefresh(refresh); } catch (Exception e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage()); } }</code><technical_language>If I correctly, this method establish socket connection, means is potentially long running (e.g. in case of a timeout). move connectionChecker job (or this is same, simply delete this line here)</technical_language>

Target:
public void initialize() { Configuration config = getThing().getConfiguration(); String ipAddress = (String) config.get(SonyAudioBindingConstants.HOST_PARAMETER); String path = (String) config.get(SonyAudioBindingConstants.SCALAR_PATH_PARAMETER); Object port_o = config.get(SonyAudioBindingConstants.SCALAR_PORT_PARAMETER); int port = 10000; if (port_o instanceof BigDecimal) { port = ((BigDecimal) port_o).intValue(); } else if (port_o instanceof Integer) { port = (int) port_o; } Object refresh_o = config.get(SonyAudioBindingConstants.REFRESHINTERVAL); int refresh = 0; if (refresh_o instanceof BigDecimal) { refresh = ((BigDecimal) refresh_o).intValue(); } else if (refresh_o instanceof Integer) { refresh = (int) refresh_o; } try { connection = new SonyAudioConnection(ipAddress, port, path, this, scheduler, webSocketClient); Runnable connectionChecker = () -> { try { if (!connection.checkConnection()) { if (getThing().getStatusInfo().getStatus() != ThingStatus.OFFLINE) { logger.info("Lost connection"); updateStatus(ThingStatus.OFFLINE); } } } catch (Exception ex) { logger.warn("Exception in check connection to @{}. Cause: {}", connection.getConnectionName(), ex.getMessage(), ex); } }; connectionCheckerFuture = scheduler.scheduleWithFixedDelay(connectionChecker, 1, 10, TimeUnit.SECONDS); startAutomaticRefresh(refresh); } catch (URISyntaxException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage()); } }
Source:
<code>public static void closeWelcomePage() { if (welcomePageClosed) return; try { bot.viewByTitle("Welcome").close(); welcomePageClosed = true; } catch (WidgetNotFoundException e) { <START> welcomePageClosed = true; <END> } }</code><technical_language>put this a finally block? Saves line of code..</technical_language>

Target:
public static void closeWelcomePage() { if (welcomePageClosed) return; try { bot.viewByTitle("Welcome").close(); } catch (WidgetNotFoundException e) { } finally { welcomePageClosed = true; } }
Source:
<code>public Response addMetadataStoreRealm(@PathParam("realm") String realm) { try { if (!_metadataStoreDirectory.addMetadataStoreRealm(_namespace, realm)) { return serverError(); } } catch (IllegalArgumentException ex) { return notFound(ex.getMessage()); <START> } catch (IllegalStateException ex) { return serverError(); <END> } return created(); }</code><technical_language>throwing IllegalStateException</technical_language>

Target:
public Response addMetadataStoreRealm(@PathParam("realm") String realm) { try { if (!_metadataStoreDirectory.addMetadataStoreRealm(_namespace, realm)) { return serverError(); } } catch (IllegalArgumentException ex) { return notFound(ex.getMessage()); } return created(); }
Source:
<code>static CommentDetailFragment newInstance(SiteModel site, CommentModel commentModel) { CommentDetailFragment fragment = new CommentDetailFragment(); Bundle args = new Bundle(); args.putInt(KEY_MODE, FROM_BLOG_COMMENT); <START> args.putLong(KEY_SITE_ID, site.getSiteId()); <END> args.putLong(KEY_COMMENT_ID, commentModel.getRemoteCommentId()); fragment.setArguments(args); return fragment; }</code><technical_language>fix this, pass local ids (site.getId() int) serialized site model</technical_language>

Target:
static CommentDetailFragment newInstance(SiteModel site, CommentModel commentModel) { CommentDetailFragment fragment = new CommentDetailFragment(); Bundle args = new Bundle(); args.putInt(KEY_MODE, FROM_BLOG_COMMENT); args.putInt(KEY_SITE_LOCAL_ID, site.getId()); args.putLong(KEY_COMMENT_ID, commentModel.getRemoteCommentId()); fragment.setArguments(args); return fragment; }
Source:
<code>public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final HeapObject other = (HeapObject) obj; if ( node == null ) { return other.node == null; } <START> else return node.equals(other.node); <END> }</code><technical_language>need else clause if clause a return</technical_language>

Target:
public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final HeapObject other = (HeapObject) obj; if ( node == null ) { return other.node == null; } return node.equals(other.node); }
Source:
<code>public void sendConfirmationEmailForSubmission(String courseId, String feedbackSessionName, String userId, String unregisteredStudentEmail, String unregisteredStudentRegKey) throws EntityDoesNotExistException { Assumption.assertNotNull(ERROR_NULL_PARAMETER, courseId); Assumption.assertNotNull(ERROR_NULL_PARAMETER, feedbackSessionName); feedbackSessionsLogic.sendConfirmationEmailForSubmission(courseId, <START> feedbackSessionName, <END> userId, unregisteredStudentEmail, unregisteredStudentRegKey); }</code><technical_language>feedbackSessionName previous line</technical_language>

Target:
public void sendConfirmationEmailForSubmission(String courseId, String feedbackSessionName, String userId, String unregisteredStudentEmail, String unregisteredStudentRegKey) throws EntityDoesNotExistException { Assumption.assertNotNull(ERROR_NULL_PARAMETER, courseId); Assumption.assertNotNull(ERROR_NULL_PARAMETER, feedbackSessionName); Assumption.assertFalse(ERROR_NULL_PARAMETER, userId == null && (unregisteredStudentEmail == null || unregisteredStudentRegKey == null)); feedbackSessionsLogic.sendConfirmationEmailForSubmission(courseId, feedbackSessionName, userId, unregisteredStudentEmail, unregisteredStudentRegKey); }
Source:
<code>private void backup() { List<BackupOperation> batch = ImmutableList.copyOf(operations); operations.clear(); BackupRequest request = BackupRequest.request( context.descriptor(), context.nodeId(), context.currentTerm(), context.currentIndex(), batch); log.trace("Sending to {}", request, nodeId); <START> context.protocol().backup(nodeId, request).join(); <END> lastSent = System.currentTimeMillis(); }</code><technical_language>Instead of join change method signature return completable future return cf backup propagate call stack</technical_language>

Target:
private void backup() { List<BackupOperation> batch = ImmutableList.copyOf(operations); operations.clear(); BackupRequest request = BackupRequest.request( context.descriptor(), context.memberId(), context.currentTerm(), context.currentIndex(), batch); log.trace("Sending to {}", request, memberId); context.protocol().backup(memberId, request); lastSent = System.currentTimeMillis(); }
Source:
<code>public void shutdown() throws InterruptedException { stopPeriodRebalance(); <START> stopOnDemandTimer(); <END> logger.info("Shutting down pipeline", Pipeline.Type.DEFAULT.name()); shutdownPipeline(_eventThread, _eventQueue); logger.info("Shutting down pipeline", Pipeline.Type.TASK.name()); shutdownPipeline(_taskEventThread, _taskEventQueue); _asyncTasksThreadPool.shutdownNow(); try { _asyncTasksThreadPool.awaitTermination(EVENT_THREAD_JOIN_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Timeout when terminating async tasks. Some async tasks are still executing."); } shutdownAsyncFIFOWorkers(); enableClusterStatusMonitor(false); _rebalancerRef.closeRebalancer(); }</code><technical_language>stopOnDemandTimer FINALIZE notification? This is done for PeriodRebalance timer</technical_language>

Target:
public void shutdown() throws InterruptedException { stopPeriodRebalance(); shutdownOnDemandTimer(); logger.info("Shutting down pipeline", Pipeline.Type.DEFAULT.name()); shutdownPipeline(_eventThread, _eventQueue); logger.info("Shutting down pipeline", Pipeline.Type.TASK.name()); shutdownPipeline(_taskEventThread, _taskEventQueue); _asyncTasksThreadPool.shutdownNow(); try { _asyncTasksThreadPool.awaitTermination(EVENT_THREAD_JOIN_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Timeout when terminating async tasks. Some async tasks are still executing."); } shutdownAsyncFIFOWorkers(); enableClusterStatusMonitor(false); _rebalancerRef.closeRebalancer(); }
Source:
<code>public boolean allInnerJoins() { return m_joinType == JoinType.INNER && <START> (m_leftNode == null ? true : m_leftNode.allInnerJoins()) && <END> (m_rightNode == null ? true : m_rightNode.allInnerJoins()); }</code><technical_language>X ? true : Y simplifies X || Y</technical_language>

Target:
public boolean allInnerJoins() { return m_joinType == JoinType.INNER && (m_leftNode == null || m_leftNode.allInnerJoins()) && (m_rightNode == null || m_rightNode.allInnerJoins()); }
Source:
<code>protected boolean canCreateSymLinks() { <START> if (!isWindowsVistaOrHigher()) <END> return true; if (canCreateSymLinkOnWindows == null) { IPath tempDir = getTempDir(); String linkName = FileSystemHelper.getRandomLocation(tempDir).lastSegment(); try { createSymLink(tempDir.toFile(), linkName, "testTarget", false); new File(tempDir.toFile(), linkName).delete(); canCreateSymLinkOnWindows = Boolean.TRUE; } catch (AssertionFailedError e) { canCreateSymLinkOnWindows = Boolean.FALSE; } } return canCreateSymLinkOnWindows.booleanValue(); }</code><technical_language>This called result cached in canCreateSymLinks field for non-Windows platforms</technical_language>

Target:
protected boolean canCreateSymLinks() { if (canCreateSymLink == null) { if (isWindowsVistaOrHigher()) { IPath tempDir = getTempDir(); String linkName = FileSystemHelper.getRandomLocation(tempDir).lastSegment(); try { createSymLink(tempDir.toFile(), linkName, "testTarget", false); new File(tempDir.toFile(), linkName).delete(); canCreateSymLink = Boolean.TRUE; } catch (AssertionFailedError e) { canCreateSymLink = Boolean.FALSE; } } else { canCreateSymLink = Boolean.TRUE; } } return canCreateSymLink.booleanValue(); }
Source:
<code>private void waitForTransportState(String state) { if (stateMap.get("TransportState") != null) { long start = System.currentTimeMillis(); while (!stateMap.get("TransportState").equals(state)) { try { Thread.sleep(50); <START> if (System.currentTimeMillis() - start > (this.notificationTimeout.longValue() * 1000)) { <END> break; } } catch (InterruptedException e) { logger.error("InterruptedException during playing a notification sound"); } } } }</code><technical_language>adding unneeded braces</technical_language>

Target:
private void waitForTransportState(String state) { if (stateMap.get("TransportState") != null) { long start = System.currentTimeMillis(); while (!stateMap.get("TransportState").equals(state)) { try { Thread.sleep(50); if (System.currentTimeMillis() - start > this.notificationTimeout.longValue() * 1000) { break; } } catch (InterruptedException e) { logger.error("InterruptedException during playing a notification sound"); } } } }
Source:
<code>public static InternalFileContent createWorkspaceFileContent(IFile file) { String path= file.getLocationURI().getPath(); path= normalizePath(path, file); InputStream input; try { long fileReadTime = System.currentTimeMillis(); IFileStore store = EFS.getStore(file.getLocationURI()); IFileInfo fileInfo = store.fetchInfo(); input= file.getContents(true); <START> if ((input instanceof FileInputStream)) { <END> try { return createFileContent(path, file.getCharset(), input, fileInfo.getLastModified(), fileInfo.getLength(), fileReadTime); } finally { try { input.close(); } catch (IOException e) { } } } } catch (CoreException e) { switch (e.getStatus().getCode()) { case IResourceStatus.NOT_FOUND_LOCAL: case IResourceStatus.NO_LOCATION_LOCAL: case IResourceStatus.FAILED_READ_LOCAL: case IResourceStatus.RESOURCE_NOT_LOCAL: case IResourceStatus.RESOURCE_NOT_FOUND: break; default: CCorePlugin.log(e); break; } } return null; }</code><technical_language>Redundant parentheses</technical_language>

Target:
public static InternalFileContent createWorkspaceFileContent(IFile file) { String path= file.getLocationURI().getPath(); path= normalizePath(path, file); InputStream input; try { long fileReadTime = System.currentTimeMillis(); IFileStore store = EFS.getStore(file.getLocationURI()); IFileInfo fileInfo = store.fetchInfo(); input= file.getContents(true); if (input instanceof FileInputStream) { try { return createFileContent(path, file.getCharset(), input, fileInfo.getLastModified(), fileInfo.getLength(), fileReadTime); } finally { try { input.close(); } catch (IOException e) { } } } } catch (CoreException e) { switch (e.getStatus().getCode()) { case IResourceStatus.NOT_FOUND_LOCAL: case IResourceStatus.NO_LOCATION_LOCAL: case IResourceStatus.FAILED_READ_LOCAL: case IResourceStatus.RESOURCE_NOT_LOCAL: case IResourceStatus.RESOURCE_NOT_FOUND: break; default: CCorePlugin.log(e); break; } } return null; }
Source:
<code>private boolean hasPlainToString(Class<?> cls, Object obj) { try { if (cls.getMethod("toString") == plainToString) { return true; } <START> String plainToStringValue = cls.getName() + "@" + Integer.toHexString(obj.hashCode()); <END> return plainToStringValue.equals(obj.toString()); } catch (Exception e) { return false; } }</code><technical_language>default toString call obj.hashCode() System.identityHashCode()</technical_language>

Target:
private boolean hasPlainToString(Class<?> cls, Object obj) { try { if (cls.getMethod("toString") == plainToString) { return true; } String plainToStringValue = cls.getName() + "@" + Integer.toHexString(System.identityHashCode(obj)); return plainToStringValue.equals(obj.toString()); } catch (Exception e) { return false; } }
Source:
<code>String getDetails() throws ReportException; String getParameters() throws ReportException; ResultsPage getAllResults() throws ReportException; ResultsPage getResults() throws ReportException; void setConfiguration(Resource config); void setPage(int page); default Map<String, String> getParamPatternMap(SlingHttpServletRequest request) { Map<String, String> parameters = new HashMap<>(); Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String key = paramNames.nextElement(); parameters.put(key, StringEscapeUtils.escapeSql(request.getParameter(key))); } <START> LoggerFactory.getLogger(this.getClass()).trace("Loading parameters from request: {}", parameters); <END> return parameters; }</code><technical_language>Typically define Logger a class variable.. private static final Logger log = LoggerFactor.getLogger(this.getClass()); .. is trace right level? feels more a Debug me</technical_language>

Target:
String getDetails() throws ReportException; String getParameters() throws ReportException; ResultsPage getAllResults() throws ReportException; ResultsPage getResults() throws ReportException; void setConfiguration(Resource config); void setPage(int page); default Map<String, String> getParamPatternMap(SlingHttpServletRequest request) { Map<String, String> parameters = new HashMap<>(); Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String key = paramNames.nextElement(); parameters.put(key, StringEscapeUtils.escapeSql(request.getParameter(key))); } LoggerFactory.getLogger(this.getClass()).debug("Loading parameters from request: {}", parameters); return parameters; }
Source:
<code>public Object get(String handle, StorageRecordType recordType) { try { <START> storageLock.lock(); <END> if (_storage == null) { throw new RuntimeException(EXCEPTION_STORAGE); } String value = _storage.get(recordType.getKey(handle)); if (value == null) { return null; } if (recordType.equals(ACCESS_TOKEN_RESPONSE)) { AccessTokenResponse accessTokenResponse = gson.fromJson(value, AccessTokenResponse.class); return accessTokenResponse; } else if (recordType.equals(SERVICE_CONFIGURATION)) { PersistedParams params = gson.fromJson(value, PersistedParams.class); return params; } else if (recordType.equals(LAST_USED)) { Date lastUsedDate = gson.fromJson(value, Date.class); return lastUsedDate; } return null; } finally { storageLock.unlock(); } }</code><technical_language>try block</technical_language>

Target:
public @Nullable Object get(String handle, StorageRecordType recordType) { storageLock.lock(); try { if (storage == null) { throw new IllegalStateException(EXCEPTION_STORAGE); } String value = storage.get(recordType.getKey(handle)); if (value == null) { return null; } if (recordType.equals(ACCESS_TOKEN_RESPONSE)) { try { AccessTokenResponse accessTokenResponse = gson.fromJson(value, AccessTokenResponse.class); return accessTokenResponse; } catch (Exception e) { logger.error( "Unable to deserialize json, discarding AccessTokenResponse. " + "Please check json against standard or with oauth provider. json:\n{}", value, e); return null; } } else if (recordType.equals(SERVICE_CONFIGURATION)) { try { PersistedParams params = gson.fromJson(value, PersistedParams.class); return params; } catch (Exception e) { logger.error("Unable to deserialize json, discarding PersistedParams. json:\n{}", value, e); return null; } } else if (recordType.equals(LAST_USED)) { try { LocalDateTime lastUsedDate = gson.fromJson(value, LocalDateTime.class); return lastUsedDate; } catch (Exception e) { logger.info("Unable to deserialize json, reset LAST_USED to now. json:\n{}", value); return LocalDateTime.now(); } } return null; } finally { storageLock.unlock(); } }
Source:
<code>public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = new HashMap<String, String>(); VDSGroup vdsGroup = getVdsGroup(); <START> jobProperties.put(VdcObjectType.VdsGroups.name().toLowerCase(), <END> vdsGroup == null ? null : vdsGroup.getname()); } return jobProperties; }</code><technical_language>GlusterConstants.CLUSTER here? ${cluster} is more readable ${vdsgroups} in properties file.</technical_language>

Target:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = new HashMap<String, String>(); VDSGroup vdsGroup = getVdsGroup(); jobProperties.put(GlusterConstants.CLUSTER, vdsGroup == null ? null : vdsGroup.getname()); } return jobProperties; }
Source:
<code>private void findByName() throws IOException { RepositoryUtil repoUtil = getRepositoryUtil(); RepositoryCache repoCache = getRepositoryCache(); for (String dirs : repoUtil.getConfiguredRepositories()) { match = repoCache.lookupRepository(new File(dirs)); if (!ResourcePropertyTester.hasGerritConfiguration(match)) { <START> break; <END> } RemoteConfig remote = findRemoteByName(); if (remote != null) { return; } } match = null; }</code><technical_language>I a question : testing if configuration a Gerrit config, If don't, break. match re-init end of method null. In cases, match null,</technical_language>

Target:
private void findByName() throws IOException { RepositoryUtil repoUtil = getRepositoryUtil(); RepositoryCache repoCache = getRepositoryCache(); for (String dirs : repoUtil.getConfiguredRepositories()) { match = repoCache.lookupRepository(new File(dirs)); if (!ResourcePropertyTester.hasGerritConfiguration(match)) { continue; } RemoteConfig remote = findRemoteByName(); if (remote != null) { return; } } match = null; }
Source:
<code>protected List<String> getTags(DocumentModel docModel) { <START> return (List<String>) docModel.getPropertyValue(TAG_LIST); <END> }</code><technical_language>catch PropertyNotFoundException return Collections.emptyList() in case</technical_language>

Target:
protected List<String> getTags(DocumentModel docModel) { try { return (List<String>) docModel.getPropertyValue(TAG_LIST); } catch (PropertyNotFoundException e) { return Collections.emptyList(); } }
Source:
<code>private void initializeItems() { List<IStorageModel> items = AsyncDataProvider.getIsoStorageModels(); <START> items.addAll(AsyncDataProvider.getInstance().getExportStorageModels()); <END> items.addAll(AsyncDataProvider.getFileDataStorageModels()); items.addAll(AsyncDataProvider.getImportBlockDataStorageModels()); getModel().setItems(items); }</code><technical_language>this backported? Checkstyle is complaining it</technical_language>

Target:
private void initializeItems() { List<IStorageModel> items = AsyncDataProvider.getIsoStorageModels(); items.addAll(AsyncDataProvider.getExportStorageModels()); items.addAll(AsyncDataProvider.getFileDataStorageModels()); items.addAll(AsyncDataProvider.getImportBlockDataStorageModels()); getModel().setItems(items); }
Source:
<code>private boolean handleWebSocketHandshake(CarbonMessage carbonMessage, Session session) throws WebSocketEndpointAnnotationException { EndpointsRegistryImpl endpointsRegistry = EndpointsRegistryImpl.getInstance(); PatternPathRouter.RoutableDestination<Object> routableEndpoint = endpointsRegistry.getRoutableEndpoint(carbonMessage); try { if (routableEndpoint == null) { throw new NullPointerException("Cannot find the URI for the endpoint"); } Method method = new EndpointDispatcher().getOnOpenMethod(routableEndpoint.getDestination()); List<Object> parameterList = new LinkedList<>(); Map<String, String> paramValues = routableEndpoint.getGroupNameValues(); Arrays.stream(method.getParameters()).forEach( parameter -> { if (parameter.getType() == Session.class) { parameterList.add(session); } else if (parameter.getType() == String.class) { PathParam pathParam = parameter.getAnnotation(PathParam.class); if (pathParam != null) { parameterList.add(paramValues.get(pathParam.value())); } else { <START> parameterList.add(null); <END> throw new IllegalArgumentException("String parameters without" + " @PathParam annotation"); } } else { parameterList.add(null); } } ); executeMethod(method, routableEndpoint.getDestination(), parameterList, session); return true; } catch (Throwable throwable) { handleError(carbonMessage, throwable, routableEndpoint, session); return false; } }</code><technical_language>If throwing, do need add a null list</technical_language>

Target:
private boolean handleWebSocketHandshake(CarbonMessage carbonMessage, Session session) { EndpointsRegistryImpl endpointsRegistry = EndpointsRegistryImpl.getInstance(); String requestUri = (String) carbonMessage.getProperty(Constants.TO); PatternPathRouter.RoutableDestination<Object> routableEndpoint = endpointsRegistry.getRoutableEndpoint(requestUri); Optional<Method> methodOptional = new EndpointDispatcher().getOnOpenMethod(routableEndpoint.getDestination()); Map<String, String> paramValues = routableEndpoint.getGroupNameValues(); try { List<Object> parameterList = new LinkedList<>(); methodOptional.ifPresent( method -> { Arrays.stream(method.getParameters()).forEach( parameter -> { if (parameter.getType() == Session.class) { parameterList.add(session); } else if (parameter.getType() == String.class) { PathParam pathParam = parameter.getAnnotation(PathParam.class); if (pathParam != null) { parameterList.add(paramValues.get(pathParam.value())); } else { throw new IllegalArgumentException("String parameters without" + " @PathParam annotation"); } } else { parameterList.add(null); } } ); executeMethod(method, routableEndpoint.getDestination(), parameterList, session); } ); return true; } catch (Throwable throwable) { handleError(throwable, routableEndpoint, session); return false; } }
Source:
<code>catch (Exception e) { <START> LOG.fatal("Can't access to getPathToAliases() on " + MapredWork.class.getName(), e); <END> throw new RuntimeException("Incompatible Hive API found. Expected: 0.11.0+", e); }</code><technical_language>mapWorkClass instead of MapredWork.class</technical_language>

Target:
catch (Exception e) { mapWorkClazz = MapredWork.class; LOG.info("No Hive 0.12.0 compatible API was found, couldn't load " + mapWorkClassName); LOG.debug(e); }
Source:
<code>public View getView(int position, View convertView, ViewGroup parent) { View element = convertView; if(element == null){ LayoutInflater inflater = (LayoutInflater) this.mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); element = inflater.inflate(R.layout.song_item, null); } View userColor = (View) element.findViewById(R.id.user_color); TextView title = (TextView)element.findViewById(R.id.title); TextView artist = (TextView) element.findViewById(R.id.artist); TextView album = (TextView) element.findViewById(R.id.album); ImageButton addButton = (ImageButton) element.findViewById(R.id.add_to_playlist); addButton.setTag(position); <START> userColor.setBackgroundColor(0xFFFFFFFF); <END> title.setText(metadataList.get(position).getTitle()); artist.setText(metadataList.get(position).getArtist()); album.setText(metadataList.get(position).getAlbum()); artist.setMaxWidth(parent.getWidth()/2); return element; }</code><technical_language>this hardcoded</technical_language>

Target:
public View getView(int position, View convertView, ViewGroup parent) { View element = convertView; if(element == null){ LayoutInflater inflater = (LayoutInflater) this.mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); element = inflater.inflate(R.layout.song_item, null); } View userColor = (View) element.findViewById(R.id.user_color); TextView title = (TextView)element.findViewById(R.id.title); TextView artist = (TextView) element.findViewById(R.id.artist); TextView album = (TextView) element.findViewById(R.id.album); String macAddress = metadataList.get(position).getMacAddress(); userColor.setBackgroundColor(users.getUserByMACAddress(macAddress).getColor()); ImageButton addButton = (ImageButton) element.findViewById(R.id.add_to_playlist); addButton.setTag(position); title.setText(metadataList.get(position).getTitle()); artist.setText(metadataList.get(position).getArtist()); album.setText(metadataList.get(position).getAlbum()); artist.setMaxWidth(parent.getWidth()/2); return element; }
Source:
<code>public void testSuccessInThePresenceOfVariousErrors() throws Exception { doPut(); String dcWherePutHappened = routerConfig.routerDatacenterName; Properties props = getNonBlockingRouterProperties(); props.setProperty("router.datacenter.name", "DC1"); routerConfig = new RouterConfig(new VerifiableProperties(props)); testVariousErrors(dcWherePutHappened); <START> props = getNonBlockingRouterProperties(); <END> props.setProperty("router.datacenter.name", "DC2"); routerConfig = new RouterConfig(new VerifiableProperties(props)); testVariousErrors(dcWherePutHappened); props = getNonBlockingRouterProperties(); props.setProperty("router.datacenter.name", "DC3"); routerConfig = new RouterConfig(new VerifiableProperties(props)); testVariousErrors(dcWherePutHappened); }</code><technical_language>do need this line</technical_language>

Target:
public void testSuccessInThePresenceOfVariousErrors() throws Exception { doPut(); String dcWherePutHappened = routerConfig.routerDatacenterName; Properties props = getDefaultNonBlockingRouterProperties(); props.setProperty("router.datacenter.name", "DC1"); routerConfig = new RouterConfig(new VerifiableProperties(props)); testVariousErrors(dcWherePutHappened); props = getDefaultNonBlockingRouterProperties(); props.setProperty("router.datacenter.name", "DC2"); routerConfig = new RouterConfig(new VerifiableProperties(props)); testVariousErrors(dcWherePutHappened); props = getDefaultNonBlockingRouterProperties(); props.setProperty("router.datacenter.name", "DC3"); routerConfig = new RouterConfig(new VerifiableProperties(props)); testVariousErrors(dcWherePutHappened); }
Source:
<code>public Dialog createDialog(Activity activity, final Bundle args) { mapActivity = (MapActivity) activity; AlertDialog.Builder builder = new Builder(mapActivity); builder.setTitle(R.string.send_location_way_choose_title); builder.setItems(new String[]{ "Email", "SMS", "Clipboard", "geo:", "QR-Code" }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final double latitude = args.getDouble(MapActivityActions.KEY_LATITUDE); final double longitude = args.getDouble(MapActivityActions.KEY_LONGITUDE); final int zoom = args.getInt(MapActivityActions.KEY_ZOOM); try { final String shortOsmUrl = MapUtils.buildShortOsmUrl(latitude, longitude, zoom); final String geoUrl = MapUtils.buildGeoUrl(latitude, longitude, zoom); String sms = mapActivity.getString(R.string.send_location_sms_pattern, geoUrl, shortOsmUrl); if (which == 0) { <START> sendEmail(shortOsmUrl, geoUrl); <END> } else if (which == 1) { sendSms(sms); } else if (which == 2) { sendToClipboard(sms); } else if (which == 3) { sendGeoActivity(geoUrl); } else if (which == 4) { sendQRCode(latitude, longitude); } } catch (RuntimeException e) { Toast.makeText(mapActivity, R.string.input_output_error, Toast.LENGTH_SHORT).show(); } } }); return builder.create(); }</code><technical_language>This is stay app link rely receiver OsmAnd install instead rely proper internet address</technical_language>

Target:
public Dialog createDialog(Activity activity, final Bundle args) { mapActivity = (MapActivity) activity; AlertDialog.Builder builder = new Builder(mapActivity); builder.setTitle(R.string.send_location_way_choose_title); builder.setItems(new String[]{ "Email", "SMS", "Clipboard", "geo:", "QR-Code" }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final double latitude = args.getDouble(MapActivityActions.KEY_LATITUDE); final double longitude = args.getDouble(MapActivityActions.KEY_LONGITUDE); final int zoom = args.getInt(MapActivityActions.KEY_ZOOM); try { final String geoUrl = MapUtils.buildGeoUrl(latitude, longitude, zoom); final String httpUrl = "<LINK_0>" + ((float) latitude) + "&lon=" + ((float) longitude) + "&z=" + zoom; String sms = mapActivity.getString(R.string.send_location_sms_pattern, geoUrl, httpUrl); if (which == 0) { sendEmail(httpUrl, geoUrl); } else if (which == 1) { sendSms(sms); } else if (which == 2) { sendToClipboard(sms); } else if (which == 3) { sendGeoActivity(geoUrl); } else if (which == 4) { sendQRCode(latitude, longitude); } } catch (RuntimeException e) { Toast.makeText(mapActivity, R.string.input_output_error, Toast.LENGTH_SHORT).show(); } } }); return builder.create(); }
Source:
<code>public ZkCloudname connectWithTimeout(long waitTime, TimeUnit waitUnit) throws CloudnameException { try { zkObjectHandler = new ZkObjectHandler( new ZooKeeper(connectString, SESSION_TIMEOUT, this)); if (! connectedSignal.await(waitTime, waitUnit)) { zkObjectHandler.close(); throw new CloudnameException("Connecting to ZooKeeper timed out."); } log.fine("Connected to ZooKeeper " + connectString); } catch (IOException e) { <START> zkObjectHandler.close(); <END> throw new CloudnameException(e); } catch (InterruptedException e) { zkObjectHandler.close(); throw new CloudnameException(e); } resolver = new ZkResolver.Builder().addStrategy(new StrategyAll()) .addStrategy(new StrategyAny()).build(zkObjectHandler.getClient()); start(); return this; }</code><technical_language>close in finally finally is _always_ called. return, throw etc</technical_language>

Target:
public ZkCloudname connectWithTimeout(long waitTime, TimeUnit waitUnit) throws CloudnameException { boolean connected = false; try { zkObjectHandler = new ZkObjectHandler( new ZooKeeper(connectString, SESSION_TIMEOUT, this)); if (! connectedSignal.await(waitTime, waitUnit)) { throw new CloudnameException("Connecting to ZooKeeper timed out."); } log.fine("Connected to ZooKeeper " + connectString); connected = true; } catch (IOException e) { throw new CloudnameException(e); } catch (InterruptedException e) { throw new CloudnameException(e); } finally { if (!connected) { zkObjectHandler.close(); } } resolver = new ZkResolver.Builder().addStrategy(new StrategyAll()) .addStrategy(new StrategyAny()).build(zkObjectHandler.getClient()); scheduler.scheduleWithFixedDelay(this, 1 , 1000 , TimeUnit.MILLISECONDS); return this; }
Source:
<code>public String getUsage(ICommandSender sender) { <START> return new TextComponentTranslation("commands.bloodmagic.orb." + getName() + ".usage").getFormattedText() + "\n" + help; <END> }</code><technical_language>getUsage(...) expects a localization key</technical_language>

Target:
public String getUsage(ICommandSender sender) { return "commands.bloodmagic.orb." + getName() + ".usage"; }
Source:
<code>public WebSocketClientHandshaker07 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { <START> this.forceCloseTimeoutMillis = forceCloseTimeoutMillis; <END> return this; }</code><technical_language>nit: jut call super.setForceCloseTimeoutMillis(...) this ensure do correct if change super method content allow forceCloseTimeMillis private</technical_language>

Target:
public WebSocketClientHandshaker07 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { super.setForceCloseTimeoutMillis(forceCloseTimeoutMillis); return this; }
Source:
<code>private void doRequest(String url, String method, final OutputProvider output) throws IOException { <START> try (HttpResponse conn = requestFactory.request(0, url, method, null, null, null)) { <END> if (output instanceof HttpOutputMessage) { HttpOutputMessage httpOutput = (HttpOutputMessage)output; httpOutput.setStatus(conn.getResponseCode()); final String contentType = conn.getContentType(); if (contentType != null) { httpOutput.addHttpHeader(HttpHeaders.CONTENT_TYPE, contentType); } final String contentDisposition = conn.getHeaderField(HttpHeaders.CONTENT_DISPOSITION); if (contentDisposition != null) { httpOutput.addHttpHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); } } try (InputStream in = conn.getInputStream(); OutputStream out = output.getOutputStream()) { ByteStreams.copy(in, out); } } }</code><technical_language>I is timeout avoid changes in app behavior</technical_language>

Target:
private void doRequest(String url, String method, final OutputProvider output) throws IOException { try (HttpResponse conn = requestFactory.target(url).setTimeout(60 * 1000).setMethod(method).request()) { if (output instanceof HttpOutputMessage) { HttpOutputMessage httpOutput = (HttpOutputMessage)output; httpOutput.setStatus(conn.getResponseCode()); final String contentType = conn.getContentType(); if (contentType != null) { httpOutput.addHttpHeader(HttpHeaders.CONTENT_TYPE, contentType); } final String contentDisposition = conn.getHeaderField(HttpHeaders.CONTENT_DISPOSITION); if (contentDisposition != null) { httpOutput.addHttpHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); } } try (InputStream in = conn.getInputStream(); OutputStream out = output.getOutputStream()) { ByteStreams.copy(in, out); } } }
Source:
<code>private void enqueueModuleBuild(GitInfo branch, RepositoryBuild branchBuild, Module module) throws IOException, NonRetryableBuildException { String sha = branchBuild.getCommitInfo().get().getCurrent().getId(); String folder = module.getFolder(); String configPath = folder + (folder.isEmpty() ? "" : "/") + ".blazar.yaml"; <START> BuildConfig baseConfig = buildConfigUtils.getConfigAtRefOrDefault(branch, configPath, sha); <END> final BuildConfig mergedConfig; if (baseConfig.getBuildpack().isPresent()) { BuildConfig buildpackConfig = buildConfigUtils.getConfigForBuildpackOnBranch(baseConfig.getBuildpack().get()); mergedConfig = buildConfigUtils.mergeConfig(baseConfig, buildpackConfig); } else if (module.getBuildpack().isPresent()) { BuildConfig buildpackConfig = buildConfigUtils.getConfigForBuildpackOnBranch(module.getBuildpack().get()); mergedConfig = buildConfigUtils.mergeConfig(baseConfig, buildpackConfig); } else { mergedConfig = baseConfig; } moduleBuildService.enqueue(branchBuild, module, baseConfig, buildConfigUtils.ensureDefaultConfigurationForBuild(mergedConfig)); }</code><technical_language>I try/catch in visitLaunching method. happen if this method throws error</technical_language>

Target:
private void enqueueModuleBuild(GitInfo branch, RepositoryBuild branchBuild, Module module) throws IOException, NonRetryableBuildException { String sha = branchBuild.getCommitInfo().get().getCurrent().getId(); String folder = module.getFolder(); String configPath = folder + (folder.isEmpty() ? "" : "/") + ".blazar.yaml"; BuildConfig buildConfig = buildConfigUtils.getConfigAtRefOrDefault(branch, configPath, sha); final BuildConfig mergedConfig; if (buildConfig.getBuildpack().isPresent()) { BuildConfig buildpackConfig = buildConfigUtils.getConfigForBuildpackOnBranch(buildConfig.getBuildpack().get()); mergedConfig = buildConfigUtils.mergeConfig(buildConfig, buildpackConfig); } else if (module.getBuildpack().isPresent()) { BuildConfig buildpackConfig = buildConfigUtils.getConfigForBuildpackOnBranch(module.getBuildpack().get()); mergedConfig = buildConfigUtils.mergeConfig(buildConfig, buildpackConfig); } else { mergedConfig = buildConfig; } moduleBuildService.enqueue(branchBuild, module, buildConfig, buildConfigUtils.addMissingBuildConfigSettings(mergedConfig)); }
Source:
<code>public @Nullable StateDescription getStateDescription(@Nullable Locale locale) { <START> return stateDescriptionService.getStateDescription(this.name, locale); <END> }</code><technical_language>This result in NPE stateDescriptionService is nullable (and a dynamic+optional dependency in ItemRegistryImpl)</technical_language>

Target:
public @Nullable StateDescription getStateDescription(@Nullable Locale locale) { if (stateDescriptionService != null) { return stateDescriptionService.getStateDescription(this.name, locale); } return null; }
Source:
<code>public ParseFile(File file, String contentType) { <START> this(null, file, contentType); <END> }</code><technical_language>File#getName()</technical_language>

Target:
public ParseFile(File file, String contentType) { this(new State.Builder().name(file.getName()).mimeType(contentType).build()); if (file.length() > MAX_FILE_SIZE) { throw new IllegalArgumentException(String.format("ParseFile must be less than %d bytes", MAX_FILE_SIZE)); } this.file = file; }