auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void createGeoTiffForGrid(GridDataset gridDataset, GridDatatype grid, int timeIndex, String filename) throws GeoTiffUtilException { try { Array data = grid.readDataSlice(timeIndex, 0, -1, -1); GeotiffWriter writer = new GeotiffWriter(filename); writer.writeGrid(gridDataset, grid, data, false); writer.close(); } catch (Exception e) { throw new GeoTiffUtilException(GeoTiffUtilExceptionID.GEOTIFFWRITER_EXCEPTION, "GeoTiffUtils", "generateGeoTiffZipFromGrid", "Unable to generate Tiff image from grid [" + gridDataset.getLocationURI() + "]. Exception: " + e.getMessage()); } }

Target:
public static void createGeoTiffForGrid(GridDataset gridDataset, GridDatatype grid, int timeIndex, String filename) throws GeoTiffUtilException { GeotiffWriter writer = null; try { Array data = grid.readDataSlice(timeIndex, 0, -1, -1); writer = new GeotiffWriter(filename); writer.writeGrid(gridDataset, grid, data, false); } catch (Exception e) { throw new GeoTiffUtilException(GeoTiffUtilExceptionID.GEOTIFFWRITER_EXCEPTION, "GeoTiffUtils", "generateGeoTiffZipFromGrid", "Unable to generate Tiff image from grid [" + gridDataset.getLocationURI() + "]. Exception: " + e.getMessage()); } finally { if(writer != null) { try { writer.close(); } catch (IOException e) { LOGGER.error("GeoTiffUtils.createGeoTiffForGrid() Exception: Unable to close GeotiffWriter. Exception: " + e.getMessage()); } } } }
Source:
public static String reduceConsumerOffsetsResponses(Map<String, String> responses, Logger logger) { Map<String, KafkaConsumerOffsetsResponse> result = new HashMap<>(); responses.forEach((instance, json) -> { List<KafkaConsumerOffsetsResponse> responseList; try { responseList = JsonUtils.fromJson(json, new TypeReference<List<KafkaConsumerOffsetsResponse>>() { }); } catch (Exception e) { logger.error("Invalid response from instance {}", json, instance); return; } responseList.forEach(response -> { if (response.getConsumerOffsets() == null || StringUtils.isBlank(response.getConsumerGroupId())) { logger.warn("Empty consumer offset map from instance {}. Ignoring the result", instance); return; } KafkaConsumerOffsetsResponse reducedResponse = result.computeIfAbsent(response.getConsumerGroupId(), k -> new KafkaConsumerOffsetsResponse(response.getConsumerGroupId())); Map<String, Map<Integer, Long>> consumerOffsets = response.getConsumerOffsets(); consumerOffsets.forEach((topic, partitionOffsets) -> { Map<String, Map<Integer, Long>> reducedConsumerOffsets = reducedResponse.getConsumerOffsets(); Map<Integer, Long> reducedPartitionOffsets = reducedConsumerOffsets.computeIfAbsent(topic, k -> new HashMap<>()); reducedPartitionOffsets.putAll(partitionOffsets); }); }); }); return JsonUtils.toJson(result.values()); }

Target:
public static String reduceConsumerOffsetsResponses(Map<String, String> responses, Logger logger) { Map<String, KafkaConsumerOffsetsResponse> result = new HashMap<>(); responses.forEach((instance, json) -> { List<KafkaConsumerOffsetsResponse> responseList; try { responseList = JsonUtils.fromJson(json, new TypeReference<List<KafkaConsumerOffsetsResponse>>() { }); } catch (Exception e) { logger.error("Invalid response from instance {}", json, instance); return; } responseList.forEach(response -> { if (response.getConsumerOffsets() == null || response.getConsumerOffsets().isEmpty()) { logger.warn("Empty consumer offset map from instance {}. Ignoring the result", instance); } else if (StringUtils.isBlank(response.getConsumerGroupId())) { logger.warn("Invalid consumer group id from instance {}, Ignoring the result", instance); } else { KafkaConsumerOffsetsResponse reducedResponse = result.computeIfAbsent(response.getConsumerGroupId(), k -> new KafkaConsumerOffsetsResponse(response.getConsumerGroupId())); Map<String, Map<Integer, Long>> consumerOffsets = response.getConsumerOffsets(); consumerOffsets.forEach((topic, partitionOffsets) -> { Map<String, Map<Integer, Long>> reducedConsumerOffsets = reducedResponse.getConsumerOffsets(); Map<Integer, Long> reducedPartitionOffsets = reducedConsumerOffsets.computeIfAbsent(topic, k -> new HashMap<>()); reducedPartitionOffsets.putAll(partitionOffsets); }); } }); }); return JsonUtils.toJson(result.values()); }
Source:
public void aboutToBeShown() { super.aboutToBeShown(); this.getController().onNewLabel(new IConsumer<String>() { @Override public void apply(String value) { if (!label.isDisposed() && !(label.getText() != null && label.getText().equals(value))) { label.setText(Objects.firstNonNull(value, "")); EEFWidgetStyle style = getWidgetStyle(); @SuppressWarnings("unchecked") List<EEFConditionalStyle> conditionalStyles = getWidgetConditionalStyles(); if (conditionalStyles != null && !conditionalStyles.isEmpty()) { style = getConditionalStyle(conditionalStyles); } if (style != null) { setLabelFontStyle(style); } } } }); this.getController().onNewHelp(new IConsumer<String>() { @Override public void apply(String value) { if (help != null && !help.isDisposed() && !(help.getText() != null && help.getText().equals(value))) { help.setToolTipText(Objects.firstNonNull(value, "")); } } }); }

Target:
public void aboutToBeShown() { super.aboutToBeShown(); this.getController().onNewLabel(new IConsumer<String>() { @Override public void apply(String value) { if (!label.isDisposed() && !(label.getText() != null && label.getText().equals(value))) { label.setText(Objects.firstNonNull(value, "")); EEFWidgetStyle style = getWidgetStyle(); List<EEFConditionalStyle> conditionalStyles = getWidgetConditionalStyles(); if (conditionalStyles != null && !conditionalStyles.isEmpty()) { style = getConditionalStyle(conditionalStyles, style); } if (style != null) { setLabelFontStyle(style); } } } }); this.getController().onNewHelp(new IConsumer<String>() { @Override public void apply(String value) { if (help != null && !help.isDisposed() && !(help.getText() != null && help.getText().equals(value))) { help.setToolTipText(Objects.firstNonNull(value, "")); } } }); }
Source:
protected int doWork() { IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFileIsWritable(OUTPUT); try (final AbstractFeatureReader<Interval, LineIterator> intervalsReader = AbstractFeatureReader.getFeatureReader(INPUT.getPath(), new IntervalListCodec(), false); final BufferedWriter out = IOUtil.openFileForBufferedWriting(OUTPUT)) { Iterable<Interval> intervalIterable = intervalsReader.iterator(); if (SORT) { final SortingCollection<Interval> sortedIntervals = SortingCollection.newInstance(Interval.class, new IntervalCodec(((SAMFileHeader)intervalsReader.getHeader()).getSequenceDictionary()), Interval::compareTo, 500000, OUTPUT.toPath()); for (final Interval i: intervalsReader.iterator()) { sortedIntervals.add(i); } intervalIterable = sortedIntervals; } for (final Interval i : intervalIterable) { final String strand = i.isNegativeStrand() ? "-" : "+"; final List<?> fields = CollectionUtil.makeList(i.getContig(), i.getStart()-1, i.getEnd(), i.getName(), SCORE, strand); out.append(fields.stream().map(String::valueOf).collect(Collectors.joining("\t"))); out.newLine(); } out.close(); return 0; } catch (IOException ioe) { throw new RuntimeIOException(ioe); } }

Target:
protected int doWork() { IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFileIsWritable(OUTPUT); try (final AbstractFeatureReader<Interval, LineIterator> intervalsReader = AbstractFeatureReader.getFeatureReader(INPUT.getPath(), new IntervalListCodec(), false); CloseableIterator<Interval> intervalsToUse = getSortedIntervals(intervalsReader); final BufferedWriter out = IOUtil.openFileForBufferedWriting(OUTPUT)) { intervalsToUse.stream().forEach(i -> generateOutput(i, out)); return 0; } catch (Exception e) { throw new RuntimeIOException(e); } }
Source:
public static <T> Collection<T> findAmongst(Class<T> clazz, Collection<?> instances) { Collection<T> matches = new ArrayList<>(instances.size()); for (Object instance : instances) { if (clazz.isInstance(instance)) { matches.add(clazz.cast(instance)); } } return matches; }

Target:
public static <T> Collection<T> findAmongst(Class<T> clazz, Collection<?> instances) { return findStreamAmongst(clazz, instances) .collect(Collectors.toList()); }
Source:
public void editExchange() { agreeOverwriteExchange = false; formExchange = new ExchangeType(); if (selectedExchange != null) { formExchange.setCertificateAlias(selectedExchange.getCertificateAlias()); formExchange.setUrl(selectedExchange.getUrl()); formExchange.setDisabled(selectedExchange.isDisabled()); formExchange.setKey(selectedExchange.getKey()); formExchange.setName(selectedExchange.getName()); formExchange.setSniName(selectedExchange.getSniName()); formExchange.setTLSVersions(selectedExchange.getTLSVersions()); formExchange.setType(selectedExchange.getType()); formExchange.setUrl(selectedExchange.getUrl()); } }

Target:
public void editExchange() { isEditing = true; formExchange = new ExchangeType(); if (selectedExchange != null) { setDlgHeader("Editing " + selectedExchange.getName()); formExchange.setCertificateAlias(selectedExchange.getCertificateAlias()); formExchange.setUrl(selectedExchange.getUrl()); formExchange.setDisabled(selectedExchange.isDisabled()); formExchange.setKey(selectedExchange.getKey()); formExchange.setName(selectedExchange.getName()); formExchange.setSniName(selectedExchange.getSniName()); formExchange.setTLSVersions(selectedExchange.getTLSVersions()); formExchange.setType(selectedExchange.getType()); } }
Source:
public DoubleColumnSelector makeDoubleColumnSelector( IncrementalIndexStorageAdapter.EntryHolder currEntry, IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerDoubleColumnSelector implements DoubleColumnSelector { @Override public double get() { final Object[] dims = currEntry.getKey().getDims(); if (dimIndex >= dims.length) { return 0.0f; } long longVal = (Long) dims[dimIndex]; return (double) longVal; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { } } return new IndexerDoubleColumnSelector(); }

Target:
public DoubleColumnSelector makeDoubleColumnSelector( IncrementalIndexStorageAdapter.EntryHolder currEntry, IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerDoubleColumnSelector implements DoubleColumnSelector { @Override public double get() { final Object[] dims = currEntry.getKey().getDims(); if (dimIndex >= dims.length) { return 0.0; } long longVal = (Long) dims[dimIndex]; return (double) longVal; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { } } return new IndexerDoubleColumnSelector(); }
Source:
protected void onPostExecute(Boolean result) { String title_resource = context.getResources().getString(R.string.nominating_for_Deletion); String success_resource = context.getResources().getString(R.string.success); String successfully_nominated_resource = context.getResources().getString(R.string.successfully_nominated); String for_deletion_resource = context.getResources().getString(R.string.for_deletion); String failed_resource = context.getResources().getString(R.string.failed); String could_not_request_deletion_resource = context.getResources().getString(R.string.could_not_request_deletion); String message; String title = title_resource; if (result){ title += ":"+success_resource; message = successfully_nominated_resource + media.getDisplayTitle() + for_deletion_resource+"."; } else { title += ":"+failed_resource; message = could_not_request_deletion_resource+"."; } notificationBuilder.setDefaults(DEFAULT_ALL) .setContentTitle(title) .setStyle(new NotificationCompat.BigTextStyle() .bigText(message)) .setSmallIcon(R.drawable.ic_launcher) .setProgress(0,0,false) .setOngoing(false) .setPriority(PRIORITY_HIGH); notificationManager.notify(NOTIFICATION_DELETE, notificationBuilder.build()); }

Target:
protected void onPostExecute(Boolean result) { String title_resource = context.getResources().getString(R.string.nominating_for_deletion); String success_resource = context.getResources().getString(R.string.success); String successfully_nominated_resource = context.getResources().getString(R.string.successfully_nominated); String for_deletion_resource = context.getResources().getString(R.string.for_deletion); String failed_resource = context.getResources().getString(R.string.failed); String could_not_request_deletion_resource = context.getResources().getString(R.string.could_not_request_deletion); String could_not_request_point = context.getResources().getString(R.string.point); String message; String title = title_resource; if (result){ title += ":"+success_resource; message = successfully_nominated_resource + media.getDisplayTitle() + for_deletion_resource+could_not_request_point; } else { title += ":"+failed_resource; message = could_not_request_deletion_resource+could_not_request_point; } notificationBuilder.setDefaults(DEFAULT_ALL) .setContentTitle(title) .setStyle(new NotificationCompat.BigTextStyle() .bigText(message)) .setSmallIcon(R.drawable.ic_launcher) .setProgress(0,0,false) .setOngoing(false) .setPriority(PRIORITY_HIGH); String urlForDelete = BuildConfig.COMMONS_URL + "/wiki/Commons:Deletion_requests/File:" + media.getFilename(); Intent browserIntent = new Intent(Intent.ACTION_VIEW , Uri.parse(urlForDelete)); PendingIntent pendingIntent = PendingIntent.getActivity(context , 1 , browserIntent , PendingIntent.FLAG_UPDATE_CURRENT); notificationBuilder.setContentIntent(pendingIntent); notificationManager.notify(NOTIFICATION_DELETE, notificationBuilder.build()); }
Source:
public List<Section> processResult(ApiResult result) throws Throwable { if(result.asObject().has("error")){ throw new ApiException(new JSONException((String)result.asObject().getJSONObject("error").get("code"))); } JSONObject mobileView = result.asObject().optJSONObject("mobileview"); pageProperties = new PageProperties(mobileView); if (mobileView.has("redirected")) { title = new PageTitle(mobileView.optString("redirected"), title.getSite()); } else if (mobileView.has("normalizedtitle")) { title = new PageTitle(mobileView.optString("normalizedtitle"), title.getSite()); } return super.processResult(result); }

Target:
public List<Section> processResult(ApiResult result) throws Throwable { JSONObject mobileView = result.asObject().optJSONObject("mobileview"); if(mobileView != null){ pageProperties = new PageProperties(mobileView); if (mobileView.has("redirected")) { title = new PageTitle(mobileView.optString("redirected"), title.getSite()); } else if (mobileView.has("normalizedtitle")) { title = new PageTitle(mobileView.optString("normalizedtitle"), title.getSite()); } } return super.processResult(result); }
Source:
public void end() { try { position = motionController.getInputSafely(); } catch (InvalidSensorException e) { position = 0; updateStatus(CHECK_NAME, SystemStatus.FAIL, e); } if (Math.abs(motionController.getSetpoint() - position) > ERROR_THRESHOLD) { updateStatus(CHECK_NAME, SystemStatus.FAIL, new Exception("DISTANCE DRIVEN NOT WITHIN ERROR THRESHOLD")); } chassisMove.cancel(); motionController.disable(); motionController.reset(); runOnce = false; }

Target:
public void end() { try { position = motionController.getInputSafely(); } catch (InvalidSensorException e) { position = 0; updateStatusFail(CHECK_NAME, e); } if (Math.abs(motionController.getSetpoint() - position) > errorThreshold) { updateStatusFail(CHECK_NAME, new Exception("DISTANCE DRIVEN NOT WITHIN ERROR THRESHOLD")); } chassisMove.cancel(); motionController.disable(); motionController.reset(); runOnce = false; outputStatuses(); }
Source:
public float getPlayerPosition(){ Player player = null; for(WorldObject w : world.getObjects()){ if(w instanceof Player){ player = (Player) w; } } return player.getX(); }

Target:
public float getPlayerPosition(){ return world.getPlayer().getX(); }
Source:
public static <K, V> Predicate<EventJournalMapEvent<K, V>> mapPutEvents() { return new MapPutEventsPredicate<>(); }

Target:
public static <K, V> Predicate<EventJournalMapEvent<K, V>> mapPutEvents() { return new MapPutEventsPredicate<K, V>(); }
Source:
private void deleteDownloadedVideos() { if (isUserLoginWithDifferentAccount()) { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -> TestpressDatabase.Companion.invoke(this).clearAllTables()); DownloadService.sendRemoveAllDownloads(this, VideoDownloadService.class, false); TestpressSDKDatabase.clearDatabase(this); } }

Target:
private void deleteDownloadedVideos() { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -> TestpressDatabase.Companion.invoke(this).clearAllTables()); DownloadService.sendRemoveAllDownloads(this, VideoDownloadService.class, false); TestpressSDKDatabase.clearDatabase(this); }
Source:
public AuthResponse logInUsingFacebook(String accessToken) throws Exception { final AuthResponse response = serviceManager.loginByFacebook(accessToken); finishSocialLogIn(response, LoginPrefs.AuthBackend.FACEBOOK); return response; }

Target:
public AuthResponse logInUsingFacebook(String accessToken) throws Exception { return finishSocialLogIn(accessToken, LoginPrefs.AuthBackend.FACEBOOK); }
Source:
private TableOperatorWrapper<?> visitUnionTransformation( UnionTransformation<RowData> transform) { TableOperatorWrapper<?> wrapper = new TableOperatorWrapper<>( SimpleOperatorFactory.of(new UnionStreamOperator()), genSubOperatorName(transform), transform.getInputs().stream().map(Transformation::getOutputType).collect(Collectors.toList()), transform.getOutputType()); int numberOfHeadInput = 0; for (Transformation<?> input : transform.getInputs()) { int inputIdx = inputTransforms.indexOf(input); if (inputIdx >= 0) { numberOfHeadInput ++; orderedInputTransforms.add(input); inputSpecs.add(createInputSpec(readOrders[inputIdx], wrapper, 1)); } else { TableOperatorWrapper<?> inputWrapper = visit(input); wrapper.addInput(inputWrapper, 1); } } if (numberOfHeadInput > 0) { headWrappers.add(wrapper); } return wrapper; }

Target:
private TableOperatorWrapper<?> visitUnionTransformation( UnionTransformation<RowData> transform) { TableOperatorWrapper<?> wrapper = new TableOperatorWrapper<>( SimpleOperatorFactory.of(new UnionStreamOperator()), genSubOperatorName(transform), transform.getInputs().stream().map(Transformation::getOutputType).collect(Collectors.toList()), transform.getOutputType()); int numberOfHeadInput = 0; for (Transformation<?> input : transform.getInputs()) { int inputIdx = inputTransforms.indexOf(input); if (inputIdx >= 0) { numberOfHeadInput++; processInput(input, inputIdx, wrapper, 1); } else { TableOperatorWrapper<?> inputWrapper = visit(input); wrapper.addInput(inputWrapper, 1); } } if (numberOfHeadInput > 0) { headWrappers.add(wrapper); } return wrapper; }
Source:
private void validatePluginProperties(RuleAwarePluginProfileCommand command, RuleAwarePluginProfile newPluginProfile) { try { ValidationResult result = command.validateUsingExtension(newPluginProfile.getPluginId(), newPluginProfile.getConfiguration().getConfigurationAsMap(true)); addErrorsToConfiguration(result, newPluginProfile); }catch (RecordNotFoundException e) { newPluginProfile.addError("pluginId", String.format("Plugin with id `%s` is not found.", newPluginProfile.getPluginId())); }catch (Exception e) { } }

Target:
private void validatePluginProperties(RuleAwarePluginProfileCommand command, RuleAwarePluginProfile newPluginProfile) { try { ValidationResult result = command.validateUsingExtension(newPluginProfile.getPluginId(), newPluginProfile.getConfiguration().getConfigurationAsMap(true)); addErrorsToConfiguration(result, newPluginProfile); }catch (RecordNotFoundException e) { newPluginProfile.addError("pluginId", String.format("Plugin with id `%s` is not found.", newPluginProfile.getPluginId())); } catch (GoPluginFrameworkException e) { newPluginProfile.addError("pluginId", e.getMessage()); }catch (Exception e) { } }
Source:
protected void configureServlets() { bind(KeycloakAuthenticationFilter.class).in(Singleton.class); filterRegex("^(?!.*(/docs/))(?!.*(/keycloak/settings/?|/oauth/callback/?|/system/state/?)$).*") .through(KeycloakAuthenticationFilter.class); filterRegex("^(?!.*(/docs/))(?!.*(/keycloak/settings/?|/oauth/callback/?|/system/state/?)$).*") .through(KeycloakEnvironmentInitalizationFilter.class); filterRegex("^(?!.*(/docs/))(?!.*(/keycloak/settings/?|/api/oauth/callback/?)$).*") .through(IdentityIdLoggerFilter.class); filterRegex("/user(/password|/)?").through(UnavailableResourceInMultiUserFilter.class); filterRegex("/profile/.*/attributes").through(UnavailableResourceInMultiUserFilter.class); }

Target:
protected void configureServlets() { bind(KeycloakAuthenticationFilter.class).in(Singleton.class); filterRegex("^(?!.*(/docs/))(?!.*(/keycloak/settings/?|/oauth/callback/?|/system/state/?)$).*") .through(KeycloakAuthenticationFilter.class); filterRegex("^(?!.*(/docs/))(?!.*(/keycloak/settings/?|/oauth/callback/?|/system/state/?)$).*") .through(KeycloakEnvironmentInitalizationFilter.class); filterRegex("^(?!.*(/docs/))(?!.*(/keycloak/settings/?|/api/oauth/callback/?)$).*") .through(IdentityIdLoggerFilter.class); filterRegex("^/user(/password/?|/)?$").through(UnavailableResourceInMultiUserFilter.class); filterRegex("^/profile/(.*/)?attributes$").through(UnavailableResourceInMultiUserFilter.class); }
Source:
BinaryContent transform(Attribute attribute) throws CatalogTransformerException { BinaryContent transformedContent = null; ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread() .setContextClassLoader(getClass().getClassLoader()); ByteArrayOutputStream os = new ByteArrayOutputStream(BUFFER_SIZE); Marshaller marshaller = CONTEXT.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setEventHandler(new DefaultValidationEventHandler()); try { marshaller.marshal(GeometryAdapter.marshalFrom(attribute), os); } catch (RuntimeException e) { throw new CatalogTransformerException("Failed to marshall geometry data", e); } ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray()); transformedContent = new BinaryContentImpl(bais, new MimeType(TEXT_XML)); } catch (JAXBException e) { throw new CatalogTransformerException("Failed JAXB Transformation", e); } catch (MimeTypeParseException e) { throw new CatalogTransformerException( "Failed Transformation with MimeType Parsing error", e); } finally { Thread.currentThread().setContextClassLoader(tccl); } return transformedContent; }

Target:
static BinaryContent transform(Attribute attribute) throws CatalogTransformerException { BinaryContent transformedContent = null; ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread() .setContextClassLoader(GeometryTransformer.class.getClassLoader()); ByteArrayOutputStream os = new ByteArrayOutputStream(BUFFER_SIZE); Marshaller marshaller = CONTEXT.createMarshaller(); marshaller.setEventHandler(new DefaultValidationEventHandler()); try { marshaller.marshal(GeometryAdapter.marshalFrom(attribute), os); } catch (RuntimeException e) { throw new CatalogTransformerException("Failed to marshall geometry data", e); } ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray()); transformedContent = new BinaryContentImpl(bais, new MimeType(TEXT_XML)); } catch (JAXBException e) { throw new CatalogTransformerException("Failed JAXB Transformation", e); } catch (MimeTypeParseException e) { throw new CatalogTransformerException( "Failed Transformation with MimeType Parsing error", e); } finally { Thread.currentThread().setContextClassLoader(tccl); } return transformedContent; }
Source:
public void allowJsonRefInContext(String jsonReferenceContext, boolean allow) { ArrayNode definition = jsonRefContexts.get(jsonReferenceContext); if (definition == null) { throw new IllegalArgumentException("Invalid JSON Reference Context: " + jsonReferenceContext); } int lastIndex = definition.size() - 1; JsonNode lastElement = definition.get(lastIndex); boolean alreadyHasJsonReference = refToJsonReferenceNode.equals(lastElement); if (allow) { if (!alreadyHasJsonReference) { definition.add(refToJsonReferenceNode.deepCopy()); } } else { if (alreadyHasJsonReference) { definition.remove(lastIndex); } } }

Target:
public void allowJsonRefInContext(String jsonReferenceContext, boolean allow) { if (jsonRefContexts.get(jsonReferenceContext) == null) { throw new IllegalArgumentException("Invalid JSON Reference Context: " + jsonReferenceContext); } if (VALIDATION_REF_SECURITY_DEFINITIONS_OBJECT.equals(jsonReferenceContext)) { allowJsonRefInSecurityDefinitionsObject(allow); return; } ArrayNode definition = (ArrayNode) jsonRefContexts.get(jsonReferenceContext); List<JsonNode> children = Lists.newArrayList(definition.elements()); int indexOfJsonReference = children.indexOf(refToJsonReferenceNode); boolean alreadyHasJsonReference = indexOfJsonReference > -1; if (allow) { if (!alreadyHasJsonReference) { definition.add(refToJsonReferenceNode.deepCopy()); } } else { if (alreadyHasJsonReference) { definition.remove(indexOfJsonReference); } } }
Source:
public synchronized void start() { if (hasBeenStarted) { throw new IllegalThreadStateException("Thread already started."); } hasBeenStarted = true; VMThread.create(this, stackSize); }

Target:
public synchronized void start() { checkNotStarted(); hasBeenStarted = true; VMThread.create(this, stackSize); }
Source:
public void saveSearchFilterSettings(final String filterName, final Consumer<String> callback) { final FilterSettings settings = getDataSetQueryHelper().getCurrentTableSettings(); settings.setTableName(filterName); settings.setTableDescription(filterName); filterSettingsManager.saveFilterIntoPreferences(settings, state -> { if (state) { getListView().getListGrid().getGridPreferencesStore().setPreferenceKey(settings.getKey()); getListView().getListGrid().saveGridPreferences(); callback.accept(null); } else { callback.accept(Constants.INSTANCE.FilterWithSameNameAlreadyExists()); } }); }

Target:
public void saveSearchFilterSettings(final String filterName, final Consumer<String> callback) { final FilterSettings settings = getDataSetQueryHelper().getCurrentTableSettings(); settings.setTableName(filterName); settings.setTableDescription(filterName); filterSettingsManager.saveFilterIntoPreferences(settings, state -> { if (state) { getListView().getListGrid().getGridPreferencesStore().setPreferenceKey(settings.getKey()); getListView().getListGrid().saveGridToUserPreferences(); callback.accept(null); } else { callback.accept(Constants.INSTANCE.FilterWithSameNameAlreadyExists()); } }); }
Source:
private DataNode<ModuleData> createModuleData( @NotNull DataNode<ProjectData> projectInfoDataNode, @NotNull String targetName, @NotNull TargetInfo targetInfo, @NotNull PantsCompileOptionsExecutor executor ) { final String moduleName = PantsUtil.getCanonicalModuleName(targetName); final ModuleData moduleData = new ModuleData( targetName, PantsConstants.SYSTEM_ID, ModuleTypeId.JAVA_MODULE, moduleName, projectInfoDataNode.getData().getIdeProjectFileDirectoryPath() + "/" + moduleName, new File(executor.getBuildRoot(), targetName).getAbsolutePath() ); final DataNode<ModuleData> moduleDataNode = projectInfoDataNode.createChild(ProjectKeys.MODULE, moduleData); if(targetInfo.isPythonTarget()) { moduleDataNode.createChild(ModuleSdkData.KEY, new ModuleSdkData("python")); } else { DataNode<ProjectSdkData> sdk = ExternalSystemApiUtil.find(projectInfoDataNode, ProjectSdkData.KEY); if(sdk != null){ ModuleSdkData moduleSdk = new ModuleSdkData(sdk.getData().getSdkName()); moduleDataNode.createChild(ModuleSdkData.KEY, moduleSdk); } } final TargetMetadata metadata = new TargetMetadata(PantsConstants.SYSTEM_ID, moduleName); metadata.setTargetAddresses(ContainerUtil.map(targetInfo.getAddressInfos(), TargetAddressInfo::getTargetAddress)); metadata.setTargetAddressInfoSet(targetInfo.getAddressInfos()); metadata.setLibraryExcludes(targetInfo.getExcludes()); moduleDataNode.createChild(TargetMetadata.KEY, metadata); return moduleDataNode; }

Target:
private DataNode<ModuleData> createModuleData( @NotNull DataNode<ProjectData> projectInfoDataNode, @NotNull String targetName, @NotNull TargetInfo targetInfo, @NotNull PantsCompileOptionsExecutor executor ) { final String moduleName = PantsUtil.getCanonicalModuleName(targetName); final ModuleData moduleData = new ModuleData( targetName, PantsConstants.SYSTEM_ID, ModuleTypeId.JAVA_MODULE, moduleName, projectInfoDataNode.getData().getIdeProjectFileDirectoryPath() + "/" + moduleName, new File(executor.getBuildRoot(), targetName).getAbsolutePath() ); final DataNode<ModuleData> moduleDataNode = projectInfoDataNode.createChild(ProjectKeys.MODULE, moduleData); if(targetInfo.isPythonTarget()) { String sdkName = String.format("Python for %s", projectInfoDataNode.getData().getExternalName()); moduleDataNode.createChild(ModuleSdkData.KEY, new ModuleSdkData(sdkName)); } else { DataNode<ProjectSdkData> sdk = ExternalSystemApiUtil.find(projectInfoDataNode, ProjectSdkData.KEY); if(sdk != null){ ModuleSdkData moduleSdk = new ModuleSdkData(sdk.getData().getSdkName()); moduleDataNode.createChild(ModuleSdkData.KEY, moduleSdk); } } final TargetMetadata metadata = new TargetMetadata(PantsConstants.SYSTEM_ID, moduleName); metadata.setTargetAddresses(ContainerUtil.map(targetInfo.getAddressInfos(), TargetAddressInfo::getTargetAddress)); metadata.setTargetAddressInfoSet(targetInfo.getAddressInfos()); metadata.setLibraryExcludes(targetInfo.getExcludes()); moduleDataNode.createChild(TargetMetadata.KEY, metadata); return moduleDataNode; }
Source:
public static ColumnDef build(String name, String charset, String type, int pos, boolean signed, String enumValues[], Long columnLength) { switch(type) { case "datetime": case "timestamp": return new DateTimeColumnDef(name, type, pos, columnLength); default: return build(name, charset, type, pos, signed, enumValues); } }

Target:
public static ColumnDef build(String name, String charset, String type, int pos, boolean signed, String enumValues[], Long columnLength) { switch(type) { case "tinyint": case "smallint": case "mediumint": case "int": return new IntColumnDef(name, type, pos, signed); case "bigint": return new BigIntColumnDef(name, type, pos, signed); case "tinytext": case "text": case "mediumtext": case "longtext": case "varchar": case "char": return new StringColumnDef(name, type, pos, charset); case "tinyblob": case "blob": case "mediumblob": case "longblob": case "binary": case "varbinary": return new StringColumnDef(name, type, pos, "binary"); case "geometry": case "geometrycollection": case "linestring": case "multilinestring": case "multipoint": case "multipolygon": case "polygon": case "point": return new GeometryColumnDef(name, type, pos); case "float": case "double": return new FloatColumnDef(name, type, pos); case "decimal": return new DecimalColumnDef(name, type, pos); case "date": return new DateColumnDef(name, type, pos); case "datetime": case "timestamp": return new DateTimeColumnDef(name, type, pos, columnLength); case "time": return new TimeColumnDef(name, type, pos, columnLength); case "year": return new YearColumnDef(name, type, pos); case "enum": return new EnumColumnDef(name, type, pos, enumValues); case "set": return new SetColumnDef(name, type, pos, enumValues); case "bit": return new BitColumnDef(name, type, pos); default: throw new IllegalArgumentException("unsupported column type " + type); } }
Source:
public static boolean supportsAdd(int type) { switch (type) { case Value.BYTE: case Value.DECIMAL: case Value.DOUBLE: case Value.FLOAT: case Value.INT: case Value.LONG: case Value.SHORT: return true; default: if (JdbcUtils.customDataTypesHandler != null) { return JdbcUtils.customDataTypesHandler.supportsAdd(type); } return false; } }

Target:
public static boolean supportsAdd(int type) { switch (type) { case Value.BYTE: case Value.DECIMAL: case Value.DOUBLE: case Value.FLOAT: case Value.INT: case Value.LONG: case Value.SHORT: return true; case Value.BOOLEAN: case Value.TIME: case Value.DATE: case Value.TIMESTAMP: case Value.TIMESTAMP_TZ: case Value.BYTES: case Value.UUID: case Value.STRING: case Value.STRING_IGNORECASE: case Value.STRING_FIXED: case Value.BLOB: case Value.CLOB: case Value.NULL: case Value.JAVA_OBJECT: case Value.UNKNOWN: case Value.ARRAY: case Value.RESULT_SET: case Value.GEOMETRY: return false; default: if (JdbcUtils.customDataTypesHandler != null) { return JdbcUtils.customDataTypesHandler.supportsAdd(type); } return false; } }
Source:
public TypeProvider getTypes() { return TypeProvider.fromVariables(variables.entrySet().stream() .map(entry -> new VariableReferenceExpression(entry.getKey(), entry.getValue())) .collect(toImmutableList())); }

Target:
public TypeProvider getTypes() { return TypeProvider.viewOf(variables); }
Source:
public void attachmentStandalone() throws IOException, URISyntaxException { byte[] bytesToDB = "binary data".getBytes(); ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesToDB); Response response = db.saveAttachment(bytesIn, "foo.txt", "text/plain"); Document doc = db.find(Document.class, response.getId()); assertTrue(doc.getAttachments().containsKey("foo.txt")); HttpConnection conn = Http.GET(new DatabaseURIHelper(db.getDBUri()) .attachmentUri(response.getId(), "foo.txt")); InputStream in = clientResource.get().executeRequest(conn).responseAsInputStream(); try { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); int n; while ((n = in.read()) != -1) { bytesOut.write(n); } bytesOut.flush(); byte[] bytesFromDB = bytesOut.toByteArray(); assertArrayEquals(bytesToDB, bytesFromDB); } finally { in.close(); } }

Target:
public void attachmentStandalone() throws IOException, URISyntaxException { byte[] bytesToDB = "binary data".getBytes(); ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesToDB); Response response = db.saveAttachment(bytesIn, "foo.txt", "text/plain"); Document doc = db.find(Document.class, response.getId()); assertTrue(doc.getAttachments().containsKey("foo.txt")); HttpConnection conn = Http.GET(new DatabaseURIHelper(db.getDBUri()) .attachmentUri(response.getId(), "foo.txt")); InputStream in = clientResource.get().executeRequest(conn).responseAsInputStream(); try { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); IOUtils.copy(in, bytesOut); byte[] bytesFromDB = bytesOut.toByteArray(); assertArrayEquals(bytesToDB, bytesFromDB); } finally { in.close(); } }
Source:
public void testSchema() { Schema schema = udf_.outputSchema(null); assertNotNull(schema); assertEquals("{map: map[chararray]}", schema.toString()); }

Target:
public void testSchema() { Schema schema = udf_.outputSchema(null); assertNotNull(schema); assertEquals("{json: map[chararray]}", schema.toString()); }
Source:
private void clearTables() { CorfuStoreMetadata.Timestamp timestamp = logReplicationMetadataManager.getTimestamp(); long persistSiteConfigID = logReplicationMetadataManager.query(timestamp, LogReplicationMetadataManager.LogReplicationMetadataType.TOPOLOGY_CONFIG_ID); long persistSnapStart = logReplicationMetadataManager.query(timestamp, LogReplicationMetadataManager.LogReplicationMetadataType.LAST_SNAPSHOT_STARTED); long persitSeqNum = logReplicationMetadataManager.query(timestamp, LogReplicationMetadataManager.LogReplicationMetadataType.LAST_SNAPSHOT_SEQ_NUM); if (topologyConfigId != persistSiteConfigID || srcGlobalSnapshot != persistSnapStart || (persitSeqNum + 1)!= recvSeq) { log.warn("Skip current topologyConfigId " + topologyConfigId + " srcGlobalSnapshot " + srcGlobalSnapshot + " currentSeqNum " + recvSeq + " persistedMetadata " + logReplicationMetadataManager.getTopologyConfigId() + " startSnapshot " + logReplicationMetadataManager.getLastSnapStartTimestamp() + " lastSnapSeqNum " + logReplicationMetadataManager.getLastSnapSeqNum()); return; } TxBuilder txBuilder = logReplicationMetadataManager.getTxBuilder(); logReplicationMetadataManager.appendUpdate(txBuilder, LogReplicationMetadataManager.LogReplicationMetadataType.TOPOLOGY_CONFIG_ID, topologyConfigId); for (UUID streamID : streamViewMap.keySet()) { UUID usedStreamID = streamID; if (phase == Phase.TRANSFER_PHASE) { usedStreamID = uuidMap.get(streamID); } SMREntry entry = new SMREntry("clear", new Array[0], Serializers.PRIMITIVE); txBuilder.logUpdate(usedStreamID, entry); } txBuilder.commit(timestamp); }

Target:
private void clearTables() { CorfuStoreMetadata.Timestamp timestamp = logReplicationMetadataManager.getTimestamp(); long persistedTopologyConfigId = logReplicationMetadataManager.query(timestamp, LogReplicationMetadataManager.LogReplicationMetadataType.TOPOLOGY_CONFIG_ID); long persistedSnapshotStart = logReplicationMetadataManager.query(timestamp, LogReplicationMetadataManager.LogReplicationMetadataType.LAST_SNAPSHOT_STARTED); long persistedSequenceNum = logReplicationMetadataManager.query(timestamp, LogReplicationMetadataManager.LogReplicationMetadataType.LAST_SNAPSHOT_SEQ_NUM); if (topologyConfigId != persistedTopologyConfigId || srcGlobalSnapshot != persistedSnapshotStart || (persistedSequenceNum + 1)!= recvSeq) { log.warn("Skip clearing shadow tables. Current topologyConfigId={} srcGlobalSnapshot={}, currentSeqNum={}, " + "persistedTopologyConfigId={}, persistedSnapshotStart={}, persistedLastSequenceNum={}", topologyConfigId, srcGlobalSnapshot, recvSeq, persistedTopologyConfigId, persistedSnapshotStart, persistedSequenceNum); return; } TxBuilder txBuilder = logReplicationMetadataManager.getTxBuilder(); logReplicationMetadataManager.appendUpdate(txBuilder, LogReplicationMetadataManager.LogReplicationMetadataType.TOPOLOGY_CONFIG_ID, topologyConfigId); for (UUID streamID : streamViewMap.keySet()) { UUID usedStreamID = streamID; if (phase == Phase.TRANSFER_PHASE) { usedStreamID = uuidMap.get(streamID); } SMREntry entry = new SMREntry("clear", new Array[0], Serializers.PRIMITIVE); txBuilder.logUpdate(usedStreamID, entry); } txBuilder.commit(timestamp); }
Source:
public void edit(final VolumeRebalanceStatusModel object) { driver.edit(object); rebalanceHostsTable.asEditor().edit(object.getRebalanceSessions()); object.getPropertyChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { PropertyChangedEventArgs e = (PropertyChangedEventArgs) args; if (e.PropertyName.equals("STATUS_UPDATED")) { status.setText(constants.rebalanceComplete()); status.setVisible(object.isStatusAvailable()); } else if (e.PropertyName.equals("STOP_TIME_UPDATED")) { stopTimePanel.setVisible(object.isStopTimeVisible()); status.setVisible(object.isStatusAvailable()); } } }); }

Target:
public void edit(final VolumeRebalanceStatusModel object) { driver.edit(object); rebalanceHostsTable.asEditor().edit(object.getRebalanceSessions()); object.getPropertyChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { PropertyChangedEventArgs e = (PropertyChangedEventArgs) args; if (e.PropertyName.equals("STATUS_UPDATED")) { status.setVisible(object.isStatusAvailable()); } else if (e.PropertyName.equals("STOP_TIME_UPDATED")) { stopTimePanel.setVisible(object.isStopTimeVisible()); status.setVisible(object.isStatusAvailable()); } } }); }
Source:
public void findTraditionalPageOne() throws Exception { getClient().perform(get("/api/config/submissionforms/traditionalpageone")) .andExpect(status().isForbidden()); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/config/submissionforms/traditionalpageone")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.id", is("traditionalpageone"))) .andExpect(jsonPath("$.name", is("traditionalpageone"))) .andExpect(jsonPath("$.type", is("submissionform"))) .andExpect(jsonPath("$._links.self.href", Matchers .startsWith(REST_SERVER_URL + "config/submissionforms/traditionalpageone"))) ; }

Target:
public void findTraditionalPageOne() throws Exception { getClient().perform(get("/api/config/submissionforms/traditionalpageone")) .andExpect(status().isUnauthorized()); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/config/submissionforms/traditionalpageone")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.id", is("traditionalpageone"))) .andExpect(jsonPath("$.name", is("traditionalpageone"))) .andExpect(jsonPath("$.type", is("submissionform"))) .andExpect(jsonPath("$._links.self.href", Matchers .startsWith(REST_SERVER_URL + "config/submissionforms/traditionalpageone"))) ; }
Source:
public OperatorCoordinator create(OperatorCoordinator.Context context) { final String coordinatorThreadName = "SourceCoordinator-" + operatorID; ExecutorService coordinatorExecutor = Executors.newSingleThreadExecutor( r -> new Thread(r, coordinatorThreadName)); SourceCoordinatorContext<SplitT> sourceCoordinatorContext = new SourceCoordinatorContext<>(coordinatorExecutor, coordinatorThreadName, numWorkerThreads, context); return new SourceCoordinator<>(coordinatorExecutor, source, sourceCoordinatorContext); }

Target:
public OperatorCoordinator create(OperatorCoordinator.Context context) { final String coordinatorThreadName = "SourceCoordinator-" + operatorName; CoordinatorExecutorThreadFactory coordinatorThreadFactory = new CoordinatorExecutorThreadFactory(coordinatorThreadName); ExecutorService coordinatorExecutor = Executors.newSingleThreadExecutor(coordinatorThreadFactory); SourceCoordinatorContext<SplitT> sourceCoordinatorContext = new SourceCoordinatorContext<>(coordinatorExecutor, coordinatorThreadFactory, numWorkerThreads, context); return new SourceCoordinator<>(operatorName, coordinatorExecutor, source, sourceCoordinatorContext); }
Source:
void put(Class<?> clazz, Boolean value) { if (indexedEntities != null) { throw new IllegalStateException("Autodetect mode is not enabled for cache " + cacheName); } if (value == null) { throw new IllegalArgumentException("Null values are not allowed"); } startInternalCache(); Transaction tx = transactionHelper.suspendTxIfExists(); try { while (true) { try { knownClassesCache.put(new KeyValuePair<>(cacheName, clazz), value); break; } catch (CacheException e) { if (SuspectException.isSuspectExceptionInChain(e)) { log.tracef("Ignoring suspect exception and retrying operation for internal cache %s", QUERY_KNOWN_CLASSES_CACHE_NAME); } else { throw e; } } } } finally { transactionHelper.resume(tx); } localCacheInsert(clazz, value); }

Target:
void put(Class<?> clazz, Boolean value) { if (indexedEntities != null) { throw new IllegalStateException("Autodetect mode is not enabled for cache " + cacheName); } if (value == null) { throw new IllegalArgumentException("Null values are not allowed"); } startInternalCache(); Transaction tx = transactionHelper.suspendTxIfExists(); try { knownClassesCache.put(new KeyValuePair<>(cacheName, clazz), value); } finally { transactionHelper.resume(tx); } localCacheInsert(clazz, value); }
Source:
public IntegrationTestingConfig get() { return new IntegrationTestingConfig() { @Override public String getCoordinatorUrl() { return "http://" + dockerIp + ":8081"; } @Override public String getIndexerUrl() { return "http://" + dockerIp + ":8090"; } @Override public String getRouterUrl() { return "http://" + dockerIp + ":8888"; } @Override public String getBrokerUrl() { return "http://" + dockerIp + ":8082"; } @Override public String getHistoricalUrl() { return "http://" + dockerIp + ":8083"; } @Override public String getMiddleManagerHost() { return dockerIp; } @Override public String getZookeeperHosts() { return "http://" + dockerIp + ":2181"; } @Override public String getKafkaHost() { return "http://" + dockerIp + ":9092"; } @Override public String getProperty(String prop) { if (prop.equals("hadoopTestDir")) { return hadoopDir; } throw new UnsupportedOperationException("DockerConfigProvider does not support property " + prop); } @Override public String getUsername() { return null; } @Override public String getPassword() { return null; } }; }

Target:
public IntegrationTestingConfig get() { return new IntegrationTestingConfig() { @Override public String getCoordinatorUrl() { return "http://" + dockerIp + ":8081"; } @Override public String getIndexerUrl() { return "http://" + dockerIp + ":8090"; } @Override public String getRouterUrl() { return "http://" + dockerIp + ":8888"; } @Override public String getBrokerUrl() { return "http://" + dockerIp + ":8082"; } @Override public String getHistoricalUrl() { return "http://" + dockerIp + ":8083"; } @Override public String getMiddleManagerHost() { return dockerIp; } @Override public String getZookeeperHosts() { return dockerIp + ":2181"; } @Override public String getKafkaHost() { return dockerIp + ":9092"; } @Override public String getProperty(String prop) { if (prop.equals("hadoopTestDir")) { return hadoopDir; } throw new UnsupportedOperationException("DockerConfigProvider does not support property " + prop); } @Override public String getUsername() { return null; } @Override public String getPassword() { return null; } }; }
Source:
public void parsePropertyFiles_Populates_Two_Files_One_Empty() { initWithProperties(SAMPLE_ONE_PROPERTIES); ReportParser reportParser = new ReportParser(configuration); propertyFiles.add(""); reportParser.parseClassificationsFiles(propertyFiles); List<Map.Entry<String, String>> returnedClassifications = configuration.getClassifications(); assertThat(returnedClassifications).hasSize(5); assertThat(returnedClassifications).contains(new AbstractMap.SimpleEntry<>("AutUiVersion", "1.25.3"), Index.atIndex(1)); assertThat(returnedClassifications).contains(new AbstractMap.SimpleEntry<>("firefoxVersion", "56.0"), Index.atIndex(4)); }

Target:
public void parsePropertyFiles_Populates_Two_Files_One_Empty() { initWithProperties(SAMPLE_ONE_PROPERTIES); ReportParser reportParser = new ReportParser(configuration); classificationFiles.add(""); reportParser.parseClassificationsFiles(classificationFiles); List<Map.Entry<String, String>> returnedClassifications = configuration.getClassifications(); assertThat(returnedClassifications).hasSize(5); assertThat(returnedClassifications).contains(new AbstractMap.SimpleEntry<>("AutUiVersion", "1.25.3"), Index.atIndex(1)); assertThat(returnedClassifications).contains(new AbstractMap.SimpleEntry<>("firefoxVersion", "56.0"), Index.atIndex(4)); }
Source:
public String includedToString() { StringBuilder sb = new StringBuilder(); if (isVisited()) { Iterator it = edges.entrySet() .iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if (((Edge) pair.getValue()).isIncluded()) { if (!((Edge) pair.getValue()).isPrinted()) { sb.append(getLabel()); sb.append(" --- "); sb.append(((Edge) pair.getValue()).getWeight()); sb.append(" --- "); sb.append(((Vertex) pair.getKey()).getLabel()); sb.append("\n"); ((Edge) pair.getValue()).setPrinted(true); } } } } return sb.toString(); }

Target:
public String includedToString(){ StringBuilder sb = new StringBuilder(); if (isVisited()) { Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); if (pair.getValue().isIncluded()) { if (!pair.getValue().isPrinted()) { sb.append(getLabel()); sb.append(" --- "); sb.append(pair.getValue().getWeight()); sb.append(" --- "); sb.append(pair.getKey().getLabel()); sb.append("\n"); pair.getValue().setPrinted(true); } } } } return sb.toString(); }
Source:
public @Nullable SerialPortIdentifier getPortIdentifier(URI port) { CommPortIdentifier ident = null; if ((System.getProperty("os.name").toLowerCase().indexOf("linux") != -1)) { SerialPortUtil.appendSerialPortProperty(port.getPath()); } try { ident = CommPortIdentifier.getPortIdentifier(port.getPath()); } catch (gnu.io.NoSuchPortException e) { logger.info("No SerialPortIdentifier found for: {}", port.getPath()); return null; } return new SerialPortIdentifierImpl(ident); }

Target:
public @Nullable SerialPortIdentifier getPortIdentifier(URI port) { CommPortIdentifier ident = null; if ((System.getProperty("os.name").toLowerCase().indexOf("linux") != -1)) { SerialPortUtil.appendSerialPortProperty(port.getPath()); } try { ident = CommPortIdentifier.getPortIdentifier(port.getPath()); } catch (gnu.io.NoSuchPortException e) { logger.debug("No SerialPortIdentifier found for: {}", port.getPath()); return null; } return new SerialPortIdentifierImpl(ident); }
Source:
private <T extends BaseContainer> void validateAndAssertResult(T container, boolean isValid) { Set<ConstraintViolation<T>> validate = validate(container); Assert.assertTrue(isValid ? validate.isEmpty() : !validate.isEmpty()); }

Target:
private <T> void validateAndAssertResult(T container, boolean isValid) { Set<ConstraintViolation<T>> validate = validator.validate(container); Assert.assertEquals(isValid, validate.isEmpty()); }