auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCreateRegionWithMinMax() { List<Vector3i> mins = Arrays.asList(new Vector3i(), new Vector3i(1, 1, 1), new Vector3i(3, 4, 5)); List<Vector3i> expectedSize = Arrays.asList(new Vector3i(1, 1, 1), new Vector3i(3, 3, 3), new Vector3i(8, 5, 2)); List<Vector3i> max = Arrays.asList(new Vector3i(1, 1, 1), new Vector3i(4, 4, 4), new Vector3i(11, 9, 7)); for (int i = 0; i < mins.size(); ++i) { BlockRegion region = new BlockRegion().union(mins.get(i)).union(max.get(i)); assertEquals(mins.get(i), region.getMin(new Vector3i())); assertEquals(max.get(i), region.getMax(new Vector3i())); assertEquals(expectedSize.get(i), region.getSize(new Vector3i())); } }

Target:
public void testCreateRegionWithMinMax() { List<Vector3i> mins = Arrays.asList(new Vector3i(), new Vector3i(1, 1, 1), new Vector3i(3, 4, 5)); List<Vector3i> expectedSize = Arrays.asList(new Vector3i(1, 1, 1), new Vector3i(3, 3, 3), new Vector3i(8, 5, 2)); List<Vector3i> max = Arrays.asList(new Vector3i(), new Vector3i(3, 3, 3), new Vector3i(10, 8, 6)); for (int i = 0; i < mins.size(); ++i) { BlockRegion region = new BlockRegion(mins.get(i), max.get(i)); assertEquals(mins.get(i), region.getMin(new Vector3i())); assertEquals(max.get(i), region.getMax(new Vector3i())); assertEquals(expectedSize.get(i), region.getSize(new Vector3i())); } }
Source:
public AbstractListDataView<T> addItemAfter(T item, T after) { final Collection<T> items = getDataProvider().getItems(); if(!items.contains(after)) { throw new IllegalArgumentException("Item to insert after is not available in the data"); } if(items instanceof List) { ((List<T>)items).add(((List<T>) items).indexOf(after)+1, item); getDataProvider().refreshAll(); return this; } throw new IllegalArgumentException("DataProvider collection is not a list."); }

Target:
public AbstractListDataView<T> addItemAfter(T item, T after) { final Collection<T> items = getDataProvider().getItems(); if(!items.contains(after)) { throw new IllegalArgumentException("Item to insert after is not available in the data"); } if(items instanceof List) { final List<T> itemList = (List<T>) items; itemList.add(itemList.indexOf(after)+1, item); getDataProvider().refreshAll(); return this; } throw new IllegalArgumentException(String.format("DataProvider collection '%s' is not a list.", items.getClass().getSimpleName())); }
Source:
private static FBNetwork getFBNetworkForSubApp(SubApp subApp) { if(null != subApp.getType()) { return subApp.getType().getFBNetwork(); } else if(null != subApp.getOpposite()) { return ((SubApp)subApp.getOpposite()).getSubAppNetwork(); } else { return subApp.getSubAppNetwork(); } }

Target:
private static FBNetwork getFBNetworkForSubApp(SubApp subApp) { FBNetwork retVal = subApp.getSubAppNetwork(); if(null == retVal) { if(null != subApp.getType()) { retVal = subApp.getType().getFBNetwork(); } else if(null != subApp.getOpposite()) { retVal = ((SubApp)subApp.getOpposite()).getSubAppNetwork(); } } return retVal; }
Source:
public Map<String, Serializable> jobResultMap(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId) throws NotConnectedRestException, PermissionRestException, UnknownJobRestException { try { Scheduler s = checkAccess(sessionId, PATH_JOBS + jobId + "/resultmap"); JobResult jobResult = PAFuture.getFutureValue(s.getJobResult(jobId)); if (jobResult == null) { return null; } else { return jobResult.getResultMap(); } } catch (PermissionException e) { throw new PermissionRestException(e); } catch (UnknownJobException e) { throw new UnknownJobRestException(e); } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } }

Target:
public Map<String, String> jobResultMap(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId) throws NotConnectedRestException, PermissionRestException, UnknownJobRestException { try { Scheduler s = checkAccess(sessionId, PATH_JOBS + jobId + "/resultmap"); JobResult jobResult = PAFuture.getFutureValue(s.getJobResult(jobId)); if (jobResult == null) { return null; } else { return getJobResultMapAsString(jobResult.getResultMap()); } } catch (PermissionException e) { throw new PermissionRestException(e); } catch (UnknownJobException e) { throw new UnknownJobRestException(e); } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } }
Source:
public Object updateStatusOnGH(Runnable closure) throws ANTLRException { GitHubPRStatusStepDslContext context = new GitHubPRStatusStepDslContext(); executeInContext(closure, context); return new GitHubPRBuildStatusPublisher( context.message(), null, null, null, null ); }

Target:
public Object updateStatusOnGH(Runnable closure) { GitHubPRStatusStepDslContext context = new GitHubPRStatusStepDslContext(); executeInContext(closure, context); return new GitHubPRStatusBuilder(context.message()); }
Source:
public ProxyInputStream( InputStream originalInput, final InterceptCallback callback) throws IOException { this.originalInput = originalInput; proxyInput = new PipedInputStream(); try { proxyOutput = new PipedOutputStream(proxyInput); } catch (IOException e) { callback.done(null, e); ParseIOUtils.closeQuietly(proxyOutput); ParseIOUtils.closeQuietly(proxyInput); throw e; } Task.call(new Callable<Void>() { @Override public Void call() throws Exception { callback.done(proxyInput, null); return null; } }, ParseExecutors.io()); }

Target:
public ProxyInputStream( InputStream originalInput, final InterceptCallback callback) throws IOException { this.originalInput = originalInput; PipedInputStream tempProxyInput = new PipedInputStream(); PipedOutputStream tempProxyOutput = null; try { tempProxyOutput = new PipedOutputStream(tempProxyInput); } catch (IOException e) { callback.done(null, e); ParseIOUtils.closeQuietly(tempProxyOutput); ParseIOUtils.closeQuietly(tempProxyInput); throw e; } proxyInput = tempProxyInput; proxyOutput = tempProxyOutput; Task.call(new Callable<Void>() { @Override public Void call() throws Exception { callback.done(proxyInput, null); return null; } }, ParseExecutors.io()); }
Source:
Board(Square[][] grid) { assert grid != null; this.board = (Square[][]) grid.clone(); assert invariant() : "Initial grid cannot contain null squares"; }

Target:
Board(Square[][] grid) { assert grid != null; this.board = grid; assert invariant() : "Initial grid cannot contain null squares"; }
Source:
private static Hasher addValue(final Hasher hasher, final ReadableColumn column, final int row) { switch (column.getType()) { case BOOLEAN_TYPE: return hasher.putBoolean(column.getBoolean(row)); case DATETIME_TYPE: return hasher.putObject(column.getDateTime(row), TypeFunnel.INSTANCE); case DOUBLE_TYPE: return hasher.putDouble(column.getDouble(row)); case FLOAT_TYPE: return hasher.putFloat(column.getFloat(row)); case INT_TYPE: return hasher.putInt(column.getInt(row)); case LONG_TYPE: return hasher.putLong(column.getLong(row)); case STRING_TYPE: return hasher.putObject(column.getString(row), TypeFunnel.INSTANCE); default: throw new UnsupportedOperationException("Hashing a column of type " + column.getType()); } }

Target:
private static Hasher addValue(final Hasher hasher, final ReadableColumn column, final int row) { switch (column.getType()) { case BOOLEAN_TYPE: return hasher.putBoolean(column.getBoolean(row)); case DATETIME_TYPE: return hasher.putObject(column.getDateTime(row), TypeFunnel.INSTANCE); case DOUBLE_TYPE: return hasher.putDouble(column.getDouble(row)); case FLOAT_TYPE: return hasher.putFloat(column.getFloat(row)); case INT_TYPE: return hasher.putInt(column.getInt(row)); case LONG_TYPE: return hasher.putLong(column.getLong(row)); case STRING_TYPE: return hasher.putObject(column.getString(row), TypeFunnel.INSTANCE); default: throw new UnsupportedOperationException( "Hashing a column of type " + column.getType() + " is unsupported"); } }
Source:
public void create_new_instances_with_current_time() { final Timestamp beforeCall = Timestamps2.secondsAgo(1); final Command command = commandFactory.create(StringValue.getDefaultInstance()); final Timestamp afterCall = TimeTests.Future.secondsFromNow(1); assertTrue(Timestamps2.isBetween(command.getContext().getTimestamp(), beforeCall, afterCall)); }

Target:
public void create_new_instances_with_current_time() { final Timestamp beforeCall = TimeTests.Past.secondsAgo(1); final Command command = commandFactory.create(StringValue.getDefaultInstance()); final Timestamp afterCall = TimeTests.Future.secondsFromNow(1); assertTrue(Timestamps2.isBetween(command.getContext().getTimestamp(), beforeCall, afterCall)); }
Source:
private RefactoringStatus checkNonAbstractMembersInDestinationClasses(IMember[] membersToPushDown, IType[] destinationClassesForNonAbstract) throws JavaModelException { RefactoringStatus result= new RefactoringStatus(); List<IMember> list= new ArrayList<>(); list.addAll(Arrays.asList(membersToPushDown)); list.removeAll(Arrays.asList(getAbstractMembers(membersToPushDown))); IMember[] nonAbstractMembersToPushDown= list.toArray(new IMember[list.size()]); for (IType t : destinationClassesForNonAbstract) { result.merge(MemberCheckUtil.checkMembersInDestinationType(nonAbstractMembersToPushDown, t)); } return result; }

Target:
private RefactoringStatus checkNonAbstractMembersInDestinationClasses(IMember[] membersToPushDown, IType[] destinationClassesForNonAbstract) throws JavaModelException { RefactoringStatus result= new RefactoringStatus(); List<IMember> list= new ArrayList<>(); list.addAll(Arrays.asList(membersToPushDown)); list.removeAll(Arrays.asList(getAbstractMembers(membersToPushDown))); IMember[] nonAbstractMembersToPushDown= list.toArray(new IMember[list.size()]); for (IType type : destinationClassesForNonAbstract) { result.merge(MemberCheckUtil.checkMembersInDestinationType(nonAbstractMembersToPushDown, type)); } return result; }
Source:
protected void beforeTest() { beforeTestSetup(); client = clientSetup(pipeline -> new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(pipeline) .buildClient()); }

Target:
protected void beforeTest() { beforeTestSetup(); }
Source:
private static void forbidSystemExitCall() { final SecurityManager securityManager = new SecurityManager() { @Override public void checkExit(int status) { super.checkExit(status); throw new ExitTrappedException(); } @Override public void checkPermission(Permission permission) { } @Override public void checkPermission(Permission var1, Object var2) { } @Override public void checkSecurityAccess(String var1) { } @Override public void checkConnect(String var1, int var2, Object var3) { } @Override public void checkWrite(String var1) { } @Override public void checkDelete(String var1) { } @Override public void checkConnect(String var1, int var2) { } @Override public void checkLink(String var1) { } @Override public void checkRead(FileDescriptor var1) { } @Override public void checkAccess(Thread var1) { } @Override public void checkAccess(ThreadGroup var1) { } @Override public void checkCreateClassLoader() { } @Override public void checkListen(int var1) { } @Override public void checkAccept(String var1, int var2) { } @Override public void checkMulticast(InetAddress var1) { } @Override public void checkMulticast(InetAddress var1, byte var2) { } @Override public void checkPropertiesAccess() { } @Override public void checkPropertyAccess(String var1) { } @Override public void checkPackageAccess(String var1) { } @Override public void checkPackageDefinition(String var1) { } @Override public void checkSetFactory() { } }; System.setSecurityManager(securityManager); }

Target:
private static void forbidSystemExitCall() { System.setSecurityManager(securityManager); }
Source:
static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action) { Request request = action.getRequest(); List<RequestHandler> requestHandlers = picasso.getRequestHandlers(); if (requestHandlers != null && !requestHandlers.isEmpty()) { for (RequestHandler requestHandler : requestHandlers) { if (request.resourceId != 0 && !(requestHandler instanceof ResourceRequestHandler)) { continue; } if (requestHandler.canHandleRequest(request)) { return new BitmapHunter(picasso, dispatcher, cache, stats, action, requestHandler); } } } throw new IllegalStateException("Unrecognized type of URI: " + request.uri); }

Target:
static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action) { Request request = action.getRequest(); List<RequestHandler> requestHandlers = picasso.getRequestHandlers(); final int count = requestHandlers.size(); for (int i = 0; i < count; i++) { RequestHandler requestHandler = requestHandlers.get(i); if (requestHandler.canHandleRequest(request)) { return new BitmapHunter(picasso, dispatcher, cache, stats, action, requestHandler); } } throw new IllegalStateException("Unrecognized type of request: " + request); }
Source:
public DialogWithTitle(String title) { this.title = title; }

Target:
public DialogWithTitle(String title) { this(new WithTextMatcher(title)); }
Source:
public String build(final Date prev, final Date current) throws IOException { final DateFormat format = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm'Z'", Locale.ENGLISH ); format.setTimeZone(TimeZone.getTimeZone("UTC")); final Collection<String> lines = new LinkedList<>(); final Map<String, String> params = new MapOf<String, String>( new MapEntry<String, String>("since", format.format(prev)), new MapEntry<String, String>("until", format.format(current)) ); final List<RepoCommit.Smart> commits = new ListOf<>( new Smarts<RepoCommit.Smart>( this.repo.commits().iterate(params) ) ); int count = 0; for (final RepoCommit.Smart commit : commits) { if (count >= CommitsLog.MAX) { lines.add( String.format( " * and %d more...", commits.size() - CommitsLog.MAX ) ); break; } lines.add(CommitsLog.asText(commit)); ++count; } return new JoinedText( "\n", lines ).asString(); }

Target:
public String build(final Date prev, final Date current) throws IOException { final DateFormat format = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm'Z'", Locale.ENGLISH ); format.setTimeZone(TimeZone.getTimeZone("UTC")); final Collection<String> lines = new LinkedList<>(); final Map<String, String> params = new SolidMap<String, String>( new MapEntry<String, String>("since", format.format(prev)), new MapEntry<String, String>("until", format.format(current)) ); final SolidList<Smart> commits = new SolidList<>( new Smarts<RepoCommit.Smart>( this.repo.commits().iterate(params) ) ); int count = 0; for (final RepoCommit.Smart commit : commits) { if (count >= CommitsLog.MAX) { lines.add( String.format( " * and %d more...", commits.size() - CommitsLog.MAX ) ); break; } lines.add(CommitsLog.asText(commit)); ++count; } return new JoinedText( "\n", lines ).asString(); }
Source:
private boolean canAdd(IPluginModelBase candidate) { ISiteBundle[] currentBundles = fModel.getSite().getBundles(); IPluginBase candidateBundle = candidate.getPluginBase(); for (ISiteBundle currentBundle : currentBundles) { if (currentBundle.getId().equals(candidateBundle.getId()) && (currentBundle.getVersion() == null || currentBundle.getVersion().equals(candidateBundle.getVersion()))) return false; } return true; }

Target:
private boolean canAdd(IPluginModelBase candidate) { ISiteBundle[] currentBundles = fModel.getSite().getBundles(); IPluginBase candidateBundle = candidate.getPluginBase(); String candidateId = candidateBundle.getId(); String candidateVersion = candidateBundle.getVersion(); for (ISiteBundle currentBundle : currentBundles) { if (currentBundle.getId().equals(candidateId) && (currentBundle.getVersion() == null || currentBundle.getVersion().equals(candidateVersion))) return false; } return true; }
Source:
public static Optional<String> getShortScienceSearchURL(BibEntry entry) { return entry.getField(StandardField.TITLE).map(title -> { URIBuilder uriBuilder; try { uriBuilder = new URIBuilder(SHORTSCIENCE_SEARCH_URL); } catch (URISyntaxException e) { throw new AssertionError("ShortScience URL is invalid."); } uriBuilder.addParameter("q", title); return uriBuilder.toString(); }); }

Target:
public static Optional<String> getShortScienceSearchURL(BibEntry entry) { return entry.getField(StandardField.TITLE).map(title -> { URIBuilder uriBuilder; try { uriBuilder = new URIBuilder(SHORTSCIENCE_SEARCH_URL); } catch (URISyntaxException e) { throw new AssertionError("ShortScience URL is invalid.", e); } uriBuilder.addParameter("q", title); return uriBuilder.toString(); }); }
Source:
public static FieldRef wrap(final Field f) { return new FieldRef() { @Override public <T extends Annotation> T getAnnotation(Class<T> type) { return f.getAnnotation(type); } @Override public String getName() { return f.getName(); } @Override public Object get(Object instance) throws IllegalAccessException { try { return f.get(instance); } catch (IllegalAccessException e) { LOGGER.warning(e.getMessage() + ", please report to the respective component"); f.setAccessible(true); return f.get(instance); } } @Override public boolean isStatic() { return Modifier.isStatic(f.getModifiers()); } @Override public Class<?> getReturnType() { return f.getType(); } @Override public String getSignature() { String prefix = isStatic() ? "staticField" : "field"; return StringUtils.join(Arrays.asList(prefix, f.getDeclaringClass().getName(), getName()), ' '); } @Override public String getQualifiedName() { return f.getDeclaringClass().getName()+"."+getName(); } @Override public boolean isRoutable() { return Modifier.isPublic(f.getModifiers()); } }; }

Target:
public static FieldRef wrap(final Field f) { return new FieldRef() { @Override public <T extends Annotation> T getAnnotation(Class<T> type) { return f.getAnnotation(type); } @Override public String getName() { return f.getName(); } @Override public Object get(Object instance) throws IllegalAccessException { try { return f.get(instance); } catch (IllegalAccessException e) { LOGGER.log(Level.WARNING, "Please report to the respective component", e); f.setAccessible(true); return f.get(instance); } } @Override public boolean isStatic() { return Modifier.isStatic(f.getModifiers()); } @Override public Class<?> getReturnType() { return f.getType(); } @Override public String getSignature() { String prefix = isStatic() ? "staticField" : "field"; return StringUtils.join(Arrays.asList(prefix, f.getDeclaringClass().getName(), getName()), ' '); } @Override public String getQualifiedName() { return f.getDeclaringClass().getName()+"."+getName(); } @Override public boolean isRoutable() { return Modifier.isPublic(f.getModifiers()); } }; }
Source:
public static Cohort intersect(Cohort a, Cohort b) { Cohort ret = new Cohort(); ret.setName("(" + (a == null ? "NULL" : a.getName()) + " * " + (b == null ? "NULL" : b.getName()) + ")"); List<CohortMembership> cohortMemberships = new ArrayList<CohortMembership>(); for(CohortMembership a_member: a.getMemberships()){ for(CohortMembership b_member: b.getMemberships()){ if(a_member.getPatientId() == b_member.getPatientId()){ if(a_member.getStartDate().before(b_member.getStartDate())){ cohortMemberships.add(b_member); } } } } ret.getMemberships().addAll(cohortMemberships); return ret; }

Target:
public static Cohort intersect(Cohort a, Cohort b) { Cohort ret = new Cohort(); ret.setName("(" + (a == null ? "NULL" : a.getName()) + " * " + (b == null ? "NULL" : b.getName()) + ")"); List<CohortMembership> cohortMemberships = new ArrayList<CohortMembership>(); for(CohortMembership a_member: a.getMemberships()){ for(CohortMembership b_member: b.getMemberships()){ if(a_member.getPatientId() == b_member.getPatientId()){ if(a_member.getStartDate() != null && b_member.getStartDate() != null ) { cohortMemberships.add(a_member.getStartDate().before(b_member.getStartDate()) || a_member.getStartDate().equals(b_member.getStartDate()) ? b_member : a_member); } else { cohortMemberships.add(a_member.getStartDate() == null ? a_member : b_member); } } } } ret.getMemberships().addAll(cohortMemberships); return ret; }
Source:
private LineData generateWeightData() { List<String> xVals = new ArrayList<>(); List<Entry> yVals = new ArrayList<>(); int k = 0; for (int i = presenter.getWeightReadings().size() - 1; i >= 0; i--) { float val = Float.parseFloat(presenter.getWeightReadings().get(i).toString()); yVals.add(new Entry(k, val)); k++; } for (int i = presenter.getWeightReadingsDateTime().size() - 1; i >= 0; i--) { String date = presenter.convertDate(presenter.getWeightReadingsDateTime().get(i)); xVals.add(date + ""); } xValues = xVals; return new LineData(generateLineDataSet(yVals, getResources().getColor(R.color.glucosio_fab_weight))); }

Target:
private LineData generateWeightData() { List<String> xVals = new ArrayList<>(); List<Entry> yVals = new ArrayList<>(); int k = 0; for (int i = presenter.getWeightReadings().size() - 1; i >= 0; i--) { float val = Float.parseFloat(presenter.getWeightReadings().get(i).toString()); yVals.add(new Entry(k, val)); k++; } for (int i = presenter.getWeightReadingsDateTime().size() - 1; i >= 0; i--) { String date = presenter.convertDate(presenter.getWeightReadingsDateTime().get(i)); xVals.add(date); } xValues = xVals; return new LineData(generateLineDataSet(yVals, getResources().getColor(R.color.glucosio_fab_weight))); }
Source:
public void downloadFile(String urlPath, Path toFile) throws IOException { if (!urlPath.startsWith("/")) { throw new IllegalArgumentException(format("URL path must start with slash: %s", urlPath)); } String url = baseUrlWithoutTrailingSlash + urlPath; logger.debug(format("Download %s to %s", url, toFile.toAbsolutePath().toString())); ResponseBody responseBody = callUrl(url); try (InputStream in = responseBody.byteStream()) { Files.copy(in, toFile, StandardCopyOption.REPLACE_EXISTING); } catch (IOException | RuntimeException e) { Utils.deleteQuietly(toFile); throw e; }finally { responseBody.close(); } }

Target:
public void downloadFile(String urlPath, Path toFile) throws IOException { if (!urlPath.startsWith("/")) { throw new IllegalArgumentException(format("URL path must start with slash: %s", urlPath)); } String url = baseUrlWithoutTrailingSlash + urlPath; logger.debug(format("Download %s to %s", url, toFile.toAbsolutePath().toString())); try (ResponseBody responseBody = callUrl(url); InputStream in = responseBody.byteStream()) { Files.copy(in, toFile, StandardCopyOption.REPLACE_EXISTING); } catch (IOException | RuntimeException e) { Utils.deleteQuietly(toFile); throw e; } }
Source:
public RouterServerSSLTest(boolean testEncryption) { if (testEncryption) { testFramework.setTestEncryption(); } }

Target:
public RouterServerSSLTest(boolean testEncryption) { testFramework.setTestEncryption(testEncryption); }
Source:
private Organization loadOrganization(ScannerReport.Metadata reportMetadata) { try (DbSession dbSession = dbClient.openSession(false)) { analysisMetadata.setOrganizationsEnabled(organizationFlags.isEnabled(dbSession)); Organization organization = toOrganization(dbSession, ceTask.getOrganizationUuid()); checkOrganizationKeyConsistency(reportMetadata, organization); analysisMetadata.setOrganization(organization); return organization; } }

Target:
private Organization loadOrganization(ScannerReport.Metadata reportMetadata) { try (DbSession dbSession = dbClient.openSession(false)) { Organization organization = toOrganization(dbSession, ceTask.getOrganizationUuid()); checkOrganizationKeyConsistency(reportMetadata, organization); analysisMetadata.setOrganization(organization); analysisMetadata.setOrganizationsEnabled(organizationFlags.isEnabled(dbSession)); return organization; } }
Source:
public static void SYSCS_PERFORM_MAJOR_COMPACTION_ON_TABLE(String schemaName,String tableName) throws SQLException { LanguageConnectionContext lcc = (LanguageConnectionContext) ContextService.getContext(LanguageConnectionContext.CONTEXT_ID); assert lcc != null; DataDictionary dd = lcc.getDataDictionary(); PartitionFactory tableFactory = SIDriver.driver().getTableFactory(); schemaName = EngineUtils.validateSchema(schemaName); tableName = EngineUtils.validateTable(tableName); for (long conglomID : getConglomNumbers(getDefaultConn(), schemaName, tableName)) { try { ConglomerateDescriptor cd = dd.getConglomerateDescriptor(conglomID); if (cd != null) { TableDescriptor td = dd.getTableDescriptor(cd.getTableID()); if (td != null && td.isExternal()) continue; } } catch (StandardException e) { throw PublicAPI.wrapStandardException(Exceptions.parseException(e)); } try (Partition partition = tableFactory.getTable(Long.toString(conglomID))) { partition.compact(true); } catch (IOException e) { throw PublicAPI.wrapStandardException(Exceptions.parseException(e)); } } }

Target:
public static void SYSCS_PERFORM_MAJOR_COMPACTION_ON_TABLE(String schemaName,String tableName) throws SQLException { LanguageConnectionContext lcc = (LanguageConnectionContext) ContextService.getContext(LanguageConnectionContext.CONTEXT_ID); assert lcc != null; DataDictionary dd = lcc.getDataDictionary(); PartitionFactory tableFactory = SIDriver.driver().getTableFactory(); schemaName = EngineUtils.validateSchema(schemaName); tableName = tableName == null ? null : EngineUtils.validateTable(tableName); for (long conglomID : getConglomNumbers(getDefaultConn(), schemaName, tableName)) { try { ConglomerateDescriptor cd = dd.getConglomerateDescriptor(conglomID); if (cd != null) { TableDescriptor td = dd.getTableDescriptor(cd.getTableID()); if (td != null && td.isExternal()) continue; } } catch (StandardException e) { throw PublicAPI.wrapStandardException(Exceptions.parseException(e)); } try (Partition partition = tableFactory.getTable(Long.toString(conglomID))) { partition.compact(true); } catch (IOException e) { throw PublicAPI.wrapStandardException(Exceptions.parseException(e)); } } }
Source:
private void backoff(int numberOfAttempts) { try { long sleepMillis = (long) Math.pow(2, numberOfAttempts) * 50; LOGGER.debug("Throttled by DynamoDB, sleeping for ms.", sleepMillis); Thread.sleep(sleepMillis); } catch (InterruptedException e) { LOGGER.error("Interrupted while attempting exponential backoff."); } }

Target:
private void backoff(int numberOfAttempts) { try { long sleepMillis = (long) Math.pow(2, numberOfAttempts) * 50; LOGGER.warn("Throttled by DynamoDB, sleeping for ms.", sleepMillis); Thread.sleep(sleepMillis); } catch (InterruptedException e) { LOGGER.error("Interrupted while attempting exponential backoff."); } }
Source:
public static Query of(Query source) { Assert.notNull(source, "Source must not be null!"); Document sourceFields = source.getFieldsObject(); Document sourceSort = source.getSortObject(); Document sourceQuery = source.getQueryObject(); Query target = new Query() { @Override public Document getFieldsObject() { return BsonUtils.merge(sourceFields, super.getFieldsObject()); } @Override public Document getSortObject() { return BsonUtils.merge(sourceSort, super.getSortObject()); } @Override public Document getQueryObject() { return BsonUtils.merge(sourceQuery, super.getQueryObject()); } @Override public boolean isSorted() { return source.isSorted() || super.isSorted(); } }; Query theQuery = ProxyUtils.unwrapTargetSource(source); target.skip = theQuery.skip; target.limit = theQuery.limit; target.hint = theQuery.hint; target.collation = theQuery.collation; target.restrictedTypes.addAll(theQuery.restrictedTypes); if (source.getMeta().hasValues()) { target.setMeta(new Meta(source.getMeta())); } return target; }

Target:
public static Query of(Query source) { Assert.notNull(source, "Source must not be null!"); Document sourceFields = source.getFieldsObject(); Document sourceSort = source.getSortObject(); Document sourceQuery = source.getQueryObject(); Query target = new Query() { @Override public Document getFieldsObject() { return BsonUtils.merge(sourceFields, super.getFieldsObject()); } @Override public Document getSortObject() { return BsonUtils.merge(sourceSort, super.getSortObject()); } @Override public Document getQueryObject() { return BsonUtils.merge(sourceQuery, super.getQueryObject()); } @Override public boolean isSorted() { return source.isSorted() || super.isSorted(); } }; target.skip = source.getSkip(); target.limit = source.getLimit(); target.hint = source.getHint(); target.collation = source.getCollation(); target.restrictedTypes.addAll(source.getRestrictedTypes()); if (source.getMeta().hasValues()) { target.setMeta(new Meta(source.getMeta())); } return target; }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; boolean persistentAuth = "persistent-auth".equals(req.getHeader("Prefer")); if (persistentAuth && (req.getHeader("Authorization") != null || !containsJessionId(req))) { if (req.getSession(false) != null) { req.getSession().removeAttribute(FiltersHelper.Constants.AUTHENTICATED_KEY); } } chain.doFilter(request, response); HttpSession session = req.getSession(false); if (session != null && Boolean.TRUE.equals(session.getAttribute(FiltersHelper.Constants.AUTHENTICATED_KEY))) { String engineSessionId = (String) session.getAttribute(FiltersHelper.Constants.ENGINE_SESSION_ID_KEY); if (!persistentAuth) { try { InitialContext ctx = new InitialContext(); VdcActionParametersBase params = new VdcActionParametersBase(); params.setSessionId(engineSessionId); FiltersHelper.getBackend(ctx).runAction(VdcActionType.LogoutBySession, params); session.invalidate(); FiltersHelper.closeContext(ctx); } catch (Exception ex) { log.error(String.format("Error in logout. Message is: %1$s", ex.getMessage())); if (log.isDebugEnabled()) { log.debug("", ex); } } } else { Cookie cookie = new Cookie("JESSIONID", engineSessionId); cookie.setPath("/api"); resp.addCookie(cookie); } } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; boolean persistentAuth = "persistent-auth".equals(req.getHeader("Prefer")); if (persistentAuth && (req.getHeader("Authorization") != null || !containsJessionId(req))) { if (req.getSession(false) != null) { req.getSession().removeAttribute(FiltersHelper.Constants.AUTHENTICATED_KEY); } } chain.doFilter(request, response); HttpSession session = req.getSession(false); if (session != null && Boolean.TRUE.equals(session.getAttribute(FiltersHelper.Constants.AUTHENTICATED_KEY))) { String engineSessionId = (String) session.getAttribute(FiltersHelper.Constants.ENGINE_SESSION_ID_KEY); if (!persistentAuth) { InitialContext ctx = new InitialContext(); try { VdcActionParametersBase params = new VdcActionParametersBase(); params.setSessionId(engineSessionId); FiltersHelper.getBackend(ctx).runAction(VdcActionType.LogoutBySession, params); session.invalidate(); } finally { FiltersHelper.closeContext(ctx); } } else { Cookie cookie = new Cookie("JESSIONID", engineSessionId); cookie.setPath("/api"); resp.addCookie(cookie); } } } catch (Exception ex) { log.error(String.format("Error in REST-API session management. Message is: %1$s", ex.getMessage())); if (log.isDebugEnabled()) { log.debug("", ex); } } }
Source:
public Function<Solution_, Score<?>> createExtractor() { SolutionDescriptor<Solution_> solutionDescriptor = constraintConfigurationDescriptor.getSolutionDescriptor(); MemberAccessor constraintConfigurationMemberAccessor = solutionDescriptor.getConstraintConfigurationMemberAccessor(); return (Solution_ solution) -> { Object constraintConfiguration = Objects.requireNonNull(constraintConfigurationMemberAccessor.executeGetter(solution), "Constraint configuration provider (" + constraintConfigurationMemberAccessor + ") is null."); return (Score<?>) memberAccessor.executeGetter(constraintConfiguration); }; }

Target:
public Function<Solution_, Score<?>> createExtractor() { SolutionDescriptor<Solution_> solutionDescriptor = constraintConfigurationDescriptor.getSolutionDescriptor(); MemberAccessor constraintConfigurationMemberAccessor = solutionDescriptor.getConstraintConfigurationMemberAccessor(); return (Solution_ solution) -> { Object constraintConfiguration = Objects.requireNonNull(constraintConfigurationMemberAccessor.executeGetter(solution), "Constraint configuration provider (" + constraintConfigurationMemberAccessor + ") returns null."); return (Score<?>) memberAccessor.executeGetter(constraintConfiguration); }; }
Source:
private AbstractTopology getTopology(StartAction startAction, Map<Integer, String> hostGroups, JoinCoordinator joinCoordinator) { AbstractTopology topology = null; Map<Integer, Integer> sitesPerHostMap = m_messenger.getSitesPerHostMapFromZK(); if (startAction == StartAction.JOIN) { assert(joinCoordinator != null); JSONObject topoJson = joinCoordinator.getTopology(); try { return AbstractTopology.topologyFromJSON(topoJson); } catch (JSONException e) { VoltDB.crashLocalVoltDB("Unable to get topology from Json object", true, e); } } else if (!startAction.doesRejoin()) { final Set<Integer> liveHostIds = m_messenger.getLiveHostIds(); Preconditions.checkArgument(hostGroups.keySet().equals(liveHostIds)); int hostcount = liveHostIds.size(); int kfactor = m_catalogContext.getDeployment().getCluster().getKfactor(); String errMsg = AbstractTopology.validateLegacyClusterConfig(hostcount, sitesPerHostMap, kfactor); if (errMsg != null) { VoltDB.crashLocalVoltDB(errMsg, false, null); } topology = AbstractTopology.getTopology(sitesPerHostMap, hostGroups, kfactor); TopologyZKUtils.registerTopologyToZK(m_messenger.getZK(), topology); } else { topology = TopologyZKUtils.readTopologyFromZK(m_messenger.getZK()); } return topology; }

Target:
private AbstractTopology getTopology(StartAction startAction, Map<Integer, String> hostGroups, JoinCoordinator joinCoordinator) { AbstractTopology topology = null; Map<Integer, Integer> sitesPerHostMap = m_messenger.getSitesPerHostMapFromZK(); if (startAction == StartAction.JOIN) { assert(joinCoordinator != null); JSONObject topoJson = joinCoordinator.getTopology(); try { topology = AbstractTopology.topologyFromJSON(topoJson); } catch (JSONException e) { VoltDB.crashLocalVoltDB("Unable to get topology from Json object", true, e); } } else if (startAction.doesRejoin()) { topology = TopologyZKUtils.readTopologyFromZK(m_messenger.getZK()); } else { final Set<Integer> liveHostIds = m_messenger.getLiveHostIds(); Preconditions.checkArgument(hostGroups.keySet().equals(liveHostIds)); int hostcount = liveHostIds.size(); int kfactor = m_catalogContext.getDeployment().getCluster().getKfactor(); String errMsg = AbstractTopology.validateLegacyClusterConfig(hostcount, sitesPerHostMap, kfactor); if (errMsg != null) { VoltDB.crashLocalVoltDB(errMsg, false, null); } topology = AbstractTopology.getTopology(sitesPerHostMap, hostGroups, kfactor); TopologyZKUtils.registerTopologyToZK(m_messenger.getZK(), topology); } return topology; }
Source:
public DeleteBulkFactory(Settings settings, MetadataExtractor metaExtractor, EsMajorVersion version) { super(settings.copy().setSerializerValueWriterClassName(NoDataWriter.class.getName()), metaExtractor, version); }

Target:
public DeleteBulkFactory(Settings settings, MetadataExtractor metaExtractor, EsMajorVersion version) { super(settings, metaExtractor, version); }
Source:
public OpenPacket(final Header header, final ByteBuf buffer, final PeerFlags flags) { this.header = Objects.requireNonNull(header); this.version = uint8(buffer); this.as = uint16(buffer); this.holdTime = uint16(buffer); this.id = InetAddressUtils.getInetAddress(bytes(buffer, 4)); final int parametersLength = uint8(buffer); final List<Parameter> list = repeatRemaining(slice(buffer, parametersLength), Parameter::new); parameters = list.stream().filter(p -> p.type != 2).collect(Collectors.toList()); capabilities = list.stream().filter(p -> p.type == 2).flatMap(p -> repeatRemaining(slice(p.value, p.length), Capability::new).stream()).collect(Collectors.toList()); }

Target:
public OpenPacket(final Header header, final ByteBuf buffer, final PeerFlags flags) { this.header = Objects.requireNonNull(header); this.version = uint8(buffer); this.as = uint16(buffer); this.holdTime = uint16(buffer); this.id = InetAddressUtils.getInetAddress(bytes(buffer, 4)); final int parametersLength = uint8(buffer); this.parameters = repeatRemaining(slice(buffer, parametersLength), Parameter::new); this.capabilities = this.parameters.stream().filter(p -> p.type == 2).flatMap(p -> repeatRemaining(slice(p.value, p.length), Capability::new).stream()).collect(Collectors.toList()); }
Source:
private void setSecureStorageMasterPasswords(boolean checked) { WorkbenchPreferenceDialog preferenceDialog = new WorkbenchPreferenceDialog(); StoragePreferencePage storagePage = new StoragePreferencePage(preferenceDialog); preferenceDialog.open(); preferenceDialog.select(storagePage); try { new WaitUntil(new WidgetIsFound( org.eclipse.swt.custom.CLabel.class, new WithMnemonicTextMatcher("Secure Storage")), TimePeriod.DEFAULT); log.info("Getting master password providers"); List<PasswordProvider> items = storagePage.getMasterPasswordProviders(); for (PasswordProvider item : items) { log.info("Uncheking table item: " + item.getDescription()); item.setEnabled(checked); } new WaitUntil(new JobIsRunning(), TimePeriod.DEFAULT, false); storagePage.apply(); } catch (WaitTimeoutExpiredException exc) { log.error("Secure Storage preferences page has timed out"); log.error(exc.getMessage()); } finally { preferenceDialog.ok(); } }

Target:
private void setSecureStorageMasterPasswords(boolean checked) { WorkbenchPreferenceDialog preferenceDialog = new WorkbenchPreferenceDialog(); StoragePreferencePage storagePage = new StoragePreferencePage(preferenceDialog); preferenceDialog.open(); preferenceDialog.select(storagePage); try { new WaitUntil(new WidgetIsFound( org.eclipse.swt.custom.CLabel.class, new WithMnemonicTextMatcher(CDKLabel.Labels.SECURE_STORAGE)), TimePeriod.DEFAULT); log.info("Getting master password providers"); List<PasswordProvider> items = storagePage.getMasterPasswordProviders(); for (PasswordProvider item : items) { log.info("Uncheking table item: " + item.getDescription()); item.setEnabled(checked); } new WaitUntil(new JobIsRunning(), TimePeriod.DEFAULT, false); storagePage.apply(); } catch (WaitTimeoutExpiredException exc) { log.error("Secure Storage preferences page has timed out"); log.error(exc.getMessage()); } finally { preferenceDialog.ok(); } }
Source:
public void testNominal() { int count = new java.util.Random().nextInt(10) + 3; Variables.register("count", count); for(int i = 0; i < count; i++) { Object key = Random.getObject(); Long value = Random.getLong(); Variables.register("key", key); Variables.register("value", value); map.insert(key, value); } Assert.assertEquals(VariableType.NOMINAL, map.variableType()); }

Target:
public void testNominal() { int count = new java.util.Random().nextInt(10) + 3; Variables.register("count", count); for(int i = 0; i < count; i++) { Object key = Variables.register("key_"+i, Random.getObject()); Long value = Variables.register("value_"+i, Random.getLong()); map.insert(key, value); } Assert.assertEquals(VariableType.NOMINAL, map.variableType()); }
Source:
private static int scoreFilter(Map<Subfield, TupleDomainFilter> filters){ final int lowestScore = 10; final int lowScore = 50; final int mediumScore = 100; final int maxScore = 1000; checkArgument(!filters.isEmpty()); if (filters.size() > 1){ return maxScore; } checkArgument(filters.size() == 1); Map.Entry<Subfield, TupleDomainFilter> filter = Iterables.getOnlyElement(filters.entrySet()); if(! filter.getKey().getPath().isEmpty()){ return maxScore; } TupleDomainFilter tdf = filter.getValue(); if(tdf instanceof BigintRange) { if(((BigintRange) tdf).isSingleValue()){ return lowestScore; } return lowScore; } if(tdf instanceof BigintValues || tdf instanceof BigintMultiRange) { return lowScore; } return mediumScore; }

Target:
private static int scoreFilter(Map<Subfield, TupleDomainFilter> filters) { checkArgument(!filters.isEmpty()); if (filters.size() > 1) { return 1000; } Map.Entry<Subfield, TupleDomainFilter> filterEntry = Iterables.getOnlyElement(filters.entrySet()); if (!filterEntry.getKey().getPath().isEmpty()) { return 1000; } TupleDomainFilter filter = filterEntry.getValue(); if (filter instanceof BigintRange) { if (((BigintRange) filter).isSingleValue()) { return 10; } return 50; } if (filter instanceof BigintValues || filter instanceof BigintMultiRange) { return 50; } return 100; }
Source:
public void testInsertIntoPartitionedWithSerdePropety() { String tableName = "target_partitioned_with_serde_property"; query(format("DROP TABLE IF EXISTS %s", tableName)); String query = format( "CREATE TABLE %s(" + "id int," + "name string" + ")" + "PARTITIONED BY (dt string)" + "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'" + "WITH SERDEPROPERTIES (" + "'field.delim'='\\t'," + "'line.delim'='\\n'," + "'serialization.format'='\\t'" + ")", tableName); onHive().executeQuery(query); assertThat(query("SELECT * FROM " + tableName)).hasNoRows(); assertThat(query("INSERT INTO " + tableName + " SELECT 1, 'presto', '2018-01-01'")).containsExactly(row(1)); assertThat(query("SELECT * FROM " + tableName)).containsOnly( row( 1, "presto", "2018-01-01")); query(format("DROP TABLE %s", tableName)); }

Target:
public void testInsertIntoPartitionedWithSerdePropety() { String tableNameInDatabase = mutableTablesState().get(PARTITIONED_TABLE_WITH_SERDE).getNameInDatabase(); assertThat(query("INSERT INTO " + tableNameInDatabase + " SELECT 1, 'presto', '2018-01-01'")).containsExactly(row(1)); assertThat(query("SELECT * FROM " + tableNameInDatabase)).containsExactly(row(1, "presto", "2018-01-01")); }
Source:
public Report getReport() { return this.report; }

Target:
public AssetReport getReport() { return this.report; }
Source:
public void logResourceModification(Object resource, Map<String, Object> data, AuditEventType eventType, String description, Long accountId, String clientIp) { if (data != null) { putInAsString(data, "resource", "Failed to convert resource to json.", resource); } publishEvent(auditLogDao.create(objectManager.getType(resource), parseId(String.valueOf(ObjectUtils.getId(resource))), data, null, accountId, null, eventType.toString(), null, null, description, clientIp)); }

Target:
public void logResourceModification(Object resource, Map<String, Object> data, AuditEventType eventType, String description, Long accountId, String clientIp) { if (data != null) { putInAsString(data, "resource", "Failed to convert resource to json.", resource); } String event = objectManager.getType(resource) + "." + eventType.toString(); publishEvent(auditLogDao.create(objectManager.getType(resource), parseId(String.valueOf(ObjectUtils.getId(resource))), data, null, accountId, null, event, null, null, description, clientIp)); }
Source:
private static Map<EClass, Integer> inferRootElementsCandidates(EPackage ePackage, Collection<EClass> concreteClasses) { Map<EClass, Integer> eClassToRootScore = new HashMap<>(); eClassToRootScore.clear(); List<EClass> allClasses = ePackage.getEClassifiers().stream().filter(c -> c instanceof EClass).map(c -> (EClass) c).collect(Collectors.toList()); for (EClass eClass : concreteClasses) { if (eClass.getEAllReferences().stream().anyMatch(EReference::isContainment)) { int importance = getReferenceScore(eClass, allClasses); if (importance != -1) { eClassToRootScore.put(eClass, importance); } } } return eClassToRootScore; }

Target:
private static Map<EClass, Integer> inferRootElementsCandidates(EPackage ePackage, Collection<EClass> concreteClasses) { Map<EClass, Integer> eClassToRootScore = new HashMap<>(); List<EClass> allClasses = ePackage.getEClassifiers().stream().filter(c -> c instanceof EClass).map(c -> (EClass) c).collect(Collectors.toList()); for (EClass eClass : concreteClasses) { if (eClass.getEAllReferences().stream().anyMatch(EReference::isContainment)) { int importance = getReferenceScore(eClass, allClasses); if (importance != -1) { eClassToRootScore.put(eClass, importance); } } } return eClassToRootScore; }
Source:
public Color getBackground(Object aElement, int aColumnIndex) { if (aElement instanceof GerritTask) { GerritTask item = (GerritTask) aElement; String state = item.getAttribute(GerritTask.IS_STARRED); if (state != null) { if (state.equals("true")) { return INCOMING_COLOR; } else if (state.equals("false")) { return CLOSED_COLOR; } } } return DEFAULT_COLOR; }

Target:
public Color getBackground(Object aElement, int aColumnIndex) { if (aElement instanceof GerritTask) { GerritTask item = (GerritTask) aElement; String state = item.getAttribute(GerritTask.IS_STARRED); if (state != null) { if (state.equals(Boolean.toString(true))) { return INCOMING_COLOR; } else if (state.equals(Boolean.toString(false))) { return CLOSED_COLOR; } } } return DEFAULT_COLOR; }
Source:
public void declarative() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "job with dir"); p.setDefinition(new CpsFlowDefinition(loadPipelineScript("declarativePod.groovy"), true)); WorkflowRun b = p.scheduleBuild2(0).waitForStart(); assertNotNull(b); r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("Apache Maven 3.3.9", b); r.assertLogContains("INSIDE_CONTAINER_ENV_VAR = " + CONTAINER_ENV_VAR_VALUE + "\n", b); }

Target:
public void declarative() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "declarative pipeline with podTemplate"); p.setDefinition(new CpsFlowDefinition(loadPipelineScript("declarativePod.groovy"), true)); WorkflowRun b = p.scheduleBuild2(0).waitForStart(); assertNotNull(b); r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("Apache Maven 3.3.9", b); r.assertLogContains("INSIDE_CONTAINER_ENV_VAR = " + CONTAINER_ENV_VAR_VALUE + "\n", b); }
Source:
public <T> T execute(ChannelCallback<T> action) { return doExecute(action, false); }

Target:
public <T> T execute(ChannelCallback<T> action) { return execute(action, getConnectionFactory()); }
Source:
static Key sanityCheck(Key prev, Key current, Key shortened) { if (prev.compareTo(shortened) >= 0) { LoggerFactory.getLogger(KeyShortener.class).warn("Bug in key shortening code, please open an issue " + prev + " >= " + shortened); return null; } if (current.compareTo(shortened) <= 0) { LoggerFactory.getLogger(KeyShortener.class).warn("Bug in key shortening code, please open an issue " + current + " <= " + shortened); return null; } return shortened; }

Target:
static Key sanityCheck(Key prev, Key current, Key shortened) { if (prev.compareTo(shortened) >= 0) { log.warn("Bug in key shortening code, please open an issue " + prev + " >= " + shortened); return prev; } if (current.compareTo(shortened) <= 0) { log.warn("Bug in key shortening code, please open an issue " + current + " <= " + shortened); return prev; } return shortened; }
Source:
public void clearChatBox(){ if(TextUtils.isEmpty(messageEt.getText())){ topicActv.setText(""); streamActv.setText(""); } }

Target:
public void clearChatBox() { if (messageEt != null) { if (TextUtils.isEmpty(messageEt.getText())) { topicActv.setText(""); streamActv.setText(""); } } }