auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void createColumns() { <START> if (!fColumnsCreated) { <END> createColumn(Messages.LatencyTableViewer_startTime, new LatencyTableColumnLabelProvider() { @Override public String getTextFoITimeRange(ISegment input) { return NonNullUtils.nullToEmptyString(TmfTimestampFormat.getDefaulTimeFormat().format(input.getStart())); } }, SegmentComparators.INTERVAL_START_COMPARATOR); createColumn(Messages.LatencyTableViewer_endTime, new LatencyTableColumnLabelProvider() { @Override public String getTextFoITimeRange(ISegment input) { return NonNullUtils.nullToEmptyString(TmfTimestampFormat.getDefaulTimeFormat().format(input.getEnd())); } }, SegmentComparators.INTERVAL_END_COMPARATOR); createColumn(Messages.LatencyTableViewer_duration, new LatencyTableColumnLabelProvider() { @Override public String getTextFoITimeRange(ISegment input) { return NonNullUtils.nullToEmptyString(Long.toString(input.getLength())); } }, SegmentComparators.INTERVAL_LENGTH_COMPARATOR); LatencyAnalysis analysis = getAnalysisModule(); if (analysis != null) { for (final ISegmentAspect aspect : analysis.getSegmentAspects()) { createColumn(aspect.getName(), new LatencyTableColumnLabelProvider() { @Override public String getTextFoITimeRange(ISegment input) { return NonNullUtils.nullToEmptyString(aspect.resolve(input)); } }, null); } } fColumnsCreated = true; } }</code><technical_language>Now, if is trace opened, viewer columns. create default columns construction add analysis-provided later</technical_language>

Target:
private void createColumns() { createColumn(Messages.LatencyTableViewer_startTime, new LatencyTableColumnLabelProvider() { @Override public String getTextForSegment(ISegment input) { return NonNullUtils.nullToEmptyString(TmfTimestampFormat.getDefaulTimeFormat().format(input.getStart())); } }, SegmentComparators.INTERVAL_START_COMPARATOR); createColumn(Messages.LatencyTableViewer_endTime, new LatencyTableColumnLabelProvider() { @Override public String getTextForSegment(ISegment input) { return NonNullUtils.nullToEmptyString(TmfTimestampFormat.getDefaulTimeFormat().format(input.getEnd())); } }, SegmentComparators.INTERVAL_END_COMPARATOR); createColumn(Messages.LatencyTableViewer_duration, new LatencyTableColumnLabelProvider() { @Override public String getTextForSegment(ISegment input) { return NonNullUtils.nullToEmptyString(Long.toString(input.getLength())); } }, SegmentComparators.INTERVAL_LENGTH_COMPARATOR); }
Source:
<code>public Class classForName(String className, Map context) throws ClassNotFoundException { Class result = null; if ((result = (Class)classes.get(className)) == null) { try { result = Class.forName(className); } catch (ClassNotFoundException ex) { <START> if (className.indexOf('.') == -1) { <END> result = Class.forName("java.lang." + className); classes.put("java.lang." + className, result); } } if (result != null) { classes.put(className, result); } } return result; }</code><technical_language>I here, this if clause moved out of catch implemented follow (classForName throws ClassNotFoundException): java if (className.indexOf('.') == -1) { result = Class.forName("java.lang." + className); classes.put("java.lang." + className, result); } else { classes.put(className, Class.forName(className)); } result additional check for null is needed</technical_language>

Target:
public Class classForName(String className, Map context) throws ClassNotFoundException { Class result = classes.get(className); if (result != null) { return result; } result = (className.indexOf('.') == -1) ? Class.forName("java.lang." + className) : Class.forName(className); classes.put(className, result); return result; }
Source:
<code>public void doExtraction(OperationLogger logger, URI source, RoughArtifactCollector collector, String documentApplicabilty) throws IOException { <START> InputStream rawHtml = null; <END> try { String fileName = "file://" + source.getPath(); uriDirectoryName = fileName.substring(0, fileName.lastIndexOf('/') + 1); postProcessGuids.clear(); rawHtml = source.toURL().openStream(); DoorsTableRowCollector rowCollector = new DoorsTableRowCollector(this); Document doc = Jsoup.parse(rawHtml, "UTF-8", ""); Element body = doc.body(); for (Node cNodes : body.childNodes()) { for (Node subNodes : cNodes.childNodes()) { if (subNodes.nodeName().compareTo("tbody") == 0) { for (Node tableRow : subNodes.childNodes()) { if (tableRow instanceof Element) { rowCollector.addRawRow(tableRow); } } } } } rowCollector.createArtifacts(collector); } catch (Exception ex) { logger.log(ex); } finally { if (rawHtml != null) { rawHtml.close(); } } }</code><technical_language>rename htmlStream advertise a string</technical_language>

Target:
public void doExtraction(OperationLogger logger, URI source, RoughArtifactCollector collector, String documentApplicabilty) throws IOException { InputStream htmlStream = null; try { String fileName = "file://" + source.getPath(); uriDirectoryName = fileName.substring(0, fileName.lastIndexOf('/') + 1); postProcessGuids.clear(); this.logger = logger; htmlStream = source.toURL().openStream(); DoorsTableRowCollector rowCollector = new DoorsTableRowCollector(this); Document doc = Jsoup.parse(htmlStream, "UTF-8", ""); Element body = doc.body(); for (Node cNodes : body.childNodes()) { for (Node subNodes : cNodes.childNodes()) { if (subNodes.nodeName().compareTo("tbody") == 0) { for (Node tableRow : subNodes.childNodes()) { if (tableRow instanceof Element) { rowCollector.addRawRow(tableRow); } } } } } rowCollector.createArtifacts(collector); } catch (Exception ex) { logger.log(ex); } finally { Lib.close(htmlStream); } }
Source:
<code>protected void init() { <START> cluster = clusterDao.get(getParameters().getClusterId()); <END> }</code><technical_language>This is needed - getCluster() base class</technical_language>

Target:
protected void init() { super.setClusterId(getParameters().getClusterId()); cluster = getCluster(); }
Source:
<code>public void init() throws ServletException { try { caps |= Authn.Capabilities.class.getField(AUTHENTICATE_NEGOTIATE_INTERACTIVE).getLong(null); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException ex) { log.error("Error calculating authn capabilities while accessing constant {}", AUTHENTICATE_NEGOTIATE_INTERACTIVE); <START> } <END> final AuthenticationProfileRepository repo = (AuthenticationProfileRepository) getServletContext().getAttribute(SSOUtils.AUTH_PROFILE_REPOSITORY); repo.addObserver( new Observer() { @Override public void update(Observable o, Object arg) { cacheNegotiatingProfiles(repo); } } ); cacheNegotiatingProfiles(repo); }</code><technical_language>options... 1. this url is for interactive - extensions types. 2. this url serves interactive interactive, mode is determined url of phase0, for example: if access /login -> interactive, if access /get-ticket -> interactive. need pass mode chain of phases, reach mode query parameter session variable</technical_language>

Target:
public void init() throws ServletException { caps |= Authn.Capabilities.AUTHENTICATE_NEGOTIATE_INTERACTIVE | Authn.Capabilities.AUTHENTICATE_NEGOTIATE_NON_INTERACTIVE; final AuthenticationProfileRepository repo = (AuthenticationProfileRepository) getServletContext().getAttribute(SSOUtils.AUTH_PROFILE_REPOSITORY); repo.addObserver( new Observer() { @Override public void update(Observable o, Object arg) { cacheNegotiatingProfiles(repo); } } ); cacheNegotiatingProfiles(repo); }
Source:
<code><START> private void init() { <END> if (mMediaPlayerList != null) { Log.wtfStack(TAG, "init: The service has already been initialized"); return; } mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); sDeviceMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); mMediaPlayerList = new MediaPlayerList(Looper.myLooper(), this); mNativeInterface = AvrcpNativeInterface.getInterface(); mNativeInterface.init(AvrcpTargetService.this); }</code><technical_language>init() is called once, move start() start() stop() symmetrical</technical_language>

Target:
private void init() { }
Source:
<code>public void deleteDtoLogicallyByIdShouldDeletedLogicallyWhenChannelEntityExists() throws ObjectNotFoundException { ArgumentCaptor<ApplicationEntity> applicationsEntityArgumentCaptor = ArgumentCaptor.forClass(ApplicationEntity.class); given(this.applicationsRepository.findOne(APPLICATION_ID)).willReturn(applicationEntity); this.applicationsService.deleteDtoLogicallyById(APPLICATION_ID); verify(applicationsRepository).saveAndFlush(applicationsEntityArgumentCaptor.capture()); assertThat(applicationEntity, equalTo(applicationsEntityArgumentCaptor.getValue())); then(applicationsRepository).should().findOne(APPLICATION_ID); then(applicationsRepository).should().saveAndFlush(applicationEntity); <START> } <END></code><technical_language>deleted field of entity is checked</technical_language>

Target:
public void deleteDtoLogicallyByIdShouldDeletedLogicallyWhenChannelEntityExists() throws ObjectNotFoundException { ArgumentCaptor<ApplicationEntity> applicationsEntityArgumentCaptor = ArgumentCaptor.forClass(ApplicationEntity.class); given(this.applicationsRepository.findOne(APPLICATION_ID)).willReturn(applicationEntity); this.applicationsService.deleteDtoLogicallyById(APPLICATION_ID); verify(applicationsRepository).saveAndFlush(applicationsEntityArgumentCaptor.capture()); assertThat(applicationEntity, equalTo(applicationsEntityArgumentCaptor.getValue())); then(applicationsRepository).should().findOne(APPLICATION_ID); then(applicationsRepository).should().saveAndFlush(applicationEntity); assertThat(applicationEntity.isDeleted(), is(true)); }
Source:
<code>public DatasetDescriptor build() { ValidationException.check(schema != null, "Descriptor schema is required and cannot be null"); if (partitionStrategy == null) { if (PartitionStrategyParser.hasEmbeddedStrategy(schema)) { this.partitionStrategy = PartitionStrategyParser.parseFromSchema(schema); } } if (columnMapping == null) { if (ColumnMappingParser.hasEmbeddedColumnMapping(schema)) { this.columnMapping = ColumnMappingParser.parseFromSchema(schema); } else if (ColumnMappingParser.hasEmbeddedFieldMappings(schema)) { this.columnMapping = ColumnMappingParser.parseFromSchemaFields(schema); if (partitionStrategy == null) { this.partitionStrategy = buildPartitionStrategyForKeyMappings( ColumnMappingParser.parseKeyMappingsFromSchemaFields(schema)); } } } if (columnMapping == null && copiedMapping != null) { columnMapping = copiedMapping; } <START> if(EntityPropertiesParser.hasEmbeddedProperties(schema)) { <END> Map<String, String> schemaProperties = EntityPropertiesParser .parseFromSchema(schema); for (Map.Entry<String, String> propertySchemaEntry : schemaProperties .entrySet()) { if (!properties.containsKey(propertySchemaEntry.getKey())) { properties.put(propertySchemaEntry.getKey(), propertySchemaEntry.getValue()); } } } checkPartitionStrategy(schema, partitionStrategy); checkColumnMappings(schema, partitionStrategy, columnMapping); return new DatasetDescriptor( schema, schemaUri, format, location, properties, partitionStrategy, columnMapping, compressionType); }</code><technical_language>This pattern needed for partition strategy column mappings wanted provide backward-compatibility for existing HBC schemas. properties addition SchemaManager, I need worry embedded in Schemas. I removes a bit of code</technical_language>

Target:
public DatasetDescriptor build() { ValidationException.check(schema != null, "Descriptor schema is required and cannot be null"); if (partitionStrategy == null) { if (PartitionStrategyParser.hasEmbeddedStrategy(schema)) { this.partitionStrategy = PartitionStrategyParser.parseFromSchema(schema); } } if (columnMapping == null) { if (ColumnMappingParser.hasEmbeddedColumnMapping(schema)) { this.columnMapping = ColumnMappingParser.parseFromSchema(schema); } else if (ColumnMappingParser.hasEmbeddedFieldMappings(schema)) { this.columnMapping = ColumnMappingParser.parseFromSchemaFields(schema); if (partitionStrategy == null) { this.partitionStrategy = buildPartitionStrategyForKeyMappings( ColumnMappingParser.parseKeyMappingsFromSchemaFields(schema)); } } } if (columnMapping == null && copiedMapping != null) { columnMapping = copiedMapping; } checkPartitionStrategy(schema, partitionStrategy); checkColumnMappings(schema, partitionStrategy, columnMapping); return new DatasetDescriptor( schema, schemaUri, format, location, properties, partitionStrategy, columnMapping, compressionType); }
Source:
<code>public static void main(String[] args) { try { doMain(args); System.exit(0); } catch (JamesCliException e) { failWithMessage(e.getMessage()); } catch (ParseException e) { failWithMessage("Error parsing command line : " + e.getMessage()); } catch (IOException ioe) { failWithMessage("Error connecting to remote JMX agent : " + ioe.getMessage()); } catch (Exception e) { <START> LOG.error("Error on command: {}", e.toString()); <END> failWithMessage("Error " + e.getClass() + " while executing command:" + e.getMessage()); } }</code><technical_language>Swallowing stacktrace ;-) I in favour of: LOG.error("Error while playing command", e);</technical_language>

Target:
public static void main(String[] args) { try { doMain(args); System.exit(0); } catch (JamesCliException e) { failWithMessage(e.getMessage()); } catch (ParseException e) { failWithMessage("Error parsing command line : " + e.getMessage()); } catch (IOException ioe) { failWithMessage("Error connecting to remote JMX agent : " + ioe.getMessage()); } catch (Exception e) { LOG.error("Error while playing command", e); failWithMessage("Error " + e.getClass() + " while executing command:" + e.getMessage()); } }
Source:
<code>public void test_setForegroundLorg_eclipse_swt_graphics_Color() { Color color = new Color(control.getDisplay(), 255, 0, 0); control.setForeground(color); assertEquals(color, control.getForeground()); control.setForeground(null); assertFalse(control.getForeground().equals(color)); if ("gtk".equals(SWT.getPlatform ())) { <START> String gtkVersion = System.getProperty("org.eclipse.swt.internal.gtk.version"); boolean GTK3 = gtkVersion.substring(0, 1) == "3" ? true : false; <END> Color bg = new Color(control.getDisplay(), 0, 255, 0); control.setForeground(color); control.setBackground(bg); assertEquals("Setting a background disrupted the foreground color for " + control, color, control.getForeground()); assertEquals("Setting a background onto a widget with a foreground failed for " + control, bg, control.getBackground()); if (GTK3) { color = new Color (control.getDisplay(), 255, 0, 0, 0); control.setForeground(color); assertEquals(color, control.getForeground()); assertEquals("Setting a background onto a widget with a foreground failed for " + control, bg, control.getBackground()); } } color.dispose(); }</code><technical_language>I consider abstracting this useful goodie SwtTestUtil.java in other places also</technical_language>

Target:
public void test_setForegroundLorg_eclipse_swt_graphics_Color() { Color color = new Color(control.getDisplay(), 255, 0, 0); control.setForeground(color); assertEquals(color, control.getForeground()); control.setForeground(null); assertFalse(control.getForeground().equals(color)); if ("gtk".equals(SWT.getPlatform ())) { Color bg = new Color(control.getDisplay(), 0, 255, 0); control.setForeground(color); control.setBackground(bg); assertEquals("Setting a background disrupted the foreground color for " + control, color, control.getForeground()); assertEquals("Setting a background onto a widget with a foreground failed for " + control, bg, control.getBackground()); if (SwtTestUtil.GTK3) { color = new Color (control.getDisplay(), 255, 0, 0, 0); control.setForeground(color); assertEquals(color, control.getForeground()); assertEquals("Setting a background onto a widget with a foreground failed for " + control, bg, control.getBackground()); } } color.dispose(); }
Source:
<code>private void revokeUnauthToken(HeaderCacheElement oldToken) { synchronized (lock) { if (headerCache == oldToken) { headerCache = EMPTY_HEADER; } else { <START> LOG.info("Skipping revoke, since the revoked token has already changed"); <END> } } }</code><technical_language>LOG.trace</technical_language>

Target:
private void revokeUnauthToken(HeaderCacheElement oldToken) { synchronized (lock) { if (headerCache == oldToken) { LOG.warn("Got unauthenticated response from server, revoking the current token"); headerCache = EMPTY_HEADER; } else { LOG.info("Skipping revoke, since the revoked token has already changed"); } } }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.actionStartVisit: if (OpenMRS.getInstance().getSyncState()) { ((PatientDashboardVisitsPresenter) mPresenter).syncVisits(); } else { <START> ToastUtil.notify("Active patient visit cannot be started in offline mode"); <END> } break; default: break; } return super.onOptionsItemSelected(item); }</code><technical_language>Add this string resource file</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.actionStartVisit: if (OpenMRS.getInstance().getSyncState()) { ((PatientDashboardVisitsPresenter) mPresenter).syncVisits(); } else { ToastUtil.notify(getString(R.string.offline_mode_not_supported)); } break; default: break; } return super.onOptionsItemSelected(item); }
Source:
<code>protected List<ServiceName> installServices(OperationContext context, NativeInterfaceCommonPolicy commonPolicy, ModelNode model) throws OperationFailedException { populateHostControllerInfo(hostControllerInfo, context, model); final ServiceTarget serviceTarget = context.getServiceTarget(); final boolean onDemand = context.isBooting(); NativeManagementServices.installRemotingServicesIfNotInstalled(serviceTarget, hostControllerInfo.getLocalHostName(), context.getServiceRegistry(false), onDemand); OptionMap options = createConnectorOptions(commonPolicy); final ServiceName nativeManagementInterfaceBinding = NetworkInterfaceService.JBOSS_NETWORK_INTERFACE.append(hostControllerInfo.getNativeManagementInterface()); final String securityRealm = commonPolicy.getSecurityRealm(); if (securityRealm == null) { ROOT_LOGGER.nativeManagementInterfaceIsUnsecured(); } NativeManagementServices.installManagementWorkerService(serviceTarget, context.getServiceRegistry(false)); ManagementRemotingServices.installDomainConnectorServices(serviceTarget, ManagementRemotingServices.MANAGEMENT_ENDPOINT, nativeManagementInterfaceBinding, hostControllerInfo.getNativeManagementPort(), securityRealm, options); <START> return Arrays.asList(ManagementRemotingServices.MANAGEMENT_ENDPOINT, UndertowHttpManagementService.SERVICE_NAME); <END> }</code><technical_language>I related ManagementRemotingServices is required http-upgrade is turned on</technical_language>

Target:
protected List<ServiceName> installServices(OperationContext context, NativeInterfaceCommonPolicy commonPolicy, ModelNode model) throws OperationFailedException { populateHostControllerInfo(hostControllerInfo, context, model); final ServiceTarget serviceTarget = context.getServiceTarget(); final boolean onDemand = context.isBooting(); NativeManagementServices.installRemotingServicesIfNotInstalled(serviceTarget, hostControllerInfo.getLocalHostName(), context.getServiceRegistry(false), onDemand); OptionMap options = createConnectorOptions(commonPolicy); final ServiceName nativeManagementInterfaceBinding = NetworkInterfaceService.JBOSS_NETWORK_INTERFACE.append(hostControllerInfo.getNativeManagementInterface()); final String securityRealm = commonPolicy.getSecurityRealm(); if (securityRealm == null) { ROOT_LOGGER.nativeManagementInterfaceIsUnsecured(); } NativeManagementServices.installManagementWorkerService(serviceTarget, context.getServiceRegistry(false)); ManagementRemotingServices.installDomainConnectorServices(serviceTarget, ManagementRemotingServices.MANAGEMENT_ENDPOINT, nativeManagementInterfaceBinding, hostControllerInfo.getNativeManagementPort(), securityRealm, options); return Arrays.asList(REMOTING_BASE.append("server", MANAGEMENT_CONNECTOR), nativeManagementInterfaceBinding); }
Source:
<code>private boolean groupAndValueMatches(long groupId, Block block, int position, int nodePointer, int valuePosition) { <START> long groupIdExisting = groupIds.get(nodePointer); <END> return groupIdExisting == groupId && type.equalTo(block, position, values, valuePosition); }</code><technical_language>groupIdExisting -> existingGroupId</technical_language>

Target:
private boolean groupAndValueMatches(long groupId, Block block, int position, int nodePointer, int valuePosition) { long existingGroupId = groupIds.get(nodePointer); return existingGroupId == groupId && type.equalTo(block, position, values, valuePosition); }
Source:
<code>public List<StudentAttributes> getAllCourseStudents() { List<StudentAttributes> list = new LinkedList<StudentAttributes>(); List<CourseStudent> entities = getCourseStudentEntities(); Iterator<CourseStudent> it = entities.iterator(); <START> while (it.hasNext()) { <END> CourseStudent student = it.next(); if (!JDOHelper.isDeleted(student)) { list.add(new StudentAttributes(student)); } } return list; }</code><technical_language>this before, do reasons iterator instead of for-loop</technical_language>

Target:
public List<StudentAttributes> getAllCourseStudents() { List<StudentAttributes> list = new LinkedList<StudentAttributes>(); List<CourseStudent> entities = getCourseStudentEntities(); for (CourseStudent student : entities) { if (!JDOHelper.isDeleted(student)) { list.add(new StudentAttributes(student)); } } return list; }
Source:
<code>static List<String> getInputFieldValue(StructuredRecord input, String inputField, Splitter splitter) { List<String> text = new ArrayList<>(); Schema schema = input.getSchema().getField(inputField).getSchema(); Schema.Type type = schema.isNullable() ? schema.getNonNullable().getType() : schema.getType(); if (type.equals(Schema.Type.ARRAY)) { schema = schema.getComponentSchema(); type = schema.isNullable() ? schema.getNonNullable().getType() : schema.getType(); <START> if (type.equals(Schema.Type.STRING)) { <END> text = input.get(inputField); } else { throw new IllegalArgumentException( String.format("Field to be used for text based feature generation should be of type string, nullable " + "string or array of strings or nullable string. But was ARRAY of %s for field %s.", schema.getComponentSchema(), inputField)); } } else if (type.equals(Schema.Type.STRING)) { if (inputField != null) { text = Lists.newArrayList(splitter.split((String) input.get(inputField))); } } return text; }</code><technical_language>easier read if do: if (type != Schema.Type.String)) { throw new ... } //logic removes layer of indentation. In case, if need check. this validated configure time</technical_language>

Target:
static List<String> getInputFieldValue(StructuredRecord input, String inputField, Splitter splitter) { List<String> text = new ArrayList<>(); Schema schema = input.getSchema().getField(inputField).getSchema(); Schema.Type type = schema.isNullable() ? schema.getNonNullable().getType() : schema.getType(); try { if (type == Schema.Type.ARRAY) { Object value = input.get(inputField); if (value instanceof List) { text = input.get(inputField); } else { text = Lists.newArrayList((String[]) value); } } else { String value = input.get(inputField); if (value != null) { text = Lists.newArrayList(splitter.split(value)); } } } catch (ClassCastException e) { throw new IllegalArgumentException(String.format("Schema type mismatch for field %s. Please make sure the " + "value to be used for feature generation is an array of " + "string or a string.", inputField), e); } return text; }
Source:
<code>public Optional<TYPE> first() { Optional result = Optional.empty(); <START> List<TYPE> list = first(1).asList(); <END> if(!list.isEmpty()) { result = Optional.of(list.get(0)); } return result; }</code><technical_language>java Iterable<TYPE> resultIterable = first(1); return resultIterable.hasNext() ? Optional.of(resultIterable.next()) : Optional.empty(); need copy list</technical_language>

Target:
public Optional<TYPE> first() { Iterator<TYPE> resultIterator = first(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); }
Source:
<code>private static void runMemoryTest(Set<ITmfTrace> testTraces, String testName, int loop_count) { Performance perf = Performance.getDefault(); PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + MEMORY + '#' + testName); <START> perf.tagAsSummary(pm, TEST_SUMMARY + MEMORY + ':' + testName, Dimension.CPU_TIME); <END> for (int i = 0; i < loop_count; i++) { TmfNetworkEventMatching traceMatch = new TmfNetworkEventMatching(testTraces); System.gc(); pm.start(); traceMatch.matchEvents(); System.gc(); pm.stop(); } pm.commit(); }</code><technical_language>Dimension.USED_JAVA_HEAP</technical_language>

Target:
private static void runMemoryTest(Set<ITmfTrace> testTraces, String testName, int loop_count) { Performance perf = Performance.getDefault(); PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + MEMORY + '#' + testName); perf.tagAsSummary(pm, TEST_SUMMARY + MEMORY + ':' + testName, Dimension.USED_JAVA_HEAP); for (int i = 0; i < loop_count; i++) { TmfNetworkEventMatching traceMatch = new TmfNetworkEventMatching(testTraces); System.gc(); pm.start(); traceMatch.matchEvents(); System.gc(); pm.stop(); } pm.commit(); }
Source:
<code>public Collection<String> findAllUsersWithRole(String roleName) { <START> TypedQuery<String> query = entityManager.createNamedQuery("listUsersWithRole", String.class); <END> query.setParameter("groupname", roleName); return query.getResultList(); }</code><technical_language>pls querydsl instead (already in master)</technical_language>

Target:
public Collection<String> findAllUsersWithRole(String roleName) { JPAQuery query = new JPAQuery(entityManager); QRoleImpl role = QRoleImpl.roleImpl; QUserImpl user = QUserImpl.userImpl; return query.from(role) .where(role.name.eq(roleName)) .join(role.members, user) .list(user.username); }
Source:
<code>public void test10_01_tagConfiguration() { driver.findElement(By.id("tagConfiguration_10_01")).click(); assertThat(driver.getPageSource().contains( "<div class=\"alert alert-success\"><ul><li></li></ul></div>"), is(true)); <START> screenCapture.save(driver); <END> }</code><technical_language>[x] I think, cases difference in appearance of result screen. So, page source for evidence. --- OK btkatoutmj</technical_language>

Target:
public void test10_01_tagConfiguration() { driver.findElement(By.id("tagConfiguration_10_01")).click(); assertThat(driver.getPageSource().contains( "<div class=\"alert alert-success\"><ul><li></li></ul></div>"), is(true)); pageSource.save(driver); }
Source:
<code>protected Guid getStoragePoolIdForDomain(Guid storageDomainId) { StorageDomainQueryParametersBase params = new StorageDomainQueryParametersBase(storageDomainId); params.setSessionId(getSessionHelper().getSessionId()); <START> VdcQueryReturnValue returnValue = getBackend().RunQuery(VdcQueryType.GetStoragePoolsByStorageDomainId, <END> params); @SuppressWarnings("unchecked") List<storage_pool> storagePools = (List<storage_pool>) returnValue.getReturnValue(); if (storagePools != null && !storagePools.isEmpty()) { return storagePools.get(0).getId(); } else { return Guid.Empty; } }</code><technical_language>please getBackendCollection(Class<T> clz, VdcQueryType query, VdcQueryParametersBase queryParams) method instead of manual query invocation</technical_language>

Target:
protected Guid getStoragePoolIdForDomain(Guid storageDomainId) { StorageDomainQueryParametersBase params = new StorageDomainQueryParametersBase(storageDomainId); List<storage_pool> storagePools = getBackendCollection(storage_pool.class, VdcQueryType.GetStoragePoolsByStorageDomainId, params); if (storagePools != null && !storagePools.isEmpty()) { return storagePools.get(0).getId(); } else { return Guid.Empty; } }
Source:
<code>public MethodOutcome updateFHIRCondition(@ResourceParam Condition condition, @IdParam IdType uuid) { try { return MethodOutcomeBuilder.buildUpdate(conditionResource.updateFHIRCondition(condition, uuid.getIdPart())); } catch (Exception e) { <START> throw new InvalidRequestException("Following exception occured: " + e.getMessage() + " " + <END> ExceptionUtils.getStackTrace(e)); } }</code><technical_language>do of this exception is request invalid</technical_language>

Target:
public MethodOutcome updateFHIRCondition(@ResourceParam Condition condition, @IdParam IdType uuid) { return MethodOutcomeBuilder.buildUpdate(conditionResource.updateFHIRCondition(condition)); }
Source:
<code>public void validate(String path) { if (path == null || path.isEmpty()) { return; } String[] folders = REGEX_FOLDER_SPLIT.split(path); if (folders == null || folders.length < 1) { return; } for (String folder : folders) { if (PARENT_FOLDER_IDENTIFIER.equals(folder)) { <START> throw new IllegalArgumentException("Invalid URI path: '" + path + "'. Parent paths are not allowed."); <END> } } }</code><technical_language>Remove word "URI"</technical_language>

Target:
public void validate(String path) { if (path == null || path.isEmpty()) { return; } String[] folders = REGEX_FOLDER_SPLIT.split(path); if (folders == null || folders.length < 1) { return; } for (String folder : folders) { if (PARENT_FOLDER_IDENTIFIER.equals(folder)) { throw new IllegalArgumentException("Invalid path: '" + path + "'. Parent paths are not allowed."); } } }
Source:
<code><START> protected void createTestData() { <END> LNPTestData testData = getTestData(); try { createJsonDataFile(testData); createCsvConfigDataFile(testData); } catch (IOException ex) { log.severe(TeammatesException.toStringWithStackTrace(ex)); } }</code><technical_language>this</technical_language>

Target:
protected void createTestData() { LNPTestData testData = getTestData(); try { createJsonDataFile(testData); persistTestData(); createCsvConfigDataFile(testData); } catch (IOException | HttpRequestFailedException ex) { log.severe(TeammatesException.toStringWithStackTrace(ex)); } }
Source:
<code>void createIMMenu (long imHandle) { boolean showInputMethod = false; long settings = OS.gtk_settings_get_default (); if (settings != 0) { int buffer = new int [1]; <START> if (OS.GTK_VERSION < OS.VERSION (3, 10, 0)) { <END> OS.g_object_get (settings, OS.gtk_show_input_method_menu, buffer, 0); showInputMethod = buffer[0] != 0; } } if (imHandle == 0 || !showInputMethod) { this.imHandle = 0; if (imItem != 0) { OS.gtk_widget_destroy (imItem); imItem = 0; } if (imSeparator != 0) { OS.gtk_widget_destroy (imSeparator); imSeparator = 0; } return; } if (this.imHandle == imHandle) return; this.imHandle = imHandle; if (imSeparator == 0) { imSeparator = OS.gtk_separator_menu_item_new (); OS.gtk_widget_show (imSeparator); OS.gtk_menu_shell_insert (handle, imSeparator, -1); } if (imItem == 0) { byte[] buffer = Converter.wcsToMbcs (null, SWT.getMessage("SWT_InputMethods"), true); imItem = OS.gtk_image_menu_item_new_with_label (buffer); OS.gtk_widget_show (imItem); OS.gtk_menu_shell_insert (handle, imItem, -1); } long imSubmenu = OS.gtk_menu_new (); OS.gtk_im_multicontext_append_menuitems (imHandle, imSubmenu); OS.gtk_menu_item_set_submenu (imItem, imSubmenu); }</code><technical_language>put Gtk version check 'if (settings !=0)' block if (settings != 0 && OS.GTK.... buffer is instantiated for reason for Gtk3.10+, waste of memory cpu power :-/. Lols, picky yes</technical_language>

Target:
void createIMMenu (long imHandle) { boolean showInputMethod = false; long settings = OS.gtk_settings_get_default (); if (settings != 0 && OS.GTK_VERSION < OS.VERSION (3, 10, 0)) { int buffer = new int [1]; OS.g_object_get (settings, OS.gtk_show_input_method_menu, buffer, 0); showInputMethod = buffer[0] != 0; } if (imHandle == 0 || !showInputMethod) { this.imHandle = 0; if (imItem != 0) { OS.gtk_widget_destroy (imItem); imItem = 0; } if (imSeparator != 0) { OS.gtk_widget_destroy (imSeparator); imSeparator = 0; } return; } if (this.imHandle == imHandle) return; this.imHandle = imHandle; if (imSeparator == 0) { imSeparator = OS.gtk_separator_menu_item_new (); OS.gtk_widget_show (imSeparator); OS.gtk_menu_shell_insert (handle, imSeparator, -1); } if (imItem == 0) { byte[] buffer = Converter.wcsToMbcs (null, SWT.getMessage("SWT_InputMethods"), true); imItem = OS.gtk_image_menu_item_new_with_label (buffer); OS.gtk_widget_show (imItem); OS.gtk_menu_shell_insert (handle, imItem, -1); } long imSubmenu = OS.gtk_menu_new (); OS.gtk_im_multicontext_append_menuitems (imHandle, imSubmenu); OS.gtk_menu_item_set_submenu (imItem, imSubmenu); }
Source:
<code>private ASTValue evalRepeat(WordsEnvironment environment) throws WordsException { ASTValue times = children.get(0).eval(environment); AST statementList = children.get(1); if (times.type != ValueType.NUM) { <START> throw new InvalidTypeException(this.lineNo, ValueType.NUM.toString(), times.type.toString()); <END> } for (int i = 0; i < times.numValue; i++) { statementList.eval(environment); } return null; }</code><technical_language>original code inconsistent reference manual. allow a string if coerced a number. fix open issue for assign if like</technical_language>

Target:
private ASTValue evalRepeat(WordsEnvironment environment) throws WordsRuntimeException { ASTValue times = children.get(0).eval(environment).tryCoerceTo(ValueType.NUM); AST statementList = children.get(1); if (times.type != ValueType.NUM) { throw new WordsInvalidTypeException(ValueType.NUM.toString(), times.type.toString()); } for (int i = 0; i < times.numValue; i++) { statementList.eval(environment); } return null; }
Source:
<code>public static JSONObject getItemJsonObject(Context context, String name) { try { int stringId = context.getResources().getIdentifier(name, "string", context.getPackageName()); String item = context.getString(stringId); return new JSONObject(item); } catch (NullPointerException | JSONException e) { <START> e.printStackTrace(); <END> return DUMMY_OBJECT; } }</code><technical_language>printStackTrace in production code</technical_language>

Target:
public static JSONObject getItemJsonObject(Context context, String name) { if(context != null && name != null) { try { name = MyApplication.toId(name); int stringId = context.getResources().getIdentifier(name, "string", context.getPackageName()); if (stringId != 0) { String item = context.getString(stringId); return new JSONObject(item); } } catch (JSONException e) { } } return DUMMY_JSON_ITEM; }
Source:
<code>private Notifications getSwitches(SonyAudioClientSocket socket, Notifications notifications) throws IOException { SwitchNotifications switchNotifications = new SwitchNotifications(notifications.enabled, notifications.disabled); JsonElement switches = socket.callMethod(switchNotifications); Gson mapper = new Gson(); Type notificationListType = new TypeToken<List<Notification>>() { }.getType(); notifications.enabled = mapper.fromJson(switches.getAsJsonArray().get(0).getAsJsonObject().get("enabled"), notificationListType); <START> notifications.disabled = mapper.fromJson(switches.getAsJsonArray().get(0).getAsJsonObject().get("disabled"), <END> notificationListType); return notifications; }</code><technical_language>a field new instantiations expensive</technical_language>

Target:
private Notifications getSwitches(SonyAudioClientSocket socket, Notifications notifications) throws IOException { SwitchNotifications switchNotifications = new SwitchNotifications(notifications.enabled, notifications.disabled); JsonElement switches = socket.callMethod(switchNotifications); Type notificationListType = new TypeToken<List<Notification>>() { }.getType(); notifications.enabled = gson.fromJson(switches.getAsJsonArray().get(0).getAsJsonObject().get("enabled"), notificationListType); notifications.disabled = gson.fromJson(switches.getAsJsonArray().get(0).getAsJsonObject().get("disabled"), notificationListType); return notifications; }
Source:
<code>public boolean isUsefulForIndex() { if("place".equals(tagKey) && "houses".equals(tagValue)) return false; if(houseNumber != null) return true; if(name.isEmpty()) return false; <START> return linkedPlaceId <= 0; <END> }</code><technical_language>intellij is continuously recommending simplify this code this way, i is hard understand this</technical_language>

Target:
public boolean isUsefulForIndex() { if("place".equals(tagKey) && "houses".equals(tagValue)) return false; if(houseNumber != null) return true; if(name.isEmpty()) return false; if(linkedPlaceId > 0) return false; return true; }
Source:
<code>public void onInitialization(FMLInitializationEvent e) { try { this.registry.init(); if (!this.game.getServiceManager().provide(PermissionService.class).isPresent()) { try { this.game.getServiceManager().setProvider(this, PermissionService.class, new SpongePermissionService()); } catch (ProviderExistsException e1) { } } } catch (Throwable t) { <START> logger.error("On init", t); <END> } }</code><technical_language>Is this debug? Otherwise, give more descriptive errors</technical_language>

Target:
public void onInitialization(FMLInitializationEvent e) { try { this.registry.init(); if (!this.game.getServiceManager().provide(PermissionService.class).isPresent()) { try { this.game.getServiceManager().setProvider(this, PermissionService.class, new SpongePermissionService()); } catch (ProviderExistsException e1) { } } } catch (Throwable t) { this.controller.errorOccurred(this, t); } }
Source:
<code>protected void setNextTableToSweep(TableReference tableRef) { Mockito.doReturn(Optional.of(tableRef)).when(nextTableToSweepProvider) <START> .getNextTableToSweep(any(), Mockito.anyLong()); <END> }</code><technical_language>nit: static import anyLong() for consistency</technical_language>

Target:
protected void setNextTableToSweep(TableReference tableRef) { doReturn(Optional.of(tableRef)).when(nextTableToSweepProvider) .getNextTableToSweep(any(), anyLong()); }
Source:
<code>private void startAsync( WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException { String env = null; <START> if (!SidecarToolingWorkspaceUtil.isSidecarBasedWorkspace(workspace.getConfig().getAttributes()) <END> || envName != null || !workspace.getConfig().getEnvironments().isEmpty()) { if (envName != null && !workspace.getConfig().getEnvironments().containsKey(envName)) { throw new NotFoundException( format( "Workspace '%s:%s' doesn't contain environment '%s'", workspace.getNamespace(), workspace.getConfig().getName(), envName)); } env = firstNonNull(envName, workspace.getConfig().getDefaultEnv()); try { runtimes.validate(workspace.getConfig().getEnvironments().get(env)); } catch (InfrastructureException | ValidationException e) { throw new ServerException(e); } } workspace.getAttributes().put(UPDATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis())); workspaceDao.update(workspace); runtimes .startAsync(workspace, env, firstNonNull(options, Collections.emptyMap())) .thenAccept(aVoid -> handleStartupSuccess(workspace)) .exceptionally( ex -> { if (workspace.isTemporary()) { removeWorkspaceQuietly(workspace); } else { handleStartupError(workspace, ex.getCause()); } return null; }); }</code><technical_language>IMHO a difficult for understanding potentially error-prone statement. I understand it. Please consider rewriting in a simpler way. Currently, If I understand statement correctly: environment validated in advance if is a sidecar based workspace while be. I wrong</technical_language>

Target:
private void startAsync( WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException { String env = getValidatedEnvironmentName(workspace, envName); workspace.getAttributes().put(UPDATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis())); workspaceDao.update(workspace); runtimes .startAsync(workspace, env, firstNonNull(options, Collections.emptyMap())) .thenAccept(aVoid -> handleStartupSuccess(workspace)) .exceptionally( ex -> { if (workspace.isTemporary()) { removeWorkspaceQuietly(workspace); } else { handleStartupError(workspace, ex.getCause()); } return null; }); }
Source:
<code>public Response toResponse(JsonMappingException exception) { LOGGER.error(exception.getMessage()); <START> ImmutableMap<String, String> entity = ImmutableMap.of("message", exception.getMessage()); <END> return Response.status(400).entity(entity).type(APPLICATION_JSON).build(); }</code><technical_language>Map.of( )</technical_language>

Target:
public Response toResponse(JsonMappingException exception) { LOGGER.error(exception.getMessage()); Map<String, String> entity = Map.of("message", exception.getMessage()); return Response.status(400).entity(entity).type(APPLICATION_JSON).build(); }
Source:
<code>public JSONObject createContent() { if (sessionsBySetting.size() == 0) { return null; } Map<Boolean, Set<String>> currentSessions; synchronized (sessionsBySetting) { currentSessions = new TreeMap<>(sessionsBySetting); sessionsBySetting.clear(); <START> } <END> JSONObject payload = new JSONObject(); for (Map.Entry<Boolean, Set<String>> entry : currentSessions.entrySet()) { payload.put(entry.getKey().toString(), entry.getValue().size()); } return payload; }</code><technical_language>enough, currentSessions.entrySet() iterator collide recordRequest(). I recommend synchronizing entire block</technical_language>

Target:
public JSONObject createContent() { int sessionsWithAutoRefreshCount, sessionsWithoutAutoRefreshCount; synchronized (sessionsWithAutoRefresh) { sessionsWithAutoRefreshCount = sessionsWithAutoRefresh.size(); sessionsWithAutoRefresh.clear(); } synchronized (sessionsWithoutAutoRefresh) { sessionsWithoutAutoRefreshCount = sessionsWithoutAutoRefresh.size(); sessionsWithoutAutoRefresh.clear(); } if (sessionsWithAutoRefreshCount == 0 && sessionsWithoutAutoRefreshCount == 0) { return null; } JSONObject payload = new JSONObject(); payload.put("enabled", sessionsWithAutoRefreshCount); payload.put("disabled", sessionsWithoutAutoRefreshCount); return payload; }
Source:
<code>protected VDSReturnValue performImageVdsmOperation() { setDestinationImageId(Guid.newGuid()); newDiskImage = cloneDiskImage(getDestinationImageId()); newDiskImage.setId(Guid.newGuid()); Guid storagePoolID = newDiskImage.getStoragePoolId() != null ? newDiskImage .getStoragePoolId() : Guid.Empty; VDSReturnValue vdsReturnValue = null; Guid taskId = persistAsyncTaskPlaceHolder(VdcActionType.AddVmFromTemplate); try { vdsReturnValue = runVdsCommand(VDSCommandType.CopyImage, PostZeroHandler.fixParametersWithPostZero( new CopyImageVDSCommandParameters(storagePoolID, getParameters().getStorageDomainId(), getVmTemplateId(), getDiskImage().getId(), getImage().getImageId(), newDiskImage.getId(), getDestinationImageId(), "", getDestinationStorageDomainId(), CopyVolumeType.LeafVol, newDiskImage.getVolumeFormat(), newDiskImage.getVolumeType(), getDiskImage().isWipeAfterDelete(), false))); } catch (VdcBLLException e) { <START> log.error("Failed creating snapshot from image id -'{}'", getImage().getImageId()); <END> throw e; } if (vdsReturnValue.getSucceeded()) { getReturnValue().getInternalVdsmTaskIdList().add( createTask(taskId, vdsReturnValue.getCreationInfo(), VdcActionType.AddVmFromTemplate, VdcObjectType.Storage, getParameters().getStorageDomainId(), getDestinationStorageDomainId())); } return vdsReturnValue; }</code><technical_language>s/-//'</technical_language>

Target:
protected VDSReturnValue performImageVdsmOperation() { setDestinationImageId(Guid.newGuid()); newDiskImage = cloneDiskImage(getDestinationImageId()); newDiskImage.setId(Guid.newGuid()); Guid storagePoolID = newDiskImage.getStoragePoolId() != null ? newDiskImage .getStoragePoolId() : Guid.Empty; VDSReturnValue vdsReturnValue = null; Guid taskId = persistAsyncTaskPlaceHolder(VdcActionType.AddVmFromTemplate); try { vdsReturnValue = runVdsCommand(VDSCommandType.CopyImage, PostZeroHandler.fixParametersWithPostZero( new CopyImageVDSCommandParameters(storagePoolID, getParameters().getStorageDomainId(), getVmTemplateId(), getDiskImage().getId(), getImage().getImageId(), newDiskImage.getId(), getDestinationImageId(), "", getDestinationStorageDomainId(), CopyVolumeType.LeafVol, newDiskImage.getVolumeFormat(), newDiskImage.getVolumeType(), getDiskImage().isWipeAfterDelete(), false))); } catch (VdcBLLException e) { log.error("Failed creating snapshot from image id '{}'", getImage().getImageId()); throw e; } if (vdsReturnValue.getSucceeded()) { getReturnValue().getInternalVdsmTaskIdList().add( createTask(taskId, vdsReturnValue.getCreationInfo(), VdcActionType.AddVmFromTemplate, VdcObjectType.Storage, getParameters().getStorageDomainId(), getDestinationStorageDomainId())); } return vdsReturnValue; }
Source:
<code><START> public HazelcastEntityInformation(PersistentEntity<T, ?> entity) { <END> super(entity); if (!entity.hasIdProperty()) { throw new MappingException( String.format("Entity %s requires a field annotated with %s", entity.getName(), Id.class.getName())); } }</code><technical_language>same: package-private</technical_language>

Target:
HazelcastEntityInformation(PersistentEntity<T, ?> entity) { super(entity); if (!entity.hasIdProperty()) { throw new MappingException( String.format("Entity %s requires a field annotated with %s", entity.getName(), Id.class.getName())); } }
Source:
<code>public Object newInstance(Class[] argumentTypes, Object[] arguments, Callback[] callbacks) { setThreadCallbacks(callbacks); try { <START> if (!Arrays.equals(primaryConstructorArgTypes, argumentTypes)) { <END> return ReflectUtils.newInstance(generatedClass, argumentTypes, arguments); } try { return primaryConstructor.newInstance(arguments); } catch (InstantiationException e) { throw new CodeGenerationException(e); } catch (IllegalAccessException e) { throw new CodeGenerationException(e); } catch (InvocationTargetException e) { throw new CodeGenerationException(e.getTargetException()); } } finally { setThreadCallbacks(null); } }</code><technical_language>Arrays.equals internally a short-circuit for a==b? if not, i majority of cases ==, invert this do: if (a == b || Arrays.equals(a, b)) { createFromCxtor } else { createGettingCxtor }</technical_language>

Target:
public Object newInstance(Class[] argumentTypes, Object[] arguments, Callback[] callbacks) { setThreadCallbacks(callbacks); try { if (primaryConstructorArgTypes == argumentTypes || Arrays.equals(primaryConstructorArgTypes, argumentTypes)) { return ReflectUtils.newInstance(primaryConstructor, arguments); } return ReflectUtils.newInstance(generatedClass, argumentTypes, arguments); } finally { setThreadCallbacks(null); } }
Source:
<code>public void testCreateTeamWithRepoAccess() throws IOException { String REPO_NAME = "github-api"; String TEAM_NAME = "create-team-test"; GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG); GHRepository repo = org.getRepository(REPO_NAME); <START> GHTeam existingTeam = org.getTeamByName(TEAM_NAME); <END> if (existingTeam != null) { existingTeam.delete(); } GHTeam team = org.createTeam(TEAM_NAME, GHOrganization.Permission.PUSH, repo); Assert.assertTrue(team.getRepositories().containsKey(REPO_NAME)); }</code><technical_language>This done in a @Before method githubBeforeAfter connection. <LINK_0></technical_language>

Target:
public void testCreateTeamWithRepoAccess() throws IOException { String REPO_NAME = "github-api"; GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG); GHRepository repo = org.getRepository(REPO_NAME); GHTeam team = org.createTeam(TEAM_NAME_CREATE, GHOrganization.Permission.PUSH, repo); Assert.assertTrue(team.getRepositories().containsKey(REPO_NAME)); }
Source:
<code>public static boolean isDemoUser() { try { User u = CommCareApplication._().getSession().getLoggedInUser(); return (User.TYPE_DEMO.equals(u.getUserType())); } catch (SessionUnavailableException e) { <START> return true; <END> } }</code><technical_language>session unavailable a demo user? if a SessionUnavailableException is thrown</technical_language>

Target:
public static boolean isDemoUser() { try { User u = CommCareApplication._().getSession().getLoggedInUser(); return (User.TYPE_DEMO.equals(u.getUserType())); } catch (SessionUnavailableException e) { return false; } }