auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static boolean isLivingOnLadder(@Nonnull IBlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull EntityLivingBase entity, EnumFacing side) { boolean isSpectator = (entity instanceof EntityPlayer && ((EntityPlayer)entity).isSpectator()); if (isSpectator) return false; if (!ForgeModContainer.fullBoundingBoxLadders) { Block b1 = state.getBlock(); Block b2 = world.getBlockState(pos.offset(side)).getBlock(); return b1.isLadder(state, world, pos, entity) || b1.isLadder(state, world, pos, entity, side) || b2.isLadder(state, world, pos, entity) || b2.isLadder(state, world, pos, entity, side); } else { AxisAlignedBB bb = entity.getEntityBoundingBox().grow(0.1); int mX = MathHelper.floor(bb.minX); int mY = MathHelper.floor(bb.minY); int mZ = MathHelper.floor(bb.minZ); for (int y2 = mY; y2 < bb.maxY; y2++) { for (int x2 = mX; x2 < bb.maxX; x2++) { for (int z2 = mZ; z2 < bb.maxZ; z2++) { BlockPos tmp = new BlockPos(x2, y2, z2); state = world.getBlockState(tmp); if (state.getBlock().isLadder(state, world, tmp, entity, side)) { return true; } } } } return false; } }

Target:
public static boolean isLivingOnLadder(@Nonnull IBlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull EntityLivingBase entity, EnumFacing side) { boolean isSpectator = (entity instanceof EntityPlayer && ((EntityPlayer)entity).isSpectator()); if (isSpectator) return false; if (side == null) return false; if (!ForgeModContainer.fullBoundingBoxLadders) { return state.getBlock().isLadder(state, world, pos, entity, side) || world.getBlockState(pos.offset(side)).getBlock().isLadder(state, world, pos, entity, side); } else { AxisAlignedBB bb = entity.getEntityBoundingBox().grow(0.1); int mX = MathHelper.floor(bb.minX); int mY = MathHelper.floor(bb.minY); int mZ = MathHelper.floor(bb.minZ); for (int y2 = mY; y2 < bb.maxY; y2++) { for (int x2 = mX; x2 < bb.maxX; x2++) { for (int z2 = mZ; z2 < bb.maxZ; z2++) { BlockPos tmp = new BlockPos(x2, y2, z2); state = world.getBlockState(tmp); if (state.getBlock().isLadder(state, world, tmp, entity, side)) { return true; } } } } return false; } }
Source:
public void recognizeEntitiesForFaultyText() { StepVerifier.create(client.recognizeEntities("!@#%%")) .verifyComplete(); }

Target:
public void recognizeEntitiesForFaultyText() { StepVerifier.create(client.recognizeEntities("!@#%%")) .expectNextCount(0) .verifyComplete(); }
Source:
@Override public ExecuteBatchResult executeBatch(StatementHandle h, List<List<TypedValue>> updateBatches) throws NoSuchStatementException { try { final StatementInfo info = statementCache.getIfPresent(h.id); if (null == info) { throw new NoSuchStatementException(h); } final PreparedStatement preparedStmt = (PreparedStatement) info.statement; for (List<TypedValue> batch : updateBatches) { int i = 1; for (TypedValue value : batch) { preparedStmt.setObject(i++, value.value); } preparedStmt.addBatch(); } return new ExecuteBatchResult(preparedStmt.executeBatch()); } catch (SQLException e) { throw propagate(e); } }

Target:
@Override public ExecuteBatchResult executeBatch(StatementHandle h, List<List<TypedValue>> updateBatches) throws NoSuchStatementException { try { final StatementInfo info = statementCache.getIfPresent(h.id); if (null == info) { throw new NoSuchStatementException(h); } final PreparedStatement preparedStmt = (PreparedStatement) info.statement; int rowUpdate = 1; for (List<TypedValue> batch : updateBatches) { int i = 1; for (TypedValue value : batch) { try { preparedStmt.setObject(i, value.toJdbc(calendar)); i++; } catch (SQLException e) { throw new RuntimeException("Failed to set value on row #" + rowUpdate + " and column #" + i, e); } rowUpdate++; } preparedStmt.addBatch(); } return new ExecuteBatchResult(preparedStmt.executeBatch()); } catch (SQLException e) { throw propagate(e); } }
Source:
private void startConfiguration() throws Exception { for (final ClientBootstrapResolver clientBootstrapResolver : configuration.getClientBootstrapResolvers()) { Barrier barrier = clientBootstrapResolver.getBarrier(); if (barrier != null) { barrier.getFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { connectClient(clientBootstrapResolver); } }); } else { connectClient(clientBootstrapResolver); } } }

Target:
private void startConfiguration() throws Exception { for (final ClientBootstrapResolver clientResolver : configuration.getClientResolvers()) { Barrier barrier = clientResolver.getBarrier(); if (barrier != null) { barrier.getFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { connectClient(clientResolver); } }); } else { connectClient(clientResolver); } } }
Source:
public void postsMessageAndInvitesFriends() throws Exception { final MkBase base = new MkBase(); final URN urn = new URN("urn:test:1"); final User user = base.user(urn); final String jeff = "Jeff"; user.aliases().add(jeff); final String frank = "Frank"; final User friend = base.user(new URN("urn:test:2")); friend.aliases().add(frank); final String post = "message"; final String head = new RsPrint( new TkForward(new TkStart(base)).act( new RqWithTester( urn, new RqFake( "GET", String.format( "/start?post=%s&invite=%s", post, frank ) ) ) ) ).printHead(); final Matcher matcher = Pattern.compile( "^Location:.*/b/(\\d+)$", Pattern.MULTILINE ).matcher(head); MatcherAssert.assertThat("Location header is correct", matcher.find()); final long number = Long.parseLong(matcher.group(1)); final Alias alias = user.aliases().iterate().iterator().next(); final Bout bout = alias.inbox().bout(number); final Message message = bout.messages().iterate().iterator().next(); MatcherAssert.assertThat(message.author(), Matchers.equalTo(jeff)); MatcherAssert.assertThat(message.text(), Matchers.equalTo(post)); MatcherAssert.assertThat( bout.friends().iterate().iterator().next().alias(), Matchers.equalTo(frank) ); }

Target:
public void postsMessageAndInvitesFriends() throws Exception { final MkBase base = new MkBase(); final URN urn = new URN("urn:test:1"); final User user = base.user(urn); final String name = "Jeff"; user.aliases().add(name); final Alias[] friends = new Alias[] { base.randomAlias(), base.randomAlias(), }; final String post = "message"; final String head = new RsPrint( new TkForward(new TkStart(base)).act( new RqWithTester( urn, new RqFake( "GET", String.format( "/start?post=%s&invite=%s&invite=%s", post, friends[0].name(), friends[1].name() ) ) ) ) ).printHead(); final Matcher matcher = Pattern.compile( "^Location:.*/b/(\\d+)$", Pattern.MULTILINE ).matcher(head); MatcherAssert.assertThat("Location header is correct", matcher.find()); final Bout bout = user.aliases().iterate().iterator().next().inbox() .bout(Long.parseLong(matcher.group(1))); final Message message = bout.messages().iterate().iterator().next(); MatcherAssert.assertThat(message.author(), Matchers.equalTo(name)); MatcherAssert.assertThat(message.text(), Matchers.equalTo(post)); MatcherAssert.assertThat( Iterables.transform( bout.friends().iterate(), new Function<Friend, String>() { @Override public String apply(final Friend friend) { try { return friend.alias(); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ), Matchers.containsInAnyOrder(friends[0].name(), friends[1].name()) ); }
Source:
public void testStickContextFinalization() throws Exception { VertxInternal vertx = (VertxInternal) Vertx.vertx(); try { AtomicReference<WeakReference<Context>> ref = new AtomicReference<>(); Thread t = new Thread(() -> { Context context = vertx.getOrCreateContext(); ref.set(new WeakReference<>(context)); CountDownLatch latch = new CountDownLatch(1); context.runOnContext(v -> { latch.countDown(); }); try { latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); t.start(); t.join(10_000); t = null; long now = System.currentTimeMillis(); while (true) { assertTrue(System.currentTimeMillis() - now < 20_000); RUNNER.runSystemGC(); if (ref.get().get() == null) { break; } } } finally { vertx.close(ar -> { testComplete(); }); } await(); }

Target:
public void testStickContextFinalization() throws Exception { Vertx vertx = Vertx.vertx(); try { AtomicReference<WeakReference<Context>> ref = new AtomicReference<>(); Thread t = new Thread(() -> { Context context = vertx.getOrCreateContext(); ref.set(new WeakReference<>(context)); CountDownLatch latch = new CountDownLatch(1); context.runOnContext(v -> { latch.countDown(); }); try { latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); t.start(); t.join(10_000); t = null; long now = System.currentTimeMillis(); while (true) { assertTrue(System.currentTimeMillis() - now < 20_000); RUNNER.runSystemGC(); if (ref.get().get() == null) { break; } } } finally { vertx.close(ar -> { testComplete(); }); } await(); }
Source:
public static void buildCinderDisk(CinderDisk cinderDisk, Map<String, Object> struct) { CinderConnectionInfo connectionInfo = cinderDisk.getCinderConnectionInfo(); CinderVolumeDriver cinderVolumeDriver = CinderVolumeDriver.forValue(connectionInfo.getDriverVolumeType()); if (cinderVolumeDriver == null) { log.error("Unsupported Cinder volume driver: '{}' (disk: '{}')", connectionInfo.getDriverVolumeType(), cinderDisk.getDiskAlias()); return; } switch (cinderVolumeDriver) { case RBD: String path = (String) cinderDisk.getCinderConnectionInfo().getData().get("name"); struct.put(VdsProperties.Path, path); struct.put(VdsProperties.Format, VolumeFormat.RAW.toString().toLowerCase()); struct.put(VdsProperties.PropagateErrors, PropagateErrors.Off.toString().toLowerCase()); struct.put(VdsProperties.Protocol, cinderDisk.getCinderConnectionInfo().getDriverVolumeType()); struct.put(VdsProperties.DiskType, VdsProperties.NETWORK); List<String> hostAddresses = (ArrayList<String>) cinderDisk.getCinderConnectionInfo().getData().get("hosts"); List<String> hostPorts = (ArrayList<String>) cinderDisk.getCinderConnectionInfo().getData().get("ports"); List<Map<String, Object>> hosts = new ArrayList<>(); for (int i = 0; i < hostAddresses.size(); i++) { Map<String, Object> hostMap = new HashMap<>(); hostMap.put(VdsProperties.NetworkDiskName, hostAddresses.get(i)); hostMap.put(VdsProperties.NetworkDiskPort, hostPorts.get(i)); hostMap.put(VdsProperties.NetworkDiskTransport, VdsProperties.Tcp); hosts.add(hostMap); } struct.put(VdsProperties.NetworkDiskHosts, hosts); break; } }

Target:
public static void buildCinderDisk(CinderDisk cinderDisk, Map<String, Object> struct) { CinderConnectionInfo connectionInfo = cinderDisk.getCinderConnectionInfo(); CinderVolumeDriver cinderVolumeDriver = CinderVolumeDriver.forValue(connectionInfo.getDriverVolumeType()); if (cinderVolumeDriver == null) { log.error("Unsupported Cinder volume driver: '{}' (disk: '{}')", connectionInfo.getDriverVolumeType(), cinderDisk.getDiskAlias()); return; } switch (cinderVolumeDriver) { case RBD: Map<String, Object> connectionInfoData = cinderDisk.getCinderConnectionInfo().getData(); struct.put(VdsProperties.Path, connectionInfoData.get("name")); struct.put(VdsProperties.Format, VolumeFormat.RAW.toString().toLowerCase()); struct.put(VdsProperties.PropagateErrors, PropagateErrors.Off.toString().toLowerCase()); struct.put(VdsProperties.Protocol, cinderDisk.getCinderConnectionInfo().getDriverVolumeType()); struct.put(VdsProperties.DiskType, VdsProperties.NETWORK); List<String> hostAddresses = (ArrayList<String>) connectionInfoData.get("hosts"); List<String> hostPorts = (ArrayList<String>) connectionInfoData.get("ports"); List<Map<String, Object>> hosts = new ArrayList<>(); for (int i = 0; i < hostAddresses.size(); i++) { Map<String, Object> hostMap = new HashMap<>(); hostMap.put(VdsProperties.NetworkDiskName, hostAddresses.get(i)); hostMap.put(VdsProperties.NetworkDiskPort, hostPorts.get(i)); hostMap.put(VdsProperties.NetworkDiskTransport, VdsProperties.Tcp); hosts.add(hostMap); } struct.put(VdsProperties.NetworkDiskHosts, hosts); break; } }
Source:
public Object[] getElements(Object inputElement) { Object[] elements = contentProvider.getElements(inputElement); Object[] oElements = Arrays.copyOf(elements, elements.length + fNumFillerRows); for (int i = 0; i < fNumFillerRows; i++) { oElements[elements.length + i] = FILLER; } return oElements; }

Target:
public Object[] getElements(Object inputElement) { Object[] elements = contentProvider.getElements(inputElement); Object[] oElements = Arrays.copyOf(elements, elements.length + fNumFillerRows, new Object[0].getClass()); for (int i = 0; i < fNumFillerRows; i++) { oElements[elements.length + i] = FILLER; } return oElements; }
Source:
public void replace() { assertThat( value.apply( "hello" ).replace( "l", "w" ), equalTo( value.apply( "hewwo" ) ) ); assertThat( value.apply( "hello" ).replace( "ell", "ipp" ), equalTo( value.apply( "hippo" ) ) ); assertThat( value.apply( "hello" ).replace( "a", "x" ), equalTo( value.apply( "hello" ) ) ); }

Target:
public void replace() { assertThat( value.apply( "hello" ).replace( "l", "w" ), equalTo( value.apply( "hewwo" ) ) ); assertThat( value.apply( "hello" ).replace( "ell", "ipp" ), equalTo( value.apply( "hippo" ) ) ); assertThat( value.apply( "hello" ).replace( "a", "x" ), equalTo( value.apply( "hello" ) ) ); assertThat( value.apply( "hello" ).replace( "e", "" ), equalTo( value.apply( "hllo" ) ) ); assertThat( value.apply( "" ).replace( "", "⁻" ), equalTo( value.apply( "⁻" ) ) ); }
Source:
protected void InitOverUtilizedList() { List<VDS> relevantVdss = LinqUtils.filter(getAllRelevantVdss(), new Predicate<VDS>() { @Override public boolean eval(VDS p) { return p.getUsageCpuPercent() >= p.getHighUtilization() && p.getCpuOverCommitTimestamp() != null && (new Date().getTime() - p.getCpuOverCommitTimestamp().getTime()) >= p .getCpuOverCommitDurationMinutes() * 1000L * 60L; } }); Collections.sort(relevantVdss, createDescendingCpuComparator()); setOverUtilizedServers(LinqUtils.toMap(relevantVdss, new DefaultMapper<VDS, Guid>() { @Override public Guid createKey(VDS vds) { return vds.getId(); } })); log.infoFormat("VdsLoadBalancer: number of over utilized vdss found: {0}.", getOverUtilizedServers().size()); }

Target:
protected void InitOverUtilizedList() { List<VDS> relevantVdss = LinqUtils.filter(getAllRelevantVdss(), new Predicate<VDS>() { @Override public boolean eval(VDS p) { return p.getUsageCpuPercent() >= p.getHighUtilization() && p.getCpuOverCommitTimestamp() != null && (new Date().getTime() - p.getCpuOverCommitTimestamp().getTime()) >= (long)p .getCpuOverCommitDurationMinutes() * 1000L * 60L; } }); Collections.sort(relevantVdss, createDescendingCpuComparator()); setOverUtilizedServers(LinqUtils.toMap(relevantVdss, new DefaultMapper<VDS, Guid>() { @Override public Guid createKey(VDS vds) { return vds.getId(); } })); log.infoFormat("VdsLoadBalancer: number of over utilized vdss found: {0}.", getOverUtilizedServers().size()); }
Source:
protected String toSqlType(Type type) { if (REAL.equals(type)) { return "float"; } if (TIME_WITH_TIME_ZONE.equals(type)) { return "time"; } if (TIMESTAMP.equals(type) || TIMESTAMP_WITH_TIME_ZONE.equals(type)) { return "datetime"; } if (VARBINARY.equals(type)) { return "varbinary"; } if (isVarcharType(type)) { VarcharType varcharType = (VarcharType) type; if (varcharType.isUnbounded()) { return "longtext"; } if (varcharType.getLengthSafe() <= 255) { return "tinytext"; } if (varcharType.getLengthSafe() <= 65535) { return "text"; } if (varcharType.getLengthSafe() <= 16777215) { return "mediumtext"; } return "longtext"; } return super.toSqlType(type); }

Target:
protected String toSqlType(Type type) { if (REAL.equals(type)) { return "float"; } if (TIME_WITH_TIME_ZONE.equals(type)) { return "time"; } if (TIMESTAMP.equals(type) || TIMESTAMP_WITH_TIME_ZONE.equals(type)) { return "datetime"; } if (VARBINARY.equals(type)) { return "mediumblob"; } if (isVarcharType(type)) { VarcharType varcharType = (VarcharType) type; if (varcharType.isUnbounded()) { return "longtext"; } if (varcharType.getLengthSafe() <= 255) { return "tinytext"; } if (varcharType.getLengthSafe() <= 65535) { return "text"; } if (varcharType.getLengthSafe() <= 16777215) { return "mediumtext"; } return "longtext"; } return super.toSqlType(type); }
Source:
private static PrivateKey privateKeyFromPkcs8(String privateKeyPem) throws IOException { Reader reader = new StringReader(privateKeyPem); Section section = PemReader.readFirstSectionAndClose(reader, "PRIVATE KEY"); if (section == null) { throw new IOException("Invalid PKCS8 data."); } byte[] bytes = section.getBase64DecodedBytes(); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); Exception unexpectedException = null; try { KeyFactory keyFactory = SecurityUtils.getRsaKeyFactory(); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } catch (NoSuchAlgorithmException exception) { unexpectedException = exception; } catch (InvalidKeySpecException exception) { unexpectedException = exception; } throw new IOException("Unexpected expcetion reading PKCS data", unexpectedException); }

Target:
private static PrivateKey privateKeyFromPkcs8(String privateKeyPem) throws IOException { Reader reader = new StringReader(privateKeyPem); Section section = PemReader.readFirstSectionAndClose(reader, "PRIVATE KEY"); if (section == null) { throw new IOException("Invalid PKCS8 data."); } byte[] bytes = section.getBase64DecodedBytes(); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); try { KeyFactory keyFactory = SecurityUtils.getRsaKeyFactory(); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } catch (NoSuchAlgorithmException | InvalidKeySpecException exception) { throw new IOException("Unexpected expcetion reading PKCS data", exception); } }
Source:
public void updateDataSourceListModel() { getDataSourceListModel().removeAllElements(); for (String dsName : getDataSourceArray()) { getDataSourceListModel().addElement(dsName); } setComponentsEnabled(); firePropertyChange(Bundle.DropdownSingleTermSearchPanel_selected(), null, null); }

Target:
void updateDataSourceListModel() { getDataSourceListModel().removeAllElements(); for (String dsName : getDataSourceArray()) { getDataSourceListModel().addElement(dsName); } setComponentsEnabled(); firePropertyChange(Bundle.DropdownSingleTermSearchPanel_selected(), null, null); }
Source:
public void worksWithMockedGists() throws Exception { final Gist gist = new MkGithub().gists().create( Collections.singletonList("test-file-name.txt") ); final String file = "t.txt"; gist.write(file, "hello, everybody!"); MatcherAssert.assertThat( gist.read(file), Matchers.startsWith("hello, ") ); MatcherAssert.assertThat( gist.starred(), Matchers.equalTo(false) ); gist.star(); MatcherAssert.assertThat( gist.starred(), Matchers.equalTo(true) ); }

Target:
public void worksWithMockedGists() throws Exception { final Gist gist = new MkGithub().gists().create( Collections.singletonList("test-file-name.txt") ); final String file = "t.txt"; gist.write(file, "hello, everybody!"); MatcherAssert.assertThat( gist.read(file), Matchers.startsWith("hello, ") ); }
Source:
private void checkForUnknownCssClasses(JMethod method, ExtendedCssTree extendedCssTree) throws UnableToCompleteException { JClassType returnType = (JClassType) method.getReturnType(); JMethod[] methods = returnType.getMethods(); ImmutableList.Builder<String> methodNamesBuilder = ImmutableList.builder(); for (JMethod jMethod : methods) { methodNamesBuilder.add(jMethod.getName()); } new UnassignedCssClassVisitor(extendedCssTree.getCssTree().getMutatingVisitController(), methodNamesBuilder.build(), errorManager) .runPass(); checkErrors(); }

Target:
private void checkForUnknownCssClasses(JMethod method, ExtendedCssTree extendedCssTree) throws UnableToCompleteException { JClassType returnType = (JClassType) method.getReturnType(); JMethod[] inheritablemethods = returnType.getInheritableMethods(); ImmutableList.Builder<String> methodNamesBuilder = ImmutableList.builder(); for (JMethod jMethod : inheritablemethods) { methodNamesBuilder.add(jMethod.getName()); } new UnassignedCssClassVisitor(extendedCssTree.getCssTree().getMutatingVisitController(), methodNamesBuilder.build(), errorManager) .runPass(); checkErrors(); }
Source:
public Optional<Page> addInput(Page inputPage) { List<Optional<Block>> partialDistinctMasks = new ArrayList<>(accumulators.size()); long memorySize = 0; for (InternalPartialAccumulator accumulator : accumulators) { partialDistinctMasks.add(accumulator.addInput(inputPage)); memorySize += accumulator.getEstimatedSize(); } systemMemoryContext.setBytes(memorySize); if (!intermediateLayout.hasDistinct()) { return Optional.empty(); } return intermediateLayout.buildPartialDistinctRows(inputPage, partialDistinctMasks); }

Target:
public Optional<Page> addInput(Page inputPage) { List<Optional<Block>> partialDistinctMasks = new ArrayList<>(accumulators.size()); for (InternalPartialAccumulator accumulator : accumulators) { partialDistinctMasks.add(accumulator.addInput(inputPage)); } updateMemoryUsage(); if (!intermediateLayout.hasDistinct()) { return Optional.empty(); } return intermediateLayout.buildPartialDistinctRows(inputPage, partialDistinctMasks); }
Source:
protected boolean runSerially() { boolean useful = false; processDisconnects(); final long timestamp = clock.getTicks(); final int n = epoll.poll(); int watermark = pending.size(); int offset = 0; if (n > 0) { LOG.debug().$("epoll [n=").$(n).$(']').$(); for (int i = 0; i < n; i++) { epoll.setOffset(offset); offset += EpollAccessor.SIZEOF_EVENT; final long id = epoll.getData(); if (id == 0) { accept(timestamp); } else { int row = pending.binarySearch(id, M_ID); if (row < 0) { LOG.error().$("internal error: epoll returned unexpected id [id=").$(id).$(']').$(); continue; } publishOperation( (epoll.getEvent() & EpollAccessor.EPOLLIN) > 0 ? IOOperation.READ : IOOperation.WRITE, pending.get(row) ); pending.deleteRow(row); watermark--; } } if (watermark < pending.size()) { enqueuePending(watermark); } useful = true; } if (idleConnectionTimeout > 0) { final long deadline = timestamp - idleConnectionTimeout; if (pending.size() > 0 && pending.get(0, M_TIMESTAMP) < deadline) { processIdleConnections(deadline); useful = true; } } return processRegistrations(timestamp) || useful; }

Target:
protected boolean runSerially() { boolean useful = false; processDisconnects(); final long timestamp = clock.getTicks(); final int n = epoll.poll(); int watermark = pending.size(); int offset = 0; if (n > 0) { LOG.debug().$("epoll [n=").$(n).$(']').$(); for (int i = 0; i < n; i++) { epoll.setOffset(offset); offset += EpollAccessor.SIZEOF_EVENT; final long id = epoll.getData(); if (id == 0) { accept(timestamp); } else { int row = pending.binarySearch(id, M_ID); if (row < 0) { LOG.error().$("internal error: epoll returned unexpected id [id=").$(id).$(']').$(); continue; } publishOperation( (epoll.getEvent() & EpollAccessor.EPOLLIN) > 0 ? IOOperation.READ : IOOperation.WRITE, pending.get(row) ); pending.deleteRow(row); watermark--; } } if (watermark < pending.size()) { enqueuePending(watermark); } useful = true; } final long deadline = timestamp - idleConnectionTimeout; if (pending.size() > 0 && pending.get(0, M_TIMESTAMP) < deadline) { processIdleConnections(deadline); useful = true; } return processRegistrations(timestamp) || useful; }
Source:
protected void executeCommand() { for (int i = 0; i < getParameters().getStoresCount(); i++) { CreateOvfVolumeForStorageDomainCommandParameters parameters = new CreateOvfVolumeForStorageDomainCommandParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId()); parameters.setSkipDomainChecks(getParameters().isSkipDomainChecks()); if (hasParentCommand()) { parameters.setParentCommand(getParameters().getParentCommand()); parameters.setParentParameters(getParameters().getParentParameters()); } else { parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); } VdcReturnValueBase vdcReturnValueBase = runInternalAction(VdcActionType.CreateOvfVolumeForStorageDomain, parameters); getReturnValue().getInternalVdsmTaskIdList().addAll(vdcReturnValueBase.getInternalVdsmTaskIdList()); } setSucceeded(true); }

Target:
protected void executeCommand() { for (int i = 0; i < getParameters().getStoresCount(); i++) { CreateOvfVolumeForStorageDomainCommandParameters parameters = createCreateOvfVolumeForStorageDomainParams(); VdcReturnValueBase vdcReturnValueBase = runInternalAction(VdcActionType.CreateOvfVolumeForStorageDomain, parameters); getReturnValue().getInternalVdsmTaskIdList().addAll(vdcReturnValueBase.getInternalVdsmTaskIdList()); } setSucceeded(true); }
Source:
public void testIterator() throws Throwable { Iterator<Map.Entry<String, Long>> iterator = stats.iterator(); assertThat(iterator.hasNext()) .describedAs("iterator.hasNext()") .isFalse(); assertThatThrownBy(iterator::next); }

Target:
public void testIterator() throws Throwable { Iterator<Map.Entry<String, Long>> iterator = stats.iterator(); assertThat(iterator.hasNext()) .describedAs("iterator.hasNext()") .isFalse(); intercept(NoSuchElementException.class, iterator::next); }
Source:
public void stopReadingEarlyWhenEncounteringEntryKnownToBeCommittedAfterSweepTs() { immutableTs = 100L; enqueueWriteCommitted(TABLE_CONS, 10); enqueueWriteCommitedAt(TABLE_CONS, 30, 150); putTimestampIntoTransactionTable(50, 200); Map<Integer, Integer> largeWriteDistribution = enqueueAtLeastThresholdWritesInDefaultShardWithStartTs(100, 50); int writesInDedicated = largeWriteDistribution.get(CONS_SHARD); enqueueWriteUncommitted(TABLE_CONS, 70); enqueueWriteCommitted(TABLE_CONS, 90); sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(metricsManager).hasEntriesReadConservativeEqualTo(4 + writesInDedicated); sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(metricsManager).hasEntriesReadConservativeEqualTo(4 + writesInDedicated + 1); immutableTs = 170; sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(metricsManager).hasEntriesReadConservativeEqualTo(4 + writesInDedicated + 3); immutableTs = 250; sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(metricsManager).hasEntriesReadConservativeEqualTo(4 + 3 + writesInDedicated + 2); }

Target:
public void stopReadingEarlyWhenEncounteringEntryKnownToBeCommittedAfterSweepTs() { immutableTs = 100L; enqueueWriteCommitted(TABLE_CONS, 10); enqueueWriteCommitedAt(TABLE_CONS, 30, 150); putTimestampIntoTransactionTable(50, 200); Map<Integer, Integer> largeWriteDistribution = enqueueAtLeastThresholdWritesInDefaultShardWithStartTs(100, 50); int writesInDedicated = largeWriteDistribution.get(CONS_SHARD); enqueueWriteUncommitted(TABLE_CONS, 70); enqueueWriteCommitted(TABLE_CONS, 90); sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(metricsManager).hasEntriesReadConservativeEqualTo(4 + writesInDedicated); sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(metricsManager).hasEntriesReadConservativeEqualTo(4 + writesInDedicated + 1); immutableTs = 170; sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(metricsManager).hasEntriesReadConservativeEqualTo(4 + writesInDedicated + 3); immutableTs = 250; sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(metricsManager).hasEntriesReadConservativeEqualTo(4 + writesInDedicated + 3 + writesInDedicated + 2); }
Source:
private void assertCallbackSuccess(@NonNull Call<DescriptionEdit> call, @NonNull Callback cb) { verify(cb).success(eq(call)); verify(cb, never()).failure(eq(call), any(Throwable.class)); }

Target:
private void assertCallbackSuccess(@NonNull Call<DescriptionEdit> call, @NonNull Callback cb) { verify(cb).success(eq(call)); verify(cb, never()).failure(any(Call.class), any(Throwable.class)); }
Source:
public Void visit(GenContext state, Sequence ast) { return null; }

Target:
public Void visit(GenContext state, Sequence ast) { for (TypedAST exp : ast.getExps()) { exp.acceptVisitor(this, state); } return null; }
Source:
public void stopService(long timeout) { long startTime = System.currentTimeMillis(); waitForNonPendingState(); if (queryStatus().dwCurrentState == Winsvc.SERVICE_STOPPED) { return; } SERVICE_STATUS status = new SERVICE_STATUS(); if (! Advapi32.INSTANCE.ControlService(_handle, SERVICE_CONTROL_STOP, status)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } while(status.dwCurrentState != Winsvc.SERVICE_STOPPED) { long msRemainingBeforeTimeout = timeout - (System.currentTimeMillis() - startTime); if (msRemainingBeforeTimeout < 0) { throw new RuntimeException(String.format("Service stop exceeded timeout time of %d ms", timeout)); } int dwWaitTime = Math.min(sanitizeWaitTime(status.dwWaitHint), (int)msRemainingBeforeTimeout); try { Thread.sleep( dwWaitTime ); } catch (InterruptedException e){ throw new RuntimeException(e); } if(! Advapi32.INSTANCE.QueryServiceStatus(_handle, status)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } } }

Target:
public void stopService(long timeout) { long startTime = System.currentTimeMillis(); waitForNonPendingState(); if (queryStatus().dwCurrentState == Winsvc.SERVICE_STOPPED) { return; } SERVICE_STATUS status = new SERVICE_STATUS(); if (! Advapi32.INSTANCE.ControlService(_handle, SERVICE_CONTROL_STOP, status)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } while(status.dwCurrentState != Winsvc.SERVICE_STOPPED) { long msRemainingBeforeTimeout = timeout - (System.currentTimeMillis() - startTime); if (msRemainingBeforeTimeout < 0) { throw new RuntimeException(String.format("Service stop exceeded timeout time of %d ms", timeout)); } long dwWaitTime = Math.min(sanitizeWaitTime(status.dwWaitHint), msRemainingBeforeTimeout); try { Thread.sleep( dwWaitTime ); } catch (InterruptedException e){ throw new RuntimeException(e); } if(! Advapi32.INSTANCE.QueryServiceStatus(_handle, status)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } } }
Source:
public RepoCommit update( @NotNull(message = "path cannot be NULL") final String path, @NotNull(message = "json should not be NULL") final JsonObject json ) throws IOException { this.storage.lock(); try { final String xpath = String.format( "/github/repos/repo[@coords='%s']/contents/content[path='%s']", this.coords, path ); new JsonPatch(this.storage).patch(xpath, json); return this.commit(json); } finally { this.storage.unlock(); } }

Target:
public RepoCommit update( @NotNull(message = "path cannot be NULL") final String path, @NotNull(message = "json should not be NULL") final JsonObject json ) throws IOException { this.storage.lock(); try { final String ref = "ref"; final String branch; if (json.containsKey(ref)) { branch = json.getString(ref); } else { branch = "master"; } final String xpath = String.format( "/github/repos/repo[@coords='%s']/contents/content[path='%s' and @ref='%s']", this.coords, path, branch ); new JsonPatch(this.storage).patch(xpath, json); return this.commit(json); } finally { this.storage.unlock(); } }
Source:
public void onFinish(ISuite suite) { ThreadLeakChecker.checkForLeaks(null); }

Target:
public void onFinish(ISuite suite) { ThreadLeakChecker.checkForLeaks(); }
Source:
public void retireConcept_shouldRetireTheGivenConcept() throws Exception { int drugId = 3; String retireReason = "dummy reason"; Concept concept = conceptService.getConcept(drugId); assertFalse(concept.isRetired()); conceptService.retireConcept(concept, retireReason); assertTrue(concept.isRetired()); assertEquals(retireReason, concept.getRetireReason()); }

Target:
public void retireConcept_shouldRetireTheGivenConcept() throws Exception { String retireReason = "dummy reason"; Concept concept = conceptService.getConcept(3); assertFalse(concept.isRetired()); conceptService.retireConcept(concept, retireReason); assertTrue(concept.isRetired()); assertEquals(retireReason, concept.getRetireReason()); }
Source:
private boolean isArtifact(ITask reviewTask) { boolean hasAssosciatedTask = ReviewsUiPlugin.getDefault() .getTaskReviewsMappingStore() .getTaskUrl(reviewTask) != null; boolean hasContext = contextStore.hasContext(reviewTask); boolean hasScheduledDate = false; if (reviewTask instanceof AbstractTask) { AbstractTask abstractTask = (AbstractTask) reviewTask; hasScheduledDate = abstractTask.getScheduledForDate() != null; } boolean hasDueDate = reviewTask.getDueDate() != null; return hasAssosciatedTask && !(hasContext || hasScheduledDate || hasDueDate); }

Target:
private boolean isArtifact(ITask reviewTask) { return !(hasScheduledDate(reviewTask) || hasDueDate(reviewTask) || hasContext(reviewTask)) && hasAssosciatedTask(reviewTask); }
Source:
private Call.Listener<ResponseT> wrap(Call.Listener<ResponseT> responseListener) { return new ClientInterceptors.ForwardingListener<ResponseT>(responseListener) { @Override public void onClose(Status status, Metadata.Trailers trailers) { super.onClose(status, trailers); outstandingRequests.remove(id); if (outstandingRequests.isEmpty()) { synchronized (outstandingRequests) { outstandingRequests.notify(); } } } }; }

Target:
private Call.Listener<ResponseT> wrap(Call.Listener<ResponseT> responseListener) { return new ClientInterceptors.ForwardingListener<ResponseT>(responseListener) { @Override public void onClose(Status status, Metadata.Trailers trailers) { super.onClose(status, trailers); untrack(); } }; }
Source:
public Serializable parseDate(Serializable value) { if (value instanceof Date) { return ((Date) value).toInstant(); } if (value instanceof Long) { return Instant.ofEpochMilli((Long) value); } if (!(value instanceof String)) { return null; } String string = String.valueOf(value); if (StringUtils.isBlank(string)) { return null; } if (StringUtils.isNumeric(string)) { try { return Instant.ofEpochMilli(Long.parseLong(string)); } catch (NumberFormatException ex) { throw new IllegalArgumentException(ex); } } if (iso8601Z.matcher(string).matches()) { return Instant.parse(string); } if (iso8601Offset.matcher(string).matches()) { return OffsetDateTime.parse(string).toInstant(); } SimpleDateFormat dateFormat; if (boonDefault.matcher(string).matches()) { dateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"); } else { dateFormat = new SimpleDateFormat(); } dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try { return dateFormat.parse(value.toString()).toInstant(); } catch (ParseException e) { throw new IllegalArgumentException(e); } }

Target:
public Instant parseDate(Serializable value) { if (value instanceof Date) { return ((Date) value).toInstant(); } if (value instanceof Long) { return Instant.ofEpochMilli((Long) value); } if (!(value instanceof String)) { return null; } String string = String.valueOf(value); if (StringUtils.isBlank(string)) { return null; } if (StringUtils.isNumeric(string)) { try { return Instant.ofEpochMilli(Long.parseLong(string)); } catch (NumberFormatException ex) { LOGGER.debug("Failed to create Epoch time from a numeric: {}", string, ex); return null; } } if (iso8601Z.matcher(string).matches()) { return Instant.parse(string); } if (iso8601Offset.matcher(string).matches()) { return OffsetDateTime.parse(string).toInstant(); } SimpleDateFormat dateFormat; if (boonDefault.matcher(string).matches()) { dateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"); } else { dateFormat = new SimpleDateFormat(); } dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try { return dateFormat.parse(string).toInstant(); } catch (ParseException e) { LOGGER.debug("Failed to parse as a dateFormat time from a date string: {}", string, e); return null; } }
Source:
public PredicateFilterSqlBenchmark(LocalQueryRunner localQueryRunner) { super(localQueryRunner, "sql_predicate_filter", 5, 50, "SELECT totalprice FROM orders WHERE totalprice > 50000"); }

Target:
public PredicateFilterSqlBenchmark(LocalQueryRunner localQueryRunner) { super(localQueryRunner, "sql_predicate_filter", 5, 50, "select totalprice from orders where totalprice > 50000"); }
Source:
public void onStart( final FileAlterationObserver observer ) { if (!this.hasBeenProvisioned.getAndSet( true )) { this.logger.fine( "Initial provisioning of templates..." ); final Collection<File> templateFiles = FileUtils.listFiles( this.templateDir, FileFilterUtils.and( FileFilterUtils.suffixFileFilter( MonitoringService.MONITORING_TEMPLATE_FILE_EXTENSION ), CanReadFileFilter.CAN_READ ), new AbstractFileFilter() { @Override public boolean accept( final File file ) { return templateDir.equals( file ) || templateDir.equals( file.getParentFile() ); } } ); final Collection<TemplateEntry> templateEntries = new ArrayList<TemplateEntry>(); for (final File templateFile : templateFiles) { final TemplateEntry templateEntry = compileTemplate( templateFile ); if (templateEntry != null) { templateEntries.add( templateEntry ); this.logger.finest( "++ Added " + templateEntry ); } } this.lock.writeLock().lock(); try { for (final TemplateEntry templateEntry : templateEntries) { updateTemplateEntry( templateEntry ); } } finally { this.lock.writeLock().unlock(); } this.manager.processTemplates( templateEntries ); } }

Target:
public void onStart( final FileAlterationObserver observer ) { if (!this.hasBeenProvisioned.getAndSet(true)) { this.logger.fine("Initial provisioning of templates..."); final Collection<File> templateFiles = FileUtils.listFiles( this.templateDir, FileFilterUtils.and( FileFilterUtils.suffixFileFilter(MonitoringService.TEMPLATE_FILE_EXTENSION), CanReadFileFilter.CAN_READ), new TemplateDirectoryFileFilter(this.templateDir)); final Collection<TemplateEntry> templateEntries = new ArrayList<TemplateEntry>(); for (final File templateFile : templateFiles) { final TemplateEntry templateEntry = compileTemplate(templateFile); if (templateEntry != null) { templateEntries.add(templateEntry); this.logger.finest("++ Added " + templateEntry); } } this.lock.writeLock().lock(); try { for (final TemplateEntry templateEntry : templateEntries) { updateTemplateEntry(templateEntry); } } finally { this.lock.writeLock().unlock(); } this.manager.processTemplates(templateEntries); } }
Source:
Set<String> getEmptyRoles(String userId) { Set<String> roles = new HashSet<String>(); roles.add(ANON_ROLE); if ((userId != null) && (!userDirectoryService().getAnonymousUser().getId().equals(userId))) { roles.add(AUTH_ROLE); if (m_roleProvider != null) { roles.addAll((m_roleProvider.getAdditionalRoles(userId))); } if (userId.startsWith(DUMMY_USER_PREFIX)) { String roleId = userId.substring(DUMMY_USER_PREFIX.length()); roles.add(roleId); } } return roles; }

Target:
Set<String> getEmptyRoles(String userId) { Set<String> roles = new HashSet<String>(); roles.add(ANON_ROLE); if ((userId != null) && (!userDirectoryService().getAnonymousUser().getId().equals(userId))) { String roleId = decodeRoleFromDummyUser(userId); if (roleId != null){ roles.remove(ANON_ROLE); roles.add(roleId); } else { roles.add(AUTH_ROLE); if (m_roleProvider != null) { roles.addAll((m_roleProvider.getAdditionalRoles(userId))); } } } return roles; }
Source:
private static Result firstInWinsMerge(Result current, Result incoming) { LOGGER.trace( "While collecting metacards into map, there were metacards found with a duplicate key.\nOld: {}\nNew: {}", LogSanitizer.cleanAndEncode(current.toString()), LogSanitizer.cleanAndEncode(incoming.toString())); return current; }

Target:
private static Result firstInWinsMerge(Result current, Result incoming) { LOGGER.trace( "While collecting metacards into map, there were metacards found with a duplicate key.\nOld: {}\nNew: {}", LogSanitizer.sanitize(current), LogSanitizer.sanitize(incoming)); return current; }
Source:
public static AuthenticationPlugin<?> load(ServerAuthenticationConfig config) { return load(config, ImmutableList.<Path>of()); }

Target:
public static AuthenticationPlugin<?> load(ServerAuthenticationConfig config) { final String scheme = config.getEnabledScheme(); final Path pluginPath = config.getPluginPath(); final ClassLoader classLoader; if (config.getPluginPath() == null) { classLoader = Thread.currentThread().getContextClassLoader(); } else { Preconditions.checkArgument(pluginPath.toFile().canRead(), "Plugin path " + pluginPath + " does not exist or is not readable"); classLoader = pluginClassLoader(pluginPath); } final ServiceLoader<AuthenticationPlugin> loader = ServiceLoader.load(AuthenticationPlugin.class, classLoader); for (AuthenticationPlugin plugin : loader) { if (scheme.equals(plugin.schemeName())) { return plugin; } } throw new IllegalStateException("No AuthenticationPlugin found for scheme " + scheme + ". Check classpath and plugin path settings"); }
Source:
public IStyledLabelProvider[] getLabelProviders() { if (fLabelProviders == null) { fLabelProviders = CHEProviderSettings.getCCallHierarchyLabelProviders(); } return fLabelProviders; }

Target:
public IStyledLabelProvider[] getLabelProviders() { return fLabelProviders; }
Source:
private static Multimap<Integer, ITmfStateInterval> createThreadMultimap() { final Multimap<Integer, ITmfStateInterval> map = TreeMultimap.create( (arg0, arg1) -> arg0.compareTo(arg1), (arg0, arg1) -> { if (arg1.getStateValue() == VCPU_PREEMPT_VALUE && arg0.getStateValue() != VCPU_PREEMPT_VALUE) { if (((Long) arg0.getEndTime()).compareTo(arg1.getStartTime()) < 0) { return -1; } return ((Long) arg0.getStartTime()).compareTo(arg1.getEndTime()); } return (((Long) arg0.getStartTime()).compareTo(arg1.getStartTime())); }); return map; }

Target:
private static Multimap<Integer, ITmfStateInterval> createThreadMultimap() { final Multimap<Integer, ITmfStateInterval> map = TreeMultimap.create( Comparator.naturalOrder(), (arg0, arg1) -> { if (arg1.getStateValue() == VCPU_PREEMPT_VALUE && arg0.getStateValue() != VCPU_PREEMPT_VALUE) { if (((Long) arg0.getEndTime()).compareTo(arg1.getStartTime()) < 0) { return -1; } return ((Long) arg0.getStartTime()).compareTo(arg1.getEndTime()); } return (((Long) arg0.getStartTime()).compareTo(arg1.getStartTime())); }); return map; }
Source:
public void writeDatastaxReadAstyanax() throws Exception { datastaxExcessEnumIO.insertExcessEnumMetric(testLocators.get(0)); datastaxExcessEnumIO.insertExcessEnumMetric(testLocators.get(1)); datastaxExcessEnumIO.insertExcessEnumMetric(testLocators.get(2)); datastaxExcessEnumIO.insertExcessEnumMetric(testLocators.get(3)); Set<Locator> excessEnums = astyanaxExcessEnumIO.getExcessEnumMetrics(); assertEquals("Unexpected number of excessEnums", 4, excessEnums.size()); String excessEnumLocators = ""; for ( Iterator<Locator> it = excessEnums.iterator(); it.hasNext(); ) { excessEnumLocators += it.next().toString() + ","; } assertTrue("excess enum does not contain " + testLocators.get(0), excessEnumLocators.contains(testLocators.get(0).toString())); assertTrue("excess enum does not contain " + testLocators.get(1), excessEnumLocators.contains(testLocators.get(1).toString())); assertTrue("excess enum does not contain " + testLocators.get(2), excessEnumLocators.contains(testLocators.get(2).toString())); assertTrue("excess enum does not contain " + testLocators.get(3), excessEnumLocators.contains(testLocators.get(3).toString())); }

Target:
public void writeDatastaxReadAstyanax() throws Exception { for (Locator testLocator : testLocators) { datastaxExcessEnumIO.insertExcessEnumMetric(testLocator); } Thread.sleep(1000); Set<Locator> excessEnums = astyanaxExcessEnumIO.getExcessEnumMetrics(); assertEquals("Unexpected number of excessEnums", testLocators.size(), excessEnums.size()); for (Locator expectedLocator : testLocators) { assertTrue("excess enum does not contain " + expectedLocator, excessEnums.contains(expectedLocator)); } }
Source:
public boolean canPrincipalManage(IAuthorizationPrincipal principal, String portletDefinitionId) throws AuthorizationException { final String owner = IPermission.PORTAL_PUBLISH; final String target = IPermission.PORTLET_PREFIX + portletDefinitionId; IPortletDefinition portlet = this.portletDefinitionRegistry.getPortletDefinition(portletDefinitionId); if (portlet == null) { return doesPrincipalHavePermission( principal, owner, IPermission.PORTLET_MANAGER_APPROVED_ACTIVITY, target); } final IPortletLifecycleEntry highestLifecycleEntryDefined = portlet.getLifecycle().get(portlet.getLifecycle().size() - 1); String activity = null; switch (highestLifecycleEntryDefined.getLifecycleState()) { case CREATED: activity = IPermission.PORTLET_MANAGER_CREATED_ACTIVITY; break; case APPROVED: activity = IPermission.PORTLET_MANAGER_APPROVED_ACTIVITY; break; case PUBLISHED: activity = IPermission.PORTLET_MANAGER_ACTIVITY; break; case EXPIRED: activity = IPermission.PORTLET_MANAGER_EXPIRED_ACTIVITY; break; case MAINTENANCE: activity = IPermission.PORTLET_MANAGER_MAINTENANCE_ACTIVITY; break; } if (activity == null) { final String msg = "Unrecognized portlet lifecycle state: " + highestLifecycleEntryDefined.getLifecycleState(); throw new IllegalStateException(msg); } return doesPrincipalHavePermission(principal, owner, activity, target); }

Target:
public boolean canPrincipalManage(IAuthorizationPrincipal principal, String portletDefinitionId) throws AuthorizationException { final String owner = IPermission.PORTAL_PUBLISH; final String target = IPermission.PORTLET_PREFIX + portletDefinitionId; IPortletDefinition portlet = this.portletDefinitionRegistry.getPortletDefinition(portletDefinitionId); if (portlet == null) { return doesPrincipalHavePermission( principal, owner, IPermission.PORTLET_MANAGER_APPROVED_ACTIVITY, target); } final IPortletLifecycleEntry highestLifecycleEntryDefined = portlet.getLifecycle().get(portlet.getLifecycle().size() - 1); String activity; switch (highestLifecycleEntryDefined.getLifecycleState()) { case CREATED: activity = IPermission.PORTLET_MANAGER_CREATED_ACTIVITY; break; case APPROVED: activity = IPermission.PORTLET_MANAGER_APPROVED_ACTIVITY; break; case PUBLISHED: activity = IPermission.PORTLET_MANAGER_ACTIVITY; break; case EXPIRED: activity = IPermission.PORTLET_MANAGER_EXPIRED_ACTIVITY; break; case MAINTENANCE: activity = IPermission.PORTLET_MANAGER_MAINTENANCE_ACTIVITY; break; default: final String msg = "Unrecognized portlet lifecycle state: " + highestLifecycleEntryDefined.getLifecycleState(); throw new IllegalStateException(msg); } return doesPrincipalHavePermission(principal, owner, activity, target); }
Source:
public int getScrollBarContainerWidth() { ViewGroup.LayoutParams layoutParams = mScrollBarView.getLayoutParams(); return layoutParams.width; }

Target:
public int getScrollBarContainerWidth() { return mScrollBarView.getLayoutParams().width; }
Source:
public Repository getRepository(final IResource resource) { Repository[] repositories = org.eclipse.egit.core.Activator .getDefault().getRepositoryCache().getAllRepositories(); Repository repository = null; IPath repositoryPath = null; for (Repository r : repositories) { if (!r.isBare()) { try { IPath repoPath = new Path(r.getWorkTree() .getCanonicalPath()); if (repoPath.isPrefixOf(resource.getLocation())) { if (repository == null || repositoryPath == null || repositoryPath.isPrefixOf(repoPath)) { repository = r; repositoryPath = repoPath; } } } catch (IOException e) { Activator .error("looking up working tree path of git repository failed", e); } } } return repository; }

Target:
public Repository getRepository(final IResource resource) { Repository[] repositories = org.eclipse.egit.core.Activator .getDefault().getRepositoryCache().getAllRepositories(); Repository repository = null; int segmentCount = 0; for (Repository r : repositories) { if (!r.isBare()) { try { IPath repoPath = new Path(r.getWorkTree() .getCanonicalPath()); IPath location = resource.getLocation(); if (location != null && repoPath.isPrefixOf(resource.getLocation())) { if (repository == null || repoPath.segmentCount() > segmentCount) { repository = r; segmentCount = repoPath.segmentCount(); } } } catch (IOException e) { Activator .error("looking up working tree path of git repository failed", e); } } } return repository; }
Source:
public static Set<Class<?>> lookupBeanClasses(Class<?> lookupBeanClazz) { Set<Class<?>> classes = BEANS.getBeanManager().getBeans(lookupBeanClazz).stream() .peek(bean -> LOG.debug("{} contributed as REST {}", bean.getBeanClazz(), lookupBeanClazz.getSimpleName())) .map(IBean::getBeanClazz) .collect(Collectors.toSet()); LOG.info("Contributed classes as REST {}", classes.size(), lookupBeanClazz.getSimpleName()); return classes; }

Target:
public static Set<Class<?>> lookupBeanClasses(Class<?> lookupBeanClazz) { return BEANS.getBeanManager().getBeans(lookupBeanClazz).stream() .map(IBean::getBeanClazz) .collect(Collectors.toSet()); }