auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void saveStateShouldBeSuccessSaving() { given(modelMapper.map(stateDTO, StateEntity.class)).willReturn(stateEntity); given(applicationsRepository.findOne(FIRST_ID)).willReturn(applicationEntity); given(statesRepository.save(stateEntity)).willReturn(stateEntity); Long expectedId = statesService.saveState(stateDTO, FIRST_ID); assertThat(stateEntity, notNullValue()); assertThat(stateEntity.getCreationDate(), greaterThanOrEqualTo(now)); assertThat(stateEntity.getApplicationEntity(), equalTo(applicationEntity)); assertThat(stateEntity.getId(), equalTo(expectedId)); then(applicationsRepository).should((times(AT_ONE_TIME))).findOne(FIRST_ID); then(statesRepository).should(times(AT_ONE_TIME)).save(stateEntity); }

Target:
public void saveStateShouldBeSuccessSaving() { given(modelMapper.map(stateDTO, StateEntity.class)).willReturn(firstStateEntity); given(applicationsRepository.findOne(SECOND_ID)).willReturn(secondApplicationEntity); given(statesRepository.save(firstStateEntity)).willReturn(firstStateEntity); Long resultId = statesService.saveState(stateDTO, SECOND_ID); assertStateEntityWhenSavingStateEntity(firstStateEntity, savedStateEntity); assertThat(resultId, notNullValue()); assertThat(resultId, equalTo(FIRST_ID)); then(applicationsRepository).should().findOne(SECOND_ID); then(statesRepository).should().save(firstStateEntity); }
Source:
public BPMNDiagram getBpmnDiagram() { BPMNDiagram bpmnDiagram = di.createBPMNDiagram(); bpmnDiagram.setId(process.getId()); BPMNPlane bpmnPlane = di.createBPMNPlane(); bpmnDiagram.setPlane(bpmnPlane); List<DiagramElement> planeElement = bpmnPlane.getPlaneElement(); childElements.values().forEach(p -> { BPMNShape shape = p.getShape(); BPMNEdge edge = p.getEdge(); if (shape != null) { planeElement.add(shape); } if (edge != null) { planeElement.add(edge); } }); childElements.values().stream().flatMap(e -> e.getChildElements().stream()).forEach(p -> { BPMNShape shape = p.getShape(); BPMNEdge edge = p.getEdge(); if (shape != null) { planeElement.add(shape); } if (edge != null) { planeElement.add(edge); } }); return bpmnDiagram; }

Target:
public BPMNDiagram getBpmnDiagram() { bpmnDiagram.getPlane().setBpmnElement(process); return bpmnDiagram; }
Source:
public void testPrioritySequenceNumbers() throws Exception { final RemoteInputChannel channel = buildInputGateAndGetChannel(); sendBuffersAndBarrier(channel, 0); assertGetNextBufferSequenceNumbers(channel, 2, 0, 1, 3, 4); }

Target:
public void testPrioritySequenceNumbers() throws Exception { int sequenceNumber = 0; int bufferSize = 1; final RemoteInputChannel channel = buildInputGateAndGetChannel(sequenceNumber); sendBuffer(channel, sequenceNumber++, bufferSize++); sendBuffer(channel, sequenceNumber++, bufferSize++); sendBarrier(channel, sequenceNumber++, 0); sendBuffer(channel, sequenceNumber++, bufferSize++); sendBuffer(channel, sequenceNumber++, bufferSize++); assertGetNextBufferSequenceNumbers(channel, 2, 0, 1, 3, 4); }
Source:
public void testOnResultCalledInFragment() { FragmentStartedActivity_.intent(fragment).startForResult(AwaitingResultFragment.FIRST_REQUEST); ShadowActivity a = (ShadowActivity) ShadowExtractor.extract(fragment.getActivity()); a.receiveResult(FragmentStartedActivity_.intent(fragment).get(), Activity.RESULT_OK, new Intent()); assertThat(fragment.onResultCalled).isTrue(); }

Target:
public void testOnResultCalledInFragment() { FragmentStartedActivity_.intent(fragment).startForResult(AwaitingResultFragment.FIRST_REQUEST); ShadowActivity a = (ShadowActivity) extract(fragment.getActivity()); a.receiveResult(FragmentStartedActivity_.intent(fragment).get(), Activity.RESULT_OK, new Intent()); assertThat(fragment.onResultCalled).isTrue(); }
Source:
public void testCorrectBehaviourOfShortDescription() { final String id = "EOF"; final String shortDescription = TokenUtils.getShortDescription(id); assertNotNull(shortDescription); }

Target:
public void testCorrectBehaviourOfShortDescription() { final String id = "EOF"; final String shortDescription = TokenUtils.getShortDescription(id); assertEquals("The end of file token.", shortDescription); }
Source:
public void performSendAfterChecks() { currentMessageBuilder = createMessageBuilder(false); if (currentMessageBuilder != null) { changesMadeSinceLastSave = false; currentMessageBuilder.setHighPriority(isHighPriority); setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } }

Target:
public void performSendAfterChecks() { currentMessageBuilder = createMessageBuilder(false); if (currentMessageBuilder != null) { changesMadeSinceLastSave = false; setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } }
Source:
public boolean isEnsembleAdheringToPlacementPolicy(List<BookieSocketAddress> ensembleList, int writeQuorumSize, int ackQuorumSize) { int ensembleSize = ensembleList.size(); int minNumRacksPerWriteQuorumForThisEnsemble = Math.min(writeQuorumSize, minNumRacksPerWriteQuorum); HashSet<String> racksOrRegionsInQuorum = new HashSet<String>(); BookieSocketAddress bookie; for (int i = 0; i < ensembleList.size(); i++) { racksOrRegionsInQuorum.clear(); for (int j = 0; j < writeQuorumSize; j++) { bookie = ensembleList.get((ensembleSize + i + j) % ensembleSize); try { racksOrRegionsInQuorum.add(knownBookies.get(bookie).getNetworkLocation()); } catch (Exception e) { LOG.warn("Received exception while trying to get network location of bookie: {}", bookie, e); } } if (racksOrRegionsInQuorum.size() < minNumRacksPerWriteQuorumForThisEnsemble) { return false; } } return true; }

Target:
public boolean isEnsembleAdheringToPlacementPolicy(List<BookieSocketAddress> ensembleList, int writeQuorumSize, int ackQuorumSize) { int ensembleSize = ensembleList.size(); int minNumRacksPerWriteQuorumForThisEnsemble = Math.min(writeQuorumSize, minNumRacksPerWriteQuorum); HashSet<String> racksOrRegionsInQuorum = new HashSet<String>(); BookieSocketAddress bookie; for (int i = 0; i < ensembleList.size(); i++) { racksOrRegionsInQuorum.clear(); for (int j = 0; j < writeQuorumSize; j++) { bookie = ensembleList.get((i + j) % ensembleSize); try { racksOrRegionsInQuorum.add(knownBookies.get(bookie).getNetworkLocation()); } catch (Exception e) { LOG.warn("Received exception while trying to get network location of bookie: {}", bookie, e); } } if (racksOrRegionsInQuorum.size() < minNumRacksPerWriteQuorumForThisEnsemble) { return false; } } return true; }
Source:
public void createProjectFromXML_checkGoodName() throws Failure, IOException { final String badName = "calvin@jenkins"; final String xml = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<!DOCTYPE project[\n" + " <!ENTITY foo SYSTEM \"file:/ "]>\n" + "<project>\n" + " <actions/>\n" + " <description>&foo;</description>\n" + " <keepDependencies>false</keepDependencies>\n" + " <properties/>\n" + " <scm class=\"hudson.scm.NullSCM\"/>\n" + " <canRoam>true</canRoam>\n" + " <triggers/>\n" + " <builders/>\n" + " <publishers/>\n" + " <buildWrappers/>\n" + "</project>"; try { r.jenkins.createProjectFromXML(badName, new ByteArrayInputStream(xml.getBytes())); fail("@ is an unsafe character therefore creating a project named " + badName + " should have failed"); } catch (Failure x) { assertEquals(x.getMessage(), Messages.Hudson_UnsafeChar("@")); } }

Target:
public void createProjectFromXML_checkGoodName() throws Failure, IOException { final String badName = "calvin@jenkins"; final String xml = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<!DOCTYPE project[\n" + " <!ENTITY foo SYSTEM \"file:/ "]>\n" + "<project>\n" + " <actions/>\n" + " <description>&foo;</description>\n" + " <keepDependencies>false</keepDependencies>\n" + " <properties/>\n" + " <scm class=\"hudson.scm.NullSCM\"/>\n" + " <canRoam>true</canRoam>\n" + " <triggers/>\n" + " <builders/>\n" + " <publishers/>\n" + " <buildWrappers/>\n" + "</project>"; Failure exception = assertThrows(Failure.class, () -> { r.jenkins.createProjectFromXML(badName, new ByteArrayInputStream(xml.getBytes())); }); assertEquals(exception.getMessage(), Messages.Hudson_UnsafeChar("@")); }
Source:
public void onReceive(Context context, Intent intent) { ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conn.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { setWifiReceiverComponent(false, context); Intent serviceIntent = new Intent(context, KeyserverSyncAdapterService.class); serviceIntent.setAction(KeyserverSyncAdapterService.ACTION_UPDATE_ALL); context.startService(serviceIntent); } }

Target:
public void onReceive(Context context, Intent intent) { ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conn.getActiveNetworkInfo(); boolean isTypeWifi = (networkInfo.getType() == ConnectivityManager.TYPE_WIFI); boolean isConnected = networkInfo.isConnected(); if (isTypeWifi && isConnected) { setWifiReceiverComponent(false, context); Intent serviceIntent = new Intent(context, KeyserverSyncAdapterService.class); serviceIntent.setAction(KeyserverSyncAdapterService.ACTION_SYNC_NOW); context.startService(serviceIntent); } }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MifosBaseActivity) getActivity()).getActivityComponent().inject(this); if (getArguments() != null) { } if (savedInstanceState != null) { mSheet = (IndividualCollectionSheet) savedInstanceState.get( Constants.EXTRA_COLLECTION_INDIVIDUAL); showCollectionSheetViews(mSheet); } setHasOptionsMenu(true); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MifosBaseActivity) getActivity()).getActivityComponent().inject(this); if (savedInstanceState != null) { sheet = (IndividualCollectionSheet) savedInstanceState.get( Constants.EXTRA_COLLECTION_INDIVIDUAL); showCollectionSheetViews(sheet); } setHasOptionsMenu(true); }
Source:
public void setMessage (String message) { checkWidget (); if (message == null) error (SWT.ERROR_NULL_ARGUMENT); this.message = message; if (GTK.GTK_VERSION >= OS.VERSION (3, 4, 0)) { if ((style & SWT.SINGLE) != 0) { byte buffer = Converter.wcsToMbcs (message, true); GTK.gtk_entry_set_placeholder_text (handle, buffer); return; } } redraw (false); }

Target:
public void setMessage (String message) { checkWidget (); if (message == null) error (SWT.ERROR_NULL_ARGUMENT); this.message = message; if ((style & SWT.SINGLE) != 0) { byte buffer = Converter.wcsToMbcs (message, true); GTK.gtk_entry_set_placeholder_text (handle, buffer); return; } redraw (false); }
Source:
public boolean allGoalFilesExist() { boolean allExist = true; EntityPanel entityPanel = getController().getMainView().getMainPanel().getEntityPanel(); int numRows = entityPanel.getBotTableModel().getRowCount(); for(int i = 0; i < numRows && allExist; i++) { String goalFile = "" + entityPanel.getBotTable().getValueAt(i, 2); allExist = AgentFileChecker.fileNameExists(goalFile); } numRows = entityPanel.getEPartnerTableModel().getRowCount(); for(int i = 0; i < numRows && allExist; i++) { String goalFile = "" + entityPanel.getBotTable().getValueAt(i, 2); allExist = AgentFileChecker.fileNameExists(goalFile); } return allExist; }

Target:
public boolean allGoalFilesExist() { boolean allExist = true; BW4TClientConfig model = this.getModel(); List<BotConfig> botList = model.getBots(); for(int i = 0; i < botList.size() && allExist; i++) { allExist = allExist && AgentFileChecker.fileNameExists(botList.get(i).getFileName()); } List<EPartnerConfig> epartnerList = model.getEpartners(); for(int i = 0; i < epartnerList.size() && allExist; i++) { allExist = allExist && AgentFileChecker.fileNameExists(epartnerList.get(i).getFileName()); } return allExist; }
Source:
public T executeAsBlocking() { try { final GetResolver<T> getResolver; if (explicitGetResolver != null) { getResolver = explicitGetResolver; } else { final ContentResolverTypeMapping<T> typeMapping = storIOContentResolver.internal().typeMapping(type); if (typeMapping == null) { throw new IllegalStateException("This type does not have type mapping: " + "type = " + type + "," + "ContentProvider was not touched by this operation, please add type mapping for this type"); } getResolver = typeMapping.getResolver(); } final Cursor cursor = getResolver.performGet(storIOContentResolver, query); try { final int count = cursor.getCount(); if (count == 0) { return null; } cursor.moveToNext(); return getResolver.mapFromCursor(cursor); } finally { cursor.close(); } } catch (Exception exception) { throw new StorIOException(exception); } }

Target:
public T executeAsBlocking() { try { final GetResolver<T> getResolver; if (explicitGetResolver != null) { getResolver = explicitGetResolver; } else { final ContentResolverTypeMapping<T> typeMapping = storIOContentResolver.internal().typeMapping(type); if (typeMapping == null) { throw new IllegalStateException("This type does not have type mapping: " + "type = " + type + "," + "ContentProvider was not touched by this operation, please add type mapping for this type"); } getResolver = typeMapping.getResolver(); } final Cursor cursor = getResolver.performGet(storIOContentResolver, query); try { final int count = cursor.getCount(); if (count == 0) { return null; } cursor.moveToFirst(); return getResolver.mapFromCursor(cursor); } finally { cursor.close(); } } catch (Exception exception) { throw new StorIOException(exception); } }
Source:
public void human$setExhaustion(double exhaustion) { this.foodStats.foodExhaustionLevel = exhaustion; }

Target:
public void human$setExhaustion(double exhaustion) { this.getFoodStats().foodExhaustionLevel = (float) exhaustion; }
Source:
public <T extends Enum<?>> void setEnum(final String section, final String subsection, final String name, final T value) { String n = value.name().toLowerCase().replace('_', ' '); if (!value.name().equals(value.toString())) n = value.toString(); setString(section, subsection, name, n); }

Target:
public <T extends Enum<?>> void setEnum(final String section, final String subsection, final String name, final T value) { String n = value.name().toLowerCase().replace('_', ' '); if (value instanceof FastForwardMode) { n = ((FastForwardMode) value).toString(section, subsection, name); } setString(section, subsection, name, n); }
Source:
public void execute(String[] args, Console console) { if (args.length > 2) { String subCommand = args[0]; switch (subCommand) { case SUBCMD_LIST: listMetadata(console, args[1], args[2]); break; case SUBCMD_ADD: if (args.length < 4) { printUsage(console); } else { addMetadata(console, args[1], args[2], args[3], args.length > 4 ? Arrays.stream(args, 4, args.length).collect(Collectors.joining()) : null); } break; case SUBCMD_REMOVE: removeMetadata(console, args[1], args[2]); break; default: console.println("Unknown command '" + subCommand + "'"); printUsage(console); break; } } else { printUsage(console); } }

Target:
public void execute(String[] args, Console console) { if (args.length > 0) { String subCommand = args[0]; switch (subCommand) { case SUBCMD_LIST: listMetadata(console, args.length > 1 ? args[1] : null, args.length > 2 ? args[2] : null, false); break; case SUBCMD_LIST_INTERNAL: listMetadata(console, args.length > 1 ? args[1] : null, args.length > 2 ? args[2] : null, true); break; case SUBCMD_ADD: if (args.length < 4) { printUsage(console); } else { addMetadata(console, args[1], args[2], args[3], args.length > 4 ? args[4] : null); } break; case SUBCMD_REMOVE: removeMetadata(console, args[1], args.length > 2 ? args[2] : null); break; default: console.println("Unknown command '" + subCommand + "'"); printUsage(console); break; } } else { printUsage(console); } }
Source:
private String generateNextDemoCourseId(String instructorEmailOrProposedCourseId, int maximumIdLength){ final boolean isFirstCourseId = instructorEmailOrProposedCourseId.contains("@"); if(isFirstCourseId){ return new StringHelper().truncateHead(getDemoCourseIdRoot(instructorEmailOrProposedCourseId) , maximumIdLength); } else { final boolean isFirstTimeDuplicate = instructorEmailOrProposedCourseId.endsWith("-demo"); if(isFirstTimeDuplicate){ return new StringHelper().truncateHead(instructorEmailOrProposedCourseId + "0" , maximumIdLength); } else { final int lastIndexOfDemo = instructorEmailOrProposedCourseId.lastIndexOf("-demo"); final String root = instructorEmailOrProposedCourseId.substring(0, lastIndexOfDemo); final int previousDedupSuffix = Integer.parseInt(instructorEmailOrProposedCourseId.substring(lastIndexOfDemo + 5)); return new StringHelper().truncateHead(root + "-demo" + (previousDedupSuffix+1) , maximumIdLength); } } }

Target:
private String generateNextDemoCourseId(String instructorEmailOrProposedCourseId, int maximumIdLength){ final boolean isFirstCourseId = instructorEmailOrProposedCourseId.contains("@"); if(isFirstCourseId){ return StringHelper.truncateHead(getDemoCourseIdRoot(instructorEmailOrProposedCourseId), maximumIdLength); } else { final boolean isFirstTimeDuplicate = instructorEmailOrProposedCourseId.endsWith("-demo"); if(isFirstTimeDuplicate){ return StringHelper.truncateHead(instructorEmailOrProposedCourseId + "0", maximumIdLength); } else { final int lastIndexOfDemo = instructorEmailOrProposedCourseId.lastIndexOf("-demo"); final String root = instructorEmailOrProposedCourseId.substring(0, lastIndexOfDemo); final int previousDedupSuffix = Integer.parseInt(instructorEmailOrProposedCourseId.substring(lastIndexOfDemo + 5)); return StringHelper.truncateHead(root + "-demo" + (previousDedupSuffix + 1), maximumIdLength); } } }
Source:
public void tryMkDir(final Path dir) throws IOException { callHdfsOperation(new HdfsOperation<Void>() { @Override public Void call() throws IOException { if (!fs.exists(dir)) { fs.mkdirs(dir); LOGGER.info("Create dir in hdfs", dir.toString()); } if (fs.isFile(dir)) { throw new IOException("{} is file instead of directory, please remove it or " + "specify another directory"); } fs.mkdirs(dir); return null; } }); }

Target:
public void tryMkDir(final Path dir) throws IOException { callHdfsOperation(new HdfsOperation<Void>() { @Override public Void call() throws IOException { if (!fs.exists(dir)) { fs.mkdirs(dir); LOGGER.info("Create dir in hdfs", dir.toString()); } if (fs.isFile(dir)) { throw new IOException(dir.toString() + " is file instead of directory, please remove " + "it or specify another directory"); } fs.mkdirs(dir); return null; } }); }
Source:
public static void registerTags() { registerTag("is_open", (attribute, object) -> { return new ElementTag(object.door.isOpen()); }); registerTag("is_locked", (attribute, object) -> { return new ElementTag(object.door.isLocked()); }); registerTag("is_busy", (attribute, object) -> { return new ElementTag(BigDoorsBridge.commander.isDoorBusy(object.door.getDoorUID())); }); registerTag("is_loaded", (attribute, object) -> { return new ElementTag(BigDoorsBridge.bigDoors.areChunksLoadedForDoor(object.door)); }); registerTag("cuboid", (attribute, object) -> { return new CuboidTag(object.door.getMinimum(), object.door.getMaximum()); }); registerTag("auto_close", (attribute, object) -> { return new ElementTag(object.door.getAutoClose()); }, "autoclose"); registerTag("power_block", (attribute, object) -> { return new LocationTag(object.door.getPowerBlockLoc()); }); registerTag("owners", (attribute, object) -> { ListTag owners = new ListTag(); for (DoorOwner owner : BigDoorsBridge.commander.getDoorOwners(object.door.getDoorUID(), null)) { owners.addObject(PlayerTag.valueOf(owner.getPlayerUUID().toString(), CoreUtilities.noDebugContext)); } return owners; }); registerTag("door_type", (attribute, object) -> { return new ElementTag(object.door.getType().toString()); }); registerTag("name", (attribute, object) -> { return new ElementTag(object.door.getName()); }); }

Target:
public static void registerTags() { registerTag("is_open", (attribute, object) -> { return new ElementTag(object.door.isOpen()); }); registerTag("is_locked", (attribute, object) -> { return new ElementTag(object.door.isLocked()); }); registerTag("is_busy", (attribute, object) -> { return new ElementTag(BigDoorsBridge.commander.isDoorBusy(object.door.getDoorUID())); }); registerTag("is_loaded", (attribute, object) -> { return new ElementTag(BigDoorsBridge.bigDoors.areChunksLoadedForDoor(object.door)); }); registerTag("cuboid", (attribute, object) -> { return new CuboidTag(object.door.getMinimum(), object.door.getMaximum()); }); registerTag("auto_close", (attribute, object) -> { return new DurationTag(object.door.getAutoClose()); }); registerTag("power_block", (attribute, object) -> { return new LocationTag(object.door.getPowerBlockLoc()); }); registerTag("owners", (attribute, object) -> { ListTag owners = new ListTag(); for (DoorOwner owner : BigDoorsBridge.commander.getDoorOwners(object.door.getDoorUID(), null)) { owners.addObject(new PlayerTag(owner.getPlayerUUID())); } return owners; }); registerTag("door_type", (attribute, object) -> { return new ElementTag(object.door.getType().toString()); }); registerTag("name", (attribute, object) -> { return new ElementTag(object.door.getName()); }); }
Source:
protected void onAttachedToWindow() { super.onAttachedToWindow(); SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int color = getSelectedColor(); setSelectedColor(color); if (fromUser) { onColorChanged(color); } } }; seekBarRed.setOnSeekBarChangeListener(seekBarListener); seekBarGreen.setOnSeekBarChangeListener(seekBarListener); seekBarBlue.setOnSeekBarChangeListener(seekBarListener); seekBarAlpha.setOnSeekBarChangeListener(seekBarListener); editTextHex.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable newText) { if (editTextHex.getTag() == null) { if (parseInputToCheckIfHEX(newText.toString())) { int color = Color.parseColor(newText.toString()); setSelectedColor(color); onColorChanged(color); resetTextColor(); } else { setTextColorToRed(); } } else { resetTextColor(); } } }); }

Target:
protected void onAttachedToWindow() { super.onAttachedToWindow(); SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int color = getSelectedColor(); setSelectedColor(color); if (fromUser) { onColorChanged(color); } } }; seekBarRed.setOnSeekBarChangeListener(seekBarListener); seekBarGreen.setOnSeekBarChangeListener(seekBarListener); seekBarBlue.setOnSeekBarChangeListener(seekBarListener); seekBarAlpha.setOnSeekBarChangeListener(seekBarListener); editTextHex.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable newText) { if (editTextHex.getTag() == null) { int color = parseInputToCheckIfHEX(newText.toString()); if (color != NOT_A_HEX_VALUE) { setSelectedColor(color); onColorChanged(color); resetTextColor(); } else { setTextColorToRed(); } } else { resetTextColor(); } } }); }
Source:
private boolean uploadDependencyToBlobStore(String key, File dependency) throws KeyAlreadyExistsException, AuthorizationException, IOException { boolean uploadNew = false; try { getBlobStore().getBlobMeta(key); } catch (KeyNotFoundException e) { List<AccessControl> acls = new ArrayList<>(); acls.add(new AccessControl(AccessControlType.USER, BlobStoreAclHandler.READ | BlobStoreAclHandler.WRITE | BlobStoreAclHandler.ADMIN)); acls.add(new AccessControl(AccessControlType.OTHER, BlobStoreAclHandler.READ)); InputStream in = null; AtomicOutputStream blob = null; try { in = Files.newInputStream(dependency.toPath()); blob = getBlobStore().createBlob(key, new SettableBlobMeta(acls)); IOUtils.copy(in, blob, this.uploadChuckSize); in.close(); in = null; blob.close(); blob = null; uploadNew = true; } finally { try { if (blob != null) { blob.cancel(); } } catch (IOException throwaway) { } } } return uploadNew; }

Target:
private boolean uploadDependencyToBlobStore(String key, File dependency) throws KeyAlreadyExistsException, AuthorizationException, IOException { boolean uploadNew = false; try { getBlobStore().getBlobMeta(key); } catch (KeyNotFoundException e) { List<AccessControl> acls = new ArrayList<>(); acls.add(new AccessControl(AccessControlType.USER, BlobStoreAclHandler.READ | BlobStoreAclHandler.WRITE | BlobStoreAclHandler.ADMIN)); acls.add(new AccessControl(AccessControlType.OTHER, BlobStoreAclHandler.READ)); AtomicOutputStream blob = null; try { blob = getBlobStore().createBlob(key, new SettableBlobMeta(acls)); try(InputStream in = Files.newInputStream(dependency.toPath())) { IOUtils.copy(in, blob, this.uploadChuckSize); } blob.close(); blob = null; uploadNew = true; } finally { try { if (blob != null) { blob.cancel(); } } catch (IOException throwaway) { } } } return uploadNew; }
Source:
public boolean canFlipToNextPage() { boolean result = false; setErrorMessage(null); ISelection selection = treeViewer.getSelection(); if (selection instanceof StructuredSelection && ((StructuredSelection) selection).getFirstElement() instanceof RepresentationDescription) { RepresentationDescription representationDescription = (RepresentationDescription) ((StructuredSelection) selection).getFirstElement(); result = true; if (root instanceof DAnalysisSession) { DRepresentationContainer representationContainer = DAnalysisSessionHelper.findContainerForRepresentationDescription((DAnalysisSession) root, representationDescription); if (representationContainer != null) { IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(representationContainer); if (permissionAuthority != null && !permissionAuthority.canCreateIn(representationContainer)) { setErrorMessage(READ_ONLY_REPRESENTATION_CONTAINER); result = false; } } } if (result) { setRepresentation(representationDescription); } } return result; }

Target:
public boolean canFlipToNextPage() { boolean result = false; setErrorMessage(null); ISelection selection = treeViewer.getSelection(); if (selection instanceof StructuredSelection && ((StructuredSelection) selection).getFirstElement() instanceof RepresentationDescription) { RepresentationDescription representationDescription = (RepresentationDescription) ((StructuredSelection) selection).getFirstElement(); result = true; if (root instanceof DAnalysisSession) { Collection<DRepresentationContainer> containers = DAnalysisSessionHelper.findContainerCandidatesForRepresentationDescription((DAnalysisSession) root, representationDescription); if (!containers.isEmpty()) { result = false; for (DRepresentationContainer container : containers) { IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(container); if (permissionAuthority == null || permissionAuthority.canCreateIn(container)) { result = true; break; } } } } if (result) { setRepresentation(representationDescription); } else { setErrorMessage(READ_ONLY_REPRESENTATION_CONTAINER); } } return result; }
Source:
public void shouldParseAllTranscriptFieldsInVepOutput() { AnnotationLineMapper lineMapper = new AnnotationLineMapper(); VariantAnnotation variantAnnotation = lineMapper.mapLine(VepOutputContent.vepOutputContentTranscriptFields, 0); List<ConsequenceType> consequenceTypes = variantAnnotation.getConsequenceTypes(); assertNotNull(consequenceTypes); assertTrue(consequenceTypes.size() == 1); ConsequenceType consequenceType = consequenceTypes.get(0); assertEquals(Integer.valueOf(1), consequenceType.getcDnaPosition()); assertEquals(Integer.valueOf(4), consequenceType.getCdsPosition()); assertNull(consequenceType.getAaPosition()); assertEquals("7-?", consequenceType.getAaChange()); assertEquals("9-10", consequenceType.getCodon()); }

Target:
public void shouldParseAllTranscriptFieldsInVepOutput() { AnnotationLineMapper lineMapper = new AnnotationLineMapper(); VariantAnnotation variantAnnotation = lineMapper.mapLine(VepOutputContent.vepOutputContentTranscriptFields, 0); List<ConsequenceType> consequenceTypes = variantAnnotation.getConsequenceTypes(); assertNotNull(consequenceTypes); assertEquals(1, consequenceTypes.size()); ConsequenceType consequenceType = consequenceTypes.get(0); assertEquals(Integer.valueOf(1), consequenceType.getcDnaPosition()); assertEquals(Integer.valueOf(4), consequenceType.getCdsPosition()); assertNull(consequenceType.getAaPosition()); assertEquals("7-?", consequenceType.getAaChange()); assertEquals("9-10", consequenceType.getCodon()); }
Source:
public PlayerProfile(String name, UUID uuid, List<PlayerProperty> properties) { Validate.notNull(uuid, "uuid must not be null"); if (name == null) { name = ProfileCache.getProfile(uuid).getName(); } Validate.notNull(properties, "properties must not be null"); this.name = name; this.uuid = uuid; this.properties = properties; }

Target:
public PlayerProfile(String name, UUID uuid, List<PlayerProperty> properties) { Validate.notNull(uuid, "uuid must not be null"); Validate.notNull(properties, "properties must not be null"); if (null == name) { PlayerProfile profile = ProfileCache.getProfile(uuid); name = profile != null ? profile.getName() : null; } this.name = name; this.uuid = uuid; this.properties = properties; }
Source:
public void run() { try { while (isOpen.get()) { List<NetworkSend> sends = pollForRequests(); disconnectedIdsSet.clear(); ConnectionManagerPollResponse pollResponse = connectionManager.sendAndPoll(POLL_TIMEOUT_MS, sends); onResponse(pollResponse); } } catch (Exception e) { logger.error("RequestResponseHandlerThread received exception: ", e); } finally { shutDownLatch.countDown(); close(); } }

Target:
public void run() { try { while (isOpen.get()) { List<NetworkSend> sends = pollForRequests(); selector.poll(POLL_TIMEOUT_MS, sends); onResponse(selector.connected(), selector.disconnected(), selector.completedSends(), selector.completedReceives()); } } catch (Exception e) { logger.error("RequestResponseHandlerThread received exception: ", e); } finally { shutDownLatch.countDown(); close(); } }
Source:
private void alignGraph() { UnifiedPositionTraverser upt = new UnifiedPositionTraverser(); if (Settings.getBoolean(SETTING_EMPTY)) { EmptySegmentTraverser est = new EmptySegmentTraverser(); graph = est.addEmptySegmentsGraph(upt.unifyGraph(graph)); } else { graph = upt.unifyGraph(graph); } }

Target:
private void alignGraph() { UnifiedPositionTraverser upt = new UnifiedPositionTraverser(); graph = upt.unifyGraph(graph); if (Settings.getBoolean(SETTING_EMPTY)) { EmptySegmentTraverser est = new EmptySegmentTraverser(); graph = est.addEmptySegmentsGraph(graph); } }
Source:
public SimpleBinaryTypes getDataType() { if (datatype.equals("byte")) { return SimpleBinaryTypes.BYTE; } if (datatype.equals("word")) { return SimpleBinaryTypes.WORD; } if (datatype.equals("dword")) { return SimpleBinaryTypes.DWORD; } if (datatype.equals("float")) { return SimpleBinaryTypes.FLOAT; } if (datatype.equals("hsv")) { return SimpleBinaryTypes.HSB; } if (datatype.equals("rgb")) { return SimpleBinaryTypes.RGB; } if (datatype.equals("rgbw")) { return SimpleBinaryTypes.RGBW; } Matcher matcher = Pattern.compile("^array\\[(\\d+)\\]$").matcher(datatype); if (matcher.matches()) { return SimpleBinaryTypes.ARRAY; } if (logger.isDebugEnabled()) { logger.debug("getDataType() - unresolved type: " + datatype); } return SimpleBinaryTypes.UNKNOWN; }

Target:
public SimpleBinaryTypes getDataType() { if (datatype.equals("byte")) { return SimpleBinaryTypes.BYTE; } if (datatype.equals("word")) { return SimpleBinaryTypes.WORD; } if (datatype.equals("dword")) { return SimpleBinaryTypes.DWORD; } if (datatype.equals("float")) { return SimpleBinaryTypes.FLOAT; } if (datatype.equals("hsb")) { return SimpleBinaryTypes.HSB; } if (datatype.equals("rgb")) { return SimpleBinaryTypes.RGB; } if (datatype.equals("rgbw")) { return SimpleBinaryTypes.RGBW; } Matcher matcher = Pattern.compile("^array\\[(\\d+)\\]$").matcher(datatype); if (matcher.matches()) { return SimpleBinaryTypes.ARRAY; } if (logger.isDebugEnabled()) { logger.debug("getDataType() - unresolved type: {}", datatype); } return SimpleBinaryTypes.UNKNOWN; }
Source:
private void checkPage() { try { boolean layoutChanged = false; GridData gd = (GridData) warningComposite.getLayoutData(); if (gd.exclude != !branchCombo.getText().startsWith(Constants.R_HEADS)) { gd.exclude = !branchCombo.getText().startsWith(Constants.R_HEADS); warningComposite.setVisible(!gd.exclude); layoutChanged = true; } gd = (GridData) upstreamConfigGroup.getLayoutData(); if (gd.exclude != branchCombo.getText().startsWith(Constants.R_TAGS)) { gd.exclude = branchCombo.getText().startsWith(Constants.R_TAGS); upstreamConfigGroup.setVisible(!gd.exclude); layoutChanged = true; } if (layoutChanged) { upstreamConfigGroup.getParent().layout(true); } if (!gd.exclude) buttonConfigMerge.setSelection(false); buttonConfigRebase.setSelection(false); buttonConfigNone.setSelection(false); switch (upstreamConfig) { case MERGE: buttonConfigMerge.setSelection(true); break; case REBASE: buttonConfigRebase.setSelection(true); break; case NONE: buttonConfigNone.setSelection(true); break; } if (branchCombo.getText().length() == 0) { setErrorMessage(UIText.CreateBranchPage_MissingSourceMessage); return; } if (nameText.getText().length() == 0) { setErrorMessage(UIText.CreateBranchPage_ChooseNameMessage); return; } String message = this.myValidator.isValid(nameText.getText()); if (message != null) { setErrorMessage(message); return; } setErrorMessage(null); } finally { setPageComplete(getErrorMessage() == null); } }

Target:
private void checkPage() { try { boolean layoutChanged = false; GridData gd = (GridData) warningComposite.getLayoutData(); if (gd.exclude != !branchCombo.getText().startsWith(Constants.R_HEADS)) { gd.exclude = !branchCombo.getText().startsWith(Constants.R_HEADS); warningComposite.setVisible(!gd.exclude); layoutChanged = true; } warningComposite.getParent().getParent().layout(true); boolean showRebase = !branchCombo.getText().startsWith(Constants.R_TAGS) && !ObjectId.isId(branchCombo.getText()); gd = (GridData) upstreamConfigGroup.getLayoutData(); if (gd.exclude == showRebase) { gd.exclude = !showRebase; upstreamConfigGroup.setVisible(!gd.exclude); layoutChanged = true; } if (layoutChanged) upstreamConfigGroup.getParent().layout(true); if (!gd.exclude) buttonConfigMerge.setSelection(false); buttonConfigRebase.setSelection(false); buttonConfigNone.setSelection(false); switch (upstreamConfig) { case MERGE: buttonConfigMerge.setSelection(true); break; case REBASE: buttonConfigRebase.setSelection(true); break; case NONE: buttonConfigNone.setSelection(true); break; } if (branchCombo.getText().length() == 0) { setErrorMessage(UIText.CreateBranchPage_MissingSourceMessage); return; } if (nameText.getText().length() == 0) { setErrorMessage(UIText.CreateBranchPage_ChooseNameMessage); return; } String message = this.myValidator.isValid(nameText.getText()); if (message != null) { setErrorMessage(message); return; } setErrorMessage(null); } finally { setPageComplete(getErrorMessage() == null); } }
Source:
public void execute() throws Exception { KeystoreService ks = getKeystoreService(); AliasService as = getAliasService(); if (ks != null) { try { if (!ks.isCredentialStoreForClusterAvailable(GATEWAY_CREDENTIAL_STORE_NAME)) { ks.createCredentialStoreForCluster(GATEWAY_CREDENTIAL_STORE_NAME); } else { } } catch (KeystoreServiceException e) { throw new ServiceLifecycleException("Keystore was not loaded properly - the stored password may not match the password for the keystore.", e); } try { if (!ks.isKeystoreForGatewayAvailable()) { ks.createKeystoreForGateway(); } else { } boolean isSelfSigned; Certificate certificate; try { certificate = ks.getCertificateForGateway(); } catch (KeystoreServiceException e) { certificate = null; } isSelfSigned = (certificate == null) || X509CertificateUtil.isSelfSignedCertificate(certificate); if ((certificate == null) || isSelfSigned || force) { char[] passphrase = as.getGatewayIdentityPassphrase(); if (passphrase == null) { MasterService ms = services.getService("MasterService"); passphrase = ms.getMasterSecret(); } ks.addSelfSignedCertForGateway(getGatewayConfig().getIdentityKeyAlias(), passphrase, hostname); out.println("Certificate " + getGatewayConfig().getIdentityKeyAlias() + " has been successfully created."); } else { out.println("A non-self-signed certificate has already been installed in the configured keystore. " + "Please use --force if you wish to overwrite it with a generated self-signed certificate."); } } catch (KeystoreServiceException e) { throw new ServiceLifecycleException("Keystore was not loaded properly - the provided (or persisted) master secret may not match the password for the keystore.", e); } } }

Target:
public void execute() throws Exception { KeystoreService ks = getKeystoreService(); AliasService as = getAliasService(); if (ks != null) { try { if (!ks.isCredentialStoreForClusterAvailable(GATEWAY_CREDENTIAL_STORE_NAME)) { ks.createCredentialStoreForCluster(GATEWAY_CREDENTIAL_STORE_NAME); } else { } } catch (KeystoreServiceException e) { throw new ServiceLifecycleException("Keystore was not loaded properly - the stored password may not match the password for the keystore.", e); } try { if (!ks.isKeystoreForGatewayAvailable()) { ks.createKeystoreForGateway(); } else { } GatewayConfig config = getGatewayConfig(); if ( !isForceRequired(config, ks) || force) { char[] passphrase = as.getGatewayIdentityPassphrase(); if (passphrase == null) { MasterService ms = services.getService("MasterService"); passphrase = ms.getMasterSecret(); } ks.addSelfSignedCertForGateway(config.getIdentityKeyAlias(), passphrase, hostname); out.println("Certificate " + config.getIdentityKeyAlias() + " has been successfully created."); } else { out.println("A non-self-signed certificate has already been installed in the configured keystore. " + "Please use --force if you wish to overwrite it with a generated self-signed certificate."); } } catch (KeystoreServiceException e) { throw new ServiceLifecycleException("The identity keystore was not loaded properly - the provided password may not match the password for the keystore.", e); } } }
Source:
private void handleController0() { if (switchedUp(ControllerListener.BUTTON_TRIGGER)) { addButtonAction(ControllerId.ZERO, ButtonState.UP); } else if (switchedDown(ControllerListener.BUTTON_TRIGGER)) { addButtonAction(ControllerId.ZERO, ButtonState.DOWN); } else if (switchedUp(ControllerListener.BUTTON_GRIP)) { addButtonAction(ControllerId.ONE, ButtonState.UP); } else if (switchedDown(ControllerListener.BUTTON_GRIP)) { addButtonAction(ControllerId.ONE, ButtonState.DOWN); } else if (switchedUp(ControllerListener.BUTTON_APP_MENU)) { addButtonAction(ControllerId.TWO, ButtonState.UP); } else if (switchedDown(ControllerListener.BUTTON_APP_MENU)) { addButtonAction(ControllerId.TWO, ButtonState.DOWN); } else if (switchedDown(ControllerListener.BUTTON_TOUCHPAD)) { addAxisAction(ControllerId.X_AXIS, ButtonState.DOWN, -cachedStateAfter.rAxis[0].x); addAxisAction(ControllerId.Y_AXIS, ButtonState.DOWN, cachedStateAfter.rAxis[0].y); } else if (switchedUp(ControllerListener.BUTTON_TOUCHPAD)) { addAxisAction(ControllerId.X_AXIS, ButtonState.UP, 0.0f); addAxisAction(ControllerId.Y_AXIS, ButtonState.UP, 0.0f); } }

Target:
private void handleController0() { if (buttonUp(ControllerListener.TRIGGER_BUTTON)) { addButtonAction(ControllerId.ZERO, ButtonState.UP); } else if (buttonDown(ControllerListener.TRIGGER_BUTTON)) { addButtonAction(ControllerId.ZERO, ButtonState.DOWN); } else if (buttonUp(ControllerListener.GRIP_BUTTON)) { addButtonAction(ControllerId.ONE, ButtonState.UP); } else if (buttonDown(ControllerListener.GRIP_BUTTON)) { addButtonAction(ControllerId.ONE, ButtonState.DOWN); } else if (buttonUp(ControllerListener.APP_MENU_BUTTON)) { addButtonAction(ControllerId.TWO, ButtonState.UP); } else if (buttonDown(ControllerListener.APP_MENU_BUTTON)) { addButtonAction(ControllerId.TWO, ButtonState.DOWN); } else if (buttonDown(ControllerListener.TOUCHPAD_BUTTON)) { addAxisAction(ControllerId.X_AXIS, ButtonState.DOWN, -cachedStateAfter.rAxis[0].x); addAxisAction(ControllerId.Y_AXIS, ButtonState.DOWN, cachedStateAfter.rAxis[0].y); } else if (buttonUp(ControllerListener.TOUCHPAD_BUTTON)) { addAxisAction(ControllerId.X_AXIS, ButtonState.UP, 0.0f); addAxisAction(ControllerId.Y_AXIS, ButtonState.UP, 0.0f); } }
Source:
public static List COMserialport() { List<String> list = new ArrayList<String>(); try { String[] ports = SerialPort.list(); for(String strName : ports) { list.add(strName); } } catch (IOException e) { StatusManager.getManager().handle(new Status(IStatus.ERROR, LaunchPlugin.PLUGIN_ID, "Debugger plugin has thrown IOException", e), StatusManager.SHOW); } if (list.size() < 1) { list.add("Please connect to EM Starter Kit"); } return list; }

Target:
public static List COMserialport() { List<String> list = new ArrayList<String>(); try { Collections.addAll(list, SerialPort.list()); } catch (IOException e) { StatusManager.getManager() .handle(new Status(IStatus.ERROR, LaunchPlugin.PLUGIN_ID, "An error happened when retrieving list of available serial ports.", e), StatusManager.SHOW); } if (list.size() < 1) { list.add("Please connect to EM Starter Kit"); } return list; }
Source:
public static String readFileIntoString(String filename) throws java.io.IOException{ InputStream jsonFileInputStream = FileUtils.class.getClassLoader() .getResourceAsStream(filename); StringWriter writer = new StringWriter(); IOUtils.copy(jsonFileInputStream, writer, "utf8"); return writer.toString(); }

Target:
public static String readFileIntoString(String filename) throws java.io.IOException{ URL url = Resources.getResource(filename); return Resources.toString(url, Charsets.UTF_8); }
Source:
private ReplicationFactor(int allReplicas, int transientReplicas) { this.allReplicas = allReplicas; this.fullReplicas = allReplicas - transientReplicas; }

Target:
public ReplicationFactor(int allReplicas, int transientReplicas) { this.allReplicas = allReplicas; this.transientReplicas = transientReplicas; this.fullReplicas = allReplicas - transientReplicas; }
Source:
public Optional<Object> apply( final Object... args ) { if(args.length == 0) { return Optional.empty(); } Object arg = args[0]; if(arg != null && arg instanceof Number) { return Optional.<Object>of( ( (Number) arg ).intValue() ); } else { return Optional.<Object>of( Double.NaN ); } }

Target:
public Optional<Object> apply( final Object... args ) { if(args.length == 0) { return Optional.empty(); } Object arg = args[0]; if(arg != null && arg instanceof Number) { return Optional.<Object>of( ( (Number) arg ).intValue() ); } else { return Optional.empty(); } }
Source:
public void canFindRecursiveDirectoriesAndFiles() throws IOException { List<String> level1Dirs = Arrays.asList( testPathPrefix + UUID.randomUUID(), testPathPrefix + UUID.randomUUID(), testPathPrefix + UUID.randomUUID() ); List<String> level1Files = Arrays.asList( testPathPrefix + UUID.randomUUID(), testPathPrefix + UUID.randomUUID() ); for (String dir : level1Dirs) { mantaClient.putDirectory(dir); } for (String file : level1Files) { mantaClient.put(file, TEST_DATA, StandardCharsets.UTF_8); } List<String> level2Files = level1Dirs .stream() .flatMap(dir -> Stream.of(dir + SEPARATOR + UUID.randomUUID(), dir + SEPARATOR + UUID.randomUUID())) .collect(Collectors.toList()); for (String file : level2Files) { mantaClient.put(file, TEST_DATA, StandardCharsets.UTF_8); } int totalObjects = level1Dirs.size() + level1Files.size() + level2Files.size(); try (Stream<MantaObject> stream = mantaClient.find(testPathPrefix)) { List<MantaObject> results = stream.collect(Collectors.toList()); Assert.assertFalse(results.isEmpty(), "We should have many objects returned"); Assert.assertEquals(results.size(), totalObjects, "We should return exactly as many objects as added"); Stream<MantaObject> resultsStream = results.stream(); List<String> allObjects = new LinkedList<>(); allObjects.addAll(level1Dirs); allObjects.addAll(level1Files); allObjects.addAll(level2Files); for (String dir : level1Dirs) { Assert.assertEquals( resultsStream.filter(obj -> obj.getPath().equals(dir)).count(), 1); } } }

Target:
public void canFindRecursiveDirectoriesAndFiles() throws IOException { List<String> level1Dirs = Arrays.asList( testPathPrefix + UUID.randomUUID(), testPathPrefix + UUID.randomUUID(), testPathPrefix + UUID.randomUUID() ); List<String> level1Files = Arrays.asList( testPathPrefix + UUID.randomUUID(), testPathPrefix + UUID.randomUUID() ); for (String dir : level1Dirs) { mantaClient.putDirectory(dir); } for (String file : level1Files) { mantaClient.put(file, TEST_DATA, StandardCharsets.UTF_8); } List<String> level2Files = level1Dirs .stream() .flatMap(dir -> Stream.of(dir + SEPARATOR + UUID.randomUUID(), dir + SEPARATOR + UUID.randomUUID())) .collect(Collectors.toList()); for (String file : level2Files) { mantaClient.put(file, TEST_DATA, StandardCharsets.UTF_8); } List<String> allObjects = new LinkedList<>(); allObjects.addAll(level1Dirs); allObjects.addAll(level1Files); allObjects.addAll(level2Files); final List<MantaObject> results; try (Stream<MantaObject> stream = mantaClient.find(testPathPrefix)) { results = stream.collect(Collectors.toList()); } Assert.assertFalse(results.isEmpty(), "We should have many objects returned"); Assert.assertEquals(results.size(), allObjects.size(), "We should return exactly as many objects as added"); for (String expectedObject : allObjects) { try (Stream<MantaObject> resultsStream = results.stream()) { long count = resultsStream .filter(obj -> obj.getPath().equals(expectedObject)).count(); Assert.assertEquals(count, 1L); } } }
Source:
public void addTeam(Team team) { if(team == null || this.teams.contains(team)) { return; } this.teams.add(team); System.out.println("Game added!"); }

Target:
public int addTeam(Team team) { if(team == null || this.teams.contains(team)) { return -1; } if(this.teams.size()==tournament.TEAMS_PER_GAME) { return 0; } this.teams.add(team); return 1; }
Source:
public int getContentLength() { Header contentLength = resp.getFirstHeader("content-length"); if (contentLength == null) { return -1; } try { long l = Long.parseLong(contentLength.getValue()); if (l > Integer.MAX_VALUE) { return -1; } return (int) l; } catch (NumberFormatException e) { return -1; } }

Target:
public int getContentLength() { Header contentLength = resp.getFirstHeader("content-length"); if (contentLength == null) { return -1; } try { int l = Integer.parseInt(contentLength.getValue()); return l < 0 ? -1 : l; } catch (NumberFormatException e) { return -1; } }