auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object[][] isWithinHammingDistanceException() { return new Object[][] { {"ATAC", "GCT", 3, true}, {"ATAC", "AT", 2, false}, {"ATAC", "T", 1, false}, <START> {"", "GCAT", 0, false} <END> }; }</code><technical_language>params nicely aligned above, ;)</technical_language>

Target:
public Object[][] isWithinHammingDistanceException() { return new Object[][] { {"ATAC", "GCT" , 3}, {"ATAC", "AT" , 2}, {"ATAC", "T" , 1}, {"" , "GCAT", 0} }; }
Source:
<code>private void validateAndClose() throws Exception { try { info("Validating static and Helix cluster maps"); verifyEquivalencyWithStaticClusterMap(staticClusterMap.hardwareLayout, staticClusterMap.partitionLayout); if (validatingHelixClusterManager != null) { <START> ensureOrThrow(validatingHelixClusterManager.getErrorCount() == 0, <END> "Helix cluster manager should not have encountered any errors"); } } finally { if (validatingHelixClusterManager != null) { validatingHelixClusterManager.close(); } for (HelixAdmin admin : adminForDc.values()) { admin.close(); } } }</code><technical_language>Exception is thrown in this method</technical_language>

Target:
private void validateAndClose() { try { info("Validating static and Helix cluster maps"); verifyEquivalencyWithStaticClusterMap(staticClusterMap.hardwareLayout, staticClusterMap.partitionLayout); if (validatingHelixClusterManager != null) { ensureOrThrow(validatingHelixClusterManager.getErrorCount() == 0, "Helix cluster manager should not have encountered any errors"); } } finally { if (validatingHelixClusterManager != null) { validatingHelixClusterManager.close(); } for (HelixAdmin admin : adminForDc.values()) { admin.close(); } } }
Source:
<code>public OutputWriter createOutputWriter() { List<String> headers = new ArrayList<String>() ; for (int i = 0; i < columns.length; i++) { String columnName = columns[i].getName(); headers.add(columnName); if(columnToBeSortedOn != null) { if(columnName.equals(columnToBeSortedOn.getName())){ indexOfColumnToBeSortedOn = i ; } } } if(columnToBeSortedOn != null) { if(indexOfColumnToBeSortedOn == -1) { this.isColumnToBeSortedOnPresentInInput = false ; indexOfColumnToBeSortedOn = columns.length ; headers.add(columnToBeSortedOn.getName()) ; InputColumn<?>[] newColumns = new InputColumn<?>[columns.length + 1] ; for(int i = 0; i < columns.length; i++){ newColumns[i] = columns[i] ; } newColumns[columns.length] = columnToBeSortedOn ; <START> columns = newColumns ; <END> } } return CsvOutputWriterFactory.getWriter(_targetFile.getPath(), headers.toArray(new String[0]), separatorChar, quoteChar, escapeChar, includeHeader, columns); }</code><technical_language>minor: "columns" field ideally change. is set job configuration considered immutable</technical_language>

Target:
public OutputWriter createOutputWriter() { InputColumn<?>[] inputColumns = columns ; List<String> headers = new ArrayList<String>() ; for (int i = 0; i < columns.length; i++) { String columnName = columns[i].getName(); headers.add(columnName); if(columnToBeSortedOn != null) { if(columnName.equals(columnToBeSortedOn.getName())){ indexOfColumnToBeSortedOn = i ; } } } if(columnToBeSortedOn != null) { if(indexOfColumnToBeSortedOn == -1) { this.isColumnToBeSortedOnPresentInInput = false ; indexOfColumnToBeSortedOn = columns.length ; headers.add(columnToBeSortedOn.getName()) ; InputColumn<?>[] newColumns = new InputColumn<?>[columns.length + 1] ; for(int i = 0; i < columns.length; i++){ newColumns[i] = columns[i] ; } newColumns[columns.length] = columnToBeSortedOn ; inputColumns = newColumns ; } } return CsvOutputWriterFactory.getWriter(_targetFile.getPath(), headers.toArray(new String[0]), separatorChar, quoteChar, escapeChar, includeHeader, inputColumns); }
Source:
<code>public String getDescription() { return "A function to add a layer based on a table name\n" <START> + "The second argument is optional. It permits to set a style to the layer."; <END> }</code><technical_language>I18N, this description is SQL panel function list</technical_language>

Target:
public String getDescription() { return I18N.tr("A function to add a layer based on a table name\n" + "The second argument is optional. It permits to set a style to the layer."); }
Source:
<code>public static <T> Iterable<T> loadService(Class<T> service, ClassLoader loader) { final Iterable<T> i = ServiceLoader.load(service, loader); return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { Iterator<T> a = i.iterator(); T next; @Override public boolean hasNext() { while (a != null && a.hasNext()) { try { next = a.next(); if(next != null) { return true; } } catch (Exception e) { } } return next != null; } @Override public T next() { <START> if(next != null) { <END> T tmp = next; next = null; return tmp; } else if (!hasNext()) { throw new NoSuchElementException(); } else { T tmp = next; next = null; return tmp; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; }</code><technical_language>2 piece of code in this if in else : T tmp = next; next = null; return tmp; Is necessary repeat</technical_language>

Target:
public static <T> Iterable<T> loadService(Class<T> service, ClassLoader loader) { return ServiceLoader.load(service, loader); }
Source:
<code>public IndexManager createIndexManagerByName(String indexManagerImplementationName) { if ( StringHelper.isEmpty( indexManagerImplementationName ) ) { return createDefaultIndexManager(); } else { indexManagerImplementationName = indexManagerImplementationName.trim(); IndexManager indexManager = fromAlias( indexManagerImplementationName ); if ( indexManager == null ) { indexManagerImplementationName = aliasToFQN( indexManagerImplementationName ); Class<?> indexManagerClass = classLoaderService.classForName( indexManagerImplementationName ); <START> indexManager = ClassLoaderHelper.instanceFromClass( IndexManager.class, indexManagerClass, "index manager" ); <END> } log.indexManagerAliasResolved( indexManagerImplementationName, indexManager.getClass() ); return indexManager; } }</code><technical_language>more elegant if ClassLoaderHelper encapsulated in cassLoaderService ? I nice able load IndexManager instance service, like: indexManager = classLoaderService.classForName( IndexManager.class, indexManagerImplementationName, "index manager" );</technical_language>

Target:
public IndexManager createIndexManagerByName(String indexManagerImplementationName) { if ( StringHelper.isEmpty( indexManagerImplementationName ) ) { return createDefaultIndexManager(); } else { indexManagerImplementationName = indexManagerImplementationName.trim(); IndexManager indexManager = fromAlias( indexManagerImplementationName ); if ( indexManager == null ) { indexManagerImplementationName = aliasToFQN( indexManagerImplementationName ); Class<?> indexManagerClass = ClassLoaderHelper.classForName( indexManagerImplementationName, serviceManager ); indexManager = ClassLoaderHelper.instanceFromClass( IndexManager.class, indexManagerClass, "index manager" ); } log.indexManagerAliasResolved( indexManagerImplementationName, indexManager.getClass() ); return indexManager; } }
Source:
<code>public static void setup() throws Exception { <START> String methodName = "makeBucket(MakeBucketArgs args)"; <END> long startTime = System.currentTimeMillis(); try { client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); } catch (Exception e) { handleException(methodName, null, startTime, e); } }</code><technical_language>need declare methodName</technical_language>

Target:
public static void setup() throws Exception { long startTime = System.currentTimeMillis(); try { client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); } catch (Exception e) { handleException("makeBucket(MakeBucketArgs args)", null, startTime, e); } }
Source:
<code>private Set<Person> executeSoundexOnePersonNameQuery(String name, Integer birthyear, boolean includeVoided , String gender) { String matchMode = Context.getAdministrationService().getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_MODE); Context.getAdministrationService().setGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_MODE, OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_SOUNDEX); PersonLuceneQuery personLuceneQuery = new PersonLuceneQuery(sessionFactory); String query = LuceneQuery.escapeQuery(name); int maxResults = HibernatePersonDAO.getMaximumSearchResults(); LinkedHashSet<Person> people = new LinkedHashSet<>(); LuceneQuery<PersonName> luceneQuery = personLuceneQuery.getSoundexPersonNameQuery(query, birthyear, false, gender);; ListPart<Object[]> names = luceneQuery.listPartProjection(0, maxResults, "person.personId"); <START> names.getList().forEach(x-> people.add(getPerson((Integer) x[0]))); <END> Context.getAdministrationService().setGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_MODE, matchMode); return people; }</code><technical_language>x -></technical_language>

Target:
private Set<Person> executeSoundexOnePersonNameQuery(String name, Integer birthyear, boolean includeVoided , String gender) { PersonLuceneQuery personLuceneQuery = new PersonLuceneQuery(sessionFactory); String query = LuceneQuery.escapeQuery(name); int maxResults = HibernatePersonDAO.getMaximumSearchResults(); LinkedHashSet<Person> people = new LinkedHashSet<>(); LuceneQuery<PersonName> luceneQuery = personLuceneQuery.getSoundexPersonNameQuery(query, birthyear, false, gender);; ListPart<Object[]> names = luceneQuery.listPartProjection(0, maxResults, "person.personId"); names.getList().forEach(x -> people.add(getPerson((Integer) x[0]))); return people; }
Source:
<code>void lockOutputFiles() throws InterruptedException; boolean speculating(); Duration getTimeout(); FileOutErr getFileOutErr(); SortedMap<PathFragment, ActionInput> getInputMapping(boolean expandTreeArtifactsInRunfiles) throws IOException; void report(ProgressStatus state, String name); <START> default MetadataInjector getMetadataInjector() { <END> throw new UnsupportedOperationException(); }</code><technical_language>This is a risk for production code</technical_language>

Target:
void lockOutputFiles() throws InterruptedException; boolean speculating(); Duration getTimeout(); FileOutErr getFileOutErr(); SortedMap<PathFragment, ActionInput> getInputMapping(boolean expandTreeArtifactsInRunfiles) throws IOException; void report(ProgressStatus state, String name); MetadataInjector getMetadataInjector(); } default FutureSpawn execAsync(Spawn spawn, SpawnExecutionContext context) throws InterruptedException, IOException, ExecException { return FutureSpawn.immediate(exec(spawn, context)); }
Source:
<code>@Test public void testSimplifyCoalesceWithConstant() { RexNode inputRef1 = rexBuilder.makeInputRef( typeFactory.createTypeWithNullability( typeFactory.createSqlType(SqlTypeName.VARCHAR), true), 0); RexNode inputRef2 = rexBuilder.makeInputRef( typeFactory.createTypeWithNullability( typeFactory.createSqlType(SqlTypeName.VARCHAR), true), 1); RexCall coalesceNode = (RexCall) coalesce(inputRef2, inputRef1); ImmutableList.Builder<RexNode> newOperands = ImmutableList.builder(); newOperands.add(rexBuilder.makeLiteral("S")).add(coalesceNode.operands.get(1)); coalesceNode = coalesceNode.clone(coalesceNode.getType(), newOperands.build()); RexNode result = simplify.simplify(coalesceNode); <START> assertThat(result.getType().isNullable(), is(true)); <END> assertThat(result.getType().getSqlTypeName(), is(SqlTypeName.VARCHAR)); }</code><technical_language>please add assert message. E.g. "simplify of " + coalesceNode + " is Nullable"</technical_language>

Target:
@Test public void testSimplifyCoalesceWithConstant() { RexNode inputRef1 = rexBuilder.makeInputRef( typeFactory.createTypeWithNullability( typeFactory.createSqlType(SqlTypeName.VARCHAR), true), 0); RexNode inputRef2 = rexBuilder.makeInputRef( typeFactory.createTypeWithNullability( typeFactory.createSqlType(SqlTypeName.VARCHAR), true), 1); RexCall coalesceNode = (RexCall) coalesce(inputRef2, inputRef1); ImmutableList.Builder<RexNode> newOperands = ImmutableList.builder(); newOperands.add(rexBuilder.makeLiteral("S")).add(coalesceNode.operands.get(1)); coalesceNode = coalesceNode.clone(coalesceNode.getType(), newOperands.build()); RexNode result = simplify.simplify(coalesceNode); assertThat("simplify of " + coalesceNode + " is Nullable", result.getType().isNullable(), is(true)); assertThat("simplify of " + coalesceNode + " is VARCHAR type", result.getType().getSqlTypeName(), is(SqlTypeName.VARCHAR)); RexNode result1 = simplify.simplifyPreservingType(coalesceNode); assertThat("simplify of " + coalesceNode + " is Nullable", result1.getType().isNullable(), is(true)); assertThat("simplify of " + coalesceNode + " is VARCHAR type", result1.getType().getSqlTypeName(), is(SqlTypeName.VARCHAR)); }
Source:
<code>ForwardedHeaderExtractingRequest(HttpServletRequest request, UrlPathHelper pathHelper) { super(request); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); int port = uriComponents.getPort(); this.scheme = uriComponents.getScheme(); this.secure = "https".equals(this.scheme); this.host = uriComponents.getHost(); this.port = (port == -1 ? (this.secure ? 443 : 80) : port); UriComponents remoteUriComponents = UriComponentsBuilder.newInstance() .host(request.getRemoteHost()) .port(request.getRemotePort()) .adaptFromForwardedForHeader(httpRequest.getHeaders()) <START> .build(); <END> this.remoteHost = remoteUriComponents.getHost(); this.remoteAddr = ((this.remoteHost != null && !this.remoteHost.equals(request.getRemoteHost())) ? this.remoteHost : request.getRemoteAddr()); this.remotePort = remoteUriComponents.getPort(); String baseUrl = this.scheme + "://" + this.host + (port == -1 ? "" : ":" + port); Supplier<HttpServletRequest> delegateRequest = () -> (HttpServletRequest) getRequest(); this.forwardedPrefixExtractor = new ForwardedPrefixExtractor(delegateRequest, pathHelper, baseUrl); }</code><technical_language>is worth applying some sort of check if this needs done, e.g. "X-Forwarded-For" and/or indexOf scan if "Forward" a "for" attribute. In hot paths especially need reduce Object creation. applies for of Optional</technical_language>

Target:
ForwardedHeaderExtractingRequest(HttpServletRequest request, UrlPathHelper pathHelper) { super(request); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); int port = uriComponents.getPort(); this.scheme = uriComponents.getScheme(); this.secure = "https".equals(this.scheme); this.host = uriComponents.getHost(); this.port = (port == -1 ? (this.secure ? 443 : 80) : port); HttpHeaders headers = httpRequest.getHeaders(); boolean hasForwardedFor = StringUtils.hasText(headers.getFirst(X_FORWARDED_FOR_HEADER)) || (StringUtils.hasText(headers.getFirst(FORWARDED_HEADER)) && FORWARDED_FOR_PATTERN.matcher(headers.getFirst(FORWARDED_HEADER)).matches()); if (hasForwardedFor) { UriComponents remoteUriComponents = UriComponentsBuilder.newInstance() .host(request.getRemoteHost()) .port(request.getRemotePort()) .adaptFromForwardedForHeader(headers) .build(); this.remoteHost = remoteUriComponents.getHost(); this.remoteAddr = this.remoteHost; this.remotePort = remoteUriComponents.getPort(); } else { this.remoteHost = request.getRemoteHost(); this.remoteAddr = request.getRemoteAddr(); this.remotePort = request.getRemotePort(); } String baseUrl = this.scheme + "://" + this.host + (port == -1 ? "" : ":" + port); Supplier<HttpServletRequest> delegateRequest = () -> (HttpServletRequest) getRequest(); this.forwardedPrefixExtractor = new ForwardedPrefixExtractor(delegateRequest, pathHelper, baseUrl); }
Source:
<code>private Map<String, EnvVar> jnlpEnvVars(String workingDir) { if (workingDir == null) { workingDir = ContainerTemplate.DEFAULT_WORKING_DIR; } HashMap<String, String> env = new HashMap<>(); if (slave != null) { SlaveComputer computer = slave.getComputer(); if (computer != null) { env.put("JENKINS_SECRET", computer.getJnlpMac()); env.put("JENKINS_NAME", computer.getName()); env.put("JENKINS_AGENT_NAME", computer.getName()); } else { LOGGER.log(Level.INFO, "Computer is null for agent: {0}", slave.getNodeName()); } env.put("JENKINS_AGENT_WORKDIR", workingDir); KubernetesCloud cloud = slave.getKubernetesCloud(); if (!StringUtils.isBlank(cloud.getJenkinsTunnel())) { env.put("JENKINS_TUNNEL", cloud.getJenkinsTunnel()); } if (!cloud.isDirectConnection()) { env.put("JENKINS_URL", cloud.getJenkinsUrlOrDie()); } else { Jenkins jenkins = Jenkins.getInstanceOrNull(); if(jenkins == null) throw new IllegalStateException("Jenkins instance null"); String host; try { host = new URL(jenkins.getRootUrl()).getHost(); } catch (MalformedURLException e) { throw new IllegalStateException("Could not get Jenkins host name", e); } <START> int port = jenkins.getTcpSlaveAgentListener().getPort(); <END> env.put("JENKINS_DIRECT_CONNECTION", host + ":" + port); env.put("JENKINS_PROTOCOLS", "JNLP4-connect"); env.put("JENKINS_INSTANCE_IDENTITY", jenkins.getTcpSlaveAgentListener().getIdentityPublicKey()); } } Map<String, EnvVar> envVarsMap = new HashMap<>(); env.entrySet().forEach(item -> envVarsMap.put(item.getKey(), new EnvVar(item.getKey(), item.getValue(), null)) ); return envVarsMap; }</code><technical_language>suggestion int port = jenkins.getTcpSlaveAgentListener().getAdvertisedPort(); ? (See TcpSlaveAgentListener/index.jelly)</technical_language>

Target:
private Map<String, EnvVar> jnlpEnvVars(String workingDir) { if (workingDir == null) { workingDir = ContainerTemplate.DEFAULT_WORKING_DIR; } HashMap<String, String> env = new HashMap<>(); if (slave != null) { SlaveComputer computer = slave.getComputer(); if (computer != null) { env.put("JENKINS_SECRET", computer.getJnlpMac()); env.put("JENKINS_NAME", computer.getName()); env.put("JENKINS_AGENT_NAME", computer.getName()); } else { LOGGER.log(Level.INFO, "Computer is null for agent: {0}", slave.getNodeName()); } env.put("JENKINS_AGENT_WORKDIR", workingDir); KubernetesCloud cloud = slave.getKubernetesCloud(); if (!StringUtils.isBlank(cloud.getJenkinsTunnel())) { env.put("JENKINS_TUNNEL", cloud.getJenkinsTunnel()); } if (!cloud.isDirectConnection()) { env.put("JENKINS_URL", cloud.getJenkinsUrlOrDie()); } else { String host = getAdvertisedHost(); int port = Jenkins.get().getTcpSlaveAgentListener().getAdvertisedPort(); env.put("JENKINS_DIRECT_CONNECTION", host + ":" + port); env.put("JENKINS_PROTOCOLS", "JNLP4-connect"); env.put("JENKINS_INSTANCE_IDENTITY", Jenkins.get().getTcpSlaveAgentListener().getIdentityPublicKey()); } } Map<String, EnvVar> envVarsMap = new HashMap<>(); env.entrySet().forEach(item -> envVarsMap.put(item.getKey(), new EnvVar(item.getKey(), item.getValue(), null)) ); return envVarsMap; }
Source:
<code>private static SortAlgorithm getSortAlgorithm(QueryContext context, SortSpec[] sortSpecs) { if (Arrays.stream(sortSpecs) .filter(sortSpec -> !RadixSort.isApplicableType(sortSpec)).count() > 0) { return SortAlgorithm.TIM_SORT; } String sortAlgorithm = context.get(SessionVars.SORT_ALGORITHM, "TIM"); <START> if (sortAlgorithm.equalsIgnoreCase("TIM")) { <END> return SortAlgorithm.TIM_SORT; } else if (sortAlgorithm.equalsIgnoreCase("MSD_RADIX")) { return SortAlgorithm.MSD_RADIX_SORT; } else { throw new TajoRuntimeException(new UnsupportedException(sortAlgorithm)); } }</code><technical_language>remove hardcode constants</technical_language>

Target:
private static SortAlgorithm getSortAlgorithm(QueryContext context, SortSpec[] sortSpecs) { String sortAlgorithm = context.get(SessionVars.SORT_ALGORITHM, SortAlgorithm.TIM.name()); if (Arrays.stream(sortSpecs) .filter(sortSpec -> !RadixSort.isApplicableType(sortSpec)).count() > 0) { if (sortAlgorithm.equalsIgnoreCase(SortAlgorithm.MSD_RADIX.name())) { LOG.warn("Non-applicable types exist. Falling back to " + SortAlgorithm.TIM.name() + " sort"); } return SortAlgorithm.TIM; } if (sortAlgorithm.equalsIgnoreCase(SortAlgorithm.TIM.name())) { return SortAlgorithm.TIM; } else if (sortAlgorithm.equalsIgnoreCase(SortAlgorithm.MSD_RADIX.name())) { return SortAlgorithm.MSD_RADIX; } else { LOG.warn("Unknown sort type: " + sortAlgorithm); LOG.warn("Falling back to " + SortAlgorithm.TIM.name() + " sort"); return SortAlgorithm.TIM; } }
Source:
<code>public void run() { List<AttestationValue> values; if (trustedHostsNames.size() > FIRST_STAGE_QUERY_SIZE) { values = AttestationService.getInstance().attestHosts(trustedHostsNames.subList(0, FIRST_STAGE_QUERY_SIZE)); handleValues(values); for (int i = FIRST_STAGE_QUERY_SIZE; i < trustedHostsNames.size(); i+= SECOND_STAGE_QUERY_SIZE) { values = AttestationService.getInstance() <START> .attestHosts(trustedHostsNames.subList(i, i + SECOND_STAGE_QUERY_SIZE)); <END> handleValues(values); } } else { values = AttestationService.getInstance().attestHosts(trustedHostsNames); handleValues(values); } }</code><technical_language>Ofri, for loop is cut list small lists size=attestationSecondStageSize. is a case, if (trustedHostsNames.size-FIRST_STAGE_QUERY_SIZE)% SECOND_STAGE_QUERY_SIZE !=0, cut size for list, throw NPE. do this: for (int i = FIRST_STAGE_QUERY_SIZE, int j =0; i < trustedHostsNames.size(); i+= SECOND_STAGE_QUER Y_SIZE){ j = (i+SECOND_STAGE_QUERY_SIZE < trustedHostsNames.size()) ? i + SECOND_STAGE_QUERY_SIZE: trustedHostsNames.size(); values = AttestationService.getInstance. attestHosts(trustedHostsNames.subList(i, j)); }</technical_language>

Target:
public void run() { List<AttestationValue> values; if (trustedHostsNames.size() > FIRST_STAGE_QUERY_SIZE) { values = AttestationService.getInstance().attestHosts(trustedHostsNames.subList(0, FIRST_STAGE_QUERY_SIZE)); handleValues(values); for (int from = FIRST_STAGE_QUERY_SIZE; from < trustedHostsNames.size(); from+= SECOND_STAGE_QUERY_SIZE) { int to = (from + SECOND_STAGE_QUERY_SIZE < trustedHostsNames.size()) ? from + SECOND_STAGE_QUERY_SIZE : trustedHostsNames.size(); values = AttestationService.getInstance(). attestHosts(trustedHostsNames.subList(from, to)); handleValues(values); } } else { values = AttestationService.getInstance().attestHosts(trustedHostsNames); handleValues(values); } }
Source:
<code>private static void handleIfStatement(IfStatement ifStmt, SubscriptionContext ctx) { if (ifStmt.elseBranch() == null) { return; } StatementList body = ifStmt.body(); for (IfStatement elifBranch : ifStmt.elifBranches()) { StatementList elifBody = elifBranch.body(); if (!CheckUtils.areEquivalent(body, elifBody)) { return; } } if (!CheckUtils.areEquivalent(body, ifStmt.elseBranch().body())) { return; } PreciseIssue issue = ctx.addIssue(ifStmt.keyword(), "Remove this if statement or edit its code blocks so that they're not all the same."); List<Token> ifBodyTokens = TreeUtils.nonWhitespaceTokens(ifStmt.body()); issue.secondary(IssueLocation.preciseLocation(ifBodyTokens.get(0), ifBodyTokens.get(ifBodyTokens.size() - 1), null)); ifStmt.elifBranches().forEach(e -> { List<Token> elifBodyTokens = TreeUtils.nonWhitespaceTokens(e.body()); <START> issue.secondary(IssueLocation.preciseLocation(elifBodyTokens.get(0), elifBodyTokens.get(ifBodyTokens.size() - 1), null)); <END> }); List<Token> elseBodyTokens = TreeUtils.nonWhitespaceTokens(ifStmt.elseBranch().body()); issue.secondary(IssueLocation.preciseLocation(elseBodyTokens.get(0), elseBodyTokens.get(ifBodyTokens.size() - 1), null)); }</code><technical_language>elifBodyTokens.get(ifBodyTokens.size() - 1) is wrong here, elifBodyTokens.get(elifBodyTokens.size() - 1) Of course, fails branches number of tokens identical... Suggestion: extract a method a signature as: IssueLocation issueLocation(StatementList body)</technical_language>

Target:
private static void handleIfStatement(IfStatement ifStmt, SubscriptionContext ctx) { if (ifStmt.elseBranch() == null) { return; } StatementList body = ifStmt.body(); for (IfStatement elifBranch : ifStmt.elifBranches()) { StatementList elifBody = elifBranch.body(); if (!CheckUtils.areEquivalent(body, elifBody)) { return; } } if (!CheckUtils.areEquivalent(body, ifStmt.elseBranch().body())) { return; } PreciseIssue issue = ctx.addIssue(ifStmt.keyword(), "Remove this if statement or edit its code blocks so that they're not all the same."); issue.secondary(issueLocation(ifStmt.body())); ifStmt.elifBranches().forEach(e -> issue.secondary(issueLocation(e.body()))); issue.secondary(issueLocation(ifStmt.elseBranch().body())); }
Source:
<code>public Repository openRepository(Project.NameKey name) throws RepositoryNotFoundException { if (isUnreasonableName(name)) { throw new RepositoryNotFoundException("Invalid name: " + name); } if (!names.contains(name)) { File f = new File(basePath, name.get().endsWith( Constants.DOT_GIT_EXT) ? name.get() : name.get() + Constants.DOT_GIT_EXT); <START> if (FileKey.isGitRepository(f, FS.DETECTED)) { <END> onCreateProject(name); } else { throw new RepositoryNotFoundException(gitDirOf(name)); } } final FileKey loc = FileKey.lenient(gitDirOf(name), FS.DETECTED); try { return RepositoryCache.open(loc); } catch (IOException e1) { final RepositoryNotFoundException e2; e2 = new RepositoryNotFoundException("Cannot open repository " + name); e2.initCause(e1); throw e2; } }</code><technical_language>simplify 2 lines if (FileKey.resolve(gitDirOf(name), fs) != null) {</technical_language>

Target:
public Repository openRepository(Project.NameKey name) throws RepositoryNotFoundException { if (isUnreasonableName(name)) { throw new RepositoryNotFoundException("Invalid name: " + name); } if (!names.contains(name)) { if (FileKey.resolve(gitDirOf(name), FS.DETECTED) != null) { onCreateProject(name); } else { throw new RepositoryNotFoundException(gitDirOf(name)); } } final FileKey loc = FileKey.lenient(gitDirOf(name), FS.DETECTED); try { return RepositoryCache.open(loc); } catch (IOException e1) { final RepositoryNotFoundException e2; e2 = new RepositoryNotFoundException("Cannot open repository " + name); e2.initCause(e1); throw e2; } }
Source:
<code>default void setExitMessage(@Nullable Text message) { <START> setExitMessage(message, null); <END> }</code><technical_language>This pass ChatTypes.CHAT a default instead of null</technical_language>

Target:
default void setExitMessage(@Nullable Text message) { setExitMessage(message, ChatTypes.CHAT); }
Source:
<code>public static void main(String[] args) throws RunnerException { String benchmarkName = CorfuTableBenchmark.class.getSimpleName(); Options opt = new OptionsBuilder() .include(benchmarkName) .mode(Mode.Throughput) .timeUnit(TimeUnit.SECONDS) .warmupIterations(1) .warmupTime(TimeValue.seconds(3)) .measurementIterations(3) .measurementTime(TimeValue.seconds(10)) .threads(1) <START> .forks(1) <END> .param(DATA_SIZE_FIELD, DATA_SIZE) .param(TABLE_SIZE_FIELD, TABLE_SIZE) .param(IN_MEM_TABLE_SIZE_FIELD, SMALL_TABLE_SIZE) .shouldFailOnError(true) .jvmArgsAppend("-Xms8g", "-Xmx8g") .resultFormat(ResultFormatType.CSV) .result("target/" + benchmarkName + ".csv") .build(); new Runner(opt).run(); }</code><technical_language>pass mode, timeUnit, warmupIterations, warmupTime, measurementIterations, measurementTime, threads, forks a configurable parameters</technical_language>

Target:
public static void main(String[] args) throws RunnerException { String benchmarkName = CorfuTableBenchmark.class.getSimpleName(); int warmUpIterations = 1; TimeValue warmUpTime = TimeValue.seconds(3); int measurementIterations = 3; TimeValue measurementTime = TimeValue.seconds(10); int threads = 1; int forks = 1; Options opt = new OptionsBuilder() .include(benchmarkName) .mode(Mode.Throughput) .timeUnit(TimeUnit.SECONDS) .warmupIterations(warmUpIterations) .warmupTime(warmUpTime) .measurementIterations(measurementIterations) .measurementTime(measurementTime) .threads(threads) .forks(forks) .param(DATA_SIZE_FIELD, DATA_SIZE) .param(TABLE_SIZE_FIELD, TABLE_SIZE) .param(IN_MEM_TABLE_SIZE_FIELD, SMALL_TABLE_SIZE) .shouldFailOnError(true) .jvmArgsAppend("-Xms4g", "-Xmx4g") .resultFormat(ResultFormatType.CSV) .result("target/" + benchmarkName + ".csv") .build(); new Runner(opt).run(); }
Source:
<code>public void testThumbLargeRouteForceNoFileExists() throws Exception { createContext(largeThumbRoute); getMockEndpoint("mock:exec:/bin/sh").expectedMessageCount(1); Map<String, Object> headers = createEvent(fileID, eventTypes, "true"); template.sendBodyAndHeaders("", headers); <START> doThrow(Exception.class).when(addLargeThumbnailProcessor).process(any(Exchange.class)); <END> verify(addLargeThumbnailProcessor).process(any(Exchange.class)); assertMockEndpointsSatisfied(); }</code><technical_language>Is this throw serving a purpose here? expect in a successful case</technical_language>

Target:
public void testThumbLargeRouteForceNoFileExists() throws Exception { createContext(largeThumbRoute); getMockEndpoint("mock:exec:/bin/sh").expectedMessageCount(1); Map<String, Object> headers = createEvent(fileID, eventTypes, "true"); template.sendBodyAndHeaders("", headers); doNothing().when(addLargeThumbnailProcessor).process(any(Exchange.class)); verify(addLargeThumbnailProcessor).process(any(Exchange.class)); assertMockEndpointsSatisfied(); }
Source:
<code>protected NetworkOperationCommandTarget getTarget() { return new NetworkOperationCommandTarget() { @Override protected void executeNetworkCommand(NetworkItemModel<?> op1, NetworkItemModel<?> op2, DataFromHostSetupNetworksModel dataFromHostSetupNetworksModel, Object... params) { assert op1 instanceof NetworkInterfaceModel; assert op2 == null; NetworkInterfaceModel nicModel = (NetworkInterfaceModel) op1; VdsNetworkInterface slaveNic = nicModel.getIface(); slaveNic.setBondName(null); BondNetworkInterfaceModel bondModel = nicModel.getBond(); Bond bond = bondModel.getIface(); if (bondModel.getBonded().size() == 2) { BREAK_BOND.getCommand(bondModel, null, dataFromHostSetupNetworksModel).execute(); } else { <START> bond.getSlaves().remove(nicModel.getName()); <END> String bondName = bond.getName(); Map<String, Bond> bondsMap = Entities.entitiesByName(dataFromHostSetupNetworksModel.newOrModifiedBonds); boolean bondWasAlreadyUpdated = bondsMap.containsKey(bondName); if (!bondWasAlreadyUpdated) { addBondToParams(dataFromHostSetupNetworksModel, bond); } } } }; }</code><technical_language>Please rebase class completely modified</technical_language>

Target:
protected NetworkOperationCommandTarget getTarget() { return new NetworkOperationCommandTarget() { @Override protected void executeNetworkCommand(NetworkItemModel<?> op1, NetworkItemModel<?> op2, DataFromHostSetupNetworksModel dataFromHostSetupNetworksModel, Object... params) { assert op1 instanceof BondNetworkInterfaceModel; assert op2 == null; BondNetworkInterfaceModel bondModel = (BondNetworkInterfaceModel) op1; dataFromHostSetupNetworksModel .removeBondFromParameters(bondModel.getCreateOrUpdateBond()); detachAllNetworks(bondModel, dataFromHostSetupNetworksModel); detachAllLabels(bondModel, dataFromHostSetupNetworksModel); } }; }
Source:
<code>private boolean producerOfCorrectType(EventEnvelope event) { EventContext context = event.getEventContext(); Any anyId = context.getProducerId(); <START> boolean idTypeMatches = anyId.is(EntityHistoryId.class); <END> if (!idTypeMatches) { _warn("Event %s is produced by an entity with ID %s.", event.getMessageClass(), unpack(anyId)); return false; } else { EntityHistoryId producerId = unpack(anyId); String typeUrlRaw = producerId.getTypeUrl(); TypeUrl typeUrl = TypeUrl.parse(typeUrlRaw); return typeUrl.equals(targetType); } }</code><technical_language>method this expression in expensive operation. discuss</technical_language>

Target:
private boolean producerOfCorrectType(EventEnvelope event) { EventContext context = event.getEventContext(); Any anyId = context.getProducerId(); Object producerId = Identifier.unpack(anyId); EntityHistoryId historyId = (EntityHistoryId) producerId; String typeUrlRaw = historyId.getTypeUrl(); return typeUrlRaw.equals(targetType.value()); }
Source:
<code>public final void onError(final SocketSession erroredSession, final Throwable cause) { if (cause instanceof java.io.EOFException || cause instanceof java.net.SocketTimeoutException) { reachedEof = true; LOG.info("This websocket timed out!"); } if (erroredSession == null) { <START> LOG.error("Socket: Error: {}", this.getClass().getSimpleName(), cause); <END> if (cause instanceof java.net.ConnectException) { if (cause.getMessage().trim().equalsIgnoreCase("Connection refused")) { refusedConnection = true; LOG.error("Connection was refused"); } LOG.error("Connection had issues!"); } } else { LOG.error("Socket: {}Session Error: {}", this.getClass().getSimpleName(), cause); } }</code><technical_language>change message "Socket threw error, Socket: Error: {}"</technical_language>

Target:
public final void onError(final SocketSession erroredSession, final Throwable cause) { if (cause instanceof java.io.EOFException || cause instanceof java.net.SocketTimeoutException) { reachedEof = true; LOG.info("This websocket timed out!"); } if (erroredSession == null) { LOG.error("Socket threw an error, Socket: Error: {}", this.getClass().getSimpleName(), cause); if (cause instanceof java.net.ConnectException) { if (cause.getMessage().trim().equalsIgnoreCase("Connection refused")) { refusedConnection = true; LOG.error("Connection was refused"); } LOG.error("Connection had issues!"); } } else { LOG.error("Socket: {}Session Error: {}", this.getClass().getSimpleName(), cause); } }
Source:
<code>protected void sendAndReceive( HttpMessage message, boolean isFollowRedirect, boolean handleAntiCSRF) throws IOException { if (parent.handleAntiCsrfTokens() && handleAntiCSRF) { if (extAntiCSRF == null) { extAntiCSRF = Control.getSingleton() .getExtensionLoader() .getExtension(ExtensionAntiCSRF.class); } if (extAntiCSRF != null) { <START> if (!isRegenCsrfCalled) { <END> isRegenCsrfCalled = true; extAntiCSRF.regenerateAntiCsrfToken(message, this::sendAndReceive); } isRegenCsrfCalled = false; } } if (this.parent.getScannerParam().isInjectPluginIdInHeader()) { this.msg .getRequestHeader() .setHeader(HttpHeader.X_ZAP_SCAN_ID, Integer.toString(getId())); } message.getRequestHeader().setHeader(HttpHeader.IF_MODIFIED_SINCE, null); message.getRequestHeader().setHeader(HttpHeader.IF_NONE_MATCH, null); message.getRequestHeader().setContentLength(message.getRequestBody().length()); if (this.getDelayInMs() > 0) { try { Thread.sleep(this.getDelayInMs()); } catch (InterruptedException e) { } } parent.performScannerHookBeforeScan(message, this); if (isFollowRedirect) { parent.getHttpSender().sendAndReceive(message, getParent().getRedirectRequestConfig()); } else { parent.getHttpSender().sendAndReceive(message, false); } parent.notifyNewMessage(this, message); parent.performScannerHookAfterScan(message, this); }</code><technical_language>correct parameters instead, e.g.: Java extAntiCSRF.regenerateAntiCsrfToken(message, tokenMsg -> sendAndReceive(tokenMsg, true, false));</technical_language>

Target:
protected void sendAndReceive( HttpMessage message, boolean isFollowRedirect, boolean handleAntiCSRF) throws IOException { if (parent.handleAntiCsrfTokens() && handleAntiCSRF) { if (extAntiCSRF == null) { extAntiCSRF = Control.getSingleton() .getExtensionLoader() .getExtension(ExtensionAntiCSRF.class); } if (extAntiCSRF != null) { extAntiCSRF.regenerateAntiCsrfToken( message, tokenMsg -> sendAndReceive(tokenMsg, true, false)); } } if (this.parent.getScannerParam().isInjectPluginIdInHeader()) { this.msg .getRequestHeader() .setHeader(HttpHeader.X_ZAP_SCAN_ID, Integer.toString(getId())); } message.getRequestHeader().setHeader(HttpHeader.IF_MODIFIED_SINCE, null); message.getRequestHeader().setHeader(HttpHeader.IF_NONE_MATCH, null); message.getRequestHeader().setContentLength(message.getRequestBody().length()); if (this.getDelayInMs() > 0) { try { Thread.sleep(this.getDelayInMs()); } catch (InterruptedException e) { } } parent.performScannerHookBeforeScan(message, this); if (isFollowRedirect) { parent.getHttpSender().sendAndReceive(message, getParent().getRedirectRequestConfig()); } else { parent.getHttpSender().sendAndReceive(message, false); } parent.notifyNewMessage(this, message); parent.performScannerHookAfterScan(message, this); }
Source:
<code>public void encodeLink(String link, HierarchicalStreamWriter writer) { String path = request.getRequestURI(); <START> if (path.contains("script")) { <END> try { link = URLDecoder.decode(link, "UTF-8"); writer.startNode("href"); writer.setValue(hrefNoExt(link)); writer.endNode(); } catch (UnsupportedEncodingException e) { } } else { writer.startNode("href"); writer.setValue(href(link)); writer.endNode(); } }</code><technical_language>Stricter check. this is in 3 places, is a method override require a single path check</technical_language>

Target:
public void encodeLink(String link, HierarchicalStreamWriter writer) { if (checkPath(request)) { try { link = URLDecoder.decode(link, "UTF-8"); writer.startNode("href"); writer.setValue(hrefNoExt(link)); writer.endNode(); } catch (UnsupportedEncodingException e) { throw new RestException(e.getMessage().toString(), HttpStatus.INTERNAL_SERVER_ERROR); } } else { writer.startNode("href"); writer.setValue(href(link)); writer.endNode(); } }
Source:
<code>public void verifySourceEditorContentIsEmpty(){ waitForElementByElement(sourceModeTextArea); <START> Assert.assertEquals(sourceModeTextArea.getText().isEmpty(), true); <END> PageObjectLogging.log("verifySourceEditorContentIsEmpty", "Source editor content was cleaned", true); }</code><technical_language>please Assertion class</technical_language>

Target:
public void verifySourceEditorContentIsEmpty(){ waitForElementByElement(sourceModeTextArea); Assertion.assertEquals(sourceModeTextArea.getText().isEmpty(), true); PageObjectLogging.log("verifySourceEditorContentIsEmpty", "Source editor content was cleaned", true); }
Source:
<code><START> public void afterPropertiesSet() throws Exception { <END> this.initialized = true; }</code><technical_language>This assertion remain - caching Channels, is connection (default). I suppose allow set long set 1. change merge</technical_language>

Target:
public void afterPropertiesSet() throws Exception { this.initialized = true; if (this.cacheMode == CacheMode.CHANNEL) { Assert.isTrue(this.connectionCacheSize == 1, "When the cache mode is 'CHANNEL', the connection cache size cannot be configured."); } }
Source:
<code>private void compareMaxInactiveIntervals() { cluster.getVM(1).invoke(() -> { <START> for (int j = 0; j < 113; j++) { <END> InternalCache cache = ClusterStartupRule.getCache(); PartitionedRegion region = (PartitionedRegion) cache.getRegion("__REDIS_DATA"); List<BucketDump> buckets = region.getAllBucketEntries(j); if (buckets.isEmpty()) { continue; } assertThat(buckets.size()).isEqualTo(2); Map<Object, Object> bucket1 = buckets.get(0).getValues(); Map<Object, Object> bucket2 = buckets.get(1).getValues(); bucket1.keySet().forEach(key -> { if (bucket1.get(key) instanceof RedisHash) { RedisHash value1 = (RedisHash) bucket1.get(key); RedisHash value2 = (RedisHash) bucket2.get(key); assertThat(getIntFromBytes(value1)).isEqualTo(getIntFromBytes(value2)); } }); } }); }</code><technical_language>instead of hard coded "113", ask PartitionedRegion for max bucket. PartitionedRegion.getTotalNumberOfBuckets. This in future allow redis bucket count configured</technical_language>

Target:
private void compareMaxInactiveIntervals() { cluster.getVM(1).invoke(() -> { InternalCache cache = ClusterStartupRule.getCache(); PartitionedRegion region = (PartitionedRegion) cache.getRegion("__REDIS_DATA"); for (int j = 0; j < region.getTotalNumberOfBuckets(); j++) { List<BucketDump> buckets = region.getAllBucketEntries(j); if (buckets.isEmpty()) { continue; } assertThat(buckets.size()).isEqualTo(2); Map<Object, Object> bucket1 = buckets.get(0).getValues(); Map<Object, Object> bucket2 = buckets.get(1).getValues(); bucket1.keySet().forEach(key -> { if (bucket1.get(key) instanceof RedisHash) { RedisHash value1 = (RedisHash) bucket1.get(key); RedisHash value2 = (RedisHash) bucket2.get(key); assertThat(getIntFromBytes(value1)).isEqualTo(getIntFromBytes(value2)); } }); } }); }
Source:
<code>public void execute(Context context) throws SQLException { context.execute(new AlterColumnsBuilder(getDialect(), TABLE_WEBHOOK_DELIVERIES) .updateColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("ce_task_uuid") .setLimit(40) .setIsNullable(true) .build()) .build()); <START> context.execute(new AlterColumnsBuilder(getDialect(), TABLE_WEBHOOK_DELIVERIES) <END> .updateColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("analysis_uuid") .setLimit(40) .setIsNullable(false) .build()) .build()); }</code><technical_language>adding analysis_uuid column in migration called "make ce task uuid column nullable" is wise, imho least, is highly misleading</technical_language>

Target:
public void execute(Context context) throws SQLException { context.execute(new AlterColumnsBuilder(getDialect(), TABLE_WEBHOOK_DELIVERIES) .updateColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("ce_task_uuid") .setLimit(40) .setIsNullable(true) .build()) .build()); }
Source:
<code>public void preparePreselectedViews() { preselectedViews = new ArrayList<>(); List<Pair<MediaUnit, IncludedStructuralElement>> selectedMedia = dataEditor.getSelectedMedia(); for (Pair<MediaUnit, IncludedStructuralElement> pair : selectedMedia) { for (View view : pair.getValue().getViews()) { if (Objects.equals(view.getMediaUnit(), pair.getKey())) { preselectedViews.add(view); } } } preselectedViews = preselectedViews.stream().sorted(Comparator.comparingInt(v -> v.getMediaUnit().getOrder())) <START> .collect(Collectors.toList()); <END> }</code><technical_language>suggestion</technical_language>

Target:
public void preparePreselectedViews() { preselectedViews = new ArrayList<>(); List<Pair<MediaUnit, IncludedStructuralElement>> selectedMedia = dataEditor.getSelectedMedia(); for (Pair<MediaUnit, IncludedStructuralElement> pair : selectedMedia) { for (View view : pair.getValue().getViews()) { if (Objects.equals(view.getMediaUnit(), pair.getKey())) { preselectedViews.add(view); } } } preselectedViews.sort(Comparator.comparingInt(v -> v.getMediaUnit().getOrder())); }
Source:
<code>private void updateRecords(String query) { if (searcher != null) { searcher.cancel(true); } if (query.length() == 0) { if (prefs.getBoolean("history-hide", false)) { searcher = new NullSearcher(this); <START> ((LinearLayout)findViewById(R.id.main_empty)).setVisibility(View.INVISIBLE); <END> } else { searcher = new HistorySearcher(this); ((LinearLayout)findViewById(R.id.main_empty)).setVisibility(View.VISIBLE); } } else { searcher = new QuerySearcher(this, query); } searcher.execute(); }</code><technical_language>need cast change visibility</technical_language>

Target:
private void updateRecords(String query) { if (searcher != null) { searcher.cancel(true); } if (query.length() == 0) { if (prefs.getBoolean("history-hide", false)) { searcher = new NullSearcher(this); findViewById(R.id.main_empty).setVisibility(View.INVISIBLE); } else { searcher = new HistorySearcher(this); findViewById(R.id.main_empty).setVisibility(View.VISIBLE); } } else { searcher = new QuerySearcher(this, query); } searcher.execute(); }
Source:
<code>public void testMechanism() { DocumentModel folder = session.createDocumentModel("/", "folder", "Folder"); DocumentModel file1 = session.createDocumentModel("/folder", "file1", "File"); DocumentModel file2 = session.createDocumentModel("/folder", "file2", "File"); folder = session.createDocument(folder); <START> file1 = session.createDocument(file1); <END> file2 = session.createDocument(file2); session.save(); TrashService trashService = Framework.getService(TrashService.class); trashService.trashDocument(file1); txFeature.nextTransaction(); file1 = session.getDocument(file1.getRef()); assertTrue(session.isTrashed(file1.getRef())); Boolean isTrashed = session.getDocumentSystemProp(file1.getRef(), SYSPROP_IS_TRASHED, Boolean.class); assertTrue(isTrashed != null && isTrashed.booleanValue()); assertTrue(trashService.isMangledName(file1.getName())); trashService.trashDocument(folder); txFeature.nextTransaction(); folder = session.getDocument(folder.getRef()); file1 = session.getDocument(file1.getRef()); file2 = session.getDocument(file2.getRef()); assertTrue(session.isTrashed(folder.getRef())); assertTrue(session.isTrashed(file1.getRef())); assertTrue(session.isTrashed(file2.getRef())); assertTrue(trashService.isMangledName(folder.getName())); assertFalse(trashService.isMangledName(file2.getName())); trashService.untrashDocument(folder); txFeature.nextTransaction(); folder = session.getDocument(folder.getRef()); file1 = session.getDocument(file1.getRef()); file2 = session.getDocument(file2.getRef()); assertFalse(session.isTrashed(folder.getRef())); assertFalse(session.isTrashed(file1.getRef())); assertFalse(session.isTrashed(file2.getRef())); assertFalse(trashService.isMangledName(folder.getName())); assertFalse(trashService.isMangledName(file1.getName())); assertFalse(trashService.isMangledName(file2.getName())); }</code><technical_language>removing this? This test class is testing mechanism deleted lifecycle state intended test else. I test in property trash service test class</technical_language>

Target:
public void testMechanism() { DocumentModel doc = session.createDocumentModel("/", "file001", "File"); doc = session.createDocument(doc); session.save(); session.followTransition(doc, LifeCycleConstants.DELETE_TRANSITION); coreFeature.waitForAsyncCompletion(); assertTrue(session.isTrashed(doc.getRef())); Boolean isTrashed = session.getDocumentSystemProp(doc.getRef(), SYSPROP_IS_TRASHED, Boolean.class); assertTrue(isTrashed != null && isTrashed.booleanValue()); }
Source:
<code>public double availability() { LeaseImpl lease = leaseManager.getLease(); return lease.isValid() ? lease.getAllowedRequests() / (double) lease.getStartingAllowedRequests() <START> : 0.0; <END> }</code><technical_language>lease.getStartingAllowedRequests() equal zero? want check for that</technical_language>

Target:
public double availability() { LeaseImpl lease = leaseManager.getLease(); double leaseAvailability = lease.isValid() ? lease.getAllowedRequests() / (double) lease.getStartingAllowedRequests() : 0.0; return Math.min(leaseAvailability, super.availability()); }
Source:
<code>public void waitForInitialRemoteData() { SyncCredentials credentials = SyncCredentials.usernamePassword(UUID.randomUUID().toString(), "password", true); SyncUser user = SyncUser.login(credentials, Constants.AUTH_URL); SyncConfiguration config = new SyncConfiguration.Builder(user, Constants.USER_REALM) .waitForInitialRemoteData() .build(); Realm realm = null; try { realm = Realm.getInstance(config); <START> assertTrue(realm.isEmpty()); <END> } finally { if (realm != null) { realm.close(); } } }</code><technical_language>empty? this test? I difference if call .waitForInitialRemoteData();</technical_language>

Target:
public void waitForInitialRemoteData() { String username = UUID.randomUUID().toString(); String password = "password"; SyncUser user = SyncUser.login(SyncCredentials.usernamePassword(username, password, true), Constants.AUTH_URL); final SyncConfiguration configOld = configurationFactory.createSyncConfigurationBuilder(user, Constants.USER_REALM) .schema(StringOnly.class) .build(); Realm realm = Realm.getInstance(configOld); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { for (int i = 0; i < 10; i++) { realm.createObject(StringOnly.class).setChars("Foo" + i); } } }); SystemClock.sleep(TimeUnit.SECONDS.toMillis(10)); realm.close(); user.logout(); Realm.deleteRealm(configOld); user = SyncUser.login(SyncCredentials.usernamePassword(username, password), Constants.AUTH_URL); SyncConfiguration config = new SyncConfiguration.Builder(user, Constants.USER_REALM) .schema(StringOnly.class) .waitForInitialRemoteData() .build(); realm = Realm.getInstance(config); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { for (int i = 0; i < 10; i++) { realm.createObject(StringOnly.class).setChars("Foo 1" + i); } } }); try { assertEquals(20, realm.where(StringOnly.class).count()); } finally { realm.close(); } }