auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void write(DataOutput out) throws IOException { out.writeFloat(this.l2reg); out.writeInt(this.in); out.writeInt(this.out); if(this.serializationType == SerializationType.WEIGHTS || this.serializationType == SerializationType.MODEL_SPEC) { SerializationUtil.write2DimFloatArray(out, this.weights, this.in, this.out); SerializationUtil.writeFloatArray(out, this.bias, this.out); } else if(this.serializationType == SerializationType.GRADIENTS) { SerializationUtil.write2DimFloatArray(out, this.wGrads, this.in, this.out); <START> SerializationUtil.writeFloatArray(out, this.bGrads, this.out); <END> } }</code><technical_language>next time leverage switch case for ENUM</technical_language>

Target:
public void write(DataOutput out) throws IOException { out.writeFloat(this.l2reg); out.writeInt(this.in); out.writeInt(this.out); switch(this.serializationType) { case WEIGHTS: case MODEL_SPEC: SerializationUtil.write2DimFloatArray(out, this.weights, this.in, this.out); SerializationUtil.writeFloatArray(out, this.bias, this.out); break; case GRADIENTS: SerializationUtil.write2DimFloatArray(out, this.wGrads, this.in, this.out); SerializationUtil.writeFloatArray(out, this.bGrads, this.out); break; default: break; } }
Source:
<code>public void testFailureOnAllPollThatSends() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); try { <START> mockSelectorState.set(MockSelectorState.ThrowExceptionOnSend); <END> router.getBlobInfo(blobId).get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals("Exception received should be router closed error", routerException.getErrorCode(), RouterErrorCode.RouterClosed); } }</code><technical_language>Minor: move out of try statement throws exception is try</technical_language>

Target:
public void testFailureOnAllPollThatSends() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); mockSelectorState.set(MockSelectorState.ThrowExceptionOnSend); try { router.getBlobInfo(blobId).get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals("Exception received should be router closed error", RouterErrorCode.RouterClosed, routerException.getErrorCode()); } }
Source:
<code>public Set<String> getGroupsSet(String user) throws IOException { <START> return null; <END> }</code><technical_language>return Collections.emptySet(); ? BTW, class DummyGroupMapping is now, do need scrubbed off</technical_language>

Target:
public Set<String> getGroupsSet(String user) throws IOException { if (user.equals("root")) { return Sets.newHashSet("admin"); } else if (user.equals("nobody")) { return Sets.newHashSet("nobody"); } else { String[] groups = HadoopUsersConfTestHelper.getHadoopUserGroups(user); return (groups != null) ? Sets.newHashSet(groups) : Collections.emptySet(); } }
Source:
<code>public int executeMethod(HttpMethod method) throws IOException, HttpException { try { boolean customRedirectionNeeded = false; try { method.setFollowRedirects(mFollowRedirects); } catch (Exception e) { customRedirectionNeeded = mFollowRedirects; } HttpParams params = method.getParams(); <START> params.setParameter(HttpMethodParams.USER_AGENT, mUserAgent); <END> Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath()); int status = super.executeMethod(method); if (customRedirectionNeeded) { status = patchRedirection(status, method); } return status; } catch (IOException e) { Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occurred", e); throw e; } }</code><technical_language>This enough. For buggy GET operations detected apply specific code needed, others need else</technical_language>

Target:
public int executeMethod(HttpMethod method) throws IOException, HttpException { try { boolean customRedirectionNeeded = false; try { method.setFollowRedirects(mFollowRedirects); } catch (Exception e) { customRedirectionNeeded = mFollowRedirects; } HttpParams params = method.getParams(); String userAgent = OwnCloudClientManagerFactory.getUserAgent(); params.setParameter(HttpMethodParams.USER_AGENT, userAgent); Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath()); int status = super.executeMethod(method); if (customRedirectionNeeded) { status = patchRedirection(status, method); } return status; } catch (IOException e) { Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occurred", e); throw e; } }
Source:
<code>public Session findSession(String id) throws IOException { log.debug("Datastore manager is loading session: " + id); Session session = null; try { session = this.getStore().load(id); } catch (ClassNotFoundException ex) { <START> log.warn("An error occurred during session deserialization" + ex); <END> } return session; }</code><technical_language>if swallow exception here</technical_language>

Target:
public Session findSession(String id) throws IOException { log.debug("Datastore manager is loading session: " + id); Session session = null; try { session = this.getStore().load(id); } catch (ClassNotFoundException ex) { log.warn("An error occurred during session deserialization", ex); } return session; }
Source:
<code>public Query existsQuery(QueryShardContext context) { if (hasDocValues()) { return new DocValuesFieldExistsQuery(name()); <START> } else if (omitNorms()) { <END> return new TermQuery(new Term(FieldNamesFieldMapper.NAME, name())); } else { return new NormsFieldExistsQuery(name()); } }</code><technical_language>I omitNorms() || indexOptions() != IndexOptions.NONE</technical_language>

Target:
public Query existsQuery(QueryShardContext context) { if (hasDocValues()) { return new DocValuesFieldExistsQuery(name()); } else { return new TermQuery(new Term(FieldNamesFieldMapper.NAME, name())); } }
Source:
<code><START> public @Nullable Long getClusterRegionId() { <END> return regionId; }</code><technical_language>1. annotation, modifiers 2. getClusterRegionId() is java.lang.Long primitive? fine if 0 for cases if is set</technical_language>

Target:
public long getClusterRegionId() { return clusterRegionId; }
Source:
<code>private void testGetCoOwnersForCourse() { ______TS("Verify co-owner status of generated co-owners list"); String courseId = "idOfTypicalCourse1"; List<InstructorAttributes> generatedCoOwners = instructorsLogic.getCoOwnersForCourse(courseId); for (InstructorAttributes generatedCoOwner : generatedCoOwners) { assertTrue(generatedCoOwner.hasCoownerPrivileges()); } ______TS("Verify all co-owners present in generated co-owners list"); <START> List<InstructorAttributes> instructors = instructorsLogic.getInstructorsForCourse(courseId); <END> List<InstructorAttributes> coOwners = new ArrayList<InstructorAttributes>(); for (InstructorAttributes instructor : instructors) { if (!instructor.hasCoownerPrivileges()) { continue; } coOwners.add(instructor); } assertTrue(coOwners.toString().equals(generatedCoOwners.toString())); }</code><technical_language>Instead of generating expected results instructorsLogic (something testing), I generate dataBundle</technical_language>

Target:
private void testGetCoOwnersForCourse() { ______TS("Verify co-owner status of generated co-owners list"); String courseId = "idOfTypicalCourse1"; List<InstructorAttributes> generatedCoOwners = instructorsLogic.getCoOwnersForCourse(courseId); for (InstructorAttributes generatedCoOwner : generatedCoOwners) { assertTrue(generatedCoOwner.hasCoownerPrivileges()); } ______TS("Verify all co-owners present in generated co-owners list"); List<String> coOwnersEmailsFromDataBundle = new ArrayList<String>(); for (InstructorAttributes instructor : new ArrayList<InstructorAttributes>(dataBundle.instructors.values())) { if (!(instructor.getCourseId().equals(courseId) && instructor.hasCoownerPrivileges())) { continue; } coOwnersEmailsFromDataBundle.add(instructor.email); } List<String> generatedCoOwnersEmails = new ArrayList<String>(); for (InstructorAttributes generatedCoOwner : generatedCoOwners) { generatedCoOwnersEmails.add(generatedCoOwner.email); } assertTrue(coOwnersEmailsFromDataBundle.containsAll(generatedCoOwnersEmails) && generatedCoOwnersEmails.containsAll(coOwnersEmailsFromDataBundle)); }
Source:
<code>public static int clearTempModelFiles() { int deleteCount = 0; for (File c : AnkiDroidApp.getInstance().getCacheDir().listFiles()) { <START> if (c.getAbsolutePath().endsWith("json") && c.getAbsolutePath().contains("editedTemplate")) { <END> if (!c.delete()) { Timber.w("Unable to delete temp file %s", c.getAbsolutePath()); } else { deleteCount++; Timber.d("Deleted temp model file %s", c.getAbsolutePath()); } } } return deleteCount; }</code><technical_language>nit: invert if for readability</technical_language>

Target:
public static int clearTempModelFiles() { int deleteCount = 0; for (File c : AnkiDroidApp.getInstance().getCacheDir().listFiles()) { String absolutePath = c.getAbsolutePath(); if (absolutePath.contains("editedTemplate") && absolutePath.endsWith("json") ) { if (!c.delete()) { Timber.w("Unable to delete temp file %s", c.getAbsolutePath()); } else { deleteCount++; Timber.d("Deleted temp model file %s", c.getAbsolutePath()); } } } return deleteCount; }
Source:
<code>public Distributor getDistributor() { String clazz = config.get(DISTRIBUTOR_SECTION, "implementation").orElse(DEFAULT_DISTRIBUTOR_SERVER); LOG.info("Creating distributor server: " + clazz); try { <START> Class<?> busClazz = Class.forName(clazz); <END> Method create = busClazz.getMethod("create", Config.class); if (!Modifier.isStatic(create.getModifiers())) { throw new IllegalArgumentException(String.format( "Distributor class %s's `create(Config)` method must be static", clazz)); } if (!Distributor.class.isAssignableFrom(create.getReturnType())) { throw new IllegalArgumentException(String.format( "Distributor class %s's `create(Config)` method must return a Distributor", clazz)); } return (Distributor) create.invoke(null, config); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(String.format( "Distributor class %s must have a static `create(Config)` method", clazz)); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException("Unable to find event bus class: " + clazz, e); } }</code><technical_language>bus? copy-and-paste is showing :)</technical_language>

Target:
public Distributor getDistributor() { String clazz = config.get(DISTRIBUTOR_SECTION, "implementation").orElse(DEFAULT_DISTRIBUTOR_SERVER); LOG.info("Creating distributor server: " + clazz); try { Class<?> distributorClazz = Class.forName(clazz); Method create = distributorClazz.getMethod("create", Config.class); if (!Modifier.isStatic(create.getModifiers())) { throw new IllegalArgumentException(String.format( "Distributor class %s's `create(Config)` method must be static", clazz)); } if (!Distributor.class.isAssignableFrom(create.getReturnType())) { throw new IllegalArgumentException(String.format( "Distributor class %s's `create(Config)` method must return a Distributor", clazz)); } return (Distributor) create.invoke(null, config); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(String.format( "Distributor class %s must have a static `create(Config)` method", clazz)); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException("Unable to find distributor class: " + clazz, e); } }
Source:
<code>public Result get(final UUID id) { final Organization organization; try { organization = _organizationRepository.get(request()); } catch (final NoSuchElementException e) { return internalServerError(); } try { final Optional<Report> report = _reportRepository.getReport(id, organization); return report.map(r -> ok(Json.toJson(models.view.reports.Report.fromInternal(r)))) .orElseGet(ReportController::notFound); <START> } catch (final PersistenceException e) { <END> LOGGER.error() .setMessage("Get report failed") .setThrowable(e) .log(); return internalServerError(); } }</code><technical_language>moment repositories throw runtime exceptions for unexpected failures fall controllers result in automatic 5xx Play</technical_language>

Target:
public Result get(final UUID id) { final Organization organization; try { organization = _organizationRepository.get(request()); } catch (final NoSuchElementException e) { return internalServerError(); } final Optional<Report> report = _reportRepository.getReport(id, organization); return report .map(r -> ok(Json.toJson(models.view.reports.Report.fromInternal(r)))) .orElseGet(ReportController::notFound); }
Source:
<code>private void storeRerunData(BranchId branch, String destSetId, HashMap<String, String> reruns) { StringBuilder sb = new StringBuilder(); for (Entry<String, String> entry : reruns.entrySet()) { sb = sb.append(DispoStrings.SCRIPT_ENTRY); sb = sb.append(String.format(DispoStrings.SCRIPT_NAME, entry.getKey())); sb = sb.append(String.format(DispoStrings.SCRIPT_PATH, entry.getValue())); sb = sb.append(DispoStrings.IS_RUNNABLE); sb = sb.append(DispoStrings.SCRIPT_ENTRY_END); } DispoSetData dispoSetData = new DispoSetData(); <START> dispoSetData.setTime(new Date().toString()); <END> dispoSetData.setRerunList(DispoStrings.BATCH_RERUN_LIST + sb.toString() + DispoStrings.BATCH_RERUN_LIST_END); ArtifactReadable author = getQuery().findUser(); storageProvider.get().updateDispoSet(author, branch, destSetId, dispoSetData); }</code><technical_language>Date stored a long value, toString method Date()</technical_language>

Target:
private void storeRerunData(BranchId branch, String destSetId, HashMap<String, String> reruns) { StringBuilder sb = new StringBuilder(); for (Entry<String, String> entry : reruns.entrySet()) { sb = sb.append(DispoStrings.SCRIPT_ENTRY); sb = sb.append(String.format(DispoStrings.SCRIPT_NAME, entry.getKey())); sb = sb.append(String.format(DispoStrings.SCRIPT_PATH, entry.getValue())); sb = sb.append(DispoStrings.IS_RUNNABLE); sb = sb.append(DispoStrings.SCRIPT_ENTRY_END); } DispoSetData dispoSetData = new DispoSetData(); dispoSetData.setTime(new Date()); dispoSetData.setRerunList(DispoStrings.BATCH_RERUN_LIST + sb.toString() + DispoStrings.BATCH_RERUN_LIST_END); ArtifactReadable author = getQuery().findUser(); storageProvider.get().updateDispoSet(author, branch, destSetId, dispoSetData); }
Source:
<code>public OutputPlugin( final Optional<Filter> filter, final Batching batching ) { this.filter = filter; this.batching = batching; <START> if (filter == null) { <END> throw new RuntimeException("filter can't be null"); } if (batching == null) { throw new RuntimeException("batching can't be null"); } }</code><technical_language>filter optional in configuration</technical_language>

Target:
public OutputPlugin( final Optional<Filter> filter, final Batching batching ) { this.filter = filter; this.batching = batching; }
Source:
<code>public void testCurrentServer() throws Exception { String sqlText = "values current server"; String sqlTextAlt = "values current_server"; String expected = "1 |\n" + "----------\n" + "splicedb |"; <START> ResultSet rs = methodWatcher.executeQuery(sqlText); <END> assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); rs.close(); rs = methodWatcher.executeQuery(sqlTextAlt); assertEquals("\n" + sqlTextAlt + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); }</code><technical_language>"try-with-resources" ensure resultsets get closed: try(ResultSet rs = methodWatcher.executeQuery(sqlText)) { assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); }</technical_language>

Target:
public void testCurrentServer() throws Exception { String sqlText = "values current server"; String sqlTextAlt = "values current_server"; String expected = "1 |\n" + "----------\n" + "splicedb |"; try (ResultSet rs = methodWatcher.executeQuery(sqlText)) { assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); } try (ResultSet rs = methodWatcher.executeQuery(sqlTextAlt)) { assertEquals("\n" + sqlTextAlt + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); } }
Source:
<code>public void testMigratoinCannotBeSetWhenVMUsesScsiReservation() { prepareVmToPassCanDoAction(); VmDevice device = createVmDevice(); doReturn(vmDeviceDAO).when(command).getVmDeviceDao(); <START> when(vmDeviceDAO.getVmDeviceByVmIdAndType(vm.getId(), VmDeviceGeneralType.DISK)).thenReturn(Arrays.asList(device)); <END> vm.setMigrationSupport(MigrationSupport.MIGRATABLE); CanDoActionTestUtils.runAndAssertCanDoActionFailure(command, VdcBllMessages.MIGRATION_SUPPORT_NOT_VALID_WHEN_VM_USES_SCSI_RESERVATION); }</code><technical_language>1. share some code mockGraphicsDevice 2. in terms of ordering, seperate entities preperations mocks- reading easier</technical_language>

Target:
public void testMigratoinCannotBeSetWhenVMUsesScsiReservation() { prepareVmToPassCanDoAction(); vm.setMigrationSupport(MigrationSupport.MIGRATABLE); VmDevice device = createVmDevice(); mockVmDevice(device); mockVmValidator(); CanDoActionTestUtils.runAndAssertCanDoActionFailure(command, VdcBllMessages.MIGRATION_SUPPORT_NOT_VALID_WHEN_VM_USES_SCSI_RESERVATION); }
Source:
<code>private void displaySearchResult(GeocodeResult geocodeResult) { if (mMapView.getCallout() != null && mMapView.getCallout().isShowing()) { mMapView.getCallout().dismiss(); } mMapView.getGraphicsOverlays().clear(); mGraphicsOverlay.getGraphics().clear(); Point resultPoint = geocodeResult.getDisplayLocation(); Graphic resultLocGraphic = new Graphic(resultPoint, geocodeResult.getAttributes(), mPinSourceSymbol); mGraphicsOverlay.getGraphics().add(resultLocGraphic); mMapView.setViewpointAsync(new Viewpoint(geocodeResult.getExtent()), 3); <START> mMapView.getGraphicsOverlays().add(mGraphicsOverlay); <END> }</code><technical_language>add Callout displaying a search result instead of forcing user tap marker get callout</technical_language>

Target:
private void displaySearchResult(GeocodeResult geocodeResult) { if (mMapView.getCallout() != null && mMapView.getCallout().isShowing()) { mMapView.getCallout().dismiss(); } mMapView.getGraphicsOverlays().clear(); mGraphicsOverlay.getGraphics().clear(); Point resultPoint = geocodeResult.getDisplayLocation(); Graphic resultLocGraphic = new Graphic(resultPoint, geocodeResult.getAttributes(), mPinSourceSymbol); mGraphicsOverlay.getGraphics().add(resultLocGraphic); mMapView.setViewpointAsync(new Viewpoint(geocodeResult.getExtent()), 3); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); showCallout(resultLocGraphic); }
Source:
<code>private boolean skipOnMatrixChildren(AbstractBuild build) { <START> return notifier.isMatrixProject(build) && !notifier.getMatrixTriggerMode().forChild; <END> }</code><technical_language>missing other problem, getMatrixTriggerMode return null :laughing: private MatrixTriggerMode matrixTriggerMode = MatrixTriggerMode.ONLY_CONFIGURATIONS; reading XML. is need for set non-Matrix jobs either</technical_language>

Target:
private boolean skipOnMatrixChildren(AbstractBuild build) { if (notifier.isMatrixRun(build)) { MatrixTriggerMode matrixTriggerMode = notifier.getMatrixTriggerMode(); return !(matrixTriggerMode != null && matrixTriggerMode.forChild); } return false; }
Source:
<code>public void shouldPublishAvroAndConsumeJsonMessageWithTraceId() throws IOException{ byte[] avroMessage = new AvroUser("John Doe", 44, "black").asBytes(); <START> String jsonMessage = "{\"name\":\"John Doe\",\"age\":44,\"favoriteColor\":\"black\"}"; <END> String traceId = UUID.randomUUID().toString(); Topic topic = operations.buildTopic(topic() .withName("publishAvroConsumeJsonWithTraceId.topic") .withValidation(true) .withMessageSchema(user.getSchemaAsString()) .withContentType(AVRO).build() ); operations.createSubscription(topic, "subscription", HTTP_ENDPOINT_URL); remoteService.expectMessages(jsonMessage); WebTarget client = ClientBuilder.newClient().target(FRONTEND_URL).path("topics").path(topic.getQualifiedName()); Response response = client .request() .header("Trace-Id", traceId) .post(Entity.entity(avroMessage, MediaType.valueOf("avro/binary"))); assertThat(response).hasStatus(Response.Status.CREATED); assertThat(remoteService.waitAndGetLastRequest()).hasHeaderValue("Trace-Id", traceId); }</code><technical_language>this replaced user.asJson()</technical_language>

Target:
public void shouldPublishAvroAndConsumeJsonMessageWithTraceId() throws IOException{ String traceId = UUID.randomUUID().toString(); Topic topic = operations.buildTopic(topic() .withName("publishAvroConsumeJsonWithTraceId.topic") .withValidation(true) .withMessageSchema(user.getSchemaAsString()) .withContentType(AVRO).build() ); operations.createSubscription(topic, "subscription", HTTP_ENDPOINT_URL); remoteService.expectMessages(user.asJson()); WebTarget client = ClientBuilder.newClient().target(FRONTEND_URL).path("topics").path(topic.getQualifiedName()); Response response = client .request() .header("Trace-Id", traceId) .post(Entity.entity(user.asBytes(), MediaType.valueOf("avro/binary"))); assertThat(response).hasStatus(Response.Status.CREATED); assertThat(remoteService.waitAndGetLastRequest()).hasHeaderValue("Trace-Id", traceId); }
Source:
<code>public AuthenticationResult createEscalatedAuthenticationResult() { <START> return new AuthenticationResult(internalClientPrincipal, authorizerName, "kerberos", null); <END> }</code><technical_language>user authenticator configured name "kerberos", this hardcoded e.g for configs - druid.auth.authenticatorChain=["MyKerberosAuthenticator"] druid.auth.authenticator.MyKerberosAuthenticator.type=kerberos this set MyKerberosAuthenticator I think</technical_language>

Target:
public AuthenticationResult createEscalatedAuthenticationResult() { return new AuthenticationResult(internalClientPrincipal, authorizerName, null, null); }
Source:
<code>private Boolean performPush(StackOperation op, SessionFrame matchingFrame, boolean isNewFrame, boolean currentFramePushed, SessionFrame onDeck, EvaluationContext ec) { if (op.isOperationTriggered(ec)) { if (matchingFrame == null) { matchingFrame = onDeck; } for (StackFrameStep step : op.getStackFrameSteps()) { matchingFrame.pushStep(step.defineStep(ec)); } return pushNewFrame(matchingFrame, isNewFrame, currentFramePushed); } <START> return null; <END> }</code><technical_language>stick original strategy of returning currentFramePushed in this case, do null check calling this method</technical_language>

Target:
private boolean performPush(StackOperation op, SessionFrame matchingFrame, boolean isNewFrame, boolean currentFramePushed, SessionFrame onDeck, EvaluationContext ec) { if (op.isOperationTriggered(ec)) { if (matchingFrame == null) { matchingFrame = onDeck; } for (StackFrameStep step : op.getStackFrameSteps()) { matchingFrame.pushStep(step.defineStep(ec)); } return pushNewFrame(matchingFrame, isNewFrame, currentFramePushed); } return currentFramePushed; }
Source:
<code>public void cancel(Locality locality) { <START> for (I id: this.expirationTracker.getTrackedIds()) { <END> if (Thread.currentThread().isInterrupted()) break; if (!locality.isLocal(id)) { this.cancel(id); } } }</code><technical_language>Iterating this set prone ConcurrentModificationExceptions</technical_language>

Target:
public void cancel(Locality locality) { for (I id: this.evictionFutures.keySet()) { if (Thread.currentThread().isInterrupted()) break; if (!locality.isLocal(id)) { this.cancel(id); } } }
Source:
<code>private void setVmTicket() { Frontend.RunAction(VdcActionType.SetVmTicket, new SetVmTicketParameters(getEntity().getId(), null, <START> TICKET_VALIDITY_SECONDS), new IFrontendActionAsyncCallback() { <END> @Override public void Executed(FrontendActionAsyncResult result) { VdcReturnValueBase ticketReturnValue = result.getReturnValue(); if (ticketReturnValue != null && ticketReturnValue.getActionReturnValue() != null) { otp64 = (String) ticketReturnValue.getActionReturnValue(); if (StringHelper.isNullOrEmpty(getEntity().getDisplayIp()) || StringHelper.stringsEqual(getEntity().getDisplayIp(), "0")) { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object ReturnValue) { VncConsoleModel consoleModel = (VncConsoleModel) model; VncConsoleModel.this.host = (String) ((VdcQueryReturnValue) ReturnValue).getReturnValue(); consoleModel.setAndInvokeClient(); } }; Frontend.RunQuery(VdcQueryType.GetManagementInterfaceAddressByVmId, new IdQueryParameters(getEntity().getId()), _asyncQuery); } else { VncConsoleModel.this.host = getEntity().getDisplayIp(); setAndInvokeClient(); } } } }); }</code><technical_language>do need set timeout? expect engine accept empty call generate ticket engine default ticket timeout</technical_language>

Target:
private void setVmTicket() { Frontend.RunAction(VdcActionType.SetVmTicket, new SetVmTicketParameters(getEntity().getId(), null, TICKET_VALIDITY_SECONDS), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { VdcReturnValueBase ticketReturnValue = result.getReturnValue(); if (ticketReturnValue != null && ticketReturnValue.getActionReturnValue() != null) { otp64 = (String) ticketReturnValue.getActionReturnValue(); if (StringHelper.isNullOrEmpty(getEntity().getDisplayIp()) || StringHelper.stringsEqual(getEntity().getDisplayIp(), "0")) { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { VncConsoleModel consoleModel = (VncConsoleModel) model; VncConsoleModel.this.host = (String) ((VdcQueryReturnValue) ReturnValue).getReturnValue(); consoleModel.setAndInvokeClient(); } }; Frontend.RunQuery(VdcQueryType.GetManagementInterfaceAddressByVmId, new IdQueryParameters(getEntity().getId()), _asyncQuery); } else { VncConsoleModel.this.host = getEntity().getDisplayIp(); setAndInvokeClient(); } } } }); }
Source:
<code>private void doProvisionVcsSshConfig( List<SshPairImpl> vcsSshPairs, KubernetesEnvironment k8sEnv, String wsId) { StringBuilder sshConfigData = new StringBuilder(); for (SshPair sshPair : vcsSshPairs) { sshConfigData.append(buildConfig(sshPair.getName())); } <START> String sshConfigMapName = SSH_CONFIG_MAP_NAME; <END> Map<String, String> sshConfig = new HashMap<>(); sshConfig.put(SSH_CONFIG, sshConfigData.toString()); ConfigMap configMap = new ConfigMapBuilder() .withNewMetadata() .withName(sshConfigMapName) .endMetadata() .withData(sshConfig) .build(); k8sEnv.getConfigMaps().put(configMap.getMetadata().getName(), configMap); k8sEnv .getPodsData() .values() .forEach( p -> mountConfigFile(p.getSpec(), sshConfigMapName, p.getRole() != PodRole.INJECTABLE)); }</code><technical_language>do need this variable anymore? constant directly</technical_language>

Target:
private void doProvisionVcsSshConfig( List<SshPairImpl> vcsSshPairs, KubernetesEnvironment k8sEnv, String wsId) { StringBuilder sshConfigData = new StringBuilder(); for (SshPair sshPair : vcsSshPairs) { sshConfigData.append(buildConfig(sshPair.getName())); } Map<String, String> sshConfig = new HashMap<>(); sshConfig.put(SSH_CONFIG, sshConfigData.toString()); ConfigMap configMap = new ConfigMapBuilder() .withNewMetadata() .withName(SSH_CONFIG_MAP_NAME) .endMetadata() .withData(sshConfig) .build(); k8sEnv.getConfigMaps().put(configMap.getMetadata().getName(), configMap); k8sEnv .getPodsData() .values() .forEach( p -> mountConfigFile( p.getSpec(), SSH_CONFIG_MAP_NAME, p.getRole() != PodRole.INJECTABLE)); }
Source:
<code>public static ClientConfiguration toClientConf(AccumuloConfiguration conf) { ClientConfiguration clientConf = ClientConfiguration.create(); final String serverPrincipal = conf.get(Property.GENERAL_KERBEROS_PRINCIPAL); final KerberosName krbName; try { krbName = new KerberosName(serverPrincipal); clientConf.setProperty(ClientConfiguration.ClientProperty.KERBEROS_SERVER_PRIMARY, krbName.getServiceName()); <START> } catch (Exception e) { <END> } HashSet<String> clientKeys = new HashSet<>(); for (ClientConfiguration.ClientProperty prop : ClientConfiguration.ClientProperty.values()) { clientKeys.add(prop.getKey()); } String key; for (Map.Entry<String,String> entry : conf) { key = entry.getKey(); if (clientKeys.contains(key)) { clientConf.setProperty(key, entry.getValue()); } } return clientConf; }</code><technical_language>This overly broad, is more specific do? empty case checked for? Is a more specific exception catch? log exception debug</technical_language>

Target:
public static ClientConfiguration toClientConf(AccumuloConfiguration conf) { ClientConfiguration clientConf = ClientConfiguration.create(); final String serverPrincipal = conf.get(Property.GENERAL_KERBEROS_PRINCIPAL); final KerberosName krbName; if (serverPrincipal != null && !serverPrincipal.isEmpty()) { krbName = new KerberosName(serverPrincipal); clientConf.setProperty(KERBEROS_SERVER_PRIMARY, krbName.getServiceName()); } HashSet<String> clientKeys = new HashSet<>(); for (ClientConfiguration.ClientProperty prop : ClientConfiguration.ClientProperty.values()) { clientKeys.add(prop.getKey()); } String key; for (Map.Entry<String,String> entry : conf) { key = entry.getKey(); if (clientKeys.contains(key)) { clientConf.setProperty(key, entry.getValue()); } } return clientConf; }
Source:
<code>public File getResource(String path) { if (path == null) { return null; } final String configurationDirectory = FilenameUtils <START> .concat(OpenmrsUtil.getApplicationDataDirectory(), "configuration"); <END> final File resourceFile; final File file = new File(path); if (file.isAbsolute()) { resourceFile = file; } else { resourceFile = new File(configurationDirectory, path); } try { if (!resourceFile.getCanonicalPath().startsWith(configurationDirectory)) { log.warn("Attempted to load invalid resource: {}", file); return null; } } catch (IOException e) { log.error("Error occurred while trying to load file: {}", path, e); return null; } return resourceFile.exists() ? resourceFile : null; }</code><technical_language>If helpful, is a core method: OpenmrsUtil.getDirectoryInApplicationDataDirectory("configuration")</technical_language>

Target:
public File getResource(String path) { if (path == null) { return null; } final String configurationDirectory; try { configurationDirectory = OpenmrsUtil.getDirectoryInApplicationDataDirectory("configuration") .getCanonicalPath(); } catch (IOException e) { throw new APIException("Could not determine canonical path for configuration directory", e); } final File resourceFile; final File file = new File(path); if (file.isAbsolute()) { resourceFile = file; } else { resourceFile = new File(configurationDirectory, path); } try { if (!resourceFile.getCanonicalPath().startsWith(configurationDirectory)) { log.warn("Attempted to load invalid resource: {}", file); return null; } } catch (IOException e) { log.error("Error occurred while trying to load file: {}", path, e); return null; } return resourceFile.exists() ? resourceFile : null; }
Source:
<code>public void onUpdate() { superUpdate(); if(ticksExisted >= effectThreshhold) <START> Botania.proxy.sparkleFX(worldObj, posX, posY, posZ, 0.3F, 0.09F, 1F, 4F, 1, true); <END> if(ticksExisted >= length) this.setDead(); ticksExisted++; }</code><technical_language>tested this in multiplayer</technical_language>

Target:
public void onUpdate() { superUpdate(); if(ticksExisted >= effectThreshhold && worldObj.isRemote) Botania.proxy.wispFX(worldObj, posX, posY, posZ, 0.3F, 0.09F, 1F, 1F, -0.1F, 0.18F); if(ticksExisted >= length) this.setDead(); ticksExisted++; if (!isDead) onUpdate(); }
Source:
<code>public void waitForReady() throws InterruptedException { Thread t = Thread.currentThread(); String oldName = t.getName(); try { int retries = 0; while (true) { Thread.sleep(1000 * 10); try { <START> URL url = toAgentListenerURL(first(jenkinsUrls)); <END> retries++; t.setName(oldName + ": trying " + url + " for " + retries + " times"); HttpURLConnection con = (HttpURLConnection) openURLConnection(url, credentials, proxyCredentials, sslSocketFactory); con.setConnectTimeout(5000); con.setReadTimeout(5000); con.connect(); if (con.getResponseCode() == 200) { return; } LOGGER.info("Master isn't ready to talk to us. Will retry again: response code=" + con .getResponseCode()); } catch (IOException e) { LOGGER.log(INFO, "Failed to connect to the master. Will retry again", e); } } } finally { t.setName(oldName); } }</code><technical_language>try jenkins URLs in loop this loop in case</technical_language>

Target:
public void waitForReady() throws InterruptedException { Thread t = Thread.currentThread(); String oldName = t.getName(); try { int retries = 0; while (true) { Thread.sleep(1000 * 10); try { URL url = toAgentListenerURL(first(jenkinsUrls)); if (url == null) { return; } retries++; t.setName(oldName + ": trying " + url + " for " + retries + " times"); HttpURLConnection con = (HttpURLConnection) openURLConnection(url, credentials, proxyCredentials, sslSocketFactory); con.setConnectTimeout(5000); con.setReadTimeout(5000); con.connect(); if (con.getResponseCode() == 200) { return; } LOGGER.log(Level.INFO, "Master isn't ready to talk to us on {0}. Will retry again: response code={1}", new Object[]{url, con.getResponseCode()}); } catch (IOException e) { LOGGER.log(INFO, "Failed to connect to the master. Will retry again", e); } } } finally { t.setName(oldName); } }
Source:
<code>public void afterPropertiesSet() { <START> this.faWindowTitle = clientProperties.getForgedAlliance().getWindowTitle(); <END> eventBus.register(this); }</code><technical_language>set done in constructor</technical_language>

Target:
public void afterPropertiesSet() { eventBus.register(this); }
Source:
<code>public TmfModelResponse<ITmfXyModel> fetchXY(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<P> providers = getProviders(); boolean allCommon = Iterables.all(providers, <START> p -> p instanceof ITmfCommonXAxisModel); <END> if (allCommon) { return getCommonXResponse(filter, monitor, providers); } return getXyResponse(filter, monitor, providers); }</code><technical_language>ITmfCommonXAxisModel.class::isInstance mehhh</technical_language>

Target:
public TmfModelResponse<ITmfXyModel> fetchXY(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<P> providers = getProviders(); boolean allCommon = Iterables.all(providers, ITmfCommonXAxisModel.class::isInstance); if (allCommon) { return getCommonXResponse(filter, monitor, providers); } return getXyResponse(filter, monitor, providers); }
Source:
<code><START> public ExtendedInMemoryUserDetailsManager myUserDetailsService() { <END> ExtendedInMemoryUserDetailsManager extendedInMemoryUserDetailsManager = new ExtendedInMemoryUserDetailsManager(); List<GrantedAuthority> salaboyAuthorities = new ArrayList<>(); salaboyAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); salaboyAuthorities.add(new SimpleGrantedAuthority("GROUP_activitiTeam")); extendedInMemoryUserDetailsManager.createUser(new User("salaboy", "password", salaboyAuthorities)); List<GrantedAuthority> adminAuthorities = new ArrayList<>(); adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_ADMIN")); extendedInMemoryUserDetailsManager.createUser(new User("admin", "password", adminAuthorities)); List<GrantedAuthority> garthAuthorities = new ArrayList<>(); garthAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); garthAuthorities.add(new SimpleGrantedAuthority("GROUP_doctor")); extendedInMemoryUserDetailsManager.createUser(new User("garth", "password", garthAuthorities)); return extendedInMemoryUserDetailsManager; }</code><technical_language>@pancudaniel7 bean type as: UserDetailsService</technical_language>

Target:
public UserDetails myUserDetailsService() { ExtendedInMemoryUserDetailsManager extendedInMemoryUserDetailsManager = new ExtendedInMemoryUserDetailsManager(); List<GrantedAuthority> salaboyAuthorities = new ArrayList<>(); salaboyAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); salaboyAuthorities.add(new SimpleGrantedAuthority("GROUP_activitiTeam")); extendedInMemoryUserDetailsManager.createUser(new User("salaboy", "password", salaboyAuthorities)); List<GrantedAuthority> adminAuthorities = new ArrayList<>(); adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_ADMIN")); extendedInMemoryUserDetailsManager.createUser(new User("admin", "password", adminAuthorities)); List<GrantedAuthority> garthAuthorities = new ArrayList<>(); garthAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); garthAuthorities.add(new SimpleGrantedAuthority("GROUP_doctor")); extendedInMemoryUserDetailsManager.createUser(new User("garth", "password", garthAuthorities)); return (UserDetails) extendedInMemoryUserDetailsManager; }
Source:
<code>public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; final String token = tokenExtractor.getToken(request); if (token == null) { send403(res, "Authorization token is missed"); return; } Jws<Claims> jwt; try { if (shouldSkipAuthentication(request, token)) { chain.doFilter(req, res); return; } jwt = jwtParser.parseClaimsJws(token); LOG.debug("JWT = ", jwt); } catch (ExpiredJwtException e) { send403(res, "The specified token is expired"); return; } catch (JwtException e) { <START> send403(res, "Token validation failed: " + e.getMessage()); <END> return; } request.setAttribute("token", jwt); chain.doFilter(req, res); }</code><technical_language>I understand 403 redirection is introduced in this PR send401 here. change in this PR</technical_language>

Target:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; final String token = tokenExtractor.getToken(request); if (token == null) { send401(res, "Authorization token is missed"); return; } Jws<Claims> jwt; try { if (shouldSkipAuthentication(request, token)) { chain.doFilter(req, res); return; } jwt = jwtParser.parseClaimsJws(token); LOG.debug("JWT = ", jwt); } catch (ExpiredJwtException e) { send401(res, "The specified token is expired"); return; } catch (JwtException e) { send401(res, "Token validation failed: " + e.getMessage()); return; } request.setAttribute("token", jwt); chain.doFilter(req, res); }
Source:
<code>public void testRunMultipleQueries_ignored_failure_multiple() { ArrayList<VdcQueryType> queryTypeList = new ArrayList<VdcQueryType>(); queryTypeList.add(VdcQueryType.Search); queryTypeList.add(VdcQueryType.Search); ArrayList<VdcQueryParametersBase> queryParamsList = new ArrayList<VdcQueryParametersBase>(); queryParamsList.add(new SearchParameters("*win*", SearchType.VM)); queryParamsList.add(new SearchParameters("*lin*", SearchType.VM)); Frontend.RunMultipleQueries(queryTypeList, queryParamsList, mockMultipleQueryCallback, "test", mockService); verify(mockService).RunMultipleQueries(eq(queryTypeList), eq(queryParamsList), callbackMultipleQueries.capture()); StatusCodeException exception = new StatusCodeException(0, "0 status code"); <START> callbackMultipleQueries.getValue().onFailure(exception); <END> }</code><technical_language>assertion end here</technical_language>

Target:
public void testRunMultipleQueries_ignored_failure_multiple() { ArrayList<VdcQueryType> queryTypeList = new ArrayList<VdcQueryType>(); queryTypeList.add(VdcQueryType.Search); queryTypeList.add(VdcQueryType.Search); ArrayList<VdcQueryParametersBase> queryParamsList = new ArrayList<VdcQueryParametersBase>(); queryParamsList.add(new SearchParameters("*win*", SearchType.VM)); queryParamsList.add(new SearchParameters("*lin*", SearchType.VM)); Frontend.RunMultipleQueries(queryTypeList, queryParamsList, mockMultipleQueryCallback, "test", mockService); verify(mockService).RunMultipleQueries(eq(queryTypeList), eq(queryParamsList), callbackMultipleQueries.capture()); StatusCodeException exception = new StatusCodeException(0, "0 status code"); callbackMultipleQueries.getValue().onFailure(exception); verify(mockFrontendFailureEvent, never()).raise(eq(Frontend.class), any(FrontendFailureEventArgs.class)); }
Source:
<code>static void permitAll(HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http, RequestMatcher... requestMatchers) { ExpressionUrlAuthorizationConfigurer<?> configurer = http .getConfigurer(ExpressionUrlAuthorizationConfigurer.class); Assert.state(configurer != null, "permitAll only works with HttpSecurity.authorizeRequests()"); for (RequestMatcher matcher : requestMatchers) { if (matcher != null) { configurer.getRegistry().addMapping(0, new UrlMapping(matcher, SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll))); <START> configurer.authorizationManagerBuilder.add(0, <END> new RequestMatcherEntry<>(matcher, (a, o) -> AuthorizationDecision.GRANTED)); } } }</code><technical_language>If AuthorizationManager is produced ConfigAttribute mappings, this line removed</technical_language>

Target:
static void permitAll(HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http, RequestMatcher... requestMatchers) { ExpressionUrlAuthorizationConfigurer<?> configurer = http .getConfigurer(ExpressionUrlAuthorizationConfigurer.class); Assert.state(configurer != null, "permitAll only works with HttpSecurity.authorizeRequests()"); for (RequestMatcher matcher : requestMatchers) { if (matcher != null) { configurer.getRegistry().addMapping(0, new UrlMapping(matcher, SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll))); } } }
Source:
<code>public void acceptRecord(final SAMRecord rec, final ReferenceSequence ref) { <START> super.acceptRecord(rec, ref); <END> }</code><technical_language>Do want include secondary reads well? I not. filter secondary reads here. if filtered upstream (I are) this program clear secondary alignements filtered out</technical_language>

Target:
public void acceptRecord(final SAMRecord rec, final ReferenceSequence ref) { if (!rec.getNotPrimaryAlignmentFlag()){ super.acceptRecord(rec, ref); } }
Source:
<code>User getUser() { User user = null; <START> HttpSession session = request.getSession(false); <END> if (session != null) { user = (User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); } return user; }</code><technical_language>set final</technical_language>

Target:
User getUser() { User user = null; final HttpSession session = request.getSession(false); if (session != null) { user = (User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); } return user; }
Source:
<code>Queue<ReplicaId> orderReplicaIds(String datacenterName, List<ReplicaId> replicaIds, boolean crossDCProxyCallEnabled) { Queue<ReplicaId> orderedReplicaIds = new ArrayDeque<ReplicaId>(replicaIdCount); Map<String, Deque<ReplicaId>> replicasPerDatacenter = new HashMap<String, Deque<ReplicaId>>(); Map<String, Integer> availableReplicaCountPerDatacenter = new HashMap<String, Integer>(); for (ReplicaId replicaId : replicaIds) { String dataCenter = replicaId.getDataNodeId().getDatacenterName(); if (!replicasPerDatacenter.containsKey(dataCenter)) { replicasPerDatacenter.put(dataCenter, new LinkedList<ReplicaId>()); availableReplicaCountPerDatacenter.put(dataCenter, 0); } } for (ReplicaId replicaId : replicaIds) { <START> String dcName = replicaId.getDataNodeId().getDatacenterName(); <END> if (dcName.equals(datacenterName)) { addReplicaToDataCenter(replicaId, dcName, replicasPerDatacenter, availableReplicaCountPerDatacenter); } else if (crossDCProxyCallEnabled) { addReplicaToDataCenter(replicaId, dcName, replicasPerDatacenter, availableReplicaCountPerDatacenter); } } dataCenterCount += replicasPerDatacenter.size() - 1; shuffleAndPopulate(replicasPerDatacenter, availableReplicaCountPerDatacenter, orderedReplicaIds); return orderedReplicaIds; }</code><technical_language>looping list of replicaIds twice</technical_language>

Target:
Queue<ReplicaId> orderReplicaIds(String datacenterName, List<ReplicaId> replicaIds, boolean crossDCProxyCallEnabled) { Queue<ReplicaId> orderedReplicaIds = new ArrayDeque<ReplicaId>(replicaIdCount); List<ReplicaId> localReplicaIds = new ArrayList<ReplicaId>(replicaIdCount); List<ReplicaId> remoteReplicaIds = new ArrayList<ReplicaId>(replicaIdCount); List<ReplicaId> downReplicaIds = new ArrayList<ReplicaId>(replicaIdCount); for (ReplicaId replicaId : replicaIds) { if (replicaId.isDown()) { downReplicaIds.add(replicaId); } else if (replicaId.getDataNodeId().getDatacenterName().equals(datacenterName)) { localReplicaIds.add(replicaId); } else if (crossDCProxyCallEnabled) { remoteReplicaIds.add(replicaId); } } Collections.shuffle(localReplicaIds); orderedReplicaIds.addAll(localReplicaIds); Collections.shuffle(remoteReplicaIds); orderedReplicaIds.addAll(remoteReplicaIds); Collections.shuffle(downReplicaIds); orderedReplicaIds.addAll(downReplicaIds); return orderedReplicaIds; }
Source:
<code><START> public void testToStockWithNewParents() throws IOException { <END> SampleStockDto dto = new SampleStockDto(); dto.setRootSampleClassId(1L); dto.setParentSampleClassId(2L); dto.setSampleClassId(3L); dto.setExternalName("externalName"); dto.setTissueOriginId(4L); dto.setTissueTypeId(5L); Sample sample = Dtos.to(dto); assertNotNull(sample); assertTrue(LimsUtils.isStockSample(sample)); SampleStock analyte = (SampleStock) sample; assertNotNull(analyte.getSampleClass()); assertEquals(Long.valueOf(3L), analyte.getSampleClass().getId()); assertNotNull(analyte.getParent()); assertTrue(LimsUtils.isTissueSample(analyte.getParent())); SampleTissue tissue = (SampleTissue) analyte.getParent(); assertNotNull(tissue.getSampleClass()); assertEquals(Long.valueOf(2L), tissue.getSampleClass().getId()); assertNotNull(tissue.getTissueOrigin()); assertEquals(Long.valueOf(4L), tissue.getTissueOrigin().getId()); assertNotNull(tissue.getTissueType()); assertEquals(Long.valueOf(5L), tissue.getTissueType().getId()); assertNotNull(tissue.getParent()); assertTrue(LimsUtils.isIdentitySample(tissue.getParent())); Identity identity = (Identity) tissue.getParent(); assertEquals("externalName", identity.getExternalName()); }</code><technical_language>a test, throw IOExceptions. for (L56 L82)</technical_language>

Target:
public void testToStockWithNewParents() { SampleStockDto dto = new SampleStockDto(); dto.setRootSampleClassId(1L); dto.setParentTissueSampleClassId(2L); dto.setSampleClassId(3L); dto.setExternalName("externalName"); dto.setTissueOriginId(4L); dto.setTissueTypeId(5L); Sample sample = Dtos.to(dto); assertNotNull(sample); assertTrue(LimsUtils.isStockSample(sample)); SampleStock analyte = (SampleStock) sample; assertNotNull(analyte.getSampleClass()); assertEquals(Long.valueOf(3L), analyte.getSampleClass().getId()); assertNotNull(analyte.getParent()); assertTrue(LimsUtils.isTissueSample(analyte.getParent())); SampleTissue tissue = (SampleTissue) analyte.getParent(); assertNotNull(tissue.getSampleClass()); assertEquals(Long.valueOf(2L), tissue.getSampleClass().getId()); assertNotNull(tissue.getTissueOrigin()); assertEquals(Long.valueOf(4L), tissue.getTissueOrigin().getId()); assertNotNull(tissue.getTissueType()); assertEquals(Long.valueOf(5L), tissue.getTissueType().getId()); assertNotNull(tissue.getParent()); assertTrue(LimsUtils.isIdentitySample(tissue.getParent())); Identity identity = (Identity) tissue.getParent(); assertEquals("externalName", identity.getExternalName()); }
Source:
<code>public String getTextToEdit(Object editedObject) { if (editedObject instanceof ValueSpecification) { return new UMLLabelProvider().getText(editedObject); } <START> return "not a ValueSpecification"; END> }</code><technical_language>Move a constant</technical_language>

Target:
public String getTextToEdit(Object editedObject) { if (editedObject instanceof ValueSpecification) { return new UMLLabelProvider().getText(editedObject); } return NOT_A_VALUE_SPECIFICATION; }