auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private GeometryCollection standardizeGeometryCollection(GeometryCollection geometryCollection) { ArrayList<Geometry> geometries = new ArrayList<>(); for (int i = 0; i < geometryCollection.getNumGeometries(); i++) { Geometry geometry = standardizeGeometry(geometryCollection.getGeometryN(i)); geometries.add(geometry); } <START> if (geometryCollection.getClass() == MultiPoint.class) { <END> return GEOMETRY_FACTORY.createMultiPoint(geometries.toArray(new Point[0])); } if (geometryCollection.getClass() == MultiLineString.class) { return GEOMETRY_FACTORY.createMultiLineString(geometries.toArray(new LineString[0])); } if (geometryCollection.getClass() == MultiPolygon.class) { return GEOMETRY_FACTORY.createMultiPolygon(geometries.toArray(new Polygon[0])); } return GEOMETRY_FACTORY.createGeometryCollection(geometries.toArray(new Geometry[0])); }</code><technical_language>instanceof instead of equals getClass extended JTS classes match. This violates Liskov substitution principle</technical_language>

Target:
private GeometryCollection standardizeGeometryCollection(GeometryCollection geometryCollection) { ArrayList<Geometry> geometries = new ArrayList<>(); for (int i = 0; i < geometryCollection.getNumGeometries(); i++) { Geometry geometry = standardizeGeometry(geometryCollection.getGeometryN(i)); geometries.add(geometry); } if (geometryCollection instanceof MultiPoint) { return GEOMETRY_FACTORY.createMultiPoint(geometries.toArray(new Point[0])); } if (geometryCollection instanceof MultiLineString) { return GEOMETRY_FACTORY.createMultiLineString(geometries.toArray(new LineString[0])); } if (geometryCollection instanceof MultiPolygon) { return GEOMETRY_FACTORY.createMultiPolygon(geometries.toArray(new Polygon[0])); } return GEOMETRY_FACTORY.createGeometryCollection(geometries.toArray(new Geometry[0])); }
Source:
<code><START> public static List<Overlay> convert(MapView map, File file) throws Exception { <END> ValidationPreferences pref = new ValidationPreferences(); pref.setMaxNumberOfPointsPerShape(200000); return convert(map, file, pref); }</code><technical_language>Legacy version: OK it, getDefaultValidationPreferences()</technical_language>

Target:
public static List<Overlay> convert(MapView map, File file) throws Exception { return convert(map, file, getDefaultValidationPreferences()); }
Source:
<code>public InputStream getStream() { final Delete delete = new Delete(); delete.setQuiet(quiet); final List<DeleteObject> deleteObjects = new ArrayList<>(); for ( Map.Entry< String, Set< UUID > > entry : objects.entrySet() ) { if ( null == entry.getValue() ) { deleteObjects.add( new DeleteObject( entry.getKey(), null ) ); } else { <START> for ( UUID versionId : entry.getValue() ) <END> { deleteObjects.add( new DeleteObject( entry.getKey(), versionId ) ); } } } delete.setDeleteObjectList(deleteObjects); final String xmlOutput = XmlOutput.toXml(delete); final byte[] stringBytes = xmlOutput.getBytes(Charset.forName("UTF-8")); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }</code><technical_language>Missing final</technical_language>

Target:
public InputStream getStream() { final Delete delete = new Delete(); delete.setQuiet(quiet); final List<DeleteObject> deleteObjects = new ArrayList<>(); for ( final Map.Entry< String, Set< UUID > > entry : objects.entrySet() ) { if ( null == entry.getValue() ) { deleteObjects.add( new DeleteObject( entry.getKey(), null ) ); } else { for ( final UUID versionId : entry.getValue() ) { deleteObjects.add( new DeleteObject( entry.getKey(), versionId ) ); } } } delete.setDeleteObjectList(deleteObjects); final String xmlOutput = XmlOutput.toXml(delete); final byte[] stringBytes = xmlOutput.getBytes(Charset.forName("UTF-8")); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }
Source:
<code>public void testStartProcessFromDisplayer(){ kieWorkbenchFormsStartProcessDisplayer.initConfigs(processDisplayerConfig, onClose, onRefresh); kieWorkbenchFormsStartProcessDisplayer.startProcessFromDisplayer(); verify(service).call(any()); <START> verify(kieWorkbenchFormsEntryPoint).startProcessFromRenderContext(any(), <END> any(), any(), any(), any(), any()); }</code><technical_language>good if match expected values in here. I recommend bringing some of values defined in init here. execution/parameter specific, init generally a setup only</technical_language>

Target:
public void testStartProcessFromDisplayer() { when(formRenderer.isValid()).thenReturn(true); when(formRenderingSettings.getTimestamp()).thenReturn(100000l); MapModelRenderingContext mapModelRenderingContext = mock(MapModelRenderingContext.class); when(formRenderingSettings.getRenderingContext()).thenReturn(mapModelRenderingContext); when(service.call(any())).thenReturn(kieWorkbenchFormsEntryPoint); ProcessDefinitionKey processDefinitionKey = new ProcessDefinitionKey( "test-serverTemplateId", "test-deploymentId", "test-processId", "test-processDefName"); ProcessDisplayerConfig processDisplayerConfig = new ProcessDisplayerConfig(processDefinitionKey, "test"); processDisplayerConfig.setRenderingSettings(formRenderingSettings); kieWorkbenchFormsStartProcessDisplayer.initConfigs(processDisplayerConfig, null, null); kieWorkbenchFormsStartProcessDisplayer.startProcessFromDisplayer(); verify(service).call(any()); verify(kieWorkbenchFormsEntryPoint).startProcessFromRenderContext(100000l, null, "test-serverTemplateId", "test-deploymentId", "test-processId", ""); }
Source:
<code>public Object getCurrentTransactionId() { <START> if (TransactionImple.getTransaction() == null) <END> return null; return TransactionImple.getTransaction().get_uid(); }</code><technical_language>I I mention in initial review TransactionImple.getTransaction() do a lot of work I need cache result in a local variable in order avoid call getTransaction</technical_language>

Target:
public Object getCurrentTransactionId() { com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple transaction = TransactionImple.getTransaction(); if (transaction == null) return null; return transaction.get_uid(); }
Source:
<code>private static Object getPayload(Object obj) { SpecificRecordBase record = (SpecificRecordBase) obj; Schema schema = record.getSchema(); for (String name : payloadStrs) { Object payload = schema.getField(name); if (payload != null) { return payload; } } <START> return obj; END> }</code><technical_language>throw exception this isnt</technical_language>

Target:
private static Object getPayload(Object obj) { SpecificRecordBase record = (SpecificRecordBase) obj; Schema schema = record.getSchema(); for (String name : payloadStrs) { Schema.Field payload = schema.getField(name); if (payload != null) { return record.get(payload.pos()); } } return obj; }
Source:
<code>public void queueBuildCompleted(BuildMemory.MemoryImprint memoryImprint, TaskListener listener) { <START> String serverName = memoryImprint.getEvent().getProvider().getName(); <END> BuildCompletedCommandJob job = new BuildCompletedCommandJob(getConfig(serverName), memoryImprint, listener); GerritSendCommandQueue.queue(job); }</code><technical_language>NPE</technical_language>

Target:
public void queueBuildCompleted(BuildMemory.MemoryImprint memoryImprint, TaskListener listener) { String serverName = getServerName(memoryImprint); BuildCompletedCommandJob job = new BuildCompletedCommandJob(getConfig(serverName), memoryImprint, listener); GerritSendCommandQueue.queue(job); }
Source:
<code>private boolean isOldestRequestPastDue() { if (unexpiredRequestSendTimes.size() == 0) { <START> throw new IllegalStateException("There are no unexpired requests"); <END> } Map.Entry<ReplicaId, Long> oldestEntry = unexpiredRequestSendTimes.entrySet().iterator().next(); Histogram latencyTracker = getTracker(oldestEntry.getKey()); return (latencyTracker.getCount() >= MIN_DATA_POINTS_REQUIRED) && (time.milliseconds() - oldestEntry.getValue() >= latencyTracker.getSnapshot().getValue(quantile)); }</code><technical_language>this is IllegalStateException? inform caller this</technical_language>

Target:
private boolean isOldestRequestPastDue() { Map.Entry<ReplicaId, Long> oldestEntry = unexpiredRequestSendTimes.entrySet().iterator().next(); Histogram latencyTracker = getLatencyHistogram(oldestEntry.getKey()); return (latencyTracker.getCount() >= MIN_DATA_POINTS_REQUIRED) && (time.milliseconds() - oldestEntry.getValue() >= latencyTracker.getSnapshot().getValue(quantile)); }
Source:
<code>public static float getDistance(double lat1, double long1, double lat2, double long2) { final double R = 6370e3; final double rad_per_deg = Math.PI/180; <START> lat1 *= rad_per_deg; <END> long1 *= rad_per_deg; lat2 *= rad_per_deg; long2 *= rad_per_deg; double dLat = lat2-lat1; double dLon = long2-long1; double A = square(Math.sin(0.5*dLat)) + Math.cos(lat1) * Math.cos(lat2) * square(Math.sin(0.5*dLon)); return (float)(2 * R * Math.asin(Math.sqrt(A))); }</code><technical_language>more Java-idiomatic modify input variables (they're declared final)</technical_language>

Target:
public static float getDistance(double lat1, double long1, double lat2, double long2) { final double R = 6370e3; final double rad_per_deg = Math.PI/180; double dLat = lat2-lat1; double dLon = long2-long1; double A = square(Math.sin(0.5*dLat*rad_per_deg)) + Math.cos(lat1*rad_per_deg) * Math.cos(lat2*rad_per_deg) * square(Math.sin(0.5*dLon*rad_per_deg)); return (float)(2 * R * Math.asin(Math.sqrt(A))); }
Source:
<code>public static synchronized void buildSystemConfig() throws ApplicationServerException, FileNotFoundException { classLoaderConfig = new ClassLoaderConfiguration(); String defaultEnvironmentConfigPath = System.getProperty("catalina.home") + File.separator + "conf" + File.separator + "wso2" <START> + File.separator + LoaderConstants.ENVIRONMENT_CONFIG_FILE; <END> File environmentConfigFile = new File(defaultEnvironmentConfigPath); if (!environmentConfigFile.exists()) { String errorMessage = "Failed to load environment configuration file: " + defaultEnvironmentConfigPath; throw new FileNotFoundException(errorMessage); } populateEnvironments(environmentConfigFile); String defaultClassloaderConfigPath = System.getProperty("catalina.home") + File.separator + "conf" + File.separator + "wso2" + File.separator + LoaderConstants.CLASSLOADER_CONFIG_FILE; File classLoaderConfigFile = new File(defaultClassloaderConfigPath); if (!classLoaderConfigFile.exists()) { String errorMessage = "Failed to load default classloader configuration file: " + defaultEnvironmentConfigPath; throw new FileNotFoundException(errorMessage); } loadClassLoaderPolicy(classLoaderConfigFile); isSuccessful = true; }</code><technical_language>java 8 paths</technical_language>

Target:
public static synchronized void buildSystemConfig() throws ApplicationServerException, FileNotFoundException { classLoaderConfig = new ClassLoaderConfiguration(); Path defaultEnvironmentConfigPath = Paths .get(System.getProperty("catalina.home"), "conf", "wso2", LoaderConstants.ENVIRONMENT_CONFIG_FILE); File environmentConfigFile = defaultEnvironmentConfigPath.toFile(); if (!environmentConfigFile.exists()) { String errorMessage = "Failed to load environment configuration file: " + defaultEnvironmentConfigPath; throw new FileNotFoundException(errorMessage); } populateEnvironments(environmentConfigFile); Path defaultClassloaderConfigPath = Paths .get(System.getProperty("catalina.home"), "conf", "wso2", LoaderConstants.CLASSLOADER_CONFIG_FILE); File classLoaderConfigFile = defaultClassloaderConfigPath.toFile(); if (!classLoaderConfigFile.exists()) { String errorMessage = "Failed to load default classloader configuration file: " + defaultEnvironmentConfigPath; throw new FileNotFoundException(errorMessage); } loadClassLoaderPolicy(classLoaderConfigFile); isSuccessful = true; }
Source:
<code>protected void loadWithSdkInitialized(@NonNull final Activity activity, @NonNull final Map<String, Object> localExtras, @NonNull final Map<String, String> serverExtras) throws Exception { PersonalInfoManager personalInfoManager = MoPub.getPersonalInformationManager(); if ( personalInfoManager != null && personalInfoManager.gdprApplies() ) { boolean canCollectPersonalInfo = personalInfoManager.canCollectPersonalInformation(); AppLovinPrivacySettings.setHasUserConsent( canCollectPersonalInfo, activity.getApplicationContext() ); } parentActivity = activity; final String adMarkup = serverExtras.get( DataKeys.ADM_KEY ); final boolean hasAdMarkup = !TextUtils.isEmpty( adMarkup ); log( DEBUG, "Requesting AppLovin banner with serverExtras: " + serverExtras + ", localExtras: " + localExtras + " and has ad markup: " + hasAdMarkup ); final String zoneId; if ( hasAdMarkup ) { zoneId = DEFAULT_TOKEN_ZONE; } else { if ( AppLovinSdk.VERSION_CODE >= 750 && serverExtras != null && serverExtras.containsKey( "zone_id" ) ) { <START> zoneId = serverExtras.get( "zone_id" ); <END> } else { zoneId = DEFAULT_ZONE; } } incentivizedInterstitial = createIncentivizedInterstitialAd( zoneId, activity, sdk ); if ( hasAdMarkup ) { isTokenEvent = true; sdk.getAdService().loadNextAdForAdToken( adMarkup, this ); } else { incentivizedInterstitial.preload( this ); } }</code><technical_language>zoneId null</technical_language>

Target:
protected void loadWithSdkInitialized(@NonNull final Activity activity, @NonNull final Map<String, Object> localExtras, @NonNull final Map<String, String> serverExtras) throws Exception { PersonalInfoManager personalInfoManager = MoPub.getPersonalInformationManager(); if ( personalInfoManager != null && personalInfoManager.gdprApplies() ) { boolean canCollectPersonalInfo = personalInfoManager.canCollectPersonalInformation(); AppLovinPrivacySettings.setHasUserConsent( canCollectPersonalInfo, activity.getApplicationContext() ); } parentActivity = activity; final String adMarkup = serverExtras.get( DataKeys.ADM_KEY ); final boolean hasAdMarkup = !TextUtils.isEmpty( adMarkup ); log( DEBUG, "Requesting AppLovin banner with serverExtras: " + serverExtras + ", localExtras: " + localExtras + " and has ad markup: " + hasAdMarkup ); final String zoneId; if ( hasAdMarkup ) { zoneId = DEFAULT_TOKEN_ZONE; } else { final String serverExtrasZoneId = serverExtras.get( ZONE_ID_SERVER_EXTRAS_KEY ); if ( !TextUtils.isEmpty( serverExtrasZoneId ) ) { zoneId = serverExtrasZoneId; } else { zoneId = DEFAULT_ZONE; } } incentivizedInterstitial = createIncentivizedInterstitialAd( zoneId, activity, sdk ); if ( hasAdMarkup ) { isTokenEvent = true; sdk.getAdService().loadNextAdForAdToken( adMarkup, this ); } else { incentivizedInterstitial.preload( this ); } }
Source:
<code><START> protected abstract void readNext() throws IOException; <END> @Override public final Iterator<T> iterator(){ return new Iterator<T>(){ @Override public T next() throws NoSuchElementException { if (nextRecordStatus == Status.ERROR || bufferedRecord == null && !hasNext()) { nextRecordStatus = Status.VOID; throw new NoSuchElementException("EOF has been reached. No more documents to read."); } T ret = bufferedRecord; bufferedRecord = null; return ret; } @Override public boolean hasNext() { if (nextRecordStatus == Status.ERROR) { return false; } if (bufferedRecord != null) { return true; } else if (atEOF) { return false; } try { readNext(); } catch (IOException | NoSuchElementException e1) { return false; } catch (RuntimeException e2) { nextRecordStatus = Status.VOID; skipped += 1; return hasNext(); } return bufferedRecord != null; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }</code><technical_language>refactoring here, sense readNext() anymore</technical_language>

Target:
protected abstract void readNext() throws IOException, ParseException, NoSuchElementException; @Override public final Iterator<T> iterator(){ return new Iterator<T>(){ @Override public T next() throws NoSuchElementException { if (error) { throw new NoSuchElementException("Encountered file read error, stopping iteration."); } if (bufferedRecord == null && !hasNext()) { throw new NoSuchElementException("EOF has been reached. No more documents to read."); } T ret = bufferedRecord; bufferedRecord = null; return ret; } @Override public boolean hasNext() { if (bufferedRecord != null) { return true; } else if (atEOF) { return false; } try { readNext(); } catch (IOException e1) { error = true; return false; } catch (NoSuchElementException e2){ return false; } catch (ParseException e3) { skipped += 1; return hasNext(); } return bufferedRecord != null; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
Source:
<code>public static ImmutableMap<String, Ds3Type> removeUnusedTypes( final ImmutableMap<String, Ds3Type> types, final ImmutableList<Ds3Request> requests) { if (isEmpty(types) || isEmpty(requests)) { return ImmutableMap.of(); } final ImmutableSet.Builder<String> usedTypesBuilder = ImmutableSet.builder(); usedTypesBuilder.addAll(getUsedTypesFromRequests(requests)); usedTypesBuilder.addAll(getUsedTypesFromAllTypes(types, usedTypesBuilder.build())); final ImmutableMap.Builder<String, Ds3Type> builder = ImmutableMap.builder(); for (final Map.Entry<String, Ds3Type> entry : types.entrySet()) { <START> if (usedTypesBuilder.build().contains(entry.getKey())) { <END> builder.put(entry.getKey(), entry.getValue()); } } return builder.build(); }</code><technical_language>This builds set lookup. built used</technical_language>

Target:
public static ImmutableMap<String, Ds3Type> removeUnusedTypes( final ImmutableMap<String, Ds3Type> types, final ImmutableList<Ds3Request> requests) { if (isEmpty(types) || isEmpty(requests)) { return ImmutableMap.of(); } final ImmutableSet.Builder<String> usedTypesBuilder = ImmutableSet.builder(); usedTypesBuilder.addAll(getUsedTypesFromRequests(requests)); usedTypesBuilder.addAll(getUsedTypesFromAllTypes(types, usedTypesBuilder.build())); final ImmutableSet<String> usedTypes = usedTypesBuilder.build(); final ImmutableMap.Builder<String, Ds3Type> builder = ImmutableMap.builder(); for (final Map.Entry<String, Ds3Type> entry : types.entrySet()) { if (usedTypes.contains(entry.getKey())) { builder.put(entry.getKey(), entry.getValue()); } } return builder.build(); }
Source:
<code>public ScenarioSimulationModel unmarshal(final String rawXml, boolean migrate) throws Exception { if (rawXml == null || rawXml.trim().equals("")) { <START> throw new IllegalArgumentException("File content is empty!"); <END> } String xml = migrate ? migrateIfNecessary(rawXml) : rawXml; return internalUnmarshal(xml); }</code><technical_language>Malformed file, content is empty!</technical_language>

Target:
public ScenarioSimulationModel unmarshal(final String rawXml, boolean migrate) throws Exception { if (rawXml == null || rawXml.trim().equals("")) { throw new IllegalArgumentException("Malformed file, content is empty!"); } String xml = migrate ? migrateIfNecessary(rawXml) : rawXml; return internalUnmarshal(xml); }
Source:
<code>public void testSDXWithDataLakeAndFreeIpaStorageCanBeCreatedSuccessfully(TestContext testContext) { String sdx = resourcePropertyProvider().getName(); String diagnostics = resourcePropertyProvider().getName(); DescribeFreeIpaResponse describeFreeIpaResponse = testContext.given(FreeIpaTestDto.class) .when(freeIpaTestClient.describe()) .getResponse(); testContext .given(sdx, SdxTestDto.class).withCloudStorage() .when(sdxTestClient.create(), key(sdx)) .awaitForFlow(key(sdx)) .await(SdxClusterStatusResponse.RUNNING) .awaitForInstance(getSdxInstancesHealthyState()) .given(diagnostics, SdxDiagnosticsTestDto.class) .when(sdxTestClient.collectDiagnostics(), key(diagnostics)) <START> .awaitForFlow(key(diagnostics)) <END> .given(sdx, SdxTestDto.class) .then((tc, testDto, client) -> { getCloudFunctionality(tc).cloudStorageListContainerDataLake(getBaseLocation(testDto), testDto.getResponse().getName(), testDto.getResponse().getStackCrn()); return testDto; }) .then((tc, testDto, client) -> { getCloudFunctionality(tc).cloudStorageListContainerFreeIpa(getBaseLocation(testDto), describeFreeIpaResponse.getName(), describeFreeIpaResponse.getCrn()); return testDto; }) .validate(); }</code><technical_language>I .withSdx(sdx) is missing this step</technical_language>

Target:
public void testSDXWithDataLakeAndFreeIpaStorageCanBeCreatedSuccessfully(TestContext testContext) { String sdx = resourcePropertyProvider().getName(); DescribeFreeIpaResponse describeFreeIpaResponse = testContext.given(FreeIpaTestDto.class) .when(freeIpaTestClient.describe()) .getResponse(); testContext .given(sdx, SdxTestDto.class).withCloudStorage() .when(sdxTestClient.create(), key(sdx)) .awaitForFlow(key(sdx)) .await(SdxClusterStatusResponse.RUNNING) .awaitForInstance(getSdxInstancesHealthyState()) .then((tc, testDto, client) -> { getCloudFunctionality(tc).cloudStorageListContainerDataLake(getBaseLocation(testDto), testDto.getResponse().getName(), testDto.getResponse().getStackCrn()); return testDto; }) .then((tc, testDto, client) -> { getCloudFunctionality(tc).cloudStorageListContainerFreeIpa(getBaseLocation(testDto), describeFreeIpaResponse.getName(), describeFreeIpaResponse.getCrn()); return testDto; }) .validate(); }
Source:
<code>public List<String> saveRoleLayouts(final Role role, final Set<String> layoutIds, final LayoutAPI layoutAPI, final RoleAPI roleAPI, final SystemEventsAPI systemEventsAPI) throws DotDataException { final List<Layout> layouts = layoutAPI.loadLayoutsForRole(role); final List<String> layoutsAdded = new ArrayList<>(); final Map<String, Layout> currentLayoutMaps = layouts.stream().collect( Collectors.toMap(layout -> layout.getId(), layout -> layout)); layoutIds.forEach(layoutId -> currentLayoutMaps.remove(layoutId)); for(final Map.Entry<String, Layout> layoutToRemoveEntry : currentLayoutMaps.entrySet()) { roleAPI.removeLayoutFromRole(layoutToRemoveEntry.getValue(), role); } for(final String changedLayout : layoutIds) { final Layout layout = layoutAPI.findLayout(changedLayout); if (null != layout && UtilMethods.isSet(layout.getId())) { <START> if (!roleAPI.hasLayoutToRole(layout, role)) { <END> roleAPI.addLayoutToRole(layout, role); layoutsAdded.add(layout.getId()); } } } systemEventsAPI.pushAsync(SystemEventType.UPDATE_PORTLET_LAYOUTS, new Payload(layoutsAdded)); return layoutsAdded; }</code><technical_language>![Codacy](<LINK_0> Issue found: [These nested if statements combined](<LINK_1></technical_language>

Target:
public List<String> saveRoleLayouts(final Role role, final Set<String> layoutIds, final LayoutAPI layoutAPI, final RoleAPI roleAPI, final SystemEventsAPI systemEventsAPI) throws DotDataException { final List<Layout> layouts = layoutAPI.loadLayoutsForRole(role); final List<String> layoutsAdded = new ArrayList<>(); final Map<String, Layout> currentLayoutMaps = layouts.stream().collect( Collectors.toMap(layout -> layout.getId(), layout -> layout)); layoutIds.forEach(layoutId -> currentLayoutMaps.remove(layoutId)); for(final Map.Entry<String, Layout> layoutToRemoveEntry : currentLayoutMaps.entrySet()) { roleAPI.removeLayoutFromRole(layoutToRemoveEntry.getValue(), role); } for(final String changedLayout : layoutIds) { final Layout layout = layoutAPI.findLayout(changedLayout); if (null != layout && UtilMethods.isSet(layout.getId())) { if (!roleAPI.roleHasLayout(layout, role)) { roleAPI.addLayoutToRole(layout, role); layoutsAdded.add(layout.getId()); } } } systemEventsAPI.pushAsync(SystemEventType.UPDATE_PORTLET_LAYOUTS, new Payload(layoutsAdded)); return layoutsAdded; }
Source:
<code>public Builder withStudentProfileAttributes(StudentProfileAttributes studentProfileAttributes) { accountAttributes.studentProfile = studentProfileAttributes; <START> accountAttributes.studentProfile.sanitizeForSaving(); <END> return this; }</code><technical_language>add sanitization method end of build step? for SanitizationHelper.sanitizeGoogleId(googleId);</technical_language>

Target:
public Builder withStudentProfileAttributes(StudentProfileAttributes studentProfileAttributes) { accountAttributes.studentProfile = studentProfileAttributes; return this; }
Source:
<code>public RetryPolicyOptions() { <START> setRetryOptions(new ExponentialBackoff(), null, null); <END> }</code><technical_language>instantiate this.retryStrategy = new ExponentialBackoff()</technical_language>

Target:
public RetryPolicyOptions() { this(new ExponentialBackoff(), null, null); }
Source:
<code>public void testGetVmDeviceByVmIdTypeAndDeviceFilteringSetToFlase() { <START> List<VmDevice> devices = dao.getVmDeviceByVmIdTypeAndDevice(EXISTING_VM_ID, "disk", "disk", null, false); <END> assertEquals("there should only be " + TOTAL_DEVICES + " disks", TOTAL_DEVICES, devices.size()); }</code><technical_language>In general extract this repetitive code "run & check" private method parameters, test send correct parameters</technical_language>

Target:
public void testGetVmDeviceByVmIdTypeAndDeviceFilteringSetToFlase() { List<VmDevice> devices = dao.getVmDeviceByVmIdTypeAndDevice(EXISTING_VM_ID, "disk", "disk", null, false); assertGetVMDeviceByIdTypeAndDeviceFullResult(devices); }
Source:
<code>public void uploadMap(Path file, boolean isRanked, ByteCountListener listener) { MultiValueMap<String, Object> multipartContent = createFileMultipart(file, listener); <START> multipartContent.add("metadata", "{\"isRanked\":\"" + isRanked + "\"}"); <END> post("/maps/upload", multipartContent); }</code><technical_language>a bit confused. a solution of problems I encountered far. give specific info error message intend fix here</technical_language>

Target:
public void uploadMap(Path file, boolean isRanked, ByteCountListener listener) { MultiValueMap<String, Object> multipartContent = createFileMultipart(file, listener); multipartContent.add("metadata", ImmutableMap.of("isRanked", isRanked)); post("/maps/upload", multipartContent); }
Source:
<code>public Model getUPDATEModel(Representation representation) { return new ModelImpl() .property("condition", new StringProperty()) .property("patient", new StringProperty()) .property("clinicalStatus", new StringProperty()) .property("verificationStatus", new StringProperty()) .property("previousVersion", new StringProperty()) .property("onsetDate", new StringProperty()) .property("voided", new StringProperty()) <START> .required("condition").required("onsetDate"); <END> }</code><technical_language>line mean</technical_language>

Target:
public Model getUPDATEModel(Representation representation) { return new ModelImpl() .property("condition", new StringProperty()) .property("clinicalStatus", new StringProperty()) .property("verificationStatus", new StringProperty()) .property("previousVersion", new StringProperty()) .property("onsetDate", new StringProperty()) .property("voided", new StringProperty()); }
Source:
<code>private CliCommand getCommandExecutor() throws CommandException { final String commandName = this.args.getCommand(); <START> String commandCamel = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, commandName.toString()); <END> Iterator<CliCommand> implementations = getAllCommands(); while (implementations.hasNext()) { CliCommand implementation = implementations.next(); String className = implementation.getClass().getSimpleName(); if (className.equalsIgnoreCase(commandCamel)) { return implementation.withProvider(this.ds3Provider, this.fileUtils); } } throw new CommandException("No command class: " + commandName); }</code><technical_language>Missing final</technical_language>

Target:
private CliCommand getCommandExecutor() throws CommandException { final String commandName = this.args.getCommand(); final String commandCamel = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, commandName.toString()); final Iterator<CliCommand> implementations = getAllCommands(); while (implementations.hasNext()) { final CliCommand implementation = implementations.next(); final String className = implementation.getClass().getSimpleName(); if (className.equalsIgnoreCase(commandCamel)) { return implementation.withProvider(this.ds3Provider, this.fileUtils); } } throw new CommandException("No command class: " + commandName); }
Source:
<code>public static JSITLiteralExpression dmnFromWB(final OutputClauseLiteralExpression wb) { if (Objects.isNull(wb)) { return null; } else if (StringUtils.isEmpty(wb.getText().getValue())) { return null; <START> } <END> return LiteralExpressionPropertyConverter.dmnFromWB(wb); }</code><technical_language>wb.getText() returns null</technical_language>

Target:
public static JSITLiteralExpression dmnFromWB(final OutputClauseLiteralExpression wb) { if (Objects.isNull(wb)) { return null; } else if (Objects.isNull(wb.getText())) { return null; } else if (StringUtils.isEmpty(wb.getText().getValue())) { return null; } return LiteralExpressionPropertyConverter.dmnFromWB(wb); }
Source:
<code>public synchronized void suspend() { <START> synchronized (fSynchObject) { <END> fIsPaused = true; } TmfCoreTracer.traceRequest(fRequest, "SUSPENDED"); }</code><technical_language>synchronized block is needed</technical_language>

Target:
public void suspend() { fIsPaused = true; TmfCoreTracer.traceRequest(fRequest, "SUSPENDED"); }
Source:
<code>public StandaloneCommandBuilder setGitRepository(final String gitRepository, final String gitBranch, final String gitAuthentication) { if(gitRepository == null) { throw MESSAGES.nullParam("git-repo"); } <START> Objects.requireNonNull(gitRepository); <END> addServerArg("--git-repo", gitRepository); if (gitBranch != null) { addServerArg("--git-branch", gitBranch); } if (gitAuthentication != null) { addServerArg("--git-auth", gitAuthentication); } return this; }</code><technical_language>double check for null. streamlined java.util.Objects#requireNonNull(T, java.lang.String)</technical_language>

Target:
public StandaloneCommandBuilder setGitRepository(final String gitRepository, final String gitBranch, final String gitAuthentication) { if(gitRepository == null) { throw MESSAGES.nullParam("git-repo"); } addServerArg("--git-repo", gitRepository); if (gitBranch != null) { addServerArg("--git-branch", gitBranch); } if (gitAuthentication != null) { addServerArg("--git-auth", gitAuthentication); } return this; }
Source:
<code>public ResponseEntity<ExpenseDTO[]> createExpenses(@RequestBody @Valid Expense[] expenses) { try { if (expenses == null || expenses.length == 0) { throw new BadRequestException("No expenses found in request!"); } else { ExpenseDTO[] createdExpensesDTO = new ExpenseDTO[expenses.length]; int index = 0; for (Expense expense : expenses) { if (CurrencyUtil.getCurrency(expense.getCurrency()) == null) { throw new BadRequestException("Wrong currency code for index [" + index + "]!"); } String categoryName = expense.getCategory().getName(); AppUser user = userUtil.extractLoggedAppUserFromDatabase(); Category category = categoryDao.findByNameAndUsername(categoryName, user.getUsername()); <START> if (category == null) { <END> category = createAndSaveCategory(categoryName, user); } if (!user.getDefaultCurrency().getCurrencyCode().equals(expense.getCurrency())) { setDefaultCurrencyAmount(expense, user.getDefaultCurrency()); } expense.setCategory(category); expense.setUser(user); Expense savedExpense = expenseDao.saveAndFlush(expense); ExpenseDTO createdExpenseDto = expenseConverter.convertTo(savedExpense); createdExpensesDTO[index] = createdExpenseDto; index++; } return new ResponseEntity<>(createdExpensesDTO, HttpStatus.OK); } } catch (ConstraintViolationException e) { throw new BadRequestException(e.getMessage()); } }</code><technical_language>This for block needs shorter clearer. Move setting of category in a new method in this block I expense.setCategory(resolveCategory(..));</technical_language>

Target:
public ResponseEntity<List<ExpenseDTO>> createExpenses(@RequestBody @Valid Expense[] expenses) { try { if (expenses == null || expenses.length == 0) { throw new BadRequestException("No expenses found in request!"); } else { List<ExpenseDTO> createdExpenseListDTO = new ArrayList<>(); int index = 0; for (Expense expense : expenses) { if (CurrencyUtil.getCurrency(expense.getCurrency()) == null) { throw new BadRequestException("Wrong currency code for index [" + index + "] and Currency code [" + expense.getCurrency() + "]!"); } AppUser user = userUtil.extractLoggedAppUserFromDatabase(); Category category = resolveCategory(user, expense.getCategory().getName()); if (!user.getDefaultCurrency().getCurrencyCode().equals(expense.getCurrency())) { setDefaultCurrencyAmount(expense, user.getDefaultCurrency()); } expense.setCategory(category); expense.setUser(user); ExpenseDTO createdExpenseDto = expenseConverter.convertTo(expenseDao.saveAndFlush(expense)); createdExpenseListDTO.add(createdExpenseDto); index++; } return new ResponseEntity<>(createdExpenseListDTO, HttpStatus.OK); } } catch (ConstraintViolationException e) { throw new BadRequestException(e.getMessage()); } }
Source:
<code><START> private int getUserId(String username) { <END> try (Connection conn = getConnection(); PreparedStatement insert = conn.prepareStatement("SELECT id FROM users WHERE name = ?;")) { insert.setString(1, username); ResultSet resultSet = insert.executeQuery(); resultSet.next(); return resultSet.getInt(1); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } }</code><technical_language>pass in 'live' connection private methods this</technical_language>

Target:
private int getUserId(String username) { try (Connection conn = getConnection(); PreparedStatement userSelect = conn.prepareStatement("SELECT id FROM users WHERE name = ?;")) { userSelect.setString(1, username); ResultSet resultSet = userSelect.executeQuery(); resultSet.next(); return resultSet.getInt(1); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } }
Source:
<code><START> private void clearTenantCaches(Tenant tenant) throws UserStoreException { <END> if (tenant != null) { int tenantId = tenant.getId(); String tenantUniqueID = tenant.getTenantUniqueID(); tenantUniqueIdCache.clearCacheEntry(new TenantUniqueIDKey(tenantUniqueID)); tenantDomainCache.clearCacheEntry(new TenantIdKey(tenantId)); tenantIdCache.clearCacheEntry(new TenantDomainKey(tenant.getDomain())); tenantCacheManager.clearCacheEntry(new TenantIdKey(tenantId)); } }</code><technical_language>is this changed</technical_language>

Target:
private void clearTenantCaches(Tenant tenant) throws UserStoreException { int tenantId = tenant.getId(); String tenantUniqueID = tenant.getTenantUniqueID(); tenantUniqueIdCache.clearCacheEntry(new TenantUniqueIDKey(tenantUniqueID)); tenantDomainCache.clearCacheEntry(new TenantIdKey(tenantId)); tenantIdCache.clearCacheEntry(new TenantDomainKey(tenant.getDomain())); tenantCacheManager.clearCacheEntry(new TenantIdKey(tenantId)); }
Source:
<code>private void testResizeOrMovePort(String representationName, boolean checkMoving) { editor = openAndGetEditor(representationName, representationName); PointList originalPoints = getBendpoints(DROP_PORT_NAME); final Rectangle originalPortBounds = getEditPartBounds(DROP_PORT_NAME); int relativeClickedY = checkMoving ? -originalPortBounds.height / 2 : -1; final Point pointToDrag = originalPortBounds.getBottom().getTranslated(0, relativeClickedY); editor.select(editor.getEditPart(DROP_PORT_NAME, AbstractDiagramBorderNodeEditPart.class)); final Point endpoint = pointToDrag.getTranslated(VERTICAL_TRANSLATION); editor.drag(pointToDrag.x, pointToDrag.y, endpoint.x, endpoint.y); final Rectangle newPortBounds = getEditPartBounds(DROP_PORT_NAME); if (checkMoving) { assertThat("Port is not at expected position (probably not moved but resized)", newPortBounds.getTopRight(), PointAround.around(originalPortBounds.getTopRight().getTranslated(VERTICAL_TRANSLATION), 5)); } else { assertThat("Port is not at expected position (probably not moved but resized)", newPortBounds.getTopRight(), PointAround.around(originalPortBounds.getTopRight(), 0)); } if (originalPoints != null && checkMoving) { checkEdgeStability(DROP_PORT_NAME, originalPoints); <START> } <END> }</code><technical_language>Add this new code in "if (checkMoving)" block</technical_language>

Target:
private void testResizeOrMovePort(String representationName, boolean checkMoving) { editor = openAndGetEditor(representationName, representationName); PointList originalPoints = getBendpoints(DROP_PORT_NAME); final Rectangle originalPortBounds = getEditPartBounds(DROP_PORT_NAME); int relativeClickedY = checkMoving ? -originalPortBounds.height / 2 : -1; final Point pointToDrag = originalPortBounds.getBottom().getTranslated(0, relativeClickedY); editor.select(editor.getEditPart(DROP_PORT_NAME, AbstractDiagramBorderNodeEditPart.class)); final Point endpoint = pointToDrag.getTranslated(VERTICAL_TRANSLATION); editor.drag(pointToDrag.x, pointToDrag.y, endpoint.x, endpoint.y); final Rectangle newPortBounds = getEditPartBounds(DROP_PORT_NAME); if (checkMoving) { assertThat("Port is not at expected position (probably not moved but resized)", newPortBounds.getTopRight(), PointAround.around(originalPortBounds.getTopRight().getTranslated(VERTICAL_TRANSLATION), 5)); if (originalPoints != null) { checkEdgeStability(DROP_PORT_NAME, originalPoints); } } else { assertThat("Port is not at expected position (probably not moved but resized)", newPortBounds.getTopRight(), PointAround.around(originalPortBounds.getTopRight(), 0)); } }
Source:
<code><START> public void testNoListenerUpdate() { <END> observer.removeListener(); observer.checkAndNotify(); }</code><technical_language>This test assert anything</technical_language>

Target:
public void testNoListenerUpdate() throws Exception { initFiles(5, monitoredDirectory, "covert00"); observer.removeListener(); observer.checkAndNotify(); assertThat(observer.getRootFile().getChildren().isEmpty(), is(true)); }
Source:
<code>public static void validateJsonAgainstSchema(String jsonSchema, String jsonData) { if (jsonSchema.contains("<LINK_0>") || jsonSchema.contains("<LINK_1>")) { LOGGER.info("JSON schema version draft-03/draft-04 was detected"); validateJsonAgainstSchemaV3V4(jsonSchema, jsonData); } else { <START> LOGGER.info("JSON schema version higher than draft-03/draft-04 was detected"); <END> validateJsonAgainstSchemaV6V7(jsonSchema, jsonData); } }</code><technical_language>message is invalid (really draft-03/04 in this use-case?)</technical_language>

Target:
public static void validateJsonAgainstSchema(String jsonSchema, String jsonData) { Matcher m = Pattern.compile("\\d+", Pattern.MULTILINE).matcher(jsonSchema); if (m.find()) { int schemaVersion = Integer.valueOf(m.group()); if (schemaVersion <= 4) { LOGGER.info("JSON schema of version below or equal to draft-04 was detected"); validateJsonAgainstSchemaV3V4(jsonSchema, jsonData); } else { LOGGER.info("JSON schema of version higher than draft-04 was detected"); validateJsonAgainstSchemaV6V7(jsonSchema, jsonData); } } else { LOGGER.warn("JSON schema version can not be detected"); validateJsonAgainstSchemaV3V4(jsonSchema, jsonData); } }
Source:
<code>private int getPriority(ExecutableFlow exflow) { ExecutionOptions options = exflow.getExecutionOptions(); int priority = ExecutionOptions.DEFAULT_FLOW_PRIORITY; if (options != null && options.getFlowParameters() != null && options.getFlowParameters() .containsKey(ExecutionOptions.FLOW_PRIORITY)) { try { priority = Integer.valueOf(options.getFlowParameters().get( ExecutionOptions.FLOW_PRIORITY)); } catch (NumberFormatException ex) { priority = ExecutionOptions.DEFAULT_FLOW_PRIORITY; <START> logger.error("Failed to parse flow priority for exec_id = " <END> + exflow.getExecutionId()); } } return priority; }</code><technical_language>add add ex log.error()</technical_language>

Target:
private int getPriority(ExecutableFlow exflow) { ExecutionOptions options = exflow.getExecutionOptions(); int priority = ExecutionOptions.DEFAULT_FLOW_PRIORITY; if (options != null && options.getFlowParameters() != null && options.getFlowParameters() .containsKey(ExecutionOptions.FLOW_PRIORITY)) { try { priority = Integer.valueOf(options.getFlowParameters().get( ExecutionOptions.FLOW_PRIORITY)); } catch (NumberFormatException ex) { priority = ExecutionOptions.DEFAULT_FLOW_PRIORITY; logger.error( "Failed to parse flow priority for exec_id = " + exflow.getExecutionId(), ex); } } return priority; }
Source:
<code>private void generatePluginFiles(String pluginName) throws IOException { File pluginTargetFolder = new File(nodeModulesFolder, "@vaadin/" + pluginName); final String pluginFolder = "plugins/" + pluginName + "/"; final JsonObject json = getJsonFile(pluginFolder + PACKAGE_JSON); if (json == null) { <START> log().error("Couldn't locate files for plugin '{}'", pluginName); <END> return; } if (pluginTargetFolder.exists() && new File(pluginTargetFolder, PACKAGE_JSON).exists()) { String packageFile = FileUtils .readFileToString(new File(pluginTargetFolder, PACKAGE_JSON), StandardCharsets.UTF_8); final FrontendVersion packageVersion = new FrontendVersion( Json.parse(packageFile).getString("version")); FrontendVersion pluginVersion = new FrontendVersion( json.getString("version")); if (packageVersion.isEqualTo(pluginVersion)) { log().debug( "Skipping install of for version already installed", pluginName, pluginVersion.getFullVersion()); return; } } FileUtils.forceMkdir(pluginTargetFolder); final JsonArray files = json.getArray("files"); for (int i = 0; i < files.length(); i++) { final String file = files.getString(i); FileUtils.copyURLToFile(getUrlResource(pluginFolder + file), new File(pluginTargetFolder, file)); } FileUtils.copyURLToFile(getUrlResource(pluginFolder + PACKAGE_JSON), new File(pluginTargetFolder, PACKAGE_JSON)); }</code><technical_language>"Couldn't locate package.json ..." instead of _files_ ? adding impact "Not installing _plugin-name_ plugin."</technical_language>

Target:
private void generatePluginFiles(String pluginName) throws IOException { File pluginTargetFile = new File(nodeModulesFolder, "@vaadin/" + pluginName); final String pluginFolderName = "plugins/" + pluginName + "/"; final JsonObject packageJson = getJsonFile( pluginFolderName + PACKAGE_JSON); if (packageJson == null) { log().error( "Couldn't locate '{}' for plugin '{}'. Plugin will not be installed.", PACKAGE_JSON, pluginName); return; } if (pluginTargetFile.exists() && new File(pluginTargetFile, PACKAGE_JSON).exists()) { String packageFile = FileUtils .readFileToString(new File(pluginTargetFile, PACKAGE_JSON), StandardCharsets.UTF_8); final FrontendVersion packageVersion = new FrontendVersion( Json.parse(packageFile).getString("version")); FrontendVersion pluginVersion = new FrontendVersion( packageJson.getString("version")); if (packageVersion.isEqualTo(pluginVersion)) { log().debug( "Skipping install of for version already installed", pluginName, pluginVersion.getFullVersion()); return; } } FileUtils.forceMkdir(pluginTargetFile); final JsonArray files = packageJson.getArray("files"); for (int i = 0; i < files.length(); i++) { final String file = files.getString(i); FileUtils.copyURLToFile(getResourceUrl(pluginFolderName + file), new File(pluginTargetFile, file)); } FileUtils.copyURLToFile(getResourceUrl(pluginFolderName + PACKAGE_JSON), new File(pluginTargetFile, PACKAGE_JSON)); }
Source:
<code>public Map<Integer, List<ObservationLevel>> getObservationLevelsMap(final List<Integer> studyIds) { try { final Map<Integer, List<ObservationLevel>> observationLevelsMap = new HashMap<>(); <START> final String sqlString = "SELECT study_id AS studyId, dataset_type_id AS datasetTypeId, name AS studyName FROM project " <END> + " where dataset_type_id != " + DatasetTypeEnum.SUMMARY_DATA.getId() + " AND study_id IN (:studyIds)"; final SQLQuery sqlQuery = this.getSession().createSQLQuery(sqlString); sqlQuery.addScalar("studyId", new IntegerType()); sqlQuery.addScalar("datasetTypeId", new IntegerType()); sqlQuery.addScalar("studyName", new StringType()); sqlQuery.setParameterList("studyIds", studyIds); sqlQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); final List<Map<String, Object>> results = sqlQuery.list(); for (final Map<String, Object> result : results) { final ObservationLevel observationLevel = new ObservationLevel((Integer)result.get("datasetTypeId"), String.valueOf(result.get("studyName"))); final Integer studyId = (Integer) result.get("studyId"); if(observationLevelsMap.get(studyId) != null) { observationLevelsMap.get(studyId).add(observationLevel); } else { final List<ObservationLevel> observationLevels = new ArrayList<>(); observationLevels.add(observationLevel); observationLevelsMap.put(studyId, observationLevels); } } return observationLevelsMap; } catch (final HibernateException e) { throw new MiddlewareQueryException("Error getting getObservationLevelsMap for studyIds=" + studyIds + ":" + e.getMessage(), e); } }</code><technical_language>clear "studyName" in query "datasetName"</technical_language>

Target:
public Map<Integer, List<ObservationLevel>> getObservationLevelsMap(final List<Integer> studyIds) { try { final Map<Integer, List<ObservationLevel>> observationLevelsMap = new HashMap<>(); final String sqlString = "SELECT study_id AS studyId, dataset_type_id AS datasetTypeId, name AS datasetName FROM project " + " where dataset_type_id != " + DatasetTypeEnum.SUMMARY_DATA.getId() + " AND study_id IN (:studyIds)"; final SQLQuery sqlQuery = this.getSession().createSQLQuery(sqlString); sqlQuery.addScalar("studyId", new IntegerType()); sqlQuery.addScalar("datasetTypeId", new IntegerType()); sqlQuery.addScalar("datasetName", new StringType()); sqlQuery.setParameterList("studyIds", studyIds); sqlQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); final List<Map<String, Object>> results = sqlQuery.list(); for (final Map<String, Object> result : results) { final ObservationLevel observationLevel = new ObservationLevel((Integer)result.get("datasetTypeId"), String.valueOf(result.get("datasetName"))); final Integer studyId = (Integer) result.get("studyId"); observationLevelsMap.putIfAbsent(studyId, new ArrayList<>()); observationLevelsMap.get(studyId).add(observationLevel); } return observationLevelsMap; } catch (final HibernateException e) { throw new MiddlewareQueryException("Error getting getObservationLevelsMap for studyIds=" + studyIds + ":" + e.getMessage(), e); } }
Source:
<code>public List<InterpreterCompletion> completion(String buffer, int cursor) { String lines[] = buffer.split(System.getProperty("line.separator")); if (lines.length > 0 && lines[0].startsWith("%") && cursor <= lines[0].trim().length()) { int idx = lines[0].indexOf(' '); if (idx < 0 || (idx > 0 && cursor <= idx)) { return getInterpreterCompletion(); } } String replName = getRequiredReplName(buffer); if (replName != null && cursor > replName.length()) { <START> Matcher m = Pattern.compile(String.format("%%%s\\s*", replName)).matcher(buffer); <END> if (m.find()) { cursor -= m.group().length(); } } String body = getScriptBody(buffer); Interpreter repl = getRepl(replName); if (repl == null) { return null; } InterpreterContext interpreterContext = getInterpreterContextWithoutRunner(null); List completion = repl.completion(body, cursor, interpreterContext); return completion; }</code><technical_language>another match here? correct/reuse logic in L307, getRequiredReplName etc</technical_language>

Target:
public List<InterpreterCompletion> completion(String buffer, int cursor) { String lines[] = buffer.split(System.getProperty("line.separator")); if (lines.length > 0 && lines[0].startsWith("%") && cursor <= lines[0].trim().length()) { int idx = lines[0].indexOf(' '); if (idx < 0 || (idx > 0 && cursor <= idx)) { return getInterpreterCompletion(); } } String trimmedBuffer = buffer != null ? buffer.trim() : null; cursor = calculateCursorPosition(buffer, trimmedBuffer, cursor); String replName = getRequiredReplName(trimmedBuffer); String body = getScriptBody(trimmedBuffer); Interpreter repl = getRepl(replName); if (repl == null) { return null; } InterpreterContext interpreterContext = getInterpreterContextWithoutRunner(null); List completion = repl.completion(body, cursor, interpreterContext); return completion; }