auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void parseCoreEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException { final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NODE_IDENTIFIER: TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.parseAndSetParameter(value, operation, reader); break; case PATH: case RELATIVE_TO: throw new XMLStreamException("the attribute '" + attribute.getLocalName() + "' is no longer supported", reader.getLocation()); default: throw unexpectedAttribute(reader, i); } } final EnumSet<Element> required = EnumSet.of(Element.PROCESS_ID); final EnumSet<Element> encountered = EnumSet.noneOf(Element.class); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final Element element = Element.forName(reader.getLocalName()); required.remove(element); switch (element) { case PROCESS_ID: { if (!encountered.add(element)) { throw duplicateNamedElement(reader, reader.getLocalName()); } parseProcessIdEnvironmentElement(reader, operation); break; } default: throw unexpectedElement(reader); } } if (!required.isEmpty()) { throw missingRequiredElement(reader, required); } }

Target:
protected void parseCoreEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException { final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NODE_IDENTIFIER: TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.parseAndSetParameter(value, operation, reader); break; case PATH: case RELATIVE_TO: throw TransactionLogger.ROOT_LOGGER.unsupportedAttribute(attribute.getLocalName(), reader.getLocation()); default: throw unexpectedAttribute(reader, i); } } final EnumSet<Element> required = EnumSet.of(Element.PROCESS_ID); final EnumSet<Element> encountered = EnumSet.noneOf(Element.class); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final Element element = Element.forName(reader.getLocalName()); required.remove(element); switch (element) { case PROCESS_ID: { if (!encountered.add(element)) { throw duplicateNamedElement(reader, reader.getLocalName()); } parseProcessIdEnvironmentElement(reader, operation); break; } default: throw unexpectedElement(reader); } } if (!required.isEmpty()) { throw missingRequiredElement(reader, required); } }
Source:
protected boolean canDoAction() { setGlusterVolumeId(getGeoRepSession().getMasterVolumeId()); return super.canDoAction(); }

Target:
protected boolean canDoAction() { return super.canDoAction(); }
Source:
public void onProviderDisabled(String provider) { Timber.d("Provider %s disabled", provider); if (provider.equals("gps")) { NearbyParentFragment nearbyParentFragment = new NearbyParentFragment(); nearbyParentFragment.enableLocationOffDialog(); } }

Target:
public void onProviderDisabled(String provider) { Timber.d("Provider %s disabled", provider); }
Source:
public Map<String, Integer> getRowCounts() throws Exception { Map<String, Integer> ret = new HashMap<String, Integer>(); Connection con = this.getConnection(); DatabaseMetaData metaData = con.getMetaData(); ResultSet rs = metaData.getTables(null, "PUBLIC", "%", null); while (rs.next()) { String tableName = rs.getString(3); Statement stmt = con.createStatement(); ResultSet resultSet = stmt.executeQuery("SELECT count(*) AS rowcount FROM " + tableName); resultSet.next(); ret.put(tableName, resultSet.getInt("rowcount")); resultSet.close(); } return ret; }

Target:
public Map<String, Integer> getRowCounts() throws Exception { Map<String, Integer> ret = new HashMap<String, Integer>(); Connection con = this.getConnection(); DatabaseMetaData metaData = con.getMetaData(); DatabaseConnection dbcon = new DatabaseConnection(con); ResultSet rs = metaData.getTables(null, "PUBLIC", "%", null); while (rs.next()) { String tableName = rs.getString(3); ret.put(tableName, dbcon.getRowCount(tableName)); } return ret; }
Source:
protected void innerMap( InputRow inputRow, Object value, Context context ) throws IOException, InterruptedException { final Optional<Bucket> bucket = getConfig().getBucket(inputRow); if (!bucket.isPresent()) { throw new ISE("WTF?! No bucket found for row: %s", inputRow); } final long truncatedTimestamp = granularitySpec.getQueryGranularity().truncate(inputRow.getTimestampFromEpoch()); final byte[] hashedDimensions = hashFunction.hashBytes( HadoopDruidIndexerConfig.jsonMapper.writeValueAsBytes( Rows.toGroupKey( truncatedTimestamp, inputRow ) ) ).asBytes(); byte[] serializedInputRow = inputRow instanceof SegmentInputRow ? InputRowSerde.toBytes(inputRow, combiningAggs) : InputRowSerde.toBytes(inputRow, aggregators); context.write( new SortableBytes( bucket.get().toGroupKey(), ByteBuffer.allocate(Longs.BYTES + hashedDimensions.length) .putLong(truncatedTimestamp) .put(hashedDimensions) .array() ).toBytesWritable(), new BytesWritable(InputRowSerde.toBytes(inputRow, aggregators)) ); }

Target:
protected void innerMap( InputRow inputRow, Object value, Context context ) throws IOException, InterruptedException { final Optional<Bucket> bucket = getConfig().getBucket(inputRow); if (!bucket.isPresent()) { throw new ISE("WTF?! No bucket found for row: %s", inputRow); } final long truncatedTimestamp = granularitySpec.getQueryGranularity().truncate(inputRow.getTimestampFromEpoch()); final byte[] hashedDimensions = hashFunction.hashBytes( HadoopDruidIndexerConfig.jsonMapper.writeValueAsBytes( Rows.toGroupKey( truncatedTimestamp, inputRow ) ) ).asBytes(); byte[] serializedInputRow = inputRow instanceof SegmentInputRow ? InputRowSerde.toBytes(inputRow, combiningAggs) : InputRowSerde.toBytes(inputRow, aggregators); context.write( new SortableBytes( bucket.get().toGroupKey(), ByteBuffer.allocate(Longs.BYTES + hashedDimensions.length) .putLong(truncatedTimestamp) .put(hashedDimensions) .array() ).toBytesWritable(), new BytesWritable(serializedInputRow) ); }
Source:
private AdalAuthorizatonGrant processPasswordGrant( AdalAuthorizatonGrant authGrant) throws Exception { if (!(authGrant.getAuthorizationGrant() instanceof ResourceOwnerPasswordCredentialsGrant)) { return authGrant; } ResourceOwnerPasswordCredentialsGrant grant = (ResourceOwnerPasswordCredentialsGrant) authGrant .getAuthorizationGrant(); UserDiscoveryResponse discoveryResponse = UserDiscoveryRequest .execute(this.authenticationAuthority .getUserRealmEndpoint(grant.getUsername())); if (discoveryResponse.isAccountFederated()) { WSTrustResponse response = WSTrustRequest.execute(MexParser .getWsTrustEndpointFromMexEndpoint(discoveryResponse .getFederationMetadataUrl()), grant.getUsername(), grant.getPassword().getValue()); AuthorizationGrant updatedGrant = null; if (response.isTokenSaml2()) { updatedGrant = new SAML2BearerGrant(new Base64URL( Base64.encodeBase64String(response.getToken() .getBytes()))); } else { updatedGrant = new SAML11BearerGrant(new Base64URL( Base64.encodeBase64String(response.getToken() .getBytes()))); } authGrant = new AdalAuthorizatonGrant(updatedGrant, authGrant.getCustomParameters()); } return authGrant; }

Target:
private AdalAuthorizatonGrant processPasswordGrant( AdalAuthorizatonGrant authGrant) throws Exception { if (!(authGrant.getAuthorizationGrant() instanceof ResourceOwnerPasswordCredentialsGrant)) { return authGrant; } ResourceOwnerPasswordCredentialsGrant grant = (ResourceOwnerPasswordCredentialsGrant) authGrant .getAuthorizationGrant(); UserDiscoveryResponse discoveryResponse = UserDiscoveryRequest .execute(this.authenticationAuthority .getUserRealmEndpoint(grant.getUsername())); if (discoveryResponse.isAccountFederated()) { WSTrustResponse response = WSTrustRequest.execute(MexParser .getWsTrustEndpointFromMexEndpoint(discoveryResponse .getFederationMetadataUrl()), grant.getUsername(), grant.getPassword().getValue()); AuthorizationGrant updatedGrant = null; if (response.isTokenSaml2()) { updatedGrant = new SAML2BearerGrant(new Base64URL( Base64.encodeBase64String(response.getToken().getBytes( "UTF-8")))); } else { updatedGrant = new SAML11BearerGrant(new Base64URL( Base64.encodeBase64String(response.getToken() .getBytes()))); } authGrant = new AdalAuthorizatonGrant(updatedGrant, authGrant.getCustomParameters()); } return authGrant; }
Source:
private void populateSubAttributeList(Object attributeValue) { String attributeType = getAttribute().getType(); if ("javax.management.openmbean.CompositeData".equals(attributeType)) { CompositeData data = (CompositeData) attributeValue; for (String key : data.getCompositeType().keySet()) { this.subAttributeList.put(key, new HashMap<String, Object>()); } } else if (("java.util.HashMap".equals(attributeType)) || ("java.util.Map".equals(attributeType))){ HashMap<String, Double> data = (HashMap<String, Double>) attributeValue; for (String key : data.keySet()) { this.subAttributeList.put(key, new HashMap<String, Object>()); } } }

Target:
private void populateSubAttributeList(Object attributeValue) { String attributeType = getAttribute().getType(); if ("javax.management.openmbean.CompositeData".equals(attributeType)) { CompositeData data = (CompositeData) attributeValue; for (String key : data.getCompositeType().keySet()) { this.subAttributeList.put(key, new HashMap<String, Object>()); } } else if (("java.util.HashMap".equals(attributeType)) || ("java.util.Map".equals(attributeType))){ Map<String, Double> data = (Map<String, Double>) attributeValue; for (String key : data.keySet()) { this.subAttributeList.put(key, new HashMap<String, Object>()); } } }
Source:
public void setup() throws Exception { VerifiableProperties verProps = new VerifiableProperties(System.getProperties()); azureDest = new AzureCloudDestination(new AzureCloudConfig(verProps), new MetricRegistry()); cosmosCollectionLink = verProps.getString(AzureCloudConfig.COSMOS_COLLECTION_LINK); }

Target:
public void setup() throws Exception { VerifiableProperties verProps = new VerifiableProperties(System.getProperties()); azureDest = (AzureCloudDestination) new AzureCloudDestinationFactory(verProps, new MetricRegistry()).getCloudDestination(); cosmosCollectionLink = verProps.getString(AzureCloudConfig.COSMOS_COLLECTION_LINK); }
Source:
private void checkArchiveAttributesAllowed() { if (getProject() == null || (isReference() && getRefid().getReferencedObject(getProject()) instanceof ArchiveFileSet)) { checkAttributesAllowed(); } }

Target:
private void checkArchiveAttributesAllowed() { if (getProject() == null || (isReference() && (getRefid().getReferencedObject( getProject()) instanceof ArchiveFileSet))) { checkAttributesAllowed(); } }
Source:
public void setUp() throws IOException { tmpFile = File.createTempFile("storage-debug", ".json"); tmpFile.deleteOnExit(); objectStorage = new JsonStorage<>(tmpFile, this.getClass().getClassLoader(), 0, 0, 0); objectStorage.put("DummyObject", new DummyObject()); }

Target:
public void setUp() throws IOException { tmpFile = File.createTempFile("storage-debug", ".json"); tmpFile.deleteOnExit(); objectStorage = new JsonStorage<>(tmpFile, this.getClass().getClassLoader(), 0, 0, 0); }
Source:
public WorkflowItemRest fromModel(XmlWorkflowItem obj) { WorkflowItemRest witem = new WorkflowItemRest(); Collection collection = obj.getCollection(); Item item = obj.getItem(); EPerson submitter = null; try { submitter = obj.getSubmitter(); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } witem.setId(obj.getID()); witem.setCollection(collection != null ? collectionConverter.convert(collection) : null); witem.setItem(itemConverter.convert(item)); witem.setSubmitter(epersonConverter.convert(submitter)); if (collection != null) { witem.setStatus(true); SubmissionDefinitionRest def = submissionDefinitionConverter .convert(submissionConfigReader.getSubmissionConfigByCollection(collection.getHandle())); witem.setSubmissionDefinition(def); for (SubmissionSectionRest sections : def.getPanels()) { SubmissionStepConfig stepConfig = submissionSectionConverter.toModel(sections); ClassLoader loader = this.getClass().getClassLoader(); Class stepClass; try { stepClass = loader.loadClass(stepConfig.getProcessingClassName()); Object stepInstance = stepClass.newInstance(); if (stepInstance instanceof AbstractRestProcessingStep) { AbstractRestProcessingStep stepProcessing = (AbstractRestProcessingStep) stepClass.newInstance(); for (ErrorRest error : stepProcessing.validate(submissionService, obj, stepConfig)) { addError(witem.getErrors(), error); witem.setStatus(false); } witem.getSections() .put(sections.getId(), stepProcessing.getData(submissionService, obj, stepConfig)); } else { log.warn("The submission step class specified by '" + stepConfig.getProcessingClassName() + "' does not extend the class org.dspace.app.rest.submit.AbstractRestProcessingStep!" + " Therefore it cannot be used by the Configurable Submission as the " + "<processing-class>!"); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return witem; }

Target:
public WorkflowItemRest fromModel(XmlWorkflowItem obj) { WorkflowItemRest witem = new WorkflowItemRest(); fillFromModel(obj, witem); return witem; }
Source:
private ModuleType determineType(List<ModuleDeploymentRequest> modules) { Collections.sort(modules); Assert.isTrue(modules != null && modules.size() > 0, "at least one module required"); if (modules.size() == 1) { return modules.get(0).getType(); } ModuleType firstType = modules.get(0).getType(); ModuleType lastType = modules.get(modules.size() - 1).getType(); boolean hasInput = (!firstType.equals(ModuleType.source)); boolean hasOutput = (!lastType.equals(ModuleType.sink)); if (hasInput && hasOutput) { return ModuleType.processor; } if (hasInput) { return ModuleType.sink; } if (hasOutput) { return ModuleType.source; } throw new IllegalArgumentException("invalid module composition; must expose input and/or output channel"); }

Target:
private ModuleType determineType(List<ModuleDeploymentRequest> modules) { Collections.sort(modules); Assert.isTrue(modules != null && modules.size() > 0, "at least one module required"); if (modules.size() == 1) { return modules.get(0).getType(); } ModuleType firstType = modules.get(0).getType(); ModuleType lastType = modules.get(modules.size() - 1).getType(); boolean hasInput = firstType != ModuleType.source; boolean hasOutput = lastType != ModuleType.sink; if (hasInput && hasOutput) { return ModuleType.processor; } if (hasInput) { return ModuleType.sink; } if (hasOutput) { return ModuleType.source; } throw new IllegalArgumentException("invalid module composition; must expose input and/or output channel"); }
Source:
public Set<ClusterComponent> getParcelComponentsByBlueprint(Stack stack) { Cluster cluster = stack.getCluster(); Set<ClusterComponent> components = getParcelComponents(cluster); if (stack.isDatalake()) { ClusterComponent stackComponent = components.stream() .filter(clusterComponent -> clusterComponent.getName().equals(StackType.CDH.name())) .findFirst().orElse(null); if (Objects.isNull(stackComponent)) { throw new NotFoundException("Runtime component not found!"); } return Set.of(stackComponent); } else { Map<String, ClusterComponent> cmProductMap = new HashMap<>(); Set<ClouderaManagerProduct> cmProducts = new HashSet<>(); for (ClusterComponent clusterComponent : components) { ClouderaManagerProduct product = clusterComponent.getAttributes().getSilent(ClouderaManagerProduct.class); cmProductMap.put(product.getName(), clusterComponent); cmProducts.add(product); } cmProducts = filterParcelsByBlueprint(cmProducts, cluster.getBlueprint()); return cmProducts.stream().map(cmp -> cmProductMap.get(cmp.getName())).collect(Collectors.toSet()); } }

Target:
public Set<ClusterComponent> getParcelComponentsByBlueprint(Stack stack) { Cluster cluster = stack.getCluster(); Set<ClusterComponent> components = getParcelComponents(cluster); if (stack.isDatalake()) { ClusterComponent stackComponent = components.stream() .filter(clusterComponent -> clusterComponent.getName().equals(StackType.CDH.name())) .findFirst().orElseThrow(() -> new NotFoundException("Runtime component not found!")); LOGGER.debug("For datalake clusters only the CDH parcel is used in CM: {}", stackComponent); return Set.of(stackComponent); } else { Map<String, ClusterComponent> cmProductMap = new HashMap<>(); Set<ClouderaManagerProduct> cmProducts = new HashSet<>(); for (ClusterComponent clusterComponent : components) { ClouderaManagerProduct product = clusterComponent.getAttributes().getSilent(ClouderaManagerProduct.class); cmProductMap.put(product.getName(), clusterComponent); cmProducts.add(product); } cmProducts = filterParcelsByBlueprint(cmProducts, cluster.getBlueprint(), false); LOGGER.debug("The following parcels are used in CM based on blueprint: {}", cmProducts); return cmProducts.stream().map(cmp -> cmProductMap.get(cmp.getName())).collect(Collectors.toSet()); } }
Source:
public Function<A, Object> getLeftMapping(int joinerIndex) { throw new UnsupportedOperationException(); }

Target:
public Function<A, Object> getLeftMapping(int joinerIndex) { throw new UnsupportedOperationException("Impossible state: getLeftMapping() is never called on a NoneBiJoiner."); }
Source:
public static <T> Iterable<T> latest(final Observable<? extends T> source) { return new Iterable<T>() { @Override public Iterator<T> iterator() { LatestObserverIterator<T> lio = new LatestObserverIterator<T>(); lio.subscription = source.materialize().subscribe(lio); return lio; } }; }

Target:
public static <T> Iterable<T> latest(final Observable<? extends T> source) { return new Iterable<T>() { @Override public Iterator<T> iterator() { LatestObserverIterator<T> lio = new LatestObserverIterator<T>(); source.materialize().subscribe(lio); return lio; } }; }
Source:
public Set<String> listViews(String catalogName, String databaseName) { Catalog currentCatalog = catalogs.get(getCurrentCatalog()); try { return Stream.concat( currentCatalog.listViews(getCurrentDatabase()).stream(), listTemporaryTablesInternal(catalogName, databaseName) .filter(e -> e.getValue() instanceof CatalogView) .map(e -> e.getKey().getObjectName()) ).collect(Collectors.toSet()); } catch (DatabaseNotExistException e) { throw new ValidationException("Current database does not exist", e); } }

Target:
public Set<String> listViews(String catalogName, String databaseName) { Catalog currentCatalog = catalogs.get(getCurrentCatalog()); try { return Stream.concat( currentCatalog.listViews(getCurrentDatabase()).stream(), listTemporaryViewsInternal(catalogName, databaseName) .map(e -> e.getKey().getObjectName()) ).collect(Collectors.toSet()); } catch (DatabaseNotExistException e) { throw new ValidationException("Current database does not exist", e); } }
Source:
public WebElement displayedToStudentCheckBox(int instrNum) { return browser.driver.findElement(By.cssSelector("#instructorTable" + instrNum + " input[name=\"instructorisdisplayed\"]")); }

Target:
public WebElement displayedToStudentCheckBox(int instrNum) { return browser.driver.findElement(By.cssSelector("#instructorTable" + instrNum + " input[name='" + Const.ParamsNames.INSTRUCTOR_IS_DISPLAYED_TO_STUDENT + "']")); }
Source:
protected void sortByDateAdded() { if (sortByAdded.isChecked()) { return; } sortByAdded.setChecked(true); applicationSettings.setLastUsedSearchSortOrder(SearchSortOrder.Combined); refreshSearch(); }

Target:
protected void sortByDateAdded() { if (applicationSettings.getLastUsedSearchSortOrder() == SearchSortOrder.Combined) { return; } invalidateOptionsMenu(); applicationSettings.setLastUsedSearchSortOrder(SearchSortOrder.Combined); refreshSearch(); }
Source:
public static void initAuth(ConfigProvider configuration) { AuthScheme scheme = AuthScheme.BASIC; String username = configuration.getProperty(scheme, "username"); String password = configuration.getProperty(scheme, "password"); if (username != null) { LOG.info("Setting scheme: user: {}", scheme, username); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.BASIC); Credentials credentials = new UsernamePasswordCredentials(username, password); credentialsProvider.setCredentials(authScope, credentials); } registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()); credentialsProvider.setCredentials(AuthScope.ANY, DEFAULT_TOKEN_CREDENTIALS); authRegistry = registryBuilder.build(); }

Target:
public static void initAuth(ConfigProvider configuration) { AuthScheme scheme = AuthScheme.BASIC; String username = configuration.getProperty(scheme, "username"); String password = configuration.getProperty(scheme, "password"); if ((username != null) && (password != null)) { LOG.info("Setting up scheme {}", scheme); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.BASIC); Credentials credentials = new UsernamePasswordCredentials(username, password); credentialsProvider.setCredentials(authScope, credentials); } else if ((username != null) || (password != null)) { LOG.warn("Not setting up scheme {}, missing credentials {}", scheme, (username == null) ? "username" : "password"); } registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()); credentialsProvider.setCredentials(AuthScope.ANY, DEFAULT_TOKEN_CREDENTIALS); authRegistry = registryBuilder.build(); }
Source:
private GetBlockLocationsResult getBlockLocationsInt(final String srcArg, final String src, final long offset, final long length, final boolean needBlockToken, final boolean checkSafeMode) throws IOException { if (offset < 0) { throw new HadoopIllegalArgumentException( "Negative offset is not supported. File: " + src); } if (length < 0) { throw new HadoopIllegalArgumentException( "Negative length is not supported. File: " + src); } GetBlockLocationsResult ret; final INodeFile inodeFile = INodeFile.valueOf(dir.getINode(src), src); if (inodeFile.isFileStoredInDB()) { LOG.debug("SMALL_FILE The file is stored in the database. Returning Phantom Blocks"); ret = getPhantomBlockLocationsUpdateTimes(srcArg, src, needBlockToken); } else { ret = getBlockLocationsInt(srcArg, src, offset, length, needBlockToken); } if (checkSafeMode && isInSafeMode()) { for (LocatedBlock b : ret.blocks.getLocatedBlocks()) { if ((b.getLocations() == null) || (b.getLocations().length == 0)) { SafeModeException se = new SafeModeException( "Zero blocklocations for " + src, safeMode()); throw new RetriableException(se); } } } inodeFile.logProvenanceEvent(FileProvenanceEntry.Operation.getBlockLocations()); return ret; }

Target:
private GetBlockLocationsResult getBlockLocationsInt(final String srcArg, final String src, final long offset, final long length, final boolean needBlockToken, final boolean checkSafeMode) throws IOException { if (offset < 0) { throw new HadoopIllegalArgumentException( "Negative offset is not supported. File: " + src); } if (length < 0) { throw new HadoopIllegalArgumentException( "Negative length is not supported. File: " + src); } GetBlockLocationsResult ret; final INodeFile inodeFile = INodeFile.valueOf(dir.getINode(src), src); if (inodeFile.isFileStoredInDB()) { LOG.debug("SMALL_FILE The file is stored in the database. Returning Phantom Blocks"); ret = getPhantomBlockLocationsUpdateTimes(srcArg, src, needBlockToken); } else { ret = getBlockLocationsInt(srcArg, src, offset, length, needBlockToken); } if (checkSafeMode && isInSafeMode()) { for (LocatedBlock b : ret.blocks.getLocatedBlocks()) { if ((b.getLocations() == null) || (b.getLocations().length == 0)) { SafeModeException se = new SafeModeException( "Zero blocklocations for " + src, safeMode()); throw new RetriableException(se); } } } inodeFile.logProvenanceEvent(getNamenodeId(), FileProvenanceEntry.Operation.getBlockLocations()); return ret; }
Source:
public GraphicCanvas(Composite parent) { super(parent); m_objects = new ArrayList<IGraphicObject>(); Listener mouseListener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.MouseEnter: case SWT.MouseMove: IGraphicObject obj = getGraphicObject(event.x, event.y); String tooltip = obj.getTooltip(); setToolTipText(tooltip); break; } } }; addListener(SWT.MouseMove, mouseListener); addListener(SWT.MouseEnter, mouseListener); }

Target:
public GraphicCanvas(Composite parent) { super(parent); m_objects = new ArrayList<IGraphicObject>(); Listener mouseListener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.MouseEnter: case SWT.MouseMove: IGraphicObject obj = getGraphicObject(event.x, event.y); String tooltip = obj.getTooltip(event.x, event.y); setToolTipText(tooltip); break; } } }; addListener(SWT.MouseMove, mouseListener); addListener(SWT.MouseEnter, mouseListener); }
Source:
public LdapUserData getUserByAid(String aid, LDAPConnection conn) { String filter = ldapAttributeMapper.getFindUserByAidFilter(aid.replaceAll("@OX.AC.UK", "")); LdapUserData mappedEntry = null; try { mappedEntry = (LdapUserData) searchDirectoryForSingleEntry(filter, conn, null, null, null); } catch (LDAPException e) { M_log.error("Failed to find user for AID: " + aid, e); } return mappedEntry; }

Target:
public LdapUserData getUserByAid(String aid, LDAPConnection conn) { String filter = ldapAttributeMapper.getFindUserByAidFilter(aid.replace("@ox.ac.uk", "")); LdapUserData mappedEntry = null; try { mappedEntry = (LdapUserData) searchDirectoryForSingleEntry(filter, conn, null, null, null); } catch (LDAPException e) { M_log.error("Failed to find user for AID: " + aid, e); } return mappedEntry; }
Source:
public void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); assertEquals("[Test] \nExpecting:\n <[\"Yoda\", \"Luke\"]>\nto not start with:\n <[\"Han\", \"Leia\"]>\n", message); }

Target:
public void should_create_error_message() { String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); assertThat(message).isEqualTo("[Test] \nExpecting:\n <[\"Yoda\", \"Luke\"]>\nto not start with:\n " + "<[\"Han\", \"Leia\"]>\n"); }
Source:
private boolean valueEquals(SAMBinaryTagAndValue that) { if (this.value == null) { return that.value == null; } else if (that.value == null) { return false; } else if (this.value instanceof byte[]) { return that.value instanceof byte[] ? Arrays.equals((byte[])this.value, (byte[])that.value) : false; } else if (this.value instanceof short[]) { return that.value instanceof short[] ? Arrays.equals((short[])this.value, (short[])that.value) : false; } else if (this.value instanceof int[]) { return that.value instanceof int[] ? Arrays.equals((int[])this.value, (int[])that.value) : false; } else if (this.value instanceof float[]) { return that.value instanceof float[] ? Arrays.equals((float[])this.value, (float[])that.value) : false; } else { return this.value.equals(that.value); } }

Target:
private boolean valueEquals(SAMBinaryTagAndValue that) { if (this.value instanceof byte[]) { return that.value instanceof byte[] ? Arrays.equals((byte[])this.value, (byte[])that.value) : false; } else if (this.value instanceof short[]) { return that.value instanceof short[] ? Arrays.equals((short[])this.value, (short[])that.value) : false; } else if (this.value instanceof int[]) { return that.value instanceof int[] ? Arrays.equals((int[])this.value, (int[])that.value) : false; } else if (this.value instanceof float[]) { return that.value instanceof float[] ? Arrays.equals((float[])this.value, (float[])that.value) : false; } else { return this.value.equals(that.value); } }
Source:
private void validateIdentifier(final Contentlet contentlet) { if (UtilMethods.isSet(contentlet.getIdentifier())) { boolean isIdentifier = false; try { isIdentifier = APILocator.getIdentifierAPI().isIdentifier(contentlet.getIdentifier()); } catch (DotDataException e) { isIdentifier = false; } if (!isIdentifier) { throw new DoesNotExistException("The identifier: " + contentlet.getIdentifier() + " does not exists"); } } }

Target:
private void validateIdentifier(final Contentlet contentlet) { if (UtilMethods.isSet(contentlet.getIdentifier())) { final Optional<ShortyId> shortyId = APILocator.getShortyAPI().getShorty(contentlet.getIdentifier()); final boolean isIdentifier = shortyId.isPresent() && shortyId.get().subType== ShortType.IDENTIFIER; if (!isIdentifier) { throw new DoesNotExistException("The identifier: " + contentlet.getIdentifier() + " does not exists"); } } }
Source:
public void zoom(boolean zoomIn) { Point cursorDisplayLocation = getDisplay().getCursorLocation(); Point cursorControlLocation = toControl(cursorDisplayLocation); Point cursorScaleLocation = fTimeGraphScale.toControl(cursorDisplayLocation); if (!getBounds().contains(cursorControlLocation) && !fTimeGraphScale.getBounds().contains(cursorScaleLocation)) { return; } int nameSpace = fTimeProvider.getNameSpace(); int timeSpace = fTimeProvider.getTimeSpace(); int xPos = Math.max(nameSpace, Math.min(nameSpace + timeSpace, cursorControlLocation.x)); long time0 = fTimeProvider.getTime0(); long time1 = fTimeProvider.getTime1(); long interval = time1 - time0; if (interval == 0) { interval = 1; } long newInterval; if (zoomIn) { newInterval = Math.max(Math.round(interval * ZOOM_IN_FACTOR), fTimeProvider.getMinTimeInterval()); } else { newInterval = (long) Math.ceil(interval * ZOOM_OUT_FACTOR); } long center = time0 + Math.round(((double) (xPos - nameSpace) / timeSpace * interval)); long newTime0 = center - Math.round((double) newInterval * (center - time0) / interval); newTime0 = Math.max(fTimeProvider.getMinTime(), Math.min(newTime0, fTimeProvider.getMaxTime() - newInterval)); long newTime1 = newTime0 + newInterval; fTimeProvider.setStartFinishTimeNotify(newTime0, newTime1); }

Target:
public void zoom(boolean zoomIn) { Point cursorDisplayLocation = getDisplay().getCursorLocation(); Point cursorControlLocation = getParent().toControl(cursorDisplayLocation); Rectangle controlBounds = getBounds(); if (!controlBounds.contains(cursorControlLocation.x, controlBounds.y)) { return; } int nameSpace = fTimeProvider.getNameSpace(); int timeSpace = fTimeProvider.getTimeSpace(); int xPos = Math.max(nameSpace, Math.min(nameSpace + timeSpace, cursorControlLocation.x)); long time0 = fTimeProvider.getTime0(); long time1 = fTimeProvider.getTime1(); long interval = time1 - time0; if (interval == 0) { interval = 1; } long newInterval; if (zoomIn) { newInterval = Math.max(Math.round(interval * ZOOM_IN_FACTOR), fTimeProvider.getMinTimeInterval()); } else { newInterval = (long) Math.ceil(interval * ZOOM_OUT_FACTOR); } long center = time0 + Math.round(((double) (xPos - nameSpace) / timeSpace * interval)); long newTime0 = center - Math.round((double) newInterval * (center - time0) / interval); newTime0 = Math.max(fTimeProvider.getMinTime(), Math.min(newTime0, fTimeProvider.getMaxTime() - newInterval)); long newTime1 = newTime0 + newInterval; fTimeProvider.setStartFinishTimeNotify(newTime0, newTime1); }
Source:
public CustomThreadListAdapter(HomeActivity activity, String label, ListView listView, List<MailThread> mails) { super(); this.label = label; this.activity = activity; this.listView = listView; this.threads = new ArrayList<>(); this.threads_in_DB = new ArrayList<>(); this.threads_not_in_DB = new ArrayList<>(); threads_in_DB = mails; refreshThreads(); }

Target:
public CustomThreadListAdapter(HomeActivity activity, String label, ListView listView, List<MailThread> mails) { super(); this.label = label; this.activity = activity; this.listView = listView; this.threads = new ArrayList<>(); this.threads_not_in_DB = new ArrayList<>(); this.threads_in_DB = mails; refreshThreads(); }
Source:
private void createColumns(final Composite parent, final TableViewer viewer) { String[] titles = { "Function", "New Overhead (%)", "Old Overhead (%)", "Result", "Event", "" }; int[] bounds = { 100, 133, 135, 100, 100, 1 }; final PerfDiffTableSorter tableSorter = new PerfDiffTableSorter(); final Table table = tableviewer.getTable(); for (int i = 0; i < titles.length; i++) { final int index = i; createTableViewerColumn(titles[i], bounds[i], index, tableSorter, table); } tableviewer.setLabelProvider(new PerfDiffLabelProvider()); tableviewer.setSorter(tableSorter); }

Target:
private void createColumns(final Composite parent, final TableViewer viewer) { final PerfDiffTableSorter tableSorter = new PerfDiffTableSorter(); final Table table = tableviewer.getTable(); for (int i = 0; i < COL_TITLES.length; i++) { createTableViewerColumn(COL_TITLES[i], COL_BOUNDS[i], i, tableSorter, table); } tableviewer.setLabelProvider(new PerfDiffLabelProvider()); tableviewer.setSorter(tableSorter); }
Source:
public void shouldSolveProblem() throws Exception { Problem problem = new Problem(); problem.setId(5); problem.setMessage("Fix it!"); Solution solution = new Solution(); solution.setId(7); solution.setMessage("Fixed"); workflowService.setProblem(problem); workflowService.setSolution(solution); Task currentTask = taskService.getById(7); workflowService.reportProblem(currentTask); currentTask = taskService.getById(5); workflowService.solveProblem(currentTask); Task correctionTask = taskService.getById(7); Process process = currentTask.getProcess(); for (Task task : process.getTasks()) { if (currentTask.getOrdering() < task.getOrdering() && task.getOrdering() < correctionTask.getOrdering()) { System.out.println(task.getTitle() + " " + task.getProcessingStatusAsString()); assertEquals("Solve of problem was incorrect - tasks between were not set up to done!", TaskStatus.DONE, task.getProcessingStatusEnum()); } } assertEquals("Solve of problem was incorrect - tasks from which correction was send was not set up to open!", TaskStatus.OPEN, correctionTask.getProcessingStatusEnum()); MockDatabase.cleanDatabase(); MockDatabase.insertProcessesForWorkflowFull(); }

Target:
public void shouldSolveProblem() throws Exception { Problem problem = new Problem(); problem.setId(5); problem.setMessage("Fix it!"); Solution solution = new Solution(); solution.setId(7); solution.setMessage("Fixed"); workflowService.setProblem(problem); workflowService.setSolution(solution); Task currentTask = taskService.getById(7); workflowService.reportProblem(currentTask); currentTask = taskService.getById(5); workflowService.solveProblem(currentTask); Task correctionTask = taskService.getById(7); Process process = currentTask.getProcess(); for (Task task : process.getTasks()) { if (currentTask.getOrdering() < task.getOrdering() && task.getOrdering() < correctionTask.getOrdering()) { assertEquals("Solve of problem was incorrect - tasks between were not set up to done!", TaskStatus.DONE, task.getProcessingStatusEnum()); } } assertEquals("Solve of problem was incorrect - tasks from which correction was send was not set up to open!", TaskStatus.OPEN, correctionTask.getProcessingStatusEnum()); MockDatabase.cleanDatabase(); MockDatabase.insertProcessesForWorkflowFull(); }
Source:
public boolean doubleClick(final String place) { boolean result = false; try { WebElement element = getElementToClick(place); result = doubleClickElement(element); } catch (WebDriverException e) { String msg = e.getMessage(); if (msg == null || !msg.contains("Other element would receive the double click")) { throw e; } } return result; }

Target:
public boolean doubleClick(final String place) { WebElement element = getElementToClick(place); boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (isInteractable(element)) { WebDriver driver = getSeleniumHelper().driver(); Actions action = new Actions(driver); action.doubleClick(element).perform(); result = true; } } return result; }
Source:
private static String doReplace(JsonObject object, String input) { String result = input; for (Entry<String, JsonElement> key : object.entrySet()) { JsonElement jsonElement = object.get(key.getKey()); if (jsonElement.isJsonPrimitive()) { String search = "${" + key + "}"; String replace = jsonElement.getAsString(); int index = result.indexOf(search); while (index > -1) { result = result.substring(0, index) + replace + result.substring(index + search.length()); index = result.indexOf(search); } } } return result; }

Target:
private static String doReplace(JsonObject object, String input) { String result = input; for (Entry<String, JsonElement> entry : object.entrySet()) { String key = entry.getKey(); JsonElement jsonElement = object.get(key); if (jsonElement.isJsonPrimitive()) { String search = "${" + key + "}"; String replace = jsonElement.getAsString(); int index = result.indexOf(search); while (index > -1) { result = result.substring(0, index) + replace + result.substring(index + search.length()); index = result.indexOf(search); } } } return result; }
Source:
public void setupManager( String startPoint, String inputFile, String protocol, String host, int port, String extention, int ThreadNumber, boolean doDirs, boolean doFiles, boolean recursive, boolean blankExt, Vector extToUse) { totalDone = 0; this.startPoint = startPoint; this.inputFile = inputFile; this.firstPartOfURL = protocol + "://" + host + ":" + port; this.extention = extention; this.protocol = protocol; this.host = host; this.port = port; workerCount = ThreadNumber; this.doFiles = doFiles; this.doDirs = doDirs; this.recursive = recursive; this.blankExt = blankExt; this.extToUse = extToUse; URL url; try { url = new URL(firstPartOfURL + startPoint); } catch (MalformedURLException ex) { LOG.error(ex); } LOG.info("Starting dir/file list based brute forcing"); setpUpHttpClient(); createTheThreads(); workGen = new WorkerGenerator(this); }

Target:
public void setupManager( String startPoint, String inputFile, String protocol, String host, int port, String extention, int ThreadNumber, boolean doDirs, boolean doFiles, boolean recursive, boolean blankExt, Vector extToUse) { totalDone = 0; this.startPoint = startPoint; this.inputFile = inputFile; this.firstPartOfURL = protocol + "://" + host + ":" + port; this.extention = extention; this.protocol = protocol; this.host = host; this.port = port; workerCount = ThreadNumber; this.doFiles = doFiles; this.doDirs = doDirs; this.recursive = recursive; this.blankExt = blankExt; this.extToUse = extToUse; URL url; try { url = new URL(firstPartOfURL + startPoint); } catch (MalformedURLException ex) { LOG.error("Bad URL", ex); } LOG.info("Starting dir/file list based brute forcing"); setpUpHttpClient(); createTheThreads(); workGen = new WorkerGenerator(this); }
Source:
public void clearAnnotation(String operationId) { processEngine.getHistoryService() .clearAnnotationForOperationLogById(operationId); }

Target:
public Response clearAnnotation(String operationId) { processEngine.getHistoryService() .clearAnnotationForOperationLogById(operationId); return Response.noContent().build(); }
Source:
private void setDefaultMessageListener() { setMessageListener(new ISwrveMessageListener() { public void onMessage(final SwrveMessage message) { if (SwrveBase.this.context != null) { final Context ctx = SwrveBase.this.context.get(); if (ctx == null) { SwrveLogger.e(LOG_TAG, "Can't display a in-app message without a context"); return; } Intent intent = new Intent(ctx, SwrveInAppMessageActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("inAppMessage", message); intent.putExtra("hideToolbar", config.isHideToolbar()); intent.putExtra("minSampleSize", config.getMinSampleSize()); intent.putExtra("defaultBackgroundColor", config.getDefaultBackgroundColor()); Handler iamHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { try { Bundle bundle = msg.peekData(); String eventType = bundle.getString("eventType"); processIAMMessage(message, eventType, bundle); } catch(Exception exp) { SwrveLogger.e(LOG_TAG, "Swrve IAM event from Activity error", exp); } return true; } }); intent.putExtra("messenger", new Messenger(iamHandler)); ctx.startActivity(intent); } } }); }

Target:
private void setDefaultMessageListener() { setMessageListener(new ISwrveMessageListener() { public void onMessage(final SwrveMessage message) { if (SwrveBase.this.context != null) { final Context ctx = SwrveBase.this.context.get(); if (ctx == null) { SwrveLogger.e(LOG_TAG, "Can't display a in-app message without a context"); return; } Intent intent = new Intent(ctx, SwrveInAppMessageActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(SwrveInAppMessageActivity.MESSAGE_ID_KEY, message.getId()); ctx.startActivity(intent); } } }); }
Source:
public Response update(@PathParam("id") long id, User entity) throws SQLException { User old = Context.getPermissionsManager().getUser(entity.getId()); if (old.getExpirationTime() == null && entity.getExpirationTime() != null || old.getExpirationTime() != null && !old.getExpirationTime().equals(entity.getExpirationTime()) || old.getAdmin() != entity.getAdmin() || old.getReadonly() != entity.getReadonly() || old.getDisabled() != entity.getDisabled() || old.getDeviceLimit() != entity.getDeviceLimit() || !old.getToken().equals(entity.getToken())) { Context.getPermissionsManager().checkAdmin(getUserId()); } else { Context.getPermissionsManager().checkUser(getUserId(), entity.getId()); } Context.getPermissionsManager().updateUser(entity); if (Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } return Response.ok(entity).build(); }

Target:
public Response update(@PathParam("id") long id, User entity) throws SQLException { User old = Context.getPermissionsManager().getUser(entity.getId()); if (old.getExpirationTime() == null && entity.getExpirationTime() != null || old.getExpirationTime() != null && !old.getExpirationTime().equals(entity.getExpirationTime()) || old.getAdmin() != entity.getAdmin() || old.getReadonly() != entity.getReadonly() || old.getDisabled() != entity.getDisabled() || old.getDeviceLimit() != entity.getDeviceLimit() || old.getToken() == null && entity.getToken() != null || old.getToken() != null && !old.getToken().equals(entity.getToken())) { Context.getPermissionsManager().checkAdmin(getUserId()); } else { Context.getPermissionsManager().checkUser(getUserId(), entity.getId()); } Context.getPermissionsManager().updateUser(entity); if (Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } return Response.ok(entity).build(); }
Source:
public Iterable<Map<String, String>> list() { return Iterables.transform(store.entries(), new Function<Map.Entry<Integer, Location>, Map<String, String>>() { @Override public Map<String, String> apply(Map.Entry<Integer, Location> entry) { return asMap(entry.getKey(), entry.getValue()); } }); }

Target:
public Iterable<LocationSummary> list() { return Iterables.transform(store.entries(), new Function<Map.Entry<Integer, Location>, LocationSummary>() { @Override public LocationSummary apply(Map.Entry<Integer, Location> entry) { return new LocationSummary(entry.getKey().toString(), entry.getValue()); } }); }
Source:
public List<Sample> getLast24hours( @Scope({OAuthScope.SENSORS_BASIC}) final AccessToken accessToken, @PathParam("sensor") String sensor, @QueryParam("from_utc") Long queryEndTimestampUTC) { final int slotDurationInMinutes = 1; final long queryStartTimeUTC = new DateTime(queryEndTimestampUTC, DateTimeZone.UTC).minusHours(24).getMillis(); final Optional<Long> deviceId = deviceDAO.getMostRecentSenseByAccountId(accessToken.accountId); if(!deviceId.isPresent()) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } return deviceDataDAO.generateTimeSeriesByUTCTime(queryStartTimeUTC, queryEndTimestampUTC, accessToken.accountId, deviceId.get(), slotDurationInMinutes, sensor, missingDataDefaultValue(accessToken.accountId)); }

Target:
public List<Sample> getLast24hours( @Scope({OAuthScope.SENSORS_BASIC}) final AccessToken accessToken, @PathParam("sensor") String sensor, @QueryParam("from_utc") Long queryEndTimestampUTC) { validateQueryRange(queryEndTimestampUTC, DateTime.now(), accessToken.accountId, allowedRangeInSeconds); final int slotDurationInMinutes = 5; final long queryStartTimeUTC = new DateTime(queryEndTimestampUTC, DateTimeZone.UTC).minusHours(24).getMillis(); final Optional<Long> deviceId = deviceDAO.getMostRecentSenseByAccountId(accessToken.accountId); if(!deviceId.isPresent()) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } return deviceDataDAO.generateTimeSeriesByUTCTime(queryStartTimeUTC, queryEndTimestampUTC, accessToken.accountId, deviceId.get(), slotDurationInMinutes, sensor, missingDataDefaultValue(accessToken.accountId)); }
Source:
public void close() throws IOException { if (out != null) { try { finish(); } finally { try { def.end(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } out = null; } } }

Target:
public void close() throws IOException { if (out != null) { try { finish(); } finally { try { def.end(); } catch (Exception ignored) { } IoUtils.closeQuietly(out); out = null; } } }
Source:
public void testImportViaFileManager() throws Exception { File archive = getArchiveFile("test-data/testCSVArchive.zip"); FileManager fm = Framework.getService(FileManager.class); Blob blob = Blobs.createBlob(archive); FileImporterContext context = FileImporterContext.builder(coreSession, blob, workspace1.getPathAsString()) .overwrite(true) .build(); fm.createOrUpdateDocument(context); DocumentModelList children = coreSession.getChildren(workspace1.getRef()); assertSame(2, children.size()); DocumentModel MyFile = coreSession.getChild(workspace1.getRef(), "MyFile"); DocumentModel MyNote = coreSession.getChild(workspace1.getRef(), "MyNote"); assertEquals("My File", MyFile.getTitle()); assertEquals("My Note", MyNote.getTitle()); assertEquals("MyFile", MyFile.getName()); assertEquals("MyNote", MyNote.getName()); assertEquals("this is text", MyNote.getProperty("note", "note")); assertNotNull(MyFile.getProperty("file", "content")); }

Target:
public void testImportViaFileManager() throws Exception { File archive = getArchiveFile("test-data/completeZipTestArchive.zip"); FileManager fm = Framework.getService(FileManager.class); Blob blob = Blobs.createBlob(archive); FileImporterContext context = FileImporterContext.builder(coreSession, blob, workspace1.getPathAsString()) .overwrite(true) .build(); fm.createOrUpdateDocument(context); DocumentModelList children = coreSession.getChildren(workspace1.getRef()); assertEquals(2, children.size()); DocumentModel MyFile = coreSession.getChild(workspace1.getRef(), "My File"); DocumentModel MyNote = coreSession.getChild(workspace1.getRef(), "MyNote"); assertEquals("My File", MyFile.getTitle()); assertEquals("My Note", MyNote.getTitle()); assertEquals("My File", MyFile.getName()); assertEquals("MyNote", MyNote.getName()); assertEquals("this is text", MyNote.getPropertyValue("note:note")); assertNotNull(MyFile.getPropertyValue("file:content")); List<String> contributors = Arrays.asList((String[]) MyFile.getPropertyValue("dc:contributors")); assertEquals(4, contributors.size()); assertEquals("project", MyFile.getCurrentLifeCycleState()); assertEquals("approved", MyNote.getCurrentLifeCycleState()); List<HashMap> tags = (List<HashMap>) MyFile.getPropertyValue("nxtag:tags"); assertEquals(1, tags.size()); assertEquals("mynewtag", tags.get(0).get("label")); assertEquals(2, ((List<String>) MyNote.getPropertyValue("nxtag:tags")).size()); }