auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("exchange.max-buffer-size", "1GB") .put("exchange.concurrent-request-multiplier", "13") .put("exchange.min-error-duration", "13s") .put("exchange.max-error-duration", "33s") .put("exchange.max-response-size", "1MB") .put("exchange.client-threads", "2") .put("exchange.page-buffer-client.max-callback-threads", "16") .put("exchange.acknowledge-pages", "false") .put("exchange.initial-request-count", "42") .build(); ExchangeClientConfig expected = new ExchangeClientConfig() .setMaxBufferSize(new DataSize(1, Unit.GIGABYTE)) .setConcurrentRequestMultiplier(13) .setMinErrorDuration(new Duration(33, TimeUnit.SECONDS)) .setMaxErrorDuration(new Duration(33, TimeUnit.SECONDS)) .setMaxResponseSize(new DataSize(1, Unit.MEGABYTE)) .setClientThreads(2) .setPageBufferClientMaxCallbackThreads(16) .setAcknowledgePages(false); assertFullMapping(properties, expected); }

Target:
public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("exchange.max-buffer-size", "1GB") .put("exchange.concurrent-request-multiplier", "13") .put("exchange.min-error-duration", "13s") .put("exchange.max-error-duration", "33s") .put("exchange.max-response-size", "1MB") .put("exchange.client-threads", "2") .put("exchange.page-buffer-client.max-callback-threads", "16") .put("exchange.acknowledge-pages", "false") .put("exchange.response-size-exponential-moving-average-decaying-alpha", "0.42") .build(); ExchangeClientConfig expected = new ExchangeClientConfig() .setMaxBufferSize(new DataSize(1, Unit.GIGABYTE)) .setConcurrentRequestMultiplier(13) .setMinErrorDuration(new Duration(33, TimeUnit.SECONDS)) .setMaxErrorDuration(new Duration(33, TimeUnit.SECONDS)) .setMaxResponseSize(new DataSize(1, Unit.MEGABYTE)) .setClientThreads(2) .setPageBufferClientMaxCallbackThreads(16) .setAcknowledgePages(false) .setResponseSizeExponentialMovingAverageDecayingAlpha(0.42); assertFullMapping(properties, expected); }
Source:
private void mergeAndPush() { final Granularity segmentGranularity = schema.getGranularitySpec().getSegmentGranularity(); final Period windowPeriod = config.getWindowPeriod(); final long windowMillis = windowPeriod.toStandardDuration().getMillis(); log.info("Starting merge and push."); DateTime minTimestampAsDate = segmentGranularity.truncate( new DateTime( Math.max( windowMillis, rejectionPolicy.getCurrMaxTime() .getMillis() ) - windowMillis ) ); long minTimestamp = minTimestampAsDate.getMillis(); log.info("Found [%,d] sinks. minTimestamp [%s]", sinks.size(), minTimestampAsDate); List<Map.Entry<Long, Sink>> sinksToPush = Lists.newArrayList(); for (Map.Entry<Long, Sink> entry : sinks.entrySet()) { final Long intervalStart = entry.getKey(); if (intervalStart < minTimestamp) { log.info("Adding entry [%s] for merge and push.", entry); sinksToPush.add(entry); } else { log.warn( "[%s] >= [%s] Skipping persist and merge for entry [%s]", new DateTime(intervalStart), minTimestampAsDate, entry ); } } log.info("Found [%,d] sinks to persist and merge", sinksToPush.size()); for (final Map.Entry<Long, Sink> entry : sinksToPush) { persistAndMerge(entry.getKey(), entry.getValue()); } }

Target:
private void mergeAndPush() { final Granularity segmentGranularity = schema.getGranularitySpec().getSegmentGranularity(); final Period windowPeriod = config.getWindowPeriod(); final long windowMillis = windowPeriod.toStandardDuration().getMillis(); log.info("Starting merge and push."); DateTime minTimestampAsDate = segmentGranularity.truncate( new DateTime( Math.max( windowMillis, rejectionPolicy.getCurrMaxTime() .getMillis() ) - windowMillis ) ); long minTimestamp = minTimestampAsDate.getMillis(); log.info("Found [%,d] segments. Attempting to hand off segments that start before [%s].", sinks.size(), minTimestampAsDate); List<Map.Entry<Long, Sink>> sinksToPush = Lists.newArrayList(); for (Map.Entry<Long, Sink> entry : sinks.entrySet()) { final Long intervalStart = entry.getKey(); if (intervalStart < minTimestamp) { log.info("Adding entry [%s] for merge and push.", entry); sinksToPush.add(entry); } else { log.info( "Skipping persist and merge for entry [%s] : Start time [%s] >= [%s] min timestamp required in this run. Segment will be picked up in a future run.", entry, new DateTime(intervalStart), minTimestampAsDate ); } } log.info("Found [%,d] sinks to persist and merge", sinksToPush.size()); for (final Map.Entry<Long, Sink> entry : sinksToPush) { persistAndMerge(entry.getKey(), entry.getValue()); } }
Source:
boolean matches(DownloadFileId downloadFileId) { return downloadFileStatus.downloadFileId().equals(downloadFileId); }

Target:
boolean matches(DownloadFileId downloadFileId) { return this.downloadFileId.equals(downloadFileId); }
Source:
public void shouldThrow409_whenMandateStateInvalid(){ Response response = mock(Response.class); when(response.readEntity(ConnectorErrorResponse.class)) .thenReturn(new ConnectorErrorResponse( ErrorIdentifier.MANDATE_STATE_INVALID, null, null)); Response returnedResponse = mapper.toResponse(new CreateChargeException(response)); PaymentError returnedError = (PaymentError) returnedResponse.getEntity(); assertThat(returnedResponse.getStatus(), is(409)); assertThat(returnedError.getDescription(), is(aPaymentError(CREATE_PAYMENT_MANDATE_STATE_INVALID).getDescription())); assertThat(returnedError.getCode(), is(aPaymentError(CREATE_PAYMENT_MANDATE_STATE_INVALID).getCode())); }

Target:
public void shouldThrow409_whenMandateStateInvalid(){ when(mockResponse.readEntity(ConnectorErrorResponse.class)) .thenReturn(new ConnectorErrorResponse( ErrorIdentifier.MANDATE_STATE_INVALID, null, null)); Response returnedResponse = mapper.toResponse(new CreateChargeException(mockResponse)); PaymentError returnedError = (PaymentError) returnedResponse.getEntity(); PaymentError expectedError = aPaymentError(CREATE_PAYMENT_MANDATE_STATE_INVALID); assertThat(returnedResponse.getStatus(), is(409)); assertThat(returnedError.getDescription(), is(expectedError.getDescription())); assertThat(returnedError.getCode(), is(expectedError.getCode())); }
Source:
public double getScore(Container container) { int totalComponentInstances = 0; int totalInstances = container.getInstances().size(); if (totalInstances == 0) { return 0; } for (PackingPlan.InstancePlan instancePlan : container.getInstances()) { if (componentName.equals(instancePlan.getComponentName())) { totalComponentInstances++; } } return (double) totalComponentInstances / totalInstances; }

Target:
public double getScore(Container container) { int totalComponentInstances = 0; int totalInstances = container.getInstances().size(); if (totalInstances == 0) { return 0; } for (PackingPlan.InstancePlan instancePlan : container.getInstances()) { if (componentName.equals(instancePlan.getComponentName())) { totalComponentInstances++; } } if (binaryMode) { if (totalComponentInstances == totalInstances) { return 1; } else { return 0; } } else { return (double) totalComponentInstances / totalInstances; } }
Source:
private static void close(Collection<Connection> list) throws SQLException { for (Connection conn : list) { try { conn.close(); } catch (SQLException ignore) { } } }

Target:
private static void close(Collection<Connection> list) { for (Connection conn : list) { IOUtils.closeSilently(conn); } }
Source:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { System.out.println("Channel heartBeat lost"); if (evt instanceof IdleStateEvent && IdleState.READER_IDLE == ((IdleStateEvent) evt).state()) { ctx.channel().close(); } }

Target:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { System.out.println("Channel heartBeat lost"); if (evt instanceof IdleStateEvent && IdleState.READER_IDLE == ((IdleStateEvent) evt).state()) { ctx.close(); } }
Source:
protected Integer calculateRecordsJSON(String jsonStr) { Integer rec = null; try { ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(jsonStr); if (!jsonNode.isObject()) { return null; } jsonNode = jsonNode.get("data"); if (jsonNode.isArray()) { rec = jsonNode.size(); } } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } return rec; }

Target:
protected Integer calculateRecordsJSON(String jsonStr) { return JsonPath.read(jsonStr, "$.data.length()"); }
Source:
public void testGetMcqOtherWeight_nullOtherWeight_exceptionThrown() { FeedbackMcqQuestionDetails mcqDetails = new FeedbackMcqQuestionDetails(); HashMap<String, String[]> requestParams = new HashMap<>(); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TYPE, new String[] { "MCQ" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TEXT, new String[] { "mcq question text" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_GENERATED_OPTIONS, new String[] { "NONE" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_NUMBEROFCHOICECREATED, new String[] { "2" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQCHOICE + "-0", new String[] { "Choice 1" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQCHOICE + "-1", new String[] { "Choice 2" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_HAS_WEIGHTS_ASSIGNED, new String[] { "on" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-0", new String[] { "2.57" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-1", new String[] { "1.12" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQOTHEROPTIONFLAG, new String[] { "on" }); assertTrue(mcqDetails.extractQuestionDetails(requestParams, FeedbackQuestionType.MCQ)); }

Target:
public void testGetMcqOtherWeight_nullOtherWeight_exceptionThrown() { FeedbackMcqQuestionDetails mcqDetails = new FeedbackMcqQuestionDetails(); HashMap<String, String[]> requestParams = new HashMap<>(); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TYPE, new String[] { "MCQ" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TEXT, new String[] { "mcq question text" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_GENERATED_OPTIONS, new String[] { "NONE" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_NUMBEROFCHOICECREATED, new String[] { "2" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQCHOICE + "-0", new String[] { "Choice 1" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQCHOICE + "-1", new String[] { "Choice 2" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_HAS_WEIGHTS_ASSIGNED, new String[] { "on" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-0", new String[] { "2.57" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-1", new String[] { "1.12" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQOTHEROPTIONFLAG, new String[] { "on" }); mcqDetails.extractQuestionDetails(requestParams, FeedbackQuestionType.MCQ); }
Source:
public static Toast makeText(Context context, CharSequence s, int duration) { if(VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { return Toast.makeText(context, s, duration); } IcsToast toast = new IcsToast(context); toast.setDuration(duration); TextView view = new TextView(context); view.setText(s); view.setTextColor(0xFFDADADA); view.setGravity(Gravity.CENTER); view.setBackgroundResource(R.drawable.abs__toast_frame); toast.setView(view); return toast; }

Target:
public static Toast makeText(Context context, CharSequence s, int duration) { if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH) { return Toast.makeText(context, s, duration); } IcsToast toast = new IcsToast(context); toast.setDuration(duration); TextView view = new TextView(context); view.setText(s); view.setTextColor(0xffffffff); view.setGravity(Gravity.CENTER); view.setBackgroundResource(R.drawable.abs__toast_frame); toast.setView(view); return toast; }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { return Collections.singletonList(new PermissionSubject(getParameters().getStorageDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { return Collections.emptyList(); }
Source:
default void initializeSegment(TrackingToken token, String processorName, int segment) throws UnableToInitializeTokenException { throw new UnsupportedOperationException(""); }

Target:
default void initializeSegment(TrackingToken token, String processorName, int segment) throws UnableToInitializeTokenException { throw new UnsupportedOperationException("Explicit initialization is not supported by this TokenStore implementation"); }
Source:
private void subscribeTopicUpdateChildren(@UIEventTopic(ElementContainer.TOPIC_CHILDREN) Event event) { if (!(event.getProperty(UIEvents.EventTags.ELEMENT) instanceof MToolBar)) { return; } MToolBar toolbarModel = (MToolBar) event.getProperty(UIEvents.EventTags.ELEMENT); ToolBarManager parentManager = getManager(toolbarModel); if (parentManager == null) { return; } if (UIEvents.isADD(event)) { for (Object o : UIEvents.asIterable(event, UIEvents.EventTags.NEW_VALUE)) { MToolBarElement added = (MToolBarElement) o; modelProcessSwitch(parentManager, added); } } else if (UIEvents.isREMOVE(event)) { for (Object o : UIEvents.asIterable(event, UIEvents.EventTags.OLD_VALUE)) { MToolBarElement removed = (MToolBarElement) o; disposeToolBarElement(parentManager, removed); } } else if (UIEvents.isMOVE(event)) { Object oldPos = event.getProperty(UIEvents.EventTags.OLD_VALUE); Object newPos = event.getProperty(UIEvents.EventTags.POSITION); IContributionItem ici = parentManager.getItems()[(Integer) oldPos]; parentManager.remove(ici); parentManager.insert((Integer) newPos, ici); } parentManager.update(true); ToolBar toolbar = getToolbarFrom(toolbarModel.getWidget()); if (toolbar != null) { toolbar.requestLayout(); } }

Target:
private void subscribeTopicUpdateChildren(@UIEventTopic(ElementContainer.TOPIC_CHILDREN) Event event) { if (!(event.getProperty(UIEvents.EventTags.ELEMENT) instanceof MToolBar)) { return; } MToolBar toolbarModel = (MToolBar) event.getProperty(UIEvents.EventTags.ELEMENT); ToolBarManager parentManager = getManager(toolbarModel); if (parentManager == null) { return; } if (UIEvents.isADD(event)) { for (Object o : UIEvents.asIterable(event, UIEvents.EventTags.NEW_VALUE)) { MToolBarElement added = (MToolBarElement) o; modelProcessSwitch(parentManager, added); } updateWidget(parentManager); } else if (UIEvents.isREMOVE(event)) { for (Object o : UIEvents.asIterable(event, UIEvents.EventTags.OLD_VALUE)) { MToolBarElement removed = (MToolBarElement) o; disposeToolBarElement(parentManager, removed); } updateWidget(parentManager); } else if (UIEvents.isMOVE(event)) { Object oldPos = event.getProperty(UIEvents.EventTags.OLD_VALUE); Object newPos = event.getProperty(UIEvents.EventTags.POSITION); IContributionItem ici = parentManager.getItems()[(Integer) oldPos]; parentManager.remove(ici); parentManager.insert((Integer) newPos, ici); updateWidget(parentManager); } }
Source:
public void deleteAllergy(RestApi restApi, String patientUuid, String allergyUuid, DefaultResponseCallback callback) { if (NetworkUtils.isOnline()) { restApi.deleteAllergy(patientUuid, allergyUuid).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) { allergyRoomDAO.deleteAllergyByUUID(allergyUuid); ToastUtil.success(OpenMRS.getInstance().getString(R.string.delete_allergy_success)); callback.onResponse(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callback.onErrorResponse(OpenMRS.getInstance().getString(R.string.delete_allergy_failure)); } }); } else { Data data = new Data.Builder() .putString("patient_uuid", patientUuid) .putString("allergy_uuid", allergyUuid) .build(); allergyRoomDAO.deleteAllergyByUUID(allergyUuid); callback.onResponse(); Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build(); workManager.enqueue(new OneTimeWorkRequest.Builder(DeleteAllergyWorker.class).setConstraints(constraints).setInputData(data).build()); ToastUtil.notify(OpenMRS.getInstance().getString(R.string.delete_allergy_offline)); } }

Target:
public void deleteAllergy(RestApi restApi, String patientUuid, String allergyUuid, DefaultResponseCallback callback) { if (NetworkUtils.isOnline()) { restApi.deleteAllergy(patientUuid, allergyUuid).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) { allergyRoomDAO.deleteAllergyByUUID(allergyUuid); ToastUtil.success(OpenMRS.getInstance().getString(R.string.delete_allergy_success)); callback.onResponse(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { callback.onErrorResponse(OpenMRS.getInstance().getString(R.string.delete_allergy_failure)); } }); } else { Data data = new Data.Builder() .putString(PATIENT_UUID, patientUuid) .putString(ALLERGY_UUID, allergyUuid) .build(); allergyRoomDAO.deleteAllergyByUUID(allergyUuid); callback.onResponse(); Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build(); workManager.enqueue(new OneTimeWorkRequest.Builder(DeleteAllergyWorker.class).setConstraints(constraints).setInputData(data).build()); ToastUtil.notify(OpenMRS.getInstance().getString(R.string.delete_allergy_offline)); } }
Source:
public Response move(Action action) { validateParameters(action, "storageDomain.id|name"); MoveDisksParameters params = new MoveDisksParameters(Collections.singletonList(new MoveDiskParameters( asGuid(get().getImageId()), Guid.Empty, getStorageDomainId(action)))); return doAction(VdcActionType.MoveDisks, params, action); }

Target:
public Response move(Action action) { validateParameters(action, "storageDomain.id|name"); MoveDisksParameters params = new MoveDisksParameters(Collections.singletonList(new MoveDiskParameters( asGuid(getDisk().getImageId()), Guid.Empty, getStorageDomainId(action)))); return doAction(VdcActionType.MoveDisks, params, action); }
Source:
public SchemaMetadata getSchemaMetadata() { ImmutableSchemaMetadata.Builder builder = ImmutableSchemaMetadata.builder(); Map<TableReference, SchemaDependentTableMetadata> tableMetadatas = Stream.of(tempTableDefinitions, tableDefinitions, indexDefinitions) .map(Map::keySet) .map(Set::stream) .flatMap(x -> x) .collect(Collectors.toMap( tableName -> TableReference.create(namespace, tableName), this::constructSchemaDependentTableMetadata)); builder.putAllSchemaDependentTableMetadata(tableMetadatas); return builder.build(); }

Target:
public SchemaMetadata getSchemaMetadata() { ImmutableSchemaMetadata.Builder builder = ImmutableSchemaMetadata.builder(); Map<TableReference, SchemaDependentTableMetadata> tableMetadatas = Stream.of(tableDefinitions, indexDefinitions) .map(Map::keySet) .map(Set::stream) .flatMap(x -> x) .collect(Collectors.toMap( tableName -> TableReference.create(namespace, tableName), this::constructSchemaDependentTableMetadata)); builder.putAllSchemaDependentTableMetadata(tableMetadatas); return builder.build(); }
Source:
private static Set<String> getWorkerNodeIDs(Collection<Worker> workers, WorkerBehaviorConfig workerConfig) { return Sets.<String>newHashSet(workerConfig.getAutoScaler().ipToIdLookup( Lists.newArrayList( Iterables.transform( workers, new Function<Worker, String>() { @Override public String apply(Worker input) { return input.getIp(); } } ) ) )); }

Target:
private static Collection<String> getWorkerNodeIDs(Collection<Worker> workers, WorkerBehaviorConfig workerConfig) { return workerConfig.getAutoScaler().ipToIdLookup( Lists.newArrayList( Iterables.transform( workers, new Function<Worker, String>() { @Override public String apply(Worker input) { return input.getIp(); } } ) ) ); }
Source:
public LogicalNode visitProjection(GlobalPlanContext context, LogicalPlan plan, LogicalPlan.QueryBlock block, ProjectionNode node, Stack<LogicalNode> stack) throws TajoException { LogicalNode child = super.visitProjection(context, plan, block, node, stack); ExecutionBlock execBlock = context.execBlockMap.remove(child.getPID()); if (child.getType() == NodeType.TABLE_SUBQUERY && ((TableSubQueryNode)child).getSubQuery().getType() == NodeType.UNION) { MasterPlan masterPlan = context.plan; for (DataChannel dataChannel : masterPlan.getIncomingChannels(execBlock.getId())) { dataChannel.setStoreType(BuiltinStorages.DRAW); ExecutionBlock subBlock = masterPlan.getExecBlock(dataChannel.getSrcId()); ProjectionNode copy = PlannerUtil.clone(plan, node); copy.setChild(subBlock.getPlan()); subBlock.setPlan(copy); } execBlock.setPlan(null); } else { node.setChild(execBlock.getPlan()); node.setInSchema(execBlock.getPlan().getOutSchema()); execBlock.setPlan(node); } context.execBlockMap.put(node.getPID(), execBlock); return node; }

Target:
public LogicalNode visitProjection(GlobalPlanContext context, LogicalPlan plan, LogicalPlan.QueryBlock block, ProjectionNode node, Stack<LogicalNode> stack) throws TajoException { LogicalNode child = super.visitProjection(context, plan, block, node, stack); ExecutionBlock execBlock = context.execBlockMap.remove(child.getPID()); if (child.getType() == NodeType.TABLE_SUBQUERY && ((TableSubQueryNode)child).getSubQuery().getType() == NodeType.UNION) { MasterPlan masterPlan = context.plan; for (DataChannel dataChannel : masterPlan.getIncomingChannels(execBlock.getId())) { dataChannel.setStoreType(finalOutputStoreType); ExecutionBlock subBlock = masterPlan.getExecBlock(dataChannel.getSrcId()); ProjectionNode copy = PlannerUtil.clone(plan, node); copy.setChild(subBlock.getPlan()); subBlock.setPlan(copy); } execBlock.setPlan(null); } else { node.setChild(execBlock.getPlan()); node.setInSchema(execBlock.getPlan().getOutSchema()); execBlock.setPlan(node); } context.execBlockMap.put(node.getPID(), execBlock); return node; }
Source:
private boolean canHandle(DataObject dataObject) { DataStore dataStore = dataObject.getDataStore(); if (dataStore.getRole() == DataStoreRole.Primary) { Map<String, String> mapCapabilities = dataStore.getDriver().getCapabilities(); if (mapCapabilities == null) { return false; } if (dataObject instanceof VolumeInfo || dataObject instanceof SnapshotInfo) { String value = mapCapabilities.get(DataStoreCapabilities.STORAGE_SYSTEM_SNAPSHOT.toString()); Boolean supportsStorageSystemSnapshots = new Boolean(value); if (supportsStorageSystemSnapshots) { s_logger.info("Using 'StorageSystemDataMotionStrategy'"); return true; } } else if (dataObject instanceof TemplateInfo) { String value = mapCapabilities.get(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString()); Boolean canCloneVolume = new Boolean(value); if (canCloneVolume) { s_logger.info("Using 'StorageSystemDataMotionStrategy'"); return true; } } } return false; }

Target:
private boolean canHandle(DataObject dataObject) { Preconditions.checkArgument(dataObject != null, "Passing 'null' to dataObject of canHandle(DataObject) is not supported."); DataStore dataStore = dataObject.getDataStore(); if (dataStore.getRole() == DataStoreRole.Primary) { Map<String, String> mapCapabilities = dataStore.getDriver().getCapabilities(); if (mapCapabilities == null) { return false; } if (dataObject instanceof VolumeInfo || dataObject instanceof SnapshotInfo) { String value = mapCapabilities.get(DataStoreCapabilities.STORAGE_SYSTEM_SNAPSHOT.toString()); Boolean supportsStorageSystemSnapshots = Boolean.valueOf(value); if (supportsStorageSystemSnapshots) { LOGGER.info("Using 'StorageSystemDataMotionStrategy' (dataObject is a volume or snapshot and the storage system supports snapshots)"); return true; } } else if (dataObject instanceof TemplateInfo) { String value = mapCapabilities.get(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString()); Boolean canCloneVolume = Boolean.valueOf(value); if (canCloneVolume) { LOGGER.info("Using 'StorageSystemDataMotionStrategy' (dataObject is a template and the storage system can create a volume from a volume)"); return true; } } } return false; }
Source:
public Serializer getImplementation() { Serializer obj; try { obj = implementationClass.getDeclaredConstructor().newInstance(); } catch (NoSuchMethodException e) { throw new NuxeoException("Serializer Contribution NoDefaultConstructorDefined: " + name, e); } catch (IllegalAccessException e) { throw new NuxeoException("Serializer Contribution DefaultConstructorHidden: " + name, e); } catch (InstantiationException | InvocationTargetException e) { throw new NuxeoException("Serializer Contribution ErrorOnInstanciation: " + name, e); } return obj; }

Target:
public Serializer getImplementation() { Serializer obj; try { obj = implementationClass.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new NuxeoException("Serializer Contribution Exception on Serializer construction: " + name, e); } return obj; }
Source:
private static String extractTargetRelease(Map<String, FlagStatus> streamStatus) { return (streamStatus != null && streamStatus.size() > 0) ? streamStatus.keySet().iterator().next() : ""; }

Target:
private static String extractTargetRelease(Map<String, FlagStatus> streamStatus) { return (streamStatus.size() > 0) ? streamStatus.keySet().iterator().next() : ""; }
Source:
private List<Package> getPackages(final boolean includeDefaultPackage, final Set<Package> pkgs) { final List<Package> sortedPackages = new ArrayList<>(); sortedPackages.addAll(pkgs); Collections.sort(sortedPackages, (p1, p2) -> p1.getCaption().compareTo(p2.getCaption())); if (!includeDefaultPackage) { sortedPackages.remove(0); } return sortedPackages; }

Target:
private List<Package> getPackages(final boolean includeDefaultPackage, final Set<Package> pkgs) { final List<Package> sortedPackages = new ArrayList<>(pkgs); Collections.sort(sortedPackages, (p1, p2) -> p1.getCaption().compareTo(p2.getCaption())); if (!includeDefaultPackage && !sortedPackages.isEmpty() && "".equals(sortedPackages.get(0).getPackageName())) { sortedPackages.remove(0); } return sortedPackages; }
Source:
static Predicate<ServerLocation> onlyAir() { return Sponge.getRegistry().getFactoryRegistry().provideFactory(Factory.class).onlyAir(); }

Target:
static Predicate<LocatableBlock> onlyAir() { return Sponge.getRegistry().getFactoryRegistry().provideFactory(Factory.class).onlyAir(); }
Source:
private boolean addExistingMediaToEditor(@NonNull AddExistingdMediaSource source, List<Long> mediaIdList) { ArrayMap<String, MediaFile> mediaMap = new ArrayMap<>(); for (Long mediaId : mediaIdList) { MediaModel media = mMediaStore.getSiteMediaWithId(mSite, mediaId); if (media == null) { AppLog.w(T.MEDIA, "Cannot add null media to post"); return false; } trackAddMediaEvent(source, media); MediaFile mediaFile = FluxCUtils.mediaFileFromMediaModel(media); String urlToUse = TextUtils.isEmpty(media.getUrl()) ? media.getFilePath() : media.getUrl(); mediaMap.put(urlToUse, mediaFile); } mEditorFragment.appendMediaFiles(mediaMap); return true; }

Target:
private void addExistingMediaToEditor(@NonNull AddExistingdMediaSource source, List<Long> mediaIdList) { ArrayMap<String, MediaFile> mediaMap = new ArrayMap<>(); for (Long mediaId : mediaIdList) { MediaModel media = mMediaStore.getSiteMediaWithId(mSite, mediaId); if (media == null) { AppLog.w(T.MEDIA, "Cannot add null media to post"); } else { trackAddMediaEvent(source, media); MediaFile mediaFile = FluxCUtils.mediaFileFromMediaModel(media); String urlToUse = TextUtils.isEmpty(media.getUrl()) ? media.getFilePath() : media.getUrl(); mediaMap.put(urlToUse, mediaFile); } } mEditorFragment.appendMediaFiles(mediaMap); }
Source:
public void put(final Feature feature) { final PutItemRequest putItemRequest = new PutItemRequest(); putItemRequest.withTableName(tableName) .addItemEntry("ns",new AttributeValue().withS(namespace)) .addItemEntry("name", new AttributeValue().withS(feature.name)) .addItemEntry("value", new AttributeValue().withS(feature.serialize())); amazonDynamoDB.putItem(putItemRequest); }

Target:
public void put(final Feature feature) { final PutItemRequest putItemRequest = new PutItemRequest(); putItemRequest.withTableName(tableName) .addItemEntry(NAMESPACE_ATTRIBUTE_NAME,new AttributeValue().withS(namespace)) .addItemEntry(NAME_ATTRIBUTE_NAME, new AttributeValue().withS(feature.name)) .addItemEntry(VALUE_ATTRIBUTE_NAME, new AttributeValue().withS(feature.serialize())); amazonDynamoDB.putItem(putItemRequest); }
Source:
private List<Object[]> convertIntegerToLong(List<Object[]> list, int index) { for (Object[] item : list) { item[index] = new Long((long) item[index]); } return list; }

Target:
private List<Object[]> convertIntegerToLong(List<Object[]> list, int index) { for (Object[] item : list) { item[index] = (long) item[index]; } return list; }
Source:
public void testFetchUnreachableBlobWithBitmap() throws Exception { RevBlob blob = remote.blob("foo"); RevCommit commit = remote.commit(remote.tree(remote.file("foo", blob))); generateBitmaps(server); testProtocol = new TestProtocol<>( new UploadPackFactory<Object>() { @Override public UploadPack create(Object req, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { UploadPack up = new UploadPack(db); up.setRequestPolicy(RequestPolicy.REACHABLE_COMMIT); return up; } }, null); uri = testProtocol.register(ctx, server); assertFalse(client.hasObject(blob.toObjectId())); try (Transport tn = testProtocol.open(uri, client, "server")) { tn.fetch(NullProgressMonitor.INSTANCE, Collections.singletonList(new RefSpec(blob.name()))); fail("expected TransportException"); } catch (TransportException exception) { assertTrue(exception.getMessage().contains("want " + blob.name() + " not valid")); } }

Target:
public void testFetchUnreachableBlobWithBitmap() throws Exception { RevBlob blob = remote.blob("foo"); RevCommit commit = remote.commit(remote.tree(remote.file("foo", blob))); generateBitmaps(server); testProtocol = generateReachableCommitUploadPackProtocol(); uri = testProtocol.register(ctx, server); assertFalse(client.hasObject(blob.toObjectId())); thrown.expect(TransportException.class); thrown.expectMessage(Matchers.containsString("want " + blob.name() + " not valid")); try (Transport tn = testProtocol.open(uri, client, "server")) { tn.fetch(NullProgressMonitor.INSTANCE, Collections.singletonList(new RefSpec(blob.name()))); } }
Source:
public void launch(ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { this.config = config; Oprofile.OprofileProject.setProject(getProject()); LaunchOptions options = new LaunchOptions(); options.loadConfiguration(config); IPath exePath = getExePath(config); options.setBinaryImage(exePath.toOSString()); OprofileDaemonEvent[] daemonEvents = null; if (!config.getAttribute(OprofileLaunchPlugin.ATTR_USE_DEFAULT_EVENT, false)) { OprofileCounter[] counters = oprofileCounters(config); ArrayList<OprofileDaemonEvent> events = new ArrayList<OprofileDaemonEvent>(); for (int i = 0; i < counters.length; ++i) { if (counters[i].getEnabled()) events.add(counters[i].getDaemonEvent()); } daemonEvents = new OprofileDaemonEvent[events.size()]; events.toArray(daemonEvents); } if (!preExec(options, daemonEvents, launch)) return; IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(oprofileProject()); IPath workingDirPath = new Path(oprofileWorkingDirURI().getPath()); String arguments[] = getProgramArgumentsArray( config ); Process process = null; for(int i = 0; i < options.getExecutionsNumber(); i++){ process = launcher.execute(exePath, arguments, getEnvironment(config), workingDirPath, monitor); DebugPlugin.newProcess( launch, process, renderProcessLabel( exePath.toOSString() ) ); try{ process.waitFor(); } catch (InterruptedException e){ e.printStackTrace(); } } postExec(options, daemonEvents, process); }

Target:
public void launch(ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { this.config = config; Oprofile.OprofileProject.setProject(getProject()); LaunchOptions options = new LaunchOptions(); options.loadConfiguration(config); IPath exePath = getExePath(config); options.setBinaryImage(exePath.toOSString()); OprofileDaemonEvent[] daemonEvents = null; if (!config.getAttribute(OprofileLaunchPlugin.ATTR_USE_DEFAULT_EVENT, false)) { OprofileCounter[] counters = oprofileCounters(config); ArrayList<OprofileDaemonEvent> events = new ArrayList<OprofileDaemonEvent>(); for (int i = 0; i < counters.length; ++i) { if (counters[i].getEnabled()) events.add(counters[i].getDaemonEvent()); } daemonEvents = new OprofileDaemonEvent[events.size()]; events.toArray(daemonEvents); } if (!preExec(options, daemonEvents, launch)) return; IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(oprofileProject()); IPath workingDirPath = new Path(oprofileWorkingDirURI().getPath()); String arguments[] = getProgramArgumentsArray( config ); Process process = null; for(int i = 0; i < options.getExecutionsNumber(); i++){ process = launcher.execute(exePath, arguments, getEnvironment(config), workingDirPath, monitor); DebugPlugin.newProcess( launch, process, renderProcessLabel( exePath.toOSString() ) ); try{ process.waitFor(); } catch (InterruptedException e){ process.destroy(); Status status = new Status(IStatus.ERROR, OprofileLaunchPlugin.PLUGIN_ID, OprofileLaunchMessages.getString("oprofilelaunch.error.interrupted_error.status_message")); throw new CoreException(status); } } postExec(options, daemonEvents, process); }
Source:
public static VirtualDevice prepareNicOpaque(VirtualMachineMO vmMo, VirtualEthernetCardType deviceType, String portGroupName, String macAddress, int deviceNumber, int contextNumber, boolean conntected, boolean connectOnStart) throws Exception { assert(vmMo.getRunningHost().hasOpaqueNSXNetwork()); VirtualEthernetCard nic; switch (deviceType) { case E1000: nic = new VirtualE1000(); break; case PCNet32: nic = new VirtualPCNet32(); break; case Vmxnet2: nic = new VirtualVmxnet2(); break; case Vmxnet3: nic = new VirtualVmxnet3(); break; default: assert (false); nic = new VirtualE1000(); } VirtualEthernetCardOpaqueNetworkBackingInfo nicBacking = new VirtualEthernetCardOpaqueNetworkBackingInfo(); nicBacking.setOpaqueNetworkId("br-int"); nicBacking.setOpaqueNetworkType("nsx.network"); nic.setBacking(nicBacking); VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); connectInfo.setAllowGuestControl(true); connectInfo.setConnected(conntected); connectInfo.setStartConnected(connectOnStart); nic.setAddressType("Manual"); nic.setConnectable(connectInfo); nic.setMacAddress(macAddress); nic.setUnitNumber(deviceNumber); nic.setKey(-contextNumber); return nic; }

Target:
public static VirtualDevice prepareNicOpaque(VirtualMachineMO vmMo, VirtualEthernetCardType deviceType, String portGroupName, String macAddress, int deviceNumber, int contextNumber, boolean conntected, boolean connectOnStart) throws Exception { assert(vmMo.getRunningHost().hasOpaqueNSXNetwork()); VirtualEthernetCard nic; switch (deviceType) { case E1000: nic = new VirtualE1000(); break; case PCNet32: nic = new VirtualPCNet32(); break; case Vmxnet2: nic = new VirtualVmxnet2(); break; case Vmxnet3: nic = new VirtualVmxnet3(); break; default: nic = new VirtualE1000(); } VirtualEthernetCardOpaqueNetworkBackingInfo nicBacking = new VirtualEthernetCardOpaqueNetworkBackingInfo(); nicBacking.setOpaqueNetworkId("br-int"); nicBacking.setOpaqueNetworkType("nsx.network"); nic.setBacking(nicBacking); VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); connectInfo.setAllowGuestControl(true); connectInfo.setConnected(conntected); connectInfo.setStartConnected(connectOnStart); nic.setAddressType("Manual"); nic.setConnectable(connectInfo); nic.setMacAddress(macAddress); nic.setUnitNumber(deviceNumber); nic.setKey(-contextNumber); return nic; }
Source:
private static void checkPropertyTester(IProject project, String fileName, boolean javaExpected) throws PartInitException{ if(!project.exists()){ fail("project does not exist"); } IFile file = project.getFile(fileName); IEditorPart editor = null; if (file.exists()) { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); editor = IDE.openEditor(page, file); }else{ fail("File - "+file.getFullPath()+" not found"); } NaturePropertyTester tester = new NaturePropertyTester(); boolean result = tester.test(editor, NaturePropertyTester.PROPERTY_NAME, null, "org.eclipse.jdt.core.javanature"); assertEquals("Wrong nature detection for project -"+project.getName(), javaExpected, result); }

Target:
private static void checkPropertyTester(IProject project, String fileName, boolean javaExpected) throws PartInitException{ assertTrue("project does not exist", project.exists()); IFile file = project.getFile(fileName); assertTrue("File - "+file.getFullPath()+" not found", file.exists()); IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IEditorPart editor = IDE.openEditor(page, file); NaturePropertyTester tester = new NaturePropertyTester(); boolean result = tester.test(editor, NaturePropertyTester.PROPERTY_NAME, null, "org.eclipse.jdt.core.javanature"); assertEquals("Wrong nature detection for project -"+project.getName(), javaExpected, result); }
Source:
private String getPackageName(DotName name) { String packageName; if (name.isComponentized()) { packageName = name.prefix().toString(); } else { packageName = name.local().substring(0, name.local().lastIndexOf(".")); } return packageName; }

Target:
private String getPackageName(DotName name) { if (name.isComponentized()) { return name.prefix().toString(); } else { return name.local().substring(0, name.local().lastIndexOf(".")); } }
Source:
public UnhandledServerException(String exceptionMessage) { super(Response.Status.UNSUPPORTED_MEDIA_TYPE, String.format(MESSAGE, exceptionMessage)); }

Target:
public UnhandledServerException(String exceptionMessage) { super(Response.Status.INTERNAL_SERVER_ERROR, String.format(MESSAGE, exceptionMessage)); }
Source:
public static Integer parsePageNum(String searchStr) { if (searchStr.toLowerCase().indexOf("page ") == -1) { return null; } else { int pos = searchStr.toLowerCase().indexOf("page ") + 5; StringBuilder pageNumberStr = new StringBuilder(); char c = searchStr.charAt(pos); while (Character.isDigit(c) && pos < searchStr.length()) { pageNumberStr.append(c); pos += 1; if (pos < searchStr.length()) { c = searchStr.charAt(pos); } } int pageNum = pageNumberStr.length()==0 ? 1 : Integer.valueOf(pageNumberStr.toString()); return pageNum; } }

Target:
public static Integer parsePageNum(String searchStr) { if (searchStr.toLowerCase().indexOf("page ") == -1) { return null; } else { int pos = searchStr.toLowerCase().indexOf("page ") + 5; StringBuilder pageNumberStr = new StringBuilder(); char c = searchStr.charAt(pos); while (Character.isDigit(c) && pos < searchStr.length()) { pageNumberStr.append(c); pos += 1; if (pos < searchStr.length()) { c = searchStr.charAt(pos); } } int pageNum = pageNumberStr.length() == 0 ? 1 : Integer.parseInt(pageNumberStr.toString()); return pageNum; } }
Source:
public ExtensionCallback() { super(NAME); proxyServer = new ProxyServer("ZAP-CallbackServer"); proxyServer .addOverrideMessageProxyListener(new CallbackProxyListener()); }

Target:
public ExtensionCallback() { proxyServer = new ProxyServer("ZAP-CallbackServer"); proxyServer .addOverrideMessageProxyListener(new CallbackProxyListener()); }
Source:
private CuEinvoiceDao getCuEinvoiceDao() { if (ObjectUtils.isNull(null)) { cuEinvoiceDao = SpringContext.getBean(CuEinvoiceDaoOjb.class); } return cuEinvoiceDao; }

Target:
private CuEinvoiceDao getCuEinvoiceDao() { if (ObjectUtils.isNull(cuEinvoiceDao)) { cuEinvoiceDao = SpringContext.getBean(CuEinvoiceDaoOjb.class); } return cuEinvoiceDao; }
Source:
public void pingResultIsJavaSerializable() throws IOException, ClassNotFoundException { OrderableSlsVersion timeLockVersion = OrderableSlsVersion.valueOf("0.0.0"); PingResult pr = PingResult.builder().timeLockVersion(timeLockVersion) .isLeader(true).build(); FileOutputStream fileOut = new FileOutputStream("test.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(pr); out.close(); fileOut.close(); FileInputStream fileIn = new FileInputStream("test.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); PingResult deserializedPingResult = (PingResult) in.readObject(); in.close(); fileIn.close(); assertThat(deserializedPingResult.isLeader()).isEqualTo(true); assertThat(deserializedPingResult.timeLockVersion()).isEqualTo(Optional.of(timeLockVersion)); }

Target:
public void pingResultIsJavaSerializable() throws IOException, ClassNotFoundException { OrderableSlsVersion timeLockVersion = OrderableSlsVersion.valueOf("0.27.0"); PingResult pr = PingResult.builder().timeLockVersion(timeLockVersion) .isLeader(true).build(); File file = tempFolder.newFile(); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) { out.writeObject(pr); } try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) { PingResult deserializedPingResult = (PingResult) in.readObject(); assertThat(deserializedPingResult.isLeader()).isEqualTo(true); assertThat(deserializedPingResult.timeLockVersion()).isEqualTo(Optional.of(timeLockVersion)); } }
Source:
public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt.getCompoundTag("node")); sixNodeCacheBlock = Block.getBlockById(nbt.getInteger("cacheBlockId")); sixNodeCacheBlockMeta = nbt.getByte("cacheBlockMeta"); int idx; for (idx = 0; idx < 6; idx++) { short sideElementId = nbt.getShort("EID" + idx); if (sideElementId == 0) { sideElementList[idx] = null; sideElementIdList[idx] = 0; } else { try { SixNodeDescriptor descriptor = Eln.sixNodeItem.getDescriptor(sideElementId); sideElementIdList[idx] = sideElementId; sideElementList[idx] = (SixNodeElement) descriptor.ElementClass.getConstructor(SixNode.class, Direction.class, SixNodeDescriptor.class).newInstance(this, Direction.fromInt(idx), descriptor); sideElementList[idx].readFromNBT(nbt.getCompoundTag("ED" + idx)); sideElementList[idx].initialize(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } } initializeFromNBT(); }

Target:
public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt.getCompoundTag("node")); sixNodeCacheBlock = Block.getBlockById(nbt.getInteger("cacheBlockId")); sixNodeCacheBlockMeta = nbt.getByte("cacheBlockMeta"); int idx; for (idx = 0; idx < 6; idx++) { short sideElementId = nbt.getShort("EID" + idx); if (sideElementId == 0) { sideElementList[idx] = null; sideElementIdList[idx] = 0; } else { try { SixNodeDescriptor descriptor = null; sideElementIdList[idx] = sideElementId; sideElementList[idx] = (SixNodeElement) descriptor.ElementClass.getConstructor(SixNode.class, Direction.class, SixNodeDescriptor.class).newInstance(this, Direction.fromInt(idx), descriptor); sideElementList[idx].readFromNBT(nbt.getCompoundTag("ED" + idx)); sideElementList[idx].initialize(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } } initializeFromNBT(); }
Source:
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException { if (uri == null) { if (defaultAudience != null) { uri = defaultAudience; } else { throw new IOException("JwtAccess requires Audience uri to be passed in or the " + "defaultAudience to be specified"); } } String assertion = getJwtAccess(uri); Map<String, List<String>> newRequestMetadata = new HashMap<String, List<String>>(); List<String> newAuthorizationHeaders = new ArrayList<String>(); String authorizationHeader = "Bearer #" + assertion; newAuthorizationHeaders.add(authorizationHeader); newRequestMetadata.put("Authorization", newAuthorizationHeaders); return newRequestMetadata; }

Target:
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException { if (uri == null) { if (defaultAudience != null) { uri = defaultAudience; } else { throw new IOException("JwtAccess requires Audience uri to be passed in or the " + "defaultAudience to be specified"); } } String assertion = getJwtAccess(uri); String authorizationHeader = "Bearer #" + assertion; List<String> newAuthorizationHeaders = Collections.singletonList(authorizationHeader); Map<String, List<String>> newRequestMetadata = Collections.singletonMap("Authorization", newAuthorizationHeaders); return newRequestMetadata; }
Source:
public void testStateLocationsWillBeReturnedIfExist() { final TaskManagerLocation stateLocation = new LocalTaskManagerLocation(); final TestingInputsLocationsRetriever.Builder locationRetrieverBuilder = new TestingInputsLocationsRetriever.Builder(); final ExecutionVertexID consumerId = new ExecutionVertexID(new JobVertexID(), 0); final ExecutionVertexID producerId = new ExecutionVertexID(new JobVertexID(), 0); locationRetrieverBuilder.connectConsumerToProducer(consumerId, producerId); final TestingInputsLocationsRetriever inputsLocationsRetriever = locationRetrieverBuilder.build(); inputsLocationsRetriever.markScheduled(producerId); final DefaultPreferredLocationsRetriever locationsRetriever = new DefaultPreferredLocationsRetriever( id -> Optional.of(stateLocation), inputsLocationsRetriever); final CompletableFuture<Collection<TaskManagerLocation>> preferredLocations = locationsRetriever.getPreferredLocations(consumerId, Collections.emptySet()); assertThat(preferredLocations.getNow(null), contains(stateLocation)); }

Target:
public void testStateLocationsWillBeReturnedIfExist() { final TaskManagerLocation stateLocation = new LocalTaskManagerLocation(); final TestingInputsLocationsRetriever.Builder locationRetrieverBuilder = new TestingInputsLocationsRetriever.Builder(); final ExecutionVertexID consumerId = new ExecutionVertexID(new JobVertexID(), 0); final ExecutionVertexID producerId = new ExecutionVertexID(new JobVertexID(), 0); locationRetrieverBuilder.connectConsumerToProducer(consumerId, producerId); final TestingInputsLocationsRetriever inputsLocationsRetriever = locationRetrieverBuilder.build(); inputsLocationsRetriever.markScheduled(producerId); final PreferredLocationsRetriever locationsRetriever = new DefaultPreferredLocationsRetriever( id -> Optional.of(stateLocation), inputsLocationsRetriever); final CompletableFuture<Collection<TaskManagerLocation>> preferredLocations = locationsRetriever.getPreferredLocations(consumerId, Collections.emptySet()); assertThat(preferredLocations.getNow(null), contains(stateLocation)); }
Source:
protected List<String> getLocales(File manualDir) { List<String> locales = new ArrayList<>(); if (!manualDir.exists() || !manualDir.canRead()) { log.error("manual directory doesn't exist: " + manualDir); return locales; } for (File dir : manualDir.listFiles()) { if (dir.isDirectory() && dir.canRead()) { String name = dir.getName(); if (name.length() == 5 && name.indexOf("-") == 2) { locales.add(name); } } } return locales; }

Target:
protected List<String> getLocales(File manualDir) { List<String> locales = new ArrayList<>(); if (!manualDir.exists() || !manualDir.canRead()) { log.error("manual directory doesn't exist: " + manualDir); return locales; } for (File dir : manualDir.listFiles()) { if (dir.isDirectory() && dir.canRead()) { String name = dir.getName(); Matcher m = LOCALE_PATTERN.matcher(name); if (m.matches()) { locales.add(name); } } } return locales; }
Source:
public OpenShiftClient create() { return new DefaultOpenShiftClient(configBuilder.build()); }

Target:
public OpenShiftClient create() { return new DefaultOpenShiftClient(config); }
Source:
public Expression getComputedNameExpression() { return spelExpressionParser.parseExpression(nameExpression != null ? nameExpression : ("'" + name + "'")); }

Target:
public Expression getComputedNameExpression() { return (nameExpression != null ? nameExpression : new LiteralExpression(name)); }