auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Collection<Student> selectAll(Long schoolId, Boolean activeStudents) { String whereClause = " WHERE s.currentSchoolId = :schoolId"; if(null == activeStudents || !activeStudents) { whereClause += " and s.withdrawalDate is not null"; } else { whereClause += ACTIVE_STUDENTS_CLAUSE; } if(null != schoolId) { String sql = STUDENT_HQL + whereClause; return (List<Student>) hibernateTemplate.findByNamedParam(sql, "schoolId", schoolId); } else { return hibernateTemplate.loadAll(Student.class); } }

Target:
public Collection<Student> selectAll(Long schoolId, Boolean activeStudents) { String whereClause = " WHERE s.currentSchoolId = :schoolId"; if(null == activeStudents || !activeStudents) { whereClause += " and s.withdrawalDate is not null or s.enrollStatus != '" + EnrollStatus.CURRENTLY_ENROLLED.name() + "'"; } else { whereClause += ACTIVE_STUDENTS_CLAUSE; } if(null != schoolId) { String sql = STUDENT_HQL + whereClause; return (List<Student>) hibernateTemplate.findByNamedParam(sql, "schoolId", schoolId); } else { return hibernateTemplate.loadAll(Student.class); } }
Source:
private static <T extends Annotation> AnnotationDescriptor<T> findAnnotationDescriptor( Class<?> clazz, Set<Annotation> visited, Class<T> annotationType) { Assert.notNull(annotationType, "Annotation type must not be null"); if (clazz == null || Object.class == clazz) { return null; } if (isAnnotationDeclaredLocally(annotationType, clazz)) { return new AnnotationDescriptor<>(clazz, clazz.getAnnotation(annotationType)); } for (Annotation composedAnnotation : clazz.getDeclaredAnnotations()) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(composedAnnotation) && visited.add(composedAnnotation)) { AnnotationDescriptor<T> descriptor = findAnnotationDescriptor( composedAnnotation.annotationType(), visited, annotationType); if (descriptor != null) { return new AnnotationDescriptor<>( clazz, descriptor.getDeclaringClass(), composedAnnotation, descriptor.getAnnotation()); } } } for (Class<?> ifc : clazz.getInterfaces()) { AnnotationDescriptor<T> descriptor = findAnnotationDescriptor(ifc, visited, annotationType); if (descriptor != null) { return new AnnotationDescriptor<>(clazz, descriptor.getDeclaringClass(), descriptor.getComposedAnnotation(), descriptor.getAnnotation()); } } return findAnnotationDescriptor(clazz.getSuperclass(), visited, annotationType); }

Target:
private static <T extends Annotation> AnnotationDescriptor<T> findAnnotationDescriptor( Class<?> clazz, Set<Annotation> visited, Class<T> annotationType) { Assert.notNull(annotationType, "Annotation type must not be null"); if (clazz == null || Object.class == clazz) { return null; } if (AnnotationUtils.isAnnotationDeclaredLocally(annotationType, clazz)) { return new AnnotationDescriptor<>(clazz, clazz.getAnnotation(annotationType)); } for (Annotation composedAnnotation : clazz.getDeclaredAnnotations()) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(composedAnnotation) && visited.add(composedAnnotation)) { AnnotationDescriptor<T> descriptor = findAnnotationDescriptor( composedAnnotation.annotationType(), visited, annotationType); if (descriptor != null) { return new AnnotationDescriptor<>( clazz, descriptor.getDeclaringClass(), composedAnnotation, descriptor.getAnnotation()); } } } for (Class<?> ifc : clazz.getInterfaces()) { AnnotationDescriptor<T> descriptor = findAnnotationDescriptor(ifc, visited, annotationType); if (descriptor != null) { return new AnnotationDescriptor<>(clazz, descriptor.getDeclaringClass(), descriptor.getComposedAnnotation(), descriptor.getAnnotation()); } } return findAnnotationDescriptor(clazz.getSuperclass(), visited, annotationType); }
Source:
public Set<String> getMetricNames() { return this.metricNames; }

Target:
public Set<String> getMetricNames() { return metricNames; }
Source:
public Object getObjectValue(ConnectorSession session, Block block, int position) { if (block.isNull(position)) { return null; } Slice slice = block.getSlice(position, 0, block.getSliceLength(position)); if (slice == Slices.EMPTY_SLICE) { return null; } return deserialize(slice).asText(); }

Target:
public Object getObjectValue(ConnectorSession session, Block block, int position) { if (block.isNull(position)) { return null; } Slice slice = block.getSlice(position, 0, block.getSliceLength(position)); return deserialize(slice).asText(); }
Source:
DownloadSdkNotification(@NotNull Module module) { setText("A valid App Engine SDK was not found for module :" + module.getName() + "."); createActionLabel("Install using Gradle", new Runnable() { @Override public void run() { GradleInvoker.getInstance(myProject).executeTasks(Collections.singletonList("appengineDownloadSdk")); } }); final VirtualFile buildFile = GradleUtil.getGradleBuildFile(module); if (buildFile != null && buildFile.exists()) { createActionLabel("Open build.gradle", new Runnable() { @Override public void run() { FileEditorManager.getInstance(myProject).openFile(buildFile, true); } }); } }

Target:
DownloadSdkNotification(@NotNull Module module) { setText(GctBundle.message("appengine.sdk.invalid",module.getName())); createActionLabel(GctBundle.message("appengine.sdk.gradle.install"), new Runnable() { @Override public void run() { GradleInvoker.getInstance(myProject).executeTasks(Collections.singletonList("appengineDownloadSdk")); } }); final VirtualFile buildFile = GradleUtil.getGradleBuildFile(module); if (buildFile != null && buildFile.exists()) { createActionLabel(GctBundle.message("appengine.sdk.open.gradle.build"), new Runnable() { @Override public void run() { FileEditorManager.getInstance(myProject).openFile(buildFile, true); } }); } }
Source:
public void setInSlot(Object slot, PresenterWidget<?> content) { super.setInSlot(slot, content); if (slot == getTabContentSlot()) { try { Presenter<?, ?> presenter = (Presenter<?, ?>) content; TabContentProxy<?> proxy = (TabContentProxy<?>) presenter.getProxy(); getView().setActiveTabHistoryToken(proxy.getTargetHistoryToken()); } catch (Exception e) { logger.log(Level.WARNING, "Failed setting slot. Exception message: " + e.getMessage()); } } }

Target:
public void setInSlot(Object slot, PresenterWidget<?> content) { super.setInSlot(slot, content); if (slot == getTabContentSlot()) { try { Presenter<?, ?> presenter = (Presenter<?, ?>) content; TabContentProxy<?> proxy = (TabContentProxy<?>) presenter.getProxy(); getView().setActiveTabHistoryToken(proxy.getTargetHistoryToken()); } catch (Exception e) { logger.log(Level.SEVERE, "Error while updating tab view", e); } } }
Source:
private String parseDependencyVersion(Dependency dependency, MavenRepositorySystemSession mvnRepository, RepositorySystem system, RemoteRepository remoteRepository, PomInformation pomInformation) throws ArtifactResolutionException { String parsedVersion; String version = dependency.getArtifact().getVersion(); if (StringUtils.isEmpty(version)) { parsedVersion = "[0,)"; } else if (version.contains("${")) { String propertyName = StringUtils.remove(version, "${"); propertyName = StringUtils.remove(propertyName, '}'); parsedVersion = getVersionFromProperties(propertyName, mvnRepository, system, remoteRepository, pomInformation); if (parsedVersion == null) { throw new MotechException(String.format("The property %s used in dependency %s cannot be found in pom " + "and its parents", propertyName, dependency.getArtifact().getArtifactId())); } } else { parsedVersion = version; } return parsedVersion; }

Target:
private String parseDependencyVersion(Dependency dependency, MavenRepositorySystemSession mvnRepository, RepositorySystem system, RemoteRepository remoteRepository, PomInformation pomInformation) throws ArtifactResolutionException { String parsedVersion; String version = dependency.getArtifact().getVersion(); if (StringUtils.isEmpty(version)) { parsedVersion = "[0,)"; } else { Set<String> properties = getPropertiesFromString(version); for (String propertyName : properties) { String parsedProperty = getPropertyFromPom(parsePropertyName(propertyName), mvnRepository, system, remoteRepository, pomInformation); if (parsedProperty == null) { LOGGER.error("The property: used in dependency: cannot be found in pom " + "and its parents. For this dependency the latest version will be used", propertyName, dependency.getArtifact().getArtifactId()); version = "[0,)"; break; } version = StringUtils.replace(version, propertyName, parsedProperty); } parsedVersion = version; } return parsedVersion; }
Source:
@Override public E poll() { lock.lock(); try { if (queue.isEmpty()) { return null; } E peek = queue.peek(); queue.remove(); return peek; } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); return null; } finally { lock.unlock(); } }

Target:
@Override public E poll() { lock.lock(); try { if (queue.isEmpty()) { return null; } E peek = queue.peek(); queue.remove(); return peek; } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
private boolean existPartitionColumnName(String tableName, String columnName) { final TableDesc tableDesc = catalog.getTableDesc(tableName); return tableDesc.getPartitionMethod().getExpressionSchema().contains(columnName) ? true : false; }

Target:
private boolean existPartitionColumnName(String tableName, String columnName) { final TableDesc tableDesc = catalog.getTableDesc(tableName); if (tableDesc.getPartitionMethod().getExpressionSchema().contains(columnName)) { return true; } else { return false; } }
Source:
private void updateWorkspaceOnLSStarted() { projectManager .getAll() .forEach( registeredProject -> { if (!registeredProject.getProblems().isEmpty()) { try { projectManager.update(registeredProject); eventService.publish(new ProjectUpdatedEvent(registeredProject.getPath())); } catch (Exception e) { LOG.error( String.format( "Failed to update project '%s' configuration", registeredProject.getName()), e); } } }); }

Target:
private void updateWorkspaceOnLSStarted() { projectManager .getAll() .forEach( registeredProject -> { if (!registeredProject.getProblems().isEmpty()) { try { projectManager.update(registeredProject); eventService.publish(new ProjectUpdatedEvent(registeredProject.getPath())); } catch (ForbiddenException | ServerException | NotFoundException | ConflictException | BadRequestException e) { LOG.error( String.format( "Failed to update project '%s' configuration", registeredProject.getName()), e); } } }); }
Source:
protected final ScheduledExecutor getMainThreadExecutor() { return Preconditions.checkNotNull( this.mainThreadExecutor, "Cannot get main thread executor. Resource manager driver is not initialized."); }

Target:
protected final ScheduledExecutor getMainThreadExecutor() { Preconditions.checkState(mainThreadExecutor != null, "Cannot get main thread executor. Resource manager driver is not initialized."); return mainThreadExecutor; }
Source:
protected void configureJPA() { JPAConfigParser parser = new JPAConfigParser(); install(new JpaPersistModule("default").properties(parser.parseConfig(this.config.toMap()))); bind(JPAInitializer.class).asEagerSingleton(); }

Target:
protected void configureJPA() { install(new JpaPersistModule("default").properties(this.config.getNamespaceProperties("jpa.config"))); bind(JPAInitializer.class).asEagerSingleton(); }
Source:
public void destroy() throws IOException { for (Closeable resource : resources) { try { resource.close(); } catch (Throwable t) { LOGGER.info("Exception closing resource : {}", resource, t); } } connection.close(); }

Target:
public void destroy() throws IOException { closeResources(); connection.close(); }
Source:
public NodeAndNovaTemplateOptions(AtomicReference<NodeMetadata> nodeMetadata, AtomicReference<NovaTemplateOptions> novaTemplateOptions){ this.nodeMetadata = nodeMetadata; this.novaTemplateOptions = novaTemplateOptions; }

Target:
protected NodeAndNovaTemplateOptions(AtomicReference<NodeMetadata> nodeMetadata, AtomicReference<NovaTemplateOptions> novaTemplateOptions){ this.nodeMetadata = nodeMetadata; this.novaTemplateOptions = novaTemplateOptions; }
Source:
private void buildPrefilledCardHolderDetails(PrefilledCardholderDetails prefilledCardholderDetails, JsonStringBuilder request) { if (prefilledCardholderDetails.getCardholderName().isPresent()) { request.addToMap("prefilled_cardholder_details", "cardholder_name", prefilledCardholderDetails.getCardholderName().get()); } if (prefilledCardholderDetails.getBillingAddress().isPresent()) { Address address = prefilledCardholderDetails.getBillingAddress().get(); request.addToNestedMap("line1", address.getLine1(), "prefilled_cardholder_details", "billing_address"); request.addToNestedMap("line2", address.getLine2(), "prefilled_cardholder_details", "billing_address"); request.addToNestedMap("postcode", address.getPostcode(), "prefilled_cardholder_details", "billing_address"); request.addToNestedMap("city", address.getCity(), "prefilled_cardholder_details", "billing_address"); request.addToNestedMap("country", address.getCountry(), "prefilled_cardholder_details", "billing_address"); } }

Target:
private void buildPrefilledCardHolderDetails(PrefilledCardholderDetails prefilledCardholderDetails, JsonStringBuilder request) { prefilledCardholderDetails.getCardholderName() .ifPresent(name -> request.addToMap(PREFILLED_CARDHOLDER_DETAILS, "cardholder_name", name)); prefilledCardholderDetails.getBillingAddress().ifPresent(address -> { request.addToNestedMap("line1", address.getLine1(), PREFILLED_CARDHOLDER_DETAILS, BILLING_ADDRESS); request.addToNestedMap("line2", address.getLine2(), PREFILLED_CARDHOLDER_DETAILS, BILLING_ADDRESS); request.addToNestedMap("postcode", address.getPostcode(), PREFILLED_CARDHOLDER_DETAILS, BILLING_ADDRESS); request.addToNestedMap("city", address.getCity(), PREFILLED_CARDHOLDER_DETAILS, BILLING_ADDRESS); request.addToNestedMap("country", address.getCountry(), PREFILLED_CARDHOLDER_DETAILS, BILLING_ADDRESS); }); }
Source:
public KieContainer getKieContainer(ReleaseId releaseId) throws SrampClientException, SrampAtomException { KieServices ks = KieServices.Factory.get(); KieRepository repo = ks.getRepository(); SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient(); Governance governance = new Governance(); String workflowGroupId = governance.getGovernanceWorkflowGroup(); String workflowArtifactId = governance.getGovernanceWorkflowName(); String workflowVersion = SrampMavenUtil.getVersion(SRAMP_KIE_MODEL, workflowGroupId, workflowArtifactId, governance.getGovernanceWorkflowVersion()); QueryResultSet results = null; ArtifactSummary artifactSummary = null; results = client.buildQuery(SRAMP_KIE_JAR_QUERY).parameter(workflowGroupId).parameter(workflowArtifactId).parameter(workflowVersion).count(1) .query(); if (results.size() > 0) { artifactSummary = results.get(0); InputStream is = client.getArtifactContent(artifactSummary); KieModule kModule = repo.addKieModule(ks.getResources().newInputStreamResource(is)); logger.info(Messages.i18n.format("KieSrampUtil.CreatingKieContainer", artifactSummary.getName())); KieContainer kContainer = ks.newKieContainer(kModule.getReleaseId()); logger.info(Messages.i18n.format("KieSrampUtil.FindKieBase", governance.getGovernanceWorkflowPackage())); return kContainer; } else { return null; } }

Target:
public KieContainer getKieContainer(ReleaseId releaseId) throws SrampClientException, SrampAtomException { KieServices ks = KieServices.Factory.get(); KieRepository repo = ks.getRepository(); SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient(); Governance governance = new Governance(); String workflowGroupId = governance.getGovernanceWorkflowGroup(); String workflowArtifactId = governance.getGovernanceWorkflowName(); String workflowVersion = SrampMavenUtil.getVersion(SRAMP_KIE_MODEL, workflowGroupId, workflowArtifactId, governance.getGovernanceWorkflowVersion()); if (StringUtils.isBlank(workflowVersion)) { throw new RuntimeException(Messages.i18n.format("maven.version.not.found", workflowGroupId, workflowArtifactId, workflowVersion)); } QueryResultSet results = null; ArtifactSummary artifactSummary = null; results = client.buildQuery(SRAMP_KIE_JAR_QUERY).parameter(workflowGroupId).parameter(workflowArtifactId).parameter(workflowVersion).count(1) .query(); if (results.size() > 0) { artifactSummary = results.get(0); InputStream is = client.getArtifactContent(artifactSummary); KieModule kModule = repo.addKieModule(ks.getResources().newInputStreamResource(is)); logger.info(Messages.i18n.format("KieSrampUtil.CreatingKieContainer", artifactSummary.getName())); KieContainer kContainer = ks.newKieContainer(kModule.getReleaseId()); logger.info(Messages.i18n.format("KieSrampUtil.FindKieBase", governance.getGovernanceWorkflowPackage())); return kContainer; } else { return null; } }
Source:
private void generateSubPlanForJoinNodeRecursively(JoinNode rootNode, int nextNode, List<JoinNode> nodes) { assert(nodes.size() > nextNode); JoinNode joinNode = nodes.get(nextNode); if (nodes.size() == nextNode + 1) { for (AccessPath path : joinNode.m_accessPaths) { joinNode.m_currentAccessPath = path; AbstractPlanNode plan = getSelectSubPlanForJoinNode(rootNode); if (plan == null) { continue; } m_plans.add(plan); } return; } if (! m_plans.isEmpty() && m_plans.size() % S_PLAN_ESTIMATE_PERIOD == 0) { final long usedHeapMemory = evaluatePlanSize() * S_PLAN_SIZE; if (usedHeapMemory >= S_MAX_ALLOWED_PLAN_MEMORY) { return; } } for (AccessPath path : joinNode.m_accessPaths) { joinNode.m_currentAccessPath = path; generateSubPlanForJoinNodeRecursively(rootNode, nextNode+1, nodes); } }

Target:
private void generateSubPlanForJoinNodeRecursively(JoinNode rootNode, int nextNode, List<JoinNode> nodes) { assert(nodes.size() > nextNode); JoinNode joinNode = nodes.get(nextNode); if (nodes.size() == nextNode + 1) { for (AccessPath path : joinNode.m_accessPaths) { joinNode.m_currentAccessPath = path; AbstractPlanNode plan = getSelectSubPlanForJoinNode(rootNode); if (plan == null) { continue; } m_plans.add(plan); } return; } if (! m_plans.isEmpty() && m_plans.size() % PLAN_ESTIMATE_PERIOD == 0 && shouldStopPlanning()) { return; } for (AccessPath path : joinNode.m_accessPaths) { joinNode.m_currentAccessPath = path; generateSubPlanForJoinNodeRecursively(rootNode, nextNode+1, nodes); } }
Source:
public void start(ArrayList<Object> unsupportedBlocksList) { if (!mStarted) { Map<String, Object> properties = getCommonProperties(); mHasUnsupportedBlocks = unsupportedBlocksList != null && unsupportedBlocksList.size() > 0; properties.put(KEY_UNSUPPORTED_BLOCKS, unsupportedBlocksList != null ? unsupportedBlocksList : new ArrayList<>()); AnalyticsTracker.track(Stat.EDITOR_SESSION_START, properties); mStarted = true; } else { AppLog.w(T.EDITOR, "An editor session cannot be attempted to be started more than once, " + "unless it's due to rotation or Editor switch"); } }

Target:
public void start(ArrayList<Object> unsupportedBlocksList) { if (!mStarted) { mHasUnsupportedBlocks = unsupportedBlocksList != null && unsupportedBlocksList.size() > 0; Map<String, Object> properties = getCommonProperties(); properties.put(KEY_UNSUPPORTED_BLOCKS, unsupportedBlocksList != null ? unsupportedBlocksList : new ArrayList<>()); AnalyticsTracker.track(Stat.EDITOR_SESSION_START, properties); mStarted = true; } else { AppLog.w(T.EDITOR, "An editor session cannot be attempted to be started more than once, " + "unless it's due to rotation or Editor switch"); } }
Source:
public IStructuredSelection findSelection(IEditorInput anInput) { if (!(anInput instanceof IURIEditorInput)) { return null; } URI uri = ((IURIEditorInput) anInput).getURI(); if (!uri.getScheme().equals("file")) return null; File file = new File(uri.getPath()); if (!file.exists()) return null; RepositoryUtil config = Activator.getDefault().getRepositoryUtil(); List<String> repos = config.getConfiguredRepositories(); for (String repo : repos) { Repository repository; try { repository = new RepositoryBuilder().setGitDir(new File(repo)) .build(); } catch (IOException e) { continue; } if (repository.isBare()) continue; if (file.getPath().startsWith(repository.getWorkTree().getPath())) { RepositoriesViewContentProvider cp = new RepositoriesViewContentProvider(); RepositoryNode repoNode = new RepositoryNode(null, repository); RepositoryTreeNode result = null; for (Object child : cp.getChildren(repoNode)) { if (child instanceof WorkingDirNode) { result = (WorkingDirNode) child; break; } } if (result == null) return null; IPath remainingPath = new Path(file.getPath().substring( repository.getWorkTree().getPath().length())); for (String segment : remainingPath.segments()) { for (Object child : cp.getChildren(result)) { RepositoryTreeNode<File> fileNode; try { fileNode = (RepositoryTreeNode<File>) child; } catch (ClassCastException e) { return null; } if (fileNode.getObject().getName().equals(segment)) { result = fileNode; break; } } } return new StructuredSelection(result); } } return null; }

Target:
public IStructuredSelection findSelection(IEditorInput anInput) { if (!(anInput instanceof IURIEditorInput)) { return null; } URI uri = ((IURIEditorInput) anInput).getURI(); if (!uri.getScheme().equals("file")) return null; File file = new File(uri.getPath()); if (!file.exists()) return null; RepositoryUtil config = Activator.getDefault().getRepositoryUtil(); List<String> repos = config.getConfiguredRepositories(); for (String repo : repos) { Repository repository; try { repository = FileRepositoryBuilder.create(new File(repo)); } catch (IOException e) { continue; } if (repository.isBare()) continue; if (file.getPath().startsWith(repository.getWorkTree().getPath())) { RepositoriesViewContentProvider cp = new RepositoriesViewContentProvider(); RepositoryNode repoNode = new RepositoryNode(null, repository); RepositoryTreeNode result = null; for (Object child : cp.getChildren(repoNode)) { if (child instanceof WorkingDirNode) { result = (WorkingDirNode) child; break; } } if (result == null) return null; IPath remainingPath = new Path(file.getPath().substring( repository.getWorkTree().getPath().length())); for (String segment : remainingPath.segments()) { for (Object child : cp.getChildren(result)) { RepositoryTreeNode<File> fileNode; try { fileNode = (RepositoryTreeNode<File>) child; } catch (ClassCastException e) { return null; } if (fileNode.getObject().getName().equals(segment)) { result = fileNode; break; } } } return new StructuredSelection(result); } } return null; }
Source:
public void visitAttackSignal(AttackSignal s) { InternalRobot attacker = (InternalRobot) getObjectByID(s.getRobotID()); MapLocation targetLoc = s.getTargetLoc(); double rate = 1.0; switch (attacker.type) { case STANDARDZOMBIE: case FASTZOMBIE: case RANGEDZOMBIE: case BIGZOMBIE: rate = 1.0; case SCOUT: case SOLDIER: case GUARD: case VIPER: case TURRET: int splashRadius = 0; InternalRobot[] targets = getAllRobotsWithinRadiusSq(targetLoc, splashRadius); for (InternalRobot target : targets) { if (target.getTeam() != attacker.getTeam()) { double damage = (attacker.type.attackPower) * rate; target.takeDamage(damage, attacker); } } break; default: } addSignal(s); removeDead(); }

Target:
public void visitAttackSignal(AttackSignal s) { InternalRobot attacker = (InternalRobot) getObjectByID(s.getRobotID()); MapLocation targetLoc = s.getTargetLoc(); double rate = 1.0; switch (attacker.type) { case STANDARDZOMBIE: case FASTZOMBIE: case RANGEDZOMBIE: case BIGZOMBIE: case SCOUT: case SOLDIER: case GUARD: case VIPER: case TURRET: int splashRadius = 0; InternalRobot[] targets = getAllRobotsWithinRadiusSq(targetLoc, splashRadius); for (InternalRobot target : targets) { if (target.getTeam() != attacker.getTeam()) { if (attacker.type == RobotType.GUARD && target.type.isZombie) rate = GameConstants.GUARD_ZOMBIE_MULTIPLIER; if (attacker.type.canInfect() && target.type.isInfectable()) target.setInfected(attacker); double damage = (attacker.type.attackPower) * rate; target.takeDamage(damage, attacker); } } break; default: } addSignal(s); removeDead(); }
Source:
public void testQuerySerialization() throws IOException { RegexSearchQuerySpec spec = new RegexSearchQuerySpec("(upfront|total_market)"); String json = jsonMapper.writeValueAsString(spec); RegexSearchQuerySpec serdeQuery = jsonMapper.readValue(json, RegexSearchQuerySpec.class); Assert.assertEquals(spec, serdeQuery); }

Target:
public void testQuerySerialization() throws IOException { RegexSearchQuerySpec spec = new RegexSearchQuerySpec("(upfront|total_market)"); String json = jsonMapper.writeValueAsString(spec); RegexSearchQuerySpec serdeQuery = (RegexSearchQuerySpec) jsonMapper.readValue(json, RegexSearchQuerySpec.class); Assert.assertEquals(spec, serdeQuery); }
Source:
public boolean isDomainAvailable(String domain) throws TenantMgtException { TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager(); try { int tenantID = tenantManager.getTenantId(domain); if (tenantID == -1) { return true; } } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new TenantManagementServerException("Error while getting the tenant.", e); } return false; }

Target:
public boolean isDomainAvailable(String domain) throws TenantMgtException { TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager(); try { int tenantID = tenantManager.getTenantId(domain); if (tenantID == -1) { return true; } } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new TenantManagementServerException("Error while getting the tenant - " + domain, e); } return false; }
Source:
public String toString() { StringBuilder sb = new StringBuilder("ColumnarMap{"); sb.append("positionCount=").append(getPositionCount()).append(","); sb.append("offsetsOffset=").append(offsetsOffset).append(","); sb.append("nullCheckBlock=").append(nullCheckBlock.toString()).append(","); sb.append("keysBlock=").append(keysBlock.toString()).append(","); sb.append("valuesBlock=").append(valuesBlock.toString()).append(","); sb.append("hashTablesSize=").append(hashTables == null ? 0 : hashTables.length).append(","); sb.append('}'); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append("{"); sb.append("positionCount=").append(getPositionCount()).append(","); sb.append("offsetsOffset=").append(offsetsOffset).append(","); sb.append("nullCheckBlock=").append(nullCheckBlock.toString()).append(","); sb.append("keysBlock=").append(keysBlock.toString()).append(","); sb.append("valuesBlock=").append(valuesBlock.toString()).append(","); sb.append("hashTablesSize=").append(hashTables == null ? 0 : hashTables.length).append(","); sb.append('}'); return sb.toString(); }
Source:
public SELF containsAnyElementsOf(Iterable<ELEMENT> iterable) { iterables.assertContainsAnyElementsOf(info, actual, iterable); return myself; }

Target:
public SELF containsAnyElementsOf(Iterable<ELEMENT> iterable) { containsAnyOf(toArray(iterable)); return myself; }
Source:
private ResourceInfo getResourceInfo( QueryResponse queryResponse, Object queriedAttributeValue, Map<String, Serializable> requestProperties, StringBuilder federatedSite) throws ResourceNotFoundException, UnsupportedQueryException { Metacard metacard; URI resourceUri; if (queryResponse.getResults().size() > 1) { throw new UnsupportedQueryException( "A resource request resulted in multiple metacards being returned."); } metacard = queryResponse.getResults().get(0).getMetacard(); if (requestProperties != null && requestProperties.get(ContentItem.QUALIFIER_KEYWORD) instanceof String && StringUtils.isNotBlank((String) requestProperties.get(ContentItem.QUALIFIER_KEYWORD))) { resourceUri = getDerivedResourceUri( metacard, (String) requestProperties.get(ContentItem.QUALIFIER_KEYWORD)); } else if (queriedAttributeValue instanceof URI) { resourceUri = (URI) queriedAttributeValue; } else { resourceUri = metacard.getResourceURI(); } federatedSite.append(metacard.getSourceId()); LOGGER.debug( "Trying to lookup resource URI for metacardId: {}", resourceUri, metacard.getId()); if (requestProperties != null) { if (!requestProperties.containsKey(Metacard.ID)) { requestProperties.put(Metacard.ID, metacard.getId()); } if (!requestProperties.containsKey(Metacard.RESOURCE_URI)) { requestProperties.put(Metacard.RESOURCE_URI, metacard.getResourceURI()); } } return new ResourceInfo(metacard, resourceUri); }

Target:
private ResourceInfo getResourceInfo( QueryResponse queryResponse, Object queriedAttributeValue, Map<String, Serializable> requestProperties, StringBuilder federatedSite) throws ResourceNotFoundException, UnsupportedQueryException { Metacard metacard; URI resourceUri; metacard = queryResponse.getResults().get(0).getMetacard(); if (requestProperties != null && requestProperties.get(ContentItem.QUALIFIER_KEYWORD) instanceof String && StringUtils.isNotBlank((String) requestProperties.get(ContentItem.QUALIFIER_KEYWORD))) { resourceUri = getDerivedResourceUri( metacard, (String) requestProperties.get(ContentItem.QUALIFIER_KEYWORD)); } else if (queriedAttributeValue instanceof URI) { resourceUri = (URI) queriedAttributeValue; } else { resourceUri = metacard.getResourceURI(); } federatedSite.append(metacard.getSourceId()); LOGGER.debug( "Trying to lookup resource URI for metacardId: {}", resourceUri, metacard.getId()); if (requestProperties != null) { if (!requestProperties.containsKey(Metacard.ID)) { requestProperties.put(Metacard.ID, metacard.getId()); } if (!requestProperties.containsKey(Metacard.RESOURCE_URI)) { requestProperties.put(Metacard.RESOURCE_URI, metacard.getResourceURI()); } } return new ResourceInfo(metacard, resourceUri); }
Source:
private synchronized void saveFilestoreModel(FilestoreModel model) { try { File metaFile = new File(getStorageFolder(), METAFILE); boolean isNewFile = !metaFile.exists(); RandomAccessFile fs = new RandomAccessFile(metaFile, "rw"); if (isNewFile) { metaFile.getParentFile().mkdirs(); metaFile.createNewFile(); fs.writeBytes("["); } else { fs.seek(fs.length() - 1); fs.writeBytes(","); } fs.writeBytes(gson().toJson(model)); fs.writeBytes("]"); fs.close(); } catch (IOException e) { logger.error("Writing filestore model to file {0}, {1}", METAFILE, e); } }

Target:
private synchronized void saveFilestoreModel(FilestoreModel model) { File metaFile = new File(getStorageFolder(), METAFILE); File metaFileTmp = new File(getStorageFolder(), METAFILE_TMP); boolean isNewFile = false; try { if (!metaFile.exists()) { metaFile.getParentFile().mkdirs(); metaFile.createNewFile(); isNewFile = true; } FileUtils.copyFile(metaFile, metaFileTmp); } catch (IOException e) { logger.error("Writing filestore model to file {0}, {1}", METAFILE, e); } try (RandomAccessFile fs = new RandomAccessFile(metaFileTmp, "rw")) { if (isNewFile) { fs.writeBytes("["); } else { fs.seek(fs.length() - 1); fs.writeBytes(","); } fs.writeBytes(gson().toJson(model)); fs.writeBytes("]"); fs.close(); } catch (IOException e) { logger.error("Writing filestore model to file {0}, {1}", METAFILE_TMP, e); } try { if (metaFileTmp.exists()) { FileUtils.copyFile(metaFileTmp, metaFile); metaFileTmp.delete(); } else { logger.error("Writing filestore model to file {0}", METAFILE); } } catch (IOException e) { logger.error("Writing filestore model to file {0}, {1}", METAFILE, e); } }
Source:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); return next.process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).flatMap( body -> { String bodyStr = new String(body, StandardCharsets.UTF_8); AzureJacksonAdapter jacksonAdapter = new AzureJacksonAdapter(); CloudError cloudError; try { cloudError = jacksonAdapter.deserialize( bodyStr, CloudError.class, SerializerEncoding.JSON); } catch (IOException e) { return Mono.just(bufferedResponse); } if (cloudError != null && MISSING_SUBSCRIPTION_REGISTRATION.equals(cloudError.getCode())) { ResourceManager resourceManager = ResourceManager.authenticate(credential, profile) .withDefaultSubscription(); Pattern providerPattern = Pattern.compile(".*'(.*)'"); Matcher providerMatcher = providerPattern.matcher(cloudError.getMessage()); providerMatcher.find(); return registerProviderUntilSuccess(providerMatcher.group(1), resourceManager) .flatMap(afterRegistered -> next.process()); } return Mono.just(bufferedResponse); } ); } return Mono.just(response); } ); }

Target:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return next.process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).flatMap( body -> { String bodyStr = new String(body, StandardCharsets.UTF_8); AzureJacksonAdapter jacksonAdapter = new AzureJacksonAdapter(); CloudError cloudError; try { cloudError = jacksonAdapter.deserialize( bodyStr, CloudError.class, SerializerEncoding.JSON); } catch (IOException e) { return Mono.just(bufferedResponse); } if (cloudError != null && MISSING_SUBSCRIPTION_REGISTRATION.equals(cloudError.getCode())) { ResourceManager resourceManager = ResourceManager.authenticate(credential, profile) .withDefaultSubscription(); Pattern providerPattern = Pattern.compile(".*'(.*)'"); Matcher providerMatcher = providerPattern.matcher(cloudError.getMessage()); providerMatcher.find(); return registerProviderUntilSuccess(providerMatcher.group(1), resourceManager) .flatMap(afterRegistered -> next.process()); } return Mono.just(bufferedResponse); } ); } return Mono.just(response); } ); }
Source:
public String index(Request request, Response response) throws IOException { List<String> environmentNames = environmentConfigService.environmentNames() .stream().map(CaseInsensitiveString::toString).collect(Collectors.toList()); return GSON.toJson(environmentNames); }

Target:
public String index(Request request, Response response) throws IOException { List<String> environmentNames = environmentConfigService.environmentNames() .stream().map(CaseInsensitiveString::toString).collect(Collectors.toList()); return JsonOutputWriter.OBJECT_MAPPER.writeValueAsString(environmentNames); }
Source:
public int getDurationMinutes() { return (int) TimeUnit.MILLISECONDS.toMinutes(this.getEndTime().getTime() - this.getStartTime().getTime()); }

Target:
public int getDurationMinutes() { return (int) TimeUnit.MILLISECONDS.toMinutes(this.getEndTime().getTime() - this.getStartTime().getTime()) + 1; }
Source:
public Response<String> acquireLeaseWithResponse(int duration, RequestConditions modifiedRequestConditions, Duration timeout, Context context) { try { return blobLeaseClient.acquireLeaseWithResponse(duration, modifiedRequestConditions, timeout, context); } catch (BlobStorageException ex) { throw logger.logExceptionAsError(new DataLakeStorageException(ex.getServiceMessage(), ex.getResponse(), ex.getValue())); } }

Target:
public Response<String> acquireLeaseWithResponse(int duration, RequestConditions modifiedRequestConditions, Duration timeout, Context context) { return DataLakeImplUtils.returnOrConvertException(() -> blobLeaseClient.acquireLeaseWithResponse(duration, modifiedRequestConditions, timeout, context), logger); }
Source:
public Options(long connectTimeout, TimeUnit connectTimeoutUnit, long readTimeout, TimeUnit readTimeoutUnit, boolean followRedirects) { super(); this.connectTimeout = connectTimeout; this.connectTimeoutUnit = connectTimeoutUnit; this.readTimeout = readTimeout; this.readTimeoutUnit = readTimeoutUnit; this.followRedirects = followRedirects; this.allowStreamingMode = true; }

Target:
public Options(long connectTimeout, TimeUnit connectTimeoutUnit, long readTimeout, TimeUnit readTimeoutUnit, boolean followRedirects) { super(); this.connectTimeout = connectTimeout; this.connectTimeoutUnit = connectTimeoutUnit; this.readTimeout = readTimeout; this.readTimeoutUnit = readTimeoutUnit; this.followRedirects = followRedirects; }
Source:
public void testListAvailabilityZones() throws Exception { URI endpoint = URI.create("<LINK_0>"); AvailabilityZoneApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint).build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/availability_zones_list.json")).build() ).getAvailabilityZoneApi("RegionOne"); AvailabilityZone availabilityZoneActual = Iterables.getFirst(api.list(), null); AvailabilityZone availabilityZoneExpected = getTestAvailabilityZone(); assertNotNull(availabilityZoneActual); assertEquals(availabilityZoneActual.getName(), availabilityZoneExpected.getName()); assertEquals(availabilityZoneActual.getState().available(), availabilityZoneExpected.getState().available()); }

Target:
public void testListAvailabilityZones() throws Exception { URI endpoint = URI.create("<LINK_0>"); AvailabilityZoneApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint).build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/availability_zones_list.json")).build() ).getAvailabilityZoneApi("RegionOne"); AvailabilityZone availabilityZoneActual = Iterables.getFirst(api.list(), null); AvailabilityZone availabilityZoneExpected = getTestAvailabilityZone(); assertNotNull(availabilityZoneActual); assertEquals(availabilityZoneActual, availabilityZoneExpected); }
Source:
private void makeActions() { fPreviousThreadAction = fTimeGraphCombo.getTimeGraphViewer().getPreviousItemAction(); fPreviousThreadAction.setText("Previous Thread"); fPreviousThreadAction.setToolTipText("Select Previous Thread"); fNextThreadAction = fTimeGraphCombo.getTimeGraphViewer().getNextItemAction(); fNextThreadAction.setText("Next Thread"); fNextThreadAction.setToolTipText("Select Next Thread"); }

Target:
private void makeActions() { fPreviousItemAction = fTimeGraphCombo.getTimeGraphViewer().getPreviousItemAction(); fPreviousItemAction.setText(Messages.TmfTimeGraphViewer_PreviousItemActionNameText); fPreviousItemAction.setToolTipText(Messages.TmfTimeGraphViewer_PreviousItemActionToolTipText); fNextItemAction = fTimeGraphCombo.getTimeGraphViewer().getNextItemAction(); fNextItemAction.setText(Messages.TmfTimeGraphViewer_NextItemActionNameText); fNextItemAction.setToolTipText(Messages.TmfTimeGraphViewer_NextItemActionToolTipText); }
Source:
public String getZkRealmAddress() { return _zkRealmAddress; }

Target:
public String getZkRealmAddress() { if (!_isLeaf) { throw new IllegalStateException("only leaf nodes have meaningful zkRealmAddress"); } return _zkRealmAddress; }
Source:
public void setUp() throws Exception { Map<String, Integer> samplesPosition = new HashMap<>(); samplesPosition.put("sample1", 123); VARIANT_SOURCE_ENTITY.setSamplesPosition(samplesPosition); List<VariantSourceEntity> variantSourceEntities = Collections.singletonList(VARIANT_SOURCE_ENTITY); given(variantSourceEntityRepository.findByFileIdIn(eq(Collections.singletonList("fileId")), any())) .willReturn(variantSourceEntities); given(variantSourceEntityRepository.countByFileIdIn(eq(Collections.singletonList("fileId")))) .willReturn(1L); }

Target:
public void setUp() throws Exception { VariantSourceEntity variantSourceEntity = new VariantSourceEntity("fileId", "fileName", "studyId", "studyName", VariantStudy.StudyType.CASE, VariantSource.Aggregation.NONE, null, null, null); Map<String, Integer> samplesPosition = new HashMap<>(); samplesPosition.put("sample1", 123); variantSourceEntity.setSamplesPosition(samplesPosition); List<VariantSourceEntity> variantSourceEntities = Collections.singletonList(variantSourceEntity); given(variantSourceEntityRepository.findByFileIdIn(eq(Collections.singletonList("fileId")), any())) .willReturn(variantSourceEntities); given(variantSourceEntityRepository.countByFileIdIn(eq(Collections.singletonList("fileId")))) .willReturn(Long.valueOf(variantSourceEntities.size())); }
Source:
public void onMockCreated(Object mock, MockCreationSettings settings) { this.mocks.put(mock, settings); settings.getStubbingLookUpListeners().add(new StubbingLookUpListener() { public void onStubbingLookUp(Invocation invocation, MatchableInvocation stubbingFound) { if (stubbingFound == null) { List<Invocation> matchingStubbings = new LinkedList<Invocation>(); Collection<Stubbing> stubbings = mockingDetails(invocation.getMock()).getStubbings(); for (Stubbing s : stubbings) { if (!s.wasUsed() && s.getInvocation().getMethod().getName().equals(invocation.getMethod().getName())) { matchingStubbings.add(s.getInvocation()); } } if (!matchingStubbings.isEmpty()) { Reporter.potentialStubbingProblemByJUnitRule(invocation, matchingStubbings); } } else { invocation.markVerified(); } } }); }

Target:
public void onMockCreated(Object mock, MockCreationSettings settings) { this.mocks.put(mock, settings); ((CreationSettings) settings).getStubbingLookupListeners().add(new StubbingLookupListener() { public void onStubbingLookup(Invocation invocation, MatchableInvocation stubbingFound) { if (stubbingFound == null) { List<Invocation> argMismatchStubbings = potentialArgMismatches(invocation); if (!argMismatchStubbings.isEmpty()) { Reporter.potentialStubbingProblemByJUnitRule(invocation, argMismatchStubbings); } } else { invocation.markVerified(); } } }); }
Source:
private void notifyListeners(Repository repository, IndexDiffData indexDiffData) { for (IndexDiffChangedListener listener : listeners) { SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { listener.indexDiffChanged(repository, indexDiffData); } @Override public void handleException(Throwable exception) { } }); } }

Target:
private void notifyListeners(Repository repository, IndexDiffData indexDiffData) { for (IndexDiffChangedListener listener : listeners) { SafeRunnable.run( () -> listener.indexDiffChanged(repository, indexDiffData)); } }
Source:
public void validateName(String name) { if (name == null) { throw new IllegalArgumentException("null bucket name"); } if (name.length() < 3 || name.length() > 63) { throw new IllegalArgumentException( name + " : " + "bucket name must be at least 3 and no more than 63 characters long"); } if (name.contains("..")) { String msg = "bucket name cannot contain successive periods. For more information refer " + "<LINK_0>"; throw new IllegalArgumentException(name + " : " + msg); } if (!name.matches("^[a-z0-9][a-z0-9\\.\\-]+[a-z0-9]$")) { String msg = "bucket name does not follow Amazon S3 standards. For more information refer " + "<LINK_0>"; throw new IllegalArgumentException(name + " : " + msg); } }

Target:
public static void validateName(String name) { if (name == null) { throw new IllegalArgumentException("null bucket name"); } if (name.length() < 3 || name.length() > 63) { throw new IllegalArgumentException( name + " : " + "bucket name must be at least 3 and no more than 63 characters long"); } if (name.contains("..")) { String msg = "bucket name cannot contain successive periods. For more information refer " + "<LINK_0>"; throw new IllegalArgumentException(name + " : " + msg); } if (!name.matches("^[a-z0-9][a-z0-9\\.\\-]+[a-z0-9]$")) { String msg = "bucket name does not follow Amazon S3 standards. For more information refer " + "<LINK_0>"; throw new IllegalArgumentException(name + " : " + msg); } }
Source:
public DB getDB() { return db != null ? db : mongoClient.getDB(database.getName()); }

Target:
public DB getDB() { return db; }
Source:
public void run() { errorGobbler.start(); inputGobbler.start(); try { while(!stopped) { try { process.exitValue(); stop(); } catch(IllegalThreadStateException itse) } } catch(NullPointerException npe) }

Target:
public void run() { errorGobbler.start(); inputGobbler.start(); try { process.waitFor(); } catch (InterruptedException e) stop(); }
Source:
private DashboardInfo findProjectDefaultDashboard(ProjectState projectState) { final Project.NameKey projectName = projectState.getProject().getNameKey(); Project.NameKey parent; DashboardInfo info; Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); seen.add(projectName); boolean considerLocal = true; do { info = loadProjectDefaultDashboard(projectState, considerLocal); if (info != null) { replaceTokens(info, projectName.get()); return info; } considerLocal = false; parent = projectState.getProject().getParent(allProjects); projectState = projectCache.get(parent); } while (projectState != null && seen.add(parent)); replaceTokens(info, projectName.get()); return info; }

Target:
private DashboardInfo findProjectDefaultDashboard(ProjectState projectState) { final Project.NameKey projectName = projectState.getProject().getNameKey(); Project.NameKey parent; DashboardInfo info; Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); seen.add(projectName); boolean considerLocal = true; do { info = loadProjectDefaultDashboard(projectState, considerLocal); if (info != null) { return info; } considerLocal = false; parent = projectState.getProject().getParent(allProjects); projectState = projectCache.get(parent); } while (projectState != null && seen.add(parent)); return info; }
Source:
@BeforeClass public static void beforeClass() throws Exception { pathToAppiumNodeInProperties = System.getProperty(APPIUM_PATH); for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { InetAddressValidator validator = InetAddressValidator.getInstance(); testIP = inetAddress.getHostAddress().toString(); if (validator.isValid(testIP)) { break; } testIP = null; } } if (testIP != null) { break; } } }

Target:
@BeforeClass public static void beforeClass() throws Exception { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); if ((testIP = getLocalIP(intf)) != null) { break; } } }
Source:
private boolean propagate(Map<CfgBlock, DefinedVariables> definedVariablesPerBlock) { block.predecessors().stream() .map(definedVariablesPerBlock::get) .filter(Objects::nonNull) .map(DefinedVariables::getOut) .forEach(predecessorOuts -> in = join(in, predecessorOuts)); Map<Symbol, VariableDefinition> newOut = new HashMap<>(in); kill.forEach(symbol -> newOut.put(symbol, VariableDefinition.DEFINED)); boolean outHasChanged = !newOut.equals(out); out = newOut; return outHasChanged; }

Target:
private boolean propagate(Map<CfgBlock, DefinedVariables> definedVariablesPerBlock) { block.predecessors().stream() .map(definedVariablesPerBlock::get) .map(DefinedVariables::getOut) .forEach(predecessorOuts -> in = join(in, predecessorOuts)); Map<Symbol, VariableDefinition> newOut = new HashMap<>(in); kill.forEach(symbol -> newOut.put(symbol, VariableDefinition.DEFINED)); boolean outHasChanged = !newOut.equals(out); out = newOut; return outHasChanged; }