auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void gotoAnnotation(Direction direction) { if (leftSourceViewer == null || rightSourceViewer == null) { return; } List<CompareAnnotation> annotations = getAnnotations(); if (annotations.isEmpty()) { return; } if (currentAnnotation == null) { if (direction == Direction.FORWARDS) { currentAnnotation = annotations.get(0); } else { currentAnnotation = annotations.get(annotations.size() - 1); } } else { int annotationIndex = annotations.indexOf(currentAnnotation); if (direction == Direction.FORWARDS && annotationIndex + 1 < annotations.size()) { annotationIndex++; } else if (direction == Direction.BACKWARDS && annotationIndex - 1 >= 0) { annotationIndex--; } currentAnnotation = annotations.get(annotationIndex); } if (currentAnnotation != null) { if (currentAnnotation.getSide() == LEFT_SIDE) { moveToAnnotation(rightSourceViewer, leftSourceViewer, currentAnnotation.getAnnotation().getPosition()); } else { moveToAnnotation(leftSourceViewer, rightSourceViewer, currentAnnotation.getAnnotation().getPosition()); } } }

Target:
public void gotoAnnotation(Direction direction) { if (leftSourceViewer == null || rightSourceViewer == null) { return; } List<CompareAnnotation> annotations = getAnnotations(); if (annotations.isEmpty()) { return; } int annotationIndex = annotations.indexOf(currentAnnotation); annotationIndex += direction == Direction.FORWARDS ? 1 : -1; if (annotationIndex < 0) { annotationIndex = annotations.size() - 1; } if (annotationIndex >= annotations.size()) { annotationIndex = 0; } currentAnnotation = annotations.get(annotationIndex); if (currentAnnotation.getSide() == LEFT_SIDE) { moveToAnnotation(rightSourceViewer, leftSourceViewer, currentAnnotation.getAnnotation().getPosition()); } else { moveToAnnotation(leftSourceViewer, rightSourceViewer, currentAnnotation.getAnnotation().getPosition()); } }
Source:
protected @Nullable Object resolveValue(ITmfEvent event, int baseQuark, DataDrivenScenarioInfo scenarioInfo, IAnalysisDataContainer container) { final ITmfEventField field = event.getContent().getField(fFieldName.split(".")); Object fieldValue = null; if (field == null) { if (fFieldName.equalsIgnoreCase(TmfXmlStrings.CPU)) { Integer cpu = TmfTraceUtils.resolveIntEventAspectOfClassForEvent(event.getTrace(), TmfCpuAspect.class, event); if (cpu != null) { return cpu; } } else if (fFieldName.equalsIgnoreCase(TmfXmlStrings.TIMESTAMP)) { return event.getTimestamp().getValue(); } else if (fFieldName.equalsIgnoreCase(TmfXmlStrings.HOSTID)) { return event.getTrace().getHostId(); } fieldValue = TmfTraceUtils.resolveAspectOfNameForEvent(event.getTrace(), fFieldName, event); } else { fieldValue = field.getValue(); } return fieldValue; }

Target:
protected @Nullable Object resolveValue(ITmfEvent event, int baseQuark, DataDrivenScenarioInfo scenarioInfo, IAnalysisDataContainer container) { final ITmfEventField field = event.getContent().getField(fFieldName); Object fieldValue = null; if (field == null) { final ITmfEventField splitFieldName = event.getContent().getField(fFieldName.split("\\.")); if (splitFieldName != null) { fieldValue = splitFieldName.getValue(); if (fieldValue != null) { return fieldValue; } } else if (fFieldName.equalsIgnoreCase(TmfXmlStrings.CPU)) { Integer cpu = TmfTraceUtils.resolveIntEventAspectOfClassForEvent(event.getTrace(), TmfCpuAspect.class, event); if (cpu != null) { return cpu; } } else if (fFieldName.equalsIgnoreCase(TmfXmlStrings.TIMESTAMP)) { return event.getTimestamp().getValue(); } else if (fFieldName.equalsIgnoreCase(TmfXmlStrings.HOSTID)) { return event.getTrace().getHostId(); } fieldValue = TmfTraceUtils.resolveAspectOfNameForEvent(event.getTrace(), fFieldName, event); } else { fieldValue = field.getValue(); } return fieldValue; }
Source:
synchronized public int read(byte[] buf, int off, int len) throws IOException { LOG.trace("read(buf, off={}, len={}" off, len); int read = 0; while (len > 0) { if (buffersize == 0) { fill(); if (buffersize == 0) { break; } } int tocopy = Math.min(len, buffersize); LOG.trace("tocopy={}" + tocopy); System.arraycopy(buffer, bufferoffset, buf, off, tocopy); buffersize -= tocopy; bufferoffset += tocopy; len -= tocopy; read += tocopy; off += tocopy; } LOG.trace("read={}", read); return read; }

Target:
synchronized public int read(byte[] buf, int off, int len) throws IOException { LOG.trace("read(buf, off={}, len={}", off, len); int read = 0; while (len > 0) { if (buffersize == 0) { fill(); if (buffersize == 0) { break; } } int tocopy = Math.min(len, buffersize); LOG.trace("tocopy={}" + tocopy); System.arraycopy(buffer, bufferoffset, buf, off, tocopy); buffersize -= tocopy; bufferoffset += tocopy; len -= tocopy; read += tocopy; off += tocopy; } LOG.trace("read={}", read); return read; }
Source:
public Message<?> preSend(Message<?> message, MessageChannel channel) { if (message instanceof ErrorMessage) { return message; } if (message.getPayload() instanceof byte[]) { return MessageConverterConfigurer.this.messageBuilderFactory .withPayload(message.getPayload()) .copyHeaders(message.getHeaders()) .setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType) .build(); } Message<?> sentMessage = null; Object converted; if (this.input) { return MessageConverterConfigurer.this.messageBuilderFactory .withPayload(message.getPayload()) .copyHeaders(message.getHeaders()) .setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType) .build(); } else { MutableMessageHeaders headers = new MutableMessageHeaders( message.getHeaders()); if (!headers.containsKey(MessageHeaders.CONTENT_TYPE)) { headers.put(MessageHeaders.CONTENT_TYPE, this.mimeType); } converted = this.messageConverter.toMessage(message.getPayload(), headers); } if (converted != null) { if (converted instanceof Message) { sentMessage = (Message<?>) converted; } else { sentMessage = MessageConverterConfigurer.this.messageBuilderFactory .withPayload(converted).copyHeaders(message.getHeaders()) .setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType) .build(); } } if (sentMessage == null) { throw new MessageConversionException(message, this.messageConverter.getClass().toString() + " could not convert '" + message + "' to the configured output type: '" + this.mimeType + "'"); } return sentMessage; }

Target:
public Message<?> preSend(Message<?> message, MessageChannel channel) { if (message instanceof ErrorMessage) { return message; } Message<?> sentMessage = null; Object converted; if (this.input || message.getPayload() instanceof byte[]) { return MessageConverterConfigurer.this.messageBuilderFactory .withPayload(message.getPayload()) .copyHeaders(message.getHeaders()) .setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType) .build(); } else { MutableMessageHeaders headers = new MutableMessageHeaders( message.getHeaders()); if (!headers.containsKey(MessageHeaders.CONTENT_TYPE)) { headers.put(MessageHeaders.CONTENT_TYPE, this.mimeType); } converted = this.messageConverter.toMessage(message.getPayload(), headers); } if (converted != null) { if (converted instanceof Message) { sentMessage = (Message<?>) converted; } else { sentMessage = MessageConverterConfigurer.this.messageBuilderFactory .withPayload(converted).copyHeaders(message.getHeaders()) .setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, this.mimeType) .build(); } } if (sentMessage == null) { throw new MessageConversionException(message, this.messageConverter.getClass().toString() + " could not convert '" + message + "' to the configured output type: '" + this.mimeType + "'"); } return sentMessage; }
Source:
public void testParameterSourceFactoryAndJpaParameters() { JpaExecutor executor = new JpaExecutor(this.entityManager); ParameterSourceFactory parameterSourceFactory = new ExpressionEvaluatingParameterSourceFactory(); executor.setParameterSourceFactory(parameterSourceFactory); executor.setJpaParameters(Collections.singletonList(new JpaParameter("firstName", null, "#this"))); try { executor.afterPropertiesSet(); } catch (Exception e) { assertThat(e, instanceOf(IllegalStateException.class)); assertThat(e.getMessage(), startsWith("The 'jpaParameters' and 'parameterSourceFactory' are mutually exclusive.")); } }

Target:
public void testParameterSourceFactoryAndJpaParameters() { JpaExecutor executor = new JpaExecutor(this.entityManager); ParameterSourceFactory parameterSourceFactory = new ExpressionEvaluatingParameterSourceFactory(); executor.setParameterSourceFactory(parameterSourceFactory); executor.setJpaParameters(Collections.singletonList(new JpaParameter("firstName", null, "#this"))); assertThatThrownBy(executor::afterPropertiesSet) .isExactlyInstanceOf(IllegalStateException.class) .hasMessageStartingWith("The 'jpaParameters' and 'parameterSourceFactory' are mutually exclusive."); }
Source:
public DataGeneratorContainer visit(TimeType timeType) { return DataGeneratorContainer.of(TimeGenerator.of(() -> LocalTime.now().get(MILLI_OF_SECOND))); }

Target:
public DataGeneratorContainer visit(TimeType timeType) { return DataGeneratorContainer.of(TimeGenerator.of(() -> LocalTime.now().get(MILLI_OF_DAY))); }
Source:
@Test public void deleteRecursiveOnUnix() throws Exception { assumeFalse(Functions.isWindows()); Path targetDir = temp.newFolder("target").toPath(); Path targetContents = Files.createFile(targetDir.resolve("contents.txt")); Path toDelete = temp.newFolder("toDelete").toPath(); Util.createSymlink(toDelete.toFile(), "../targetDir", "link", TaskListener.NULL); Files.createFile(toDelete.resolve("foo")); Files.createFile(toDelete.resolve("bar")); FilePath f = new FilePath(toDelete.toFile()); f.deleteRecursive(); assertTrue("symlink target should not be deleted", Files.exists(targetDir)); assertTrue("symlink target contents should not be deleted", Files.exists(targetContents)); assertFalse("could not delete target", Files.exists(toDelete)); }

Target:
@Test public void deleteRecursiveOnUnix() throws Exception { assumeFalse("Uses Unix-specific features", Functions.isWindows()); Path targetDir = temp.newFolder("target").toPath(); Path targetContents = Files.createFile(targetDir.resolve("contents.txt")); Path toDelete = temp.newFolder("toDelete").toPath(); Util.createSymlink(toDelete.toFile(), "../targetDir", "link", TaskListener.NULL); Files.createFile(toDelete.resolve("foo")); Files.createFile(toDelete.resolve("bar")); FilePath f = new FilePath(toDelete.toFile()); f.deleteRecursive(); assertTrue("symlink target should not be deleted", Files.exists(targetDir)); assertTrue("symlink target contents should not be deleted", Files.exists(targetContents)); assertFalse("could not delete target", Files.exists(toDelete)); }
Source:
protected String getTags() throws MojoExecutionException { try { Repository repo = getGitRepository(); ObjectId headId = headCommit.toObjectId(); Collection<String> tags = new JGitCommon().getTags(repo,headId); return Joiner.on(",").join(tags); } catch (GitAPIException e) { loggerBridge.error("Unable to extract tags from commit: " + headCommit.getName() + " (" + e.getClass().getName() + ")"); return ""; } }

Target:
protected String getTags() throws MojoExecutionException { try { Repository repo = getGitRepository(); ObjectId headId = headCommit.toObjectId(); Collection<String> tags = jGitCommon.getTags(repo,headId); return Joiner.on(",").join(tags); } catch (GitAPIException e) { loggerBridge.error("Unable to extract tags from commit: " + headCommit.getName() + " (" + e.getClass().getName() + ")"); return ""; } }
Source:
public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ActionParameter)) return false; ActionParameter actionParameter = (ActionParameter) o; return this.getName().equals(actionParameter.getName()); }

Target:
public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ActionParameter)) return false; ActionParameter actionParameter = (ActionParameter) o; return Objects.equals(this.getName(), actionParameter.getName()); }
Source:
public abstract String[] extractPartitions(Message payload) throws Exception; public Object getJsonFieldValue(JSONObject jsonObject) { Object fieldValue = null; String messageTimestampName = mConfig.getMessageTimestampName(); String messageTimestampSeparator = mConfig.getMessageTimestampNameSeparator(); if (messageTimestampSeparator != null) { String[] fields = messageTimestampName.split(Pattern.quote(messageTimestampSeparator)); Object finalValue = null; for (int i=0; i < fields.length; i++) { if (!jsonObject.containsKey(fields[i])) { LOG.warn("Could not find key in message", messageTimestampName); break; } if (i < (fields.length -1)) { jsonObject = (JSONObject) jsonObject.get(fields[i]); } else { finalValue = jsonObject.get(fields[i]); } } fieldValue = finalValue; } else { fieldValue = jsonObject.get(messageTimestampName); } return fieldValue; }

Target:
public abstract String[] extractPartitions(Message payload) throws Exception; public Object getJsonFieldValue(JSONObject jsonObject) { Object fieldValue = null; if (mNestedFields != null) { Object finalValue = null; for (int i=0; i < mNestedFields.length; i++) { if (!jsonObject.containsKey(mNestedFields[i])) { LOG.warn("Could not find key in message", mConfig.getMessageTimestampName()); break; } if (i < (mNestedFields.length -1)) { jsonObject = (JSONObject) jsonObject.get(mNestedFields[i]); } else { finalValue = jsonObject.get(mNestedFields[i]); } } fieldValue = finalValue; } else { fieldValue = jsonObject.get(mConfig.getMessageTimestampName()); } return fieldValue; }
Source:
public boolean datastreamExists(String datastreamName) { try { doGetDatastream(datastreamName); return true; } catch (RemoteInvocationException e) { LOG.debug(String.format("Datastream {%s} is not found", datastreamName)); return false; } }

Target:
public boolean datastreamExists(String datastreamName) { try { doGetDatastream(datastreamName); return true; } catch (RemoteInvocationException e) { if (isNotFoundHttpStatus(e)) { LOG.debug(String.format("Datastream %s is not found", datastreamName)); } else { String errorMessage = String.format("Get Datastream %s failed with error.", datastreamName); ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e); } } return false; }
Source:
private void onFragmentLoaded() { if (listAdapter == null) { listAdapter = new AllEpisodesRecycleAdapter(activity.get(), activity.get(), itemAccess, new DefaultActionButtonCallback(activity.get()), showOnlyNewEpisodes); listView.setAdapter(listAdapter); downloadObserver = new DownloadObserver(activity.get(), new Handler(), downloadObserverCallback); downloadObserver.onResume(); } listAdapter.notifyDataSetChanged(); restoreScrollPosition(); getActivity().supportInvalidateOptionsMenu(); updateShowOnlyEpisodesListViewState(); }

Target:
private void onFragmentLoaded() { if (listAdapter == null) { listAdapter = new AllEpisodesRecycleAdapter(activity.get(), activity.get(), itemAccess, new DefaultActionButtonCallback(activity.get()), showOnlyNewEpisodes()); recyclerView.setAdapter(listAdapter); downloadObserver = new DownloadObserver(activity.get(), new Handler(), downloadObserverCallback); downloadObserver.onResume(); } listAdapter.notifyDataSetChanged(); restoreScrollPosition(); getActivity().supportInvalidateOptionsMenu(); updateShowOnlyEpisodesListViewState(); }
Source:
public CommandImpl(String name, String commandLine, String type, Map<String, String> attributes) { this.name = name; this.commandLine = commandLine; this.type = type; this.attributes = new HashMap<>(attributes); }

Target:
public CommandImpl(String name, String commandLine, String type, Map<String, String> attributes) { this.name = name; this.commandLine = commandLine; this.type = type; this.attributes = unmodifiableMap(attributes); }
Source:
private static void setJobCommonProperties(Job job, InternalJob jobToSet) throws IllegalArgumentException, IllegalAccessException { autoCopyfields(CommonAttribute.class, job, jobToSet); autoCopyfields(Job.class, job, jobToSet); jobToSet.setPriority(job.getPriority()); }

Target:
private static void setJobCommonProperties(Job job, InternalJob jobToSet) throws IllegalArgumentException, IllegalAccessException { autoCopyfields(CommonAttribute.class, job, jobToSet); autoCopyfields(Job.class, job, jobToSet); jobToSet.setVariables(job.getVariables()); jobToSet.setGenericInformation(job.getGenericInformation()); jobToSet.setPriority(job.getPriority()); }
Source:
private Guid determineSourceImageGroup(DiskImage image) { if (Guid.Empty.equals(image.getParentId())) { return Guid.Empty; } else { if (!getParameters().getDestImages().isEmpty()) { return getParameters().getDestImageGroupId(); } } return image.getImageTemplateId().equals(image.getParentId()) ? imageDao.get(image.getImageTemplateId()).getDiskId() : getParameters().getImageGroupID(); }

Target:
private Guid determineSourceImageGroup(DiskImage image) { if (Guid.Empty.equals(image.getParentId())) { return Guid.Empty; } else if (!getParameters().getDestImages().isEmpty()) { return getParameters().getDestImageGroupId(); } return image.getImageTemplateId().equals(image.getParentId()) ? imageDao.get(image.getImageTemplateId()).getDiskId() : getParameters().getImageGroupID(); }
Source:
private void handleDispose() { tree.removeListener(SWT.Expand, this); tree.removeListener(SWT.Collapse, this); tree = null; session = null; }

Target:
private void handleDispose() { tree.removeListener(SWT.Dispose, this); tree.removeListener(SWT.Collapse, this); tree.removeListener(SWT.Expand, this); tree = null; session = null; }
Source:
public void testCalculateSubscriptions() throws Exception { long month = (long) 30 * 24 * 3600 * 1000; Date startTime = new Date(); Date endTime = new Date(startTime.getTime() + month); List<CalcSubscription> subscriptionsToCalculate = ImmutableList.of( new CalcSubscription.Builder() .startTime(startTime) .resource(SubscriptionResource.IP) .endTime(endTime) .build(), new CalcSubscription.Builder() .startTime(startTime) .endTime(endTime) .resource(SubscriptionResource.VLAN) .discountAmount(10.5d) .build() ); SubscriptionCalculator subscriptionCalculator = api.calculateSubscriptions(subscriptionsToCalculate); List<CalcSubscription> calculatedSubscriptions = subscriptionCalculator.getSubscriptions(); assertEquals(calculatedSubscriptions.size(), subscriptionsToCalculate.size()); for (int i = 0; i < calculatedSubscriptions.size(); i++) { checkCalcSubscription(calculatedSubscriptions.get(i), subscriptionsToCalculate.get(i)); } }

Target:
public void testCalculateSubscriptions() throws Exception { long monthInMilliseconds = (long) 30 * 24 * 3600 * 1000; Date startTime = new Date(); Date endTime = new Date(startTime.getTime() + monthInMilliseconds); List<CalcSubscription> subscriptionsToCalculate = ImmutableList.of( new CalcSubscription.Builder() .startTime(startTime) .resource(SubscriptionResource.IP) .endTime(endTime) .build(), new CalcSubscription.Builder() .startTime(startTime) .endTime(endTime) .resource(SubscriptionResource.VLAN) .discountAmount(10.5d) .build() ); SubscriptionCalculator subscriptionCalculator = api.calculateSubscriptions(subscriptionsToCalculate); List<CalcSubscription> calculatedSubscriptions = subscriptionCalculator.getSubscriptions(); assertEquals(calculatedSubscriptions.size(), subscriptionsToCalculate.size()); for (int i = 0; i < calculatedSubscriptions.size(); i++) { assertEquals(calculatedSubscriptions.get(i).getResource(), subscriptionsToCalculate.get(i).getResource()); } }
Source:
public void updateUserMetaData(Map<String, String> userMetaDataMap) { StringBuilder userMetadata = new StringBuilder("?SDK=Android&Version=" + VersionInfoUtils.getVersion()); int baseLength = userMetadata.length(); for(Map.Entry<String, String> metaData : userMetaDataMap.entrySet()){ this.userMetaDataMap.put(metaData.getKey(), metaData.getValue()); } if (this.userMetaDataMap != null) { for (Map.Entry<String, String> metaData : this.userMetaDataMap.entrySet()) { if (!(metaData.getKey().equals("SDK") || metaData.getKey().equals("Version"))) { userMetadata.append("&" + metaData.getKey() + "=" + metaData.getValue()); } else { LOGGER.warn("Keynames 'SDK' and 'Version' are reserved and will be skipped"); } } } if(userMetadata.length() > 255) { LOGGER.warn("Too many characters. User metadata was truncated.", new IllegalArgumentException("Total number of characters in user metadata" + " cannot exceed " + (255 - baseLength))); this.userMetaData = userMetadata.substring(0, 255); } else { this.userMetaData = userMetadata.toString(); } }

Target:
public void updateUserMetaData(Map<String, String> userMetaDataMap) { StringBuilder userMetadata = new StringBuilder("?SDK=Android&Version=" + VersionInfoUtils.getVersion()); int baseLength = userMetadata.length(); if (userMetaDataMap != null) { for (Map.Entry<String, String> metaData : userMetaDataMap.entrySet()) { this.userMetaDataMap.put(metaData.getKey(), metaData.getValue()); } } for (Map.Entry<String, String> metaData : this.userMetaDataMap.entrySet()) { if (!(metaData.getKey().equals("SDK") || metaData.getKey().equals("Version"))) { String metaDataValue = metaData.getValue(); if (metaDataValue == null || "".equals(metaDataValue)){ userMetadata.append("&" + metaData.getKey()); } else { userMetadata.append("&" + metaData.getKey() + "=" + metaData.getValue()); } } else { LOGGER.warn("Keynames 'SDK' and 'Version' are reserved and will be skipped"); } } if(userMetadata.length() > 255) { LOGGER.warn("Too many characters. User metadata was truncated.", new IllegalArgumentException("Total number of characters in user metadata" + " cannot exceed " + (255 - baseLength))); this.userMetaData = userMetadata.substring(0, 255); } else { this.userMetaData = userMetadata.toString(); } }
Source:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if (attribute.valueAsString() == null) throw new WrongReferenceAttributeValueException(attribute, "Attribute was not filled, therefore there is nothing to be checked."); }

Target:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if (attribute.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, "Attribute was not filled, therefore there is nothing to be checked."); }
Source:
private ModelAndView populateModelAndView(RadiologyOrder radiologyOrder, Obs obs) { ModelAndView result = new ModelAndView(RADIOLOGY_OBS_FORM_PATH); List<Obs> previousObs = radiologyService.getObsByOrderId(radiologyOrder.getOrderId()); result.addObject("obs", obs); result.addObject("previousObs", previousObs); Study study = radiologyOrder.getStudy(); result.addObject("studyUID", study.isCompleted() ? study.getStudyInstanceUid() : null); result.addObject("dicomViewerUrl", getDicomViewerUrl(study, radiologyOrder.getPatient())); if (obs.getId() != null && obs.getConcept().isComplex()) { Obs complexObsAsHtmlView = obsService.getComplexObs(Integer.valueOf(obs.getId()), WebConstants.HTML_VIEW); ComplexData complexData = complexObsAsHtmlView.getComplexData(); result.addObject("htmlView", complexData.getData()); Obs complexObsAsHyperlinkView = obsService.getComplexObs(Integer.valueOf(obs.getId()), WebConstants.HYPERLINK_VIEW); ComplexData complexData2 = complexObsAsHyperlinkView.getComplexData(); result.addObject("hyperlinkView", complexData2.getData()); } return result; }

Target:
private ModelAndView populateModelAndView(RadiologyOrder radiologyOrder, Obs obs) { ModelAndView result = new ModelAndView(RADIOLOGY_OBS_FORM_PATH); List<Obs> previousObs = radiologyService.getObsByOrderId(radiologyOrder.getOrderId()); result.addObject("obs", obs); result.addObject("previousObs", previousObs); Study study = radiologyOrder.getStudy(); result.addObject("studyUID", study.isCompleted() ? study.getStudyInstanceUid() : null); result.addObject("dicomViewerUrl", getDicomViewerUrl(study, radiologyOrder.getPatient())); if (obs.getId() != null && obs.getConcept().isComplex()) { Obs complexObsAsHtmlView = obsService.getComplexObs(Integer.valueOf(obs.getId()), WebConstants.HTML_VIEW); result.addObject("htmlView", complexObsAsHtmlView.getComplexData().getData()); Obs complexObsAsHyperlinkView = obsService.getComplexObs(Integer.valueOf(obs.getId()), WebConstants.HYPERLINK_VIEW); result.addObject("hyperlinkView", complexObsAsHyperlinkView.getComplexData().getData()); } return result; }
Source:
HystrixInvocationHandler(Target target, Map<Method, MethodHandler> dispatch) { this.target = checkNotNull(target, "target"); this.dispatch = checkNotNull(dispatch, "dispatch"); try { for (Map.Entry<Method, MethodHandler> entry : this.dispatch.entrySet()) { if (HystrixCommand.class.isAssignableFrom(entry.getKey().getReturnType())) { MethodMetadata methodMetadata = entry.getValue().getMethodMetadata(); Type type = methodMetadata.returnType(); Type actualType = ((ParameterizedType) type).getActualTypeArguments()[0]; methodMetadata.returnType(actualType); } } } catch (Exception e) { e.printStackTrace(); } }

Target:
HystrixInvocationHandler(Target target, Map<Method, MethodHandler> dispatch) { this.target = checkNotNull(target, "target"); this.dispatch = checkNotNull(dispatch, "dispatch"); }
Source:
protected boolean queryYesNoQuestion(String message) { MessageDialog dialog = new MessageDialog(getContainer().getShell(), IDEWorkbenchMessages.Question, (Image) null, message, MessageDialog.NONE, 0, IDEWorkbenchMessages.WizardDataTransfer_overwrite_button_label, IDialogConstants.CANCEL_LABEL) { @Override protected int getShellStyle() { return super.getShellStyle() | SWT.SHEET; } }; return dialog.open() == 0; }

Target:
protected boolean queryYesNoQuestion(String message) { MessageDialog dialog = new MessageDialog(getContainer().getShell(), IDEWorkbenchMessages.Question, (Image) null, message, MessageDialog.NONE, 0, IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL) { @Override protected int getShellStyle() { return super.getShellStyle() | SWT.SHEET; } }; return dialog.open() == 0; }
Source:
public CsvOutputFormat(Class<? extends Value> ... types) { this("\n", "|", types); }

Target:
public CsvOutputFormat(Class<? extends Value>... types) { this("\n", ",", types); }
Source:
private void reportToServerIfNeeded(String tokenString){ if (isReportting){ return; } boolean needResport = false; long currentTime = new Date().getTime(); if (recorderTempFile.exists()){ needResport = true; } else if ((recorderFile.length() > config.uploadThreshold) && (lastReportTime == 0 || (currentTime - lastReportTime) > config.interval * 60)){ boolean isSuccess = recorderFile.renameTo(recorderTempFile); if (isSuccess) { needResport = true; } } if (needResport && !this.isReportting){ reportToServer(tokenString); } }

Target:
private void reportToServerIfNeeded(String tokenString){ if (isReporting){ return; } boolean needToResport = false; long currentTime = new Date().getTime(); if (recorderTempFile.exists()){ needToResport = true; } else if ((recorderFile.length() > config.uploadThreshold) && (lastReportTime == 0 || (currentTime - lastReportTime) > config.interval * 60)){ boolean isSuccess = recorderFile.renameTo(recorderTempFile); if (isSuccess) { needToResport = true; } } if (needToResport && !this.isReporting){ reportToServer(tokenString); } }
Source:
public static void wait(int wait, Callable<Void> callable) throws ExecutionException { try { FutureTask<Void> task = new FutureTask<>(callable); task.run(); task.get(((wait == 0) ? 10 : wait) + 5, TimeUnit.SECONDS); } catch (@SuppressWarnings("unused") InterruptedException e) { Thread.currentThread().interrupt(); } catch (@SuppressWarnings("unused") TimeoutException e) { } }

Target:
public static long wait(int wait, Callable<Void> callable) throws ExecutionException, WaitTimeoutException { long now = System.currentTimeMillis(); wait = (wait == 0) ? DEFAULT_DOCKER_TIMEOUT : wait; try { FutureTask<Void> task = new FutureTask<>(callable); task.run(); task.get(wait, TimeUnit.SECONDS); } catch (@SuppressWarnings("unused") InterruptedException e) { Thread.currentThread().interrupt(); } catch (@SuppressWarnings("unused") TimeoutException e) { throw new WaitTimeoutException("timed out waiting for execution to complete", delta(now)); } return delta(now); }
Source:
public Class<? extends ComponentProperties>[] getNestedCompatibleComponentPropertiesClass() { return new Class[] { SalesforceConnectionProperties.class, SalesforceModuleProperties.class }; }

Target:
public Class<? extends ComponentProperties>[] getNestedCompatibleComponentPropertiesClass() { return concatPropertiesClasses(super.getNestedCompatibleComponentPropertiesClass(), new Class[] { SalesforceModuleProperties.class }); }
Source:
public List<String> findAnnotatedClassNames(Class annotationClass) throws ClassNotFoundException { List<String> annotatedClasses = new ArrayList<String>(); ArrayList<String> dynamicClasses = classNames; for (String dynamicClass : dynamicClasses) { Class<?> classz = getClassLoader().loadClass(dynamicClass); if (classz.getAnnotation(annotationClass) != null) { annotatedClasses.add(classz.getName()); } } return annotatedClasses; }

Target:
public List<String> findAnnotatedClassNames(Class annotationClass) throws ClassNotFoundException { return findAnnotatedClasses(annotationClass) .stream() .map(Class::getName) .collect(Collectors.toList()); }
Source:
public final JsonObject build(ElasticsearchSearchPredicateContext context) { JsonObject outerObject = new JsonObject(); JsonObject innerObject = new JsonObject(); if ( boost != null && !withConstantScore ) { BOOST_ACCESSOR.set( innerObject, boost ); } JsonObject result = doBuild( context, outerObject, innerObject ); if ( withConstantScore ) { result = applyConstantScore( result ); } if ( !context.isExplicitNested() && nestedPathHierarchy != null && !nestedPathHierarchy.isEmpty() ) { result = applyImplicitNested( result, new LinkedList<>( nestedPathHierarchy ) ); } return result; }

Target:
public JsonObject build(ElasticsearchSearchPredicateContext context) { JsonObject outerObject = new JsonObject(); JsonObject innerObject = new JsonObject(); if ( boost != null && !withConstantScore ) { BOOST_ACCESSOR.set( innerObject, boost ); } JsonObject result = doBuild( context, outerObject, innerObject ); return ( withConstantScore ) ? applyConstantScore( result ) : result; }
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final LayoutInflater inflater = LayoutInflater.from(getActivity()); final LinearLayout parent = (LinearLayout) view.findViewById(R.id.root); ViewHolder holder; holder = createViewHolder(inflater, parent); holder.typeView.setIcon(FontAwesomeIcons.fa_file_text_o); holder.titleView.setText(R.string.handouts_title); holder.subtitleView.setText(R.string.handouts_subtitle); holder.rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (courseData != null) { environment.getRouter().showHandouts(getActivity(), courseData); } } }); holder = createViewHolder(inflater, parent); holder.typeView.setIcon(FontAwesomeIcons.fa_bullhorn); holder.titleView.setText(R.string.announcement_title); holder.subtitleView.setText(R.string.announcement_subtitle); holder.rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (courseData != null) { environment.getRouter().showCourseAnnouncement(getActivity(), courseData); } } }); final Bundle arguments = getArguments(); @ScreenDef String screenName = null; if (arguments != null) { screenName = getArguments().getString(Router.EXTRA_SCREEN_NAME); if (!TextUtils.isEmpty(screenName)) { switch (screenName) { case COURSE_HANDOUTS: environment.getRouter().showHandouts(getActivity(), courseData); break; case COURSE_ANNOUNCEMENTS: environment.getRouter().showCourseAnnouncement(getActivity(), courseData); break; } } } }

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final LayoutInflater inflater = LayoutInflater.from(getActivity()); final LinearLayout parent = (LinearLayout) view.findViewById(R.id.root); ViewHolder holder; holder = createViewHolder(inflater, parent); holder.typeView.setIcon(FontAwesomeIcons.fa_file_text_o); holder.titleView.setText(R.string.handouts_title); holder.subtitleView.setText(R.string.handouts_subtitle); holder.rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (courseData != null) { environment.getRouter().showHandouts(getActivity(), courseData); } } }); holder = createViewHolder(inflater, parent); holder.typeView.setIcon(FontAwesomeIcons.fa_bullhorn); holder.titleView.setText(R.string.announcement_title); holder.subtitleView.setText(R.string.announcement_subtitle); holder.rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (courseData != null) { environment.getRouter().showCourseAnnouncement(getActivity(), courseData); } } }); final Bundle arguments = getArguments(); @ScreenDef String screenName; if (arguments != null) { screenName = arguments.getString(Router.EXTRA_SCREEN_NAME); if (!TextUtils.isEmpty(screenName)) { switch (screenName) { case COURSE_HANDOUT: environment.getRouter().showHandouts(getActivity(), courseData); break; case COURSE_ANNOUNCEMENT: environment.getRouter().showCourseAnnouncement(getActivity(), courseData); break; } arguments.putString(Router.EXTRA_SCREEN_NAME, null); } } }
Source:
public void testDebitResourceFields() throws HTTPError { Card card = createCard(); HashMap<String, Object> payload = new HashMap<String, Object>(); payload.put("amount", 5000); payload.put("description", "Some descriptive text for the debit in the dashboard"); payload.put("appears_on_statement_as", "Statement text"); payload.put("appears_on_statement_as", "Statement text"); Debit debit = card.debit(payload); Map<String, String> meta = new HashMap<String, String>(); meta.put("anykey", "valuegoeshere"); meta.put("facebook.id", "1234567890"); debit.meta = meta; debit.save(); assertNotNull(debit.appears_on_statement_as); assertNotNull(debit.created_at); assertNotNull(debit.currency); assertNotNull(debit.description); assertNull(debit.failure_reason); assertNull(debit.failure_reason_code); assertNotNull(debit.href); assertNotNull(debit.id); assertNotNull(debit.card_hold); assertNull(debit.customer); assertNull(debit.dispute); assertNull(debit.order); assertNotNull(debit.source); assertNotNull(debit.meta); assertNotNull(debit.status); assertNotNull(debit.transaction_number); assertNotNull(debit.updated_at); assertNotNull(debit.events); assertNotNull(debit.refunds); }

Target:
public void testDebitResourceFields() throws HTTPError { Card card = createCard(); Customer customer = createPersonCustomer(); card.associateToCustomer(customer); HashMap<String, Object> payload = new HashMap<String, Object>(); payload.put("amount", 5000); payload.put("description", "Some descriptive text for the debit in the dashboard"); payload.put("appears_on_statement_as", "Statement text"); Debit debit = card.debit(payload); Map<String, String> meta = new HashMap<String, String>(); meta.put("facebook", "1234567890"); debit.meta = meta; debit.save(); assertEquals(debit.appears_on_statement_as, "BAL*Statement text"); assertNotNull(debit.created_at); assertEquals(debit.currency, "USD"); assertEquals(debit.description, "Some descriptive text for the debit in the dashboard"); assertNull(debit.failure_reason); assertNull(debit.failure_reason_code); assertTrue(debit.href.contains("/debits/WD")); assertTrue(debit.id.startsWith("WD")); assertTrue(debit.card_hold instanceof CardHold); assertEquals(debit.customer.href, customer.href); assertNull(debit.dispute); assertNull(debit.order); assertEquals(debit.source.href, card.href); assertEquals(debit.meta.get("facebook"), "1234567890"); assertEquals(debit.status, "succeeded"); assertTrue(debit.transaction_number.startsWith("W")); assertNotNull(debit.updated_at); assertTrue(debit.events instanceof Event.Collection); assertTrue(debit.refunds instanceof Refund.Collection); }
Source:
public static String invokeComponentToString(final Component component, final ContentFilter filter) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); component.addContents( new Container() { @Override public void add(@CheckForNull Content content) { try { ((PrefilteredContent) Objects.requireNonNull(content)).writeTo(baos, filter); } catch (IOException e) { e.printStackTrace(); } } }); return baos.toString(); }

Target:
public static String invokeComponentToString(final Component component, final ContentFilter filter) throws IOException { try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) { component.addContents( new Container() { @Override public void add(@CheckForNull Content content) { try { ((PrefilteredContent) Objects.requireNonNull(content)).writeTo(baos, filter); } catch (IOException e) { e.printStackTrace(); } } }); return baos.toString(); } }
Source:
public ConfigurationBuilder getDefaultCacheBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); configurationBuilder.compatibility().disable(); return configurationBuilder; }

Target:
public ConfigurationBuilder getDefaultCacheBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); return configurationBuilder; }
Source:
public void onResponse(Releasable releasable) { assert replica.getActiveOperationsCount() != 0 : "must perform shard operation under a permit"; shardOperationOnReplica(replicaRequest.getRequest(), replica, ActionListener.wrap((replicaResult) -> replicaResult.runPostReplicaActions( ActionListener.wrap(r -> { final ReplicaResponse response = new ReplicaResponse(replica.getLocalCheckpoint(), replica.getLastSyncedGlobalCheckpoint()); releasable.close(); if (logger.isTraceEnabled()) { logger.trace("action completed on shard for request [{}]", transportReplicaAction, replicaRequest.getRequest().shardId(), replicaRequest.getRequest()); } setPhase(task, "finished"); onCompletionListener.onResponse(response); }, e -> { Releasables.closeWhileHandlingException(releasable); responseWithFailure(e); }) ), e -> { Releasables.closeWhileHandlingException(releasable); AsyncReplicaAction.this.onFailure(e); })); }

Target:
public void onResponse(Releasable releasable) { assert replica.getActiveOperationsCount() != 0 : "must perform shard operation under a permit"; try { shardOperationOnReplica(replicaRequest.getRequest(), replica, ActionListener.wrap((replicaResult) -> replicaResult.runPostReplicaActions( ActionListener.wrap(r -> { final ReplicaResponse response = new ReplicaResponse(replica.getLocalCheckpoint(), replica.getLastSyncedGlobalCheckpoint()); releasable.close(); if (logger.isTraceEnabled()) { logger.trace("action completed on shard for request [{}]", transportReplicaAction, replicaRequest.getRequest().shardId(), replicaRequest.getRequest()); } setPhase(task, "finished"); onCompletionListener.onResponse(response); }, e -> { Releasables.closeWhileHandlingException(releasable); responseWithFailure(e); }) ), e -> { Releasables.closeWhileHandlingException(releasable); AsyncReplicaAction.this.onFailure(e); })); } catch (Exception e) { Releasables.closeWhileHandlingException(releasable); AsyncReplicaAction.this.onFailure(e); } }
Source:
public Set<String> getFreeVariables() { throw new RuntimeException("Free variables of a JavaValue not yet implemented."); }

Target:
public Set<String> getFreeVariables() { return new HashSet<>(); }
Source:
private List<String> generateOptionList(String courseId) { List<String> optionList = new ArrayList<>(); switch (generateOptionsFor) { case NONE: optionList = msqChoices; break; case STUDENTS: List<StudentAttributes> studentList = StudentsLogic.inst().getStudentsForCourse(courseId); for (StudentAttributes student : studentList) { optionList.add(student.name + " (" + student.team + ")"); } optionList.sort(null); break; case STUDENTS_EXCLUDING_SELF: List<StudentAttributes> studentListExcludingSelf = StudentsLogic.inst().getStudentsForCourse(courseId); String thisStudentEmail = studentDoingQuestion.email; for (StudentAttributes student : studentListExcludingSelf) { if (thisStudentEmail.equals(student.email)) { continue; } optionList.add(student.name + " (" + student.team + ")"); } optionList.sort(null); break; case TEAMS: try { List<TeamDetailsBundle> teamList = CoursesLogic.inst().getTeamsForCourse(courseId); for (TeamDetailsBundle team : teamList) { optionList.add(team.name); } optionList.sort(null); } catch (EntityDoesNotExistException e) { Assumption.fail("Course disappeared"); } break; case INSTRUCTORS: List<InstructorAttributes> instructorList = InstructorsLogic.inst().getInstructorsForCourse( courseId); for (InstructorAttributes instructor : instructorList) { optionList.add(instructor.name); } optionList.sort(null); break; default: Assumption.fail("Trying to generate options for neither students, teams nor instructors"); break; } return optionList; }

Target:
private List<String> generateOptionList(String courseId) { List<String> optionList = new ArrayList<>(); switch (generateOptionsFor) { case NONE: optionList = msqChoices; break; case STUDENTS: case STUDENTS_EXCLUDING_SELF: List<StudentAttributes> studentList = StudentsLogic.inst().getStudentsForCourse(courseId); if (generateOptionsFor == FeedbackParticipantType.STUDENTS_EXCLUDING_SELF) { studentList.removeIf(studentInList -> studentInList.email.equals(studentDoingQuestion.email)); } for (StudentAttributes student : studentList) { optionList.add(student.name + " (" + student.team + ")"); } optionList.sort(null); break; case TEAMS: try { List<TeamDetailsBundle> teamList = CoursesLogic.inst().getTeamsForCourse(courseId); for (TeamDetailsBundle team : teamList) { optionList.add(team.name); } optionList.sort(null); } catch (EntityDoesNotExistException e) { Assumption.fail("Course disappeared"); } break; case INSTRUCTORS: List<InstructorAttributes> instructorList = InstructorsLogic.inst().getInstructorsForCourse( courseId); for (InstructorAttributes instructor : instructorList) { optionList.add(instructor.name); } optionList.sort(null); break; default: Assumption.fail("Trying to generate options for neither students, teams nor instructors"); break; } return optionList; }
Source:
public byte[] encrypt(byte[] plainTextBytes, String algorithm, boolean returnSelfContainedCipherText, String internalCryptoProviderType) throws CryptoException { failIfEncryptDecryptInputsAreInvalid(plainTextBytes, algorithm, internalCryptoProviderType); byte[] encryptedKey; try { CryptoService cryptoService = CarbonCoreDataHolder.getInstance().getCryptoService(); if (cryptoService == null) { throw new CryptoException("A crypto service implementation has not been registered."); } if (plainTextBytes.length == 0) { if (log.isDebugEnabled()) { log.debug("Plaintext is empty. An empty array will be used as the ciphertext bytes."); } encryptedKey = StringUtils.EMPTY.getBytes(); } else { if (log.isDebugEnabled()) { if (returnSelfContainedCipherText) { log.debug(String.format( "Encrypting data in self contained format, with algorithm: '%s' and internal crypto " + "provider: '%s'", algorithm, internalCryptoProviderType)); } else { log.debug(String.format( "Encrypting data with algorithm: '%s' and internal crypto " + "provider: '%s'", algorithm, internalCryptoProviderType)); } } encryptedKey = cryptoService .encrypt(plainTextBytes, algorithm, CRYPTO_API_PROVIDER_BC, returnSelfContainedCipherText, internalCryptoProviderType); } } catch (Exception e) { throw new CryptoException("An error occurred while encrypting data.", e); } return encryptedKey; }

Target:
public byte[] encrypt(byte[] plainTextBytes, String algorithm, boolean returnSelfContainedCipherText, String internalCryptoProviderType) throws CryptoException { failIfEncryptDecryptInputsAreInvalid(plainTextBytes, algorithm, internalCryptoProviderType); byte[] encryptedKey; try { CryptoService cryptoService = CarbonCoreDataHolder.getInstance().getCryptoService(); if (cryptoService == null) { throw new CryptoException("A crypto service implementation has not been registered."); } if (plainTextBytes.length == 0) { if (log.isDebugEnabled()) { log.debug("Plaintext is empty. An empty array will be used as the ciphertext bytes."); } encryptedKey = StringUtils.EMPTY.getBytes(); } else { if (log.isDebugEnabled()) { if (returnSelfContainedCipherText) { log.debug(String.format( "Encrypting data in self contained format, with algorithm: '%s' and internal crypto " + "provider: '%s'", algorithm, internalCryptoProviderType)); } else { log.debug(String.format( "Encrypting data with algorithm: '%s' and internal crypto " + "provider: '%s'", algorithm, internalCryptoProviderType)); } } encryptedKey = cryptoService .encrypt(plainTextBytes, algorithm, CRYPTO_API_PROVIDER_BC, returnSelfContainedCipherText, internalCryptoProviderType); } } catch (org.wso2.carbon.crypto.api.CryptoException e) { throw new CryptoException("An error occurred while encrypting data.", e); } return encryptedKey; }
Source:
public List<Container> getContainersForImage(String image, boolean all) throws DockerAccessException { String url; String serverApiVersion = getServerApiVersion(); if (EnvUtil.greaterOrEqualsVersion(serverApiVersion, "1.23")) { url = urlBuilder.listContainers(all, "ancestor",image); } else { url = urlBuilder.listContainers(all); } try { log.verbose(Logger.LogVerboseCategory.API,"GETing %s", url); String response = delegate.get(url, HTTP_OK); JsonArray array = JsonFactory.newJsonArray(response); List<Container> containers = new ArrayList<>(); for (int i = 0; i < array.size(); i++) { JsonObject element = array.get(i).getAsJsonObject(); if (image.equals(element.get("Image").getAsString())) { containers.add(new ContainersListElement(element)); } } return containers; } catch (IOException e) { throw new DockerAccessException(e.getMessage()); } }

Target:
public List<Container> getContainersForImage(String image, boolean all) throws DockerAccessException { String url; String serverApiVersion = getServerApiVersion(); if (EnvUtil.greaterOrEqualsVersion(serverApiVersion, "1.23")) { url = urlBuilder.listContainers(all, "ancestor",image); } else { url = urlBuilder.listContainers(all); } try { log.verbose(Logger.LogVerboseCategory.API,"GET %s", url); String response = delegate.get(url, HTTP_OK); JsonArray array = JsonFactory.newJsonArray(response); List<Container> containers = new ArrayList<>(); for (int i = 0; i < array.size(); i++) { JsonObject element = array.get(i).getAsJsonObject(); if (image.equals(element.get("Image").getAsString())) { containers.add(new ContainersListElement(element)); } } return containers; } catch (IOException e) { throw new DockerAccessException(e.getMessage()); } }