auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Object perform(String name, Object obj, ApiRequest request) { if (obj instanceof MachineDriverRecord) { MachineDriverUpdateInput machineDriverUpdate = request.proxyRequestObject(MachineDriverUpdateInput.class); ((MachineDriverRecord) obj).setMd5checksum(machineDriverUpdate.getmd5checksum()); if (StringUtils.isNotBlank(machineDriverUpdate.getUri())) { ((MachineDriverRecord) obj).setName(machineDriverUpdate.getName()); } if (StringUtils.isNotBlank(machineDriverUpdate.getUri())) { ((MachineDriverRecord) obj).setUri(machineDriverUpdate.getUri()); } ((MachineDriverRecord) obj).setState(CommonStatesConstants.INACTIVE); objectManager.persist(obj); return objectManager.reload(obj); } throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, "NotMachineDriver"); }

Target:
public Object perform(String name, Object obj, ApiRequest request) { if (obj instanceof MachineDriver) { MachineDriverUpdateInput machineDriverUpdate = request.proxyRequestObject(MachineDriverUpdateInput.class); MachineDriver driver = ((MachineDriverRecord) obj); driver.setMd5checksum(machineDriverUpdate.getmd5checksum()); if (StringUtils.isNotBlank(machineDriverUpdate.getUri())) { driver.setName(machineDriverUpdate.getName()); } if (StringUtils.isNotBlank(machineDriverUpdate.getUri())) { driver.setUri(machineDriverUpdate.getUri()); } driver.setState(CommonStatesConstants.INACTIVE); DataAccessor.fields(obj).withKey(MachineDriverErrorActionHandler.ERROR_MESSAGE) .set(null); objectManager.persist(obj); return objectManager.reload(obj); } throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, "NotMachineDriver"); }
Source:
public void addDriver(Person p) { addDriver(Objects.requireNonNull(p), false); }

Target:
public void addDriver(Person p) { addDriver(p, false); }
Source:
public EngineBackupLog getLastSuccessfulEngineBackup(String dbName) { List<EngineBackupLog> logs = multipleResults(entityManager.createNamedQuery("EngineBackupLog.getLatest", EngineBackupLog.class).setParameter("dbName", dbName)); if (logs.isEmpty()) { return null; } else { return logs.get(0); } }

Target:
public EngineBackupLog getLastSuccessfulEngineBackup(String dbName) { TypedQuery query = entityManager.createNamedQuery("EngineBackupLog.getLatest", EngineBackupLog.class).setParameter("dbName", dbName); query.setMaxResults(1); EngineBackupLog log = singleResult(query); return log; }
Source:
public String toString() { return "Integration Bus of BoundedContext Name = " + context.getValue(); }

Target:
public String toString() { return "IntegrationBroker of <" + context.getValue() + '>'; }
Source:
public void runQuery(Guid guid) { startProgress("getCount"); AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.setHandleFailure(true); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { stopProgress(); AbstractErrataCountModel errataCountModel = (AbstractErrataCountModel) model; VdcQueryReturnValue returnValueObject = (VdcQueryReturnValue) returnValue; ErrataCounts resultEntity = returnValueObject.getReturnValue(); if (resultEntity != null && returnValueObject.getSucceeded()) { errataCountModel.setMessage(null); errataCountModel.setErrataCounts(resultEntity); } else { errataCountModel.setMessage(null); errataCountModel.setMessage( constants.katelloProblemRetrievingErrata() + " " + returnValueObject.getExceptionMessage()); } } }; Frontend.getInstance().runQuery(getQueryType(), new IdQueryParameters(guid), _asyncQuery); }

Target:
public void runQuery(Guid guid) { startProgress("getCount"); AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.setHandleFailure(true); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { stopProgress(); AbstractErrataCountModel errataCountModel = (AbstractErrataCountModel) model; VdcQueryReturnValue returnValueObject = (VdcQueryReturnValue) returnValue; ErrataCounts resultEntity = returnValueObject.getReturnValue(); errataCountModel.setMessage(null); if (resultEntity != null && returnValueObject.getSucceeded()) { errataCountModel.setErrataCounts(resultEntity); } else { errataCountModel.setMessage( constants.katelloProblemRetrievingErrata() + " " + returnValueObject.getExceptionMessage()); } } }; Frontend.getInstance().runQuery(getQueryType(), new IdQueryParameters(guid), _asyncQuery); }
Source:
private void activateDataCenter() { StorageDomain masterDomain = storageDomainDao.getStorageDomains(getStoragePool().getId(), StorageDomainType.Master) .stream() .findFirst() .orElse(null); calcStoragePoolStatusByDomainsStatus(); log.info("Master domain id:'{}' Master domain status:'{}'", masterDomain != null ? masterDomain.getId() : null, masterDomain != null ? masterDomain.getStatus() : null); if (masterDomain != null && (masterDomain.getStatus() == StorageDomainStatus.Active || masterDomain.getStatus() == StorageDomainStatus.Unknown || masterDomain.getStatus() == StorageDomainStatus.Inactive)) { resetSPM(); } }

Target:
private void activateDataCenter() { StorageDomain masterDomain = storageDomainDao.getStorageDomains(getStoragePool().getId(), StorageDomainType.Master).stream().findFirst().orElse(null); calcStoragePoolStatusByDomainsStatus(); if (masterDomain == null) { log.info("no master domain found"); } else { log.info("Master domain id:'{}' has status:'{}'", masterDomain.getId(), masterDomain.getStatus()); if (masterDomain.getStatus() == StorageDomainStatus.Active || masterDomain.getStatus() == StorageDomainStatus.Unknown || masterDomain.getStatus() == StorageDomainStatus.Inactive) { resetSPM(); } } }
Source:
protected Control createDialogArea(Composite parent) { final GridData parentData = new GridData(SWT.FILL, SWT.FILL, true, true); parent.setLayout(new GridLayout(1, true)); parent.setLayoutData(parentData); final ScrolledComposite wrapper = new ScrolledComposite(parent, SWT.V_SCROLL); wrapper.setExpandHorizontal(true); wrapper.setExpandVertical(true); final FillLayout wrapperLayout = new FillLayout(); wrapperLayout.marginHeight = 10; wrapperLayout.marginWidth = 10; wrapper.setLayout(wrapperLayout); wrapper.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); final Composite emfFormsParent = new Composite(wrapper, SWT.NONE); wrapper.setContent(emfFormsParent); emfFormsParent.setLayout(new GridLayout()); try { final VViewModelProperties properties = VViewFactory.eINSTANCE.createViewModelLoadingProperties(); properties.addInheritableProperty("useOnModifyDatabinding", "true"); ECPSWTViewRenderer.INSTANCE.render(emfFormsParent, newObject, properties); } catch (final ECPRendererException e) { } wrapper.setMinSize(wrapper.computeSize(SWT.DEFAULT, SWT.DEFAULT)); return parent; }

Target:
protected Control createDialogArea(Composite parent) { final GridData parentData = new GridData(SWT.FILL, SWT.FILL, true, true); parent.setLayout(new GridLayout(1, true)); parent.setLayoutData(parentData); final ScrolledComposite wrapper = new ScrolledComposite(parent, SWT.V_SCROLL); wrapper.setExpandHorizontal(true); wrapper.setExpandVertical(true); final FillLayout wrapperLayout = new FillLayout(); wrapperLayout.marginHeight = 10; wrapperLayout.marginWidth = 10; wrapper.setLayout(wrapperLayout); wrapper.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); final Composite emfFormsParent = new Composite(wrapper, SWT.NONE); wrapper.setContent(emfFormsParent); emfFormsParent.setLayout(new GridLayout()); try { final VViewModelProperties properties = VViewFactory.eINSTANCE.createViewModelLoadingProperties(); properties.addInheritableProperty(EMFFormsSWTConstants.USE_ON_MODIFY_DATABINDING_KEY, EMFFormsSWTConstants.USE_ON_MODIFY_DATABINDING_VALUE); ECPSWTViewRenderer.INSTANCE.render(emfFormsParent, newObject, properties); } catch (final ECPRendererException e) { } wrapper.setMinSize(wrapper.computeSize(SWT.DEFAULT, SWT.DEFAULT)); return parent; }
Source:
protected List<Object[]> selectIds( SharedSessionContractImplementor session, QueryParameters queryParameters) { List<Object[]> ids = new ArrayList<>(); try { try (PreparedStatement ps = session.getJdbcCoordinator() .getStatementPreparer() .prepareStatement( idSelect, false )) { int sum = 1; for ( ParameterSpecification parameterSpecification : idSelectParameterSpecifications ) { sum += parameterSpecification.bind( ps, queryParameters, session, sum ); } ResultSet rs = session .getJdbcCoordinator() .getResultSetReturn() .extract( ps ); while ( rs.next() ) { Object[] result = new Object[targetedPersister.getIdentifierColumnNames().length]; for ( String columnName : targetedPersister.getIdentifierColumnNames() ) { Object column = rs.getObject( columnName ); result[rs.findColumn( columnName ) - 1] = column; } ids.add( result ); } } } catch ( SQLException e ) { throw convert( e, "could not select ids for bulk operation", idSelect ); } return ids; }

Target:
protected List<Object[]> selectIds( SharedSessionContractImplementor session, QueryParameters queryParameters) { List<Object[]> ids = new ArrayList<>(); try { try (PreparedStatement ps = session.getJdbcCoordinator() .getStatementPreparer() .prepareStatement( idSelect, false )) { int position = 1; for ( ParameterSpecification parameterSpecification : idSelectParameterSpecifications ) { position += parameterSpecification.bind( ps, queryParameters, session, position ); } ResultSet rs = session .getJdbcCoordinator() .getResultSetReturn() .extract( ps ); while ( rs.next() ) { Object[] result = new Object[targetedPersister.getIdentifierColumnNames().length]; for ( String columnName : targetedPersister.getIdentifierColumnNames() ) { Object column = rs.getObject( columnName ); result[rs.findColumn( columnName ) - 1] = column; } ids.add( result ); } } } catch ( SQLException e ) { throw convert( e, "could not select ids for bulk operation", idSelect ); } return ids; }
Source:
public void push(RowMap r) throws Exception { String output = r.toJSON(outputConfig); if ( output != null ) { String result = String.format("Table %s, database %s, event type is %s", r.getTable(), r.getDatabase(), r.getRowType()); System.out.println(result); } this.context.setPosition(r); }

Target:
public void push(RowMap r) throws Exception { String output = r.toJSON(outputConfig); if ( output != null ) System.out.println(output); this.context.setPosition(r); }
Source:
private static void sanitizeList(List<ITimeEvent> sourceList, Consumer<List<ITimeEvent>> listConsumer) { if (sourceList != null) { List<ITimeEvent> events = new ArrayList<>(); for (ITimeEvent event : sourceList) { if (isValidEvent(event)) { events.add(event); } else { events.add(null); } } listConsumer.accept(events); } }

Target:
private static void sanitizeList(List<ITimeEvent> sourceList, Consumer<List<ITimeEvent>> listConsumer) { if (sourceList != null) { List<ITimeEvent> events = new ArrayList<>(); for (ITimeEvent event : sourceList) { if (isValidEvent(event)) { events.add(event); } } listConsumer.accept(events); } else { listConsumer.accept(null); } }
Source:
void sendInventory() { synchronized (lock) { for (Connection connection : managedConnections) { try { final OutputStream os = connection.writeMessage(); try { os.write(Protocol.PROCESS_INVENTORY); final Collection<ManagedProcess> processCollection = processes.values(); StreamUtils.writeInt(os, processCollection.size()); for (ManagedProcess process : processCollection) { StreamUtils.writeUTFZBytes(os, process.getProcessName()); os.write(process.getAuthKey().getBytes()); StreamUtils.writeBoolean(os, process.isRunning()); StreamUtils.writeBoolean(os, process.isStopping()); } os.close(); } finally { StreamUtils.safeClose(os); } } catch (IOException e) { ProcessLogger.ROOT_LOGGER.failedToWriteMessage("PROCESS_INVENTORY", e); removeManagedConnection(connection); } } } }

Target:
void sendInventory() { synchronized (lock) { for (Connection connection : managedConnections) { try { final OutputStream os = connection.writeMessage(); try { os.write(Protocol.PROCESS_INVENTORY); final Collection<ManagedProcess> processCollection = processes.values(); StreamUtils.writeInt(os, processCollection.size()); for (ManagedProcess process : processCollection) { StreamUtils.writeUTFZBytes(os, process.getProcessName()); os.write(process.getAuthKey().getBytes(Charset.forName("US-ASCII"))); StreamUtils.writeBoolean(os, process.isRunning()); StreamUtils.writeBoolean(os, process.isStopping()); } os.close(); } finally { StreamUtils.safeClose(os); } } catch (IOException e) { ProcessLogger.ROOT_LOGGER.failedToWriteMessage("PROCESS_INVENTORY", e); removeManagedConnection(connection); } } } }
Source:
public boolean equals( Value other ) { return false; }

Target:
public boolean equals( Value other ) { return this == other; }
Source:
public AbstractDetailTabListView(DetailModelProvider<M, D> modelProvider) { this.modelProvider = modelProvider; container.add(scrollPanel); Window.addResizeHandler(e -> { Scheduler.get().scheduleDeferred(() -> resizeToFullHeight()); }); }

Target:
public AbstractDetailTabListView(DetailModelProvider<M, D> modelProvider) { this.modelProvider = modelProvider; Window.addResizeHandler(e -> { Scheduler.get().scheduleDeferred(() -> resizeToFullHeight()); }); }
Source:
private List<SearchBasedFetcher> getFetchersFromLibraryEntries(List<BibEntry> libraryEntries) { return libraryEntries.parallelStream() .filter(bibEntry -> bibEntry.getType().getName().equals("library")) .map(this::createFetcherFromLibraryEntry) .filter(Objects::nonNull) .collect(Collectors.toList()); }

Target:
private List<SearchBasedFetcher> getFetchersFromLibraryEntries(List<BibEntry> libraryEntries) { return libraryEntries.parallelStream() .filter(bibEntry -> bibEntry.getType().getName().equals(LIBRARY_ENTRY.getName())) .map(this::createFetcherFromLibraryEntry) .filter(Objects::nonNull) .collect(Collectors.toList()); }
Source:
synchronized void handleFailedBatch(ProducerBatch batch, RuntimeException exception, boolean adjustSequenceNumbers) { maybeTransitionToErrorState(exception); if (!hasProducerIdAndEpoch(batch.producerId(), batch.producerEpoch())) { log.debug("Ignoring failed batch with producer id {}, epoch {}, and sequence number " + "since the producerId has been reset internally", batch, batch.producerId(), batch.producerEpoch(), batch.baseSequence(), exception); return; } if (exception instanceof OutOfOrderSequenceException && !isTransactional()) { log.error("The broker returned for topic-partition with producerId {}, epoch {}, and sequence number {}", exception, batch.topicPartition, batch.producerId(), batch.producerEpoch(), batch.baseSequence()); resetIdempotentProducerId(); } else if (exception instanceof UnknownProducerIdException) { resetSequenceNumbers(); } else { removeInFlightBatch(batch); if (adjustSequenceNumbers) { if (!isTransactional()) { bumpEpoch(); } else { adjustSequencesDueToFailedBatch(batch); } } } }

Target:
synchronized void handleFailedBatch(ProducerBatch batch, RuntimeException exception, boolean adjustSequenceNumbers) { maybeTransitionToErrorState(exception); removeInFlightBatch(batch); if (!matchesProducerIdAndEpoch(batch)) { log.debug("Ignoring failed batch with producer id {}, epoch {}, and sequence number " + "since the producerId has been reset internally", batch, batch.producerId(), batch.producerEpoch(), batch.baseSequence(), exception); return; } if (exception instanceof OutOfOrderSequenceException && !isTransactional()) { log.error("The broker returned for topic-partition with producerId {}, epoch {}, and sequence number {}", exception, batch.topicPartition, batch.producerId(), batch.producerEpoch(), batch.baseSequence()); requestEpochBumpForPartition(batch.topicPartition); } else if (exception instanceof UnknownProducerIdException) { resetSequenceForPartition(batch.topicPartition); } else { if (adjustSequenceNumbers) { if (!isTransactional()) { requestEpochBumpForPartition(batch.topicPartition); } else { adjustSequencesDueToFailedBatch(batch); } } } }
Source:
private void createLink(String prefix, final Artifact art, String action, Artifact thisArt, RelationTypeSide relation) { try { Label label = editor.getToolkit().createLabel(this, prefix + " \"" + getTeamName( thisArt) + "\" " + action + getCompletedCancelledString(art) + " \"" + getTeamName(art) + "\" "); Hyperlink link = editor.getToolkit().createHyperlink(this, String.format("\"%s\" - %s", art.getName().length() < 60 ? art.getName() : art.getName().substring(0, 60), AtsClientService.get().getAtsId(art)), SWT.NONE); if (art.equals(thisArt)) { artAndRelToHyperlink.put(thisArt, relation, link); artAndRelToLabel.put(thisArt, relation, label); } else { artAndRelToHyperlink.put(art, relation, link); artAndRelToLabel.put(art, relation, label); } link.addHyperlinkListener(new IHyperlinkListener() { @Override public void linkEntered(HyperlinkEvent e) { } @Override public void linkExited(HyperlinkEvent e) { } @Override public void linkActivated(HyperlinkEvent e) { if (AtsObjects.isAtsWorkItemOrAction(art)) { AtsEditors.openATSAction(art, AtsOpenOption.OpenOneOrPopupSelect); } else { try { RendererManager.open(art, PresentationType.DEFAULT_OPEN); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } } } }); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); } }

Target:
private void createLink(String prefix, final Artifact art, String action, Artifact thisArt, RelationTypeSide relation) { try { Label label = editor.getToolkit().createLabel(this, prefix + " \"" + getObjectName( thisArt) + "\" " + action + getCompletedCancelledString(art) + " \"" + getObjectName(art) + "\" "); Hyperlink link = editor.getToolkit().createHyperlink(this, String.format("\"%s\" - %s", art.getName().length() < 60 ? art.getName() : art.getName().substring(0, 60), AtsClientService.get().getAtsId(art)), SWT.NONE); if (art.equals(thisArt)) { artAndRelToHyperlink.put(thisArt, relation, link); artAndRelToLabel.put(thisArt, relation, label); } else { artAndRelToHyperlink.put(art, relation, link); artAndRelToLabel.put(art, relation, label); } link.addHyperlinkListener(new IHyperlinkListener() { @Override public void linkEntered(HyperlinkEvent e) { } @Override public void linkExited(HyperlinkEvent e) { } @Override public void linkActivated(HyperlinkEvent e) { if (AtsObjects.isAtsWorkItemOrAction(art)) { AtsEditors.openATSAction(art, AtsOpenOption.OpenOneOrPopupSelect); } else { try { RendererManager.open(art, PresentationType.DEFAULT_OPEN); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } } } }); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); } }
Source:
public void Execute() { SourceUnit unit = null; try { Reader r; if (!StringUtils.isEmpty(debugUnitFile)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Reading source unit JSON data from {}", debugUnitFile); } r = Files.newBufferedReader(FileSystems.getDefault().getPath(debugUnitFile)); } else { r = new InputStreamReader(System.in); } unit = new Gson().fromJson(r, SourceUnit.class); r.close(); } catch (IOException e) { LOGGER.error("Failed to read source unit data", e); System.exit(1); } LOGGER.info("Resolving dependencies of {}", unit.Name); Resolver rs = new Resolver(unit.getProject(), unit); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Resolving deps"); } final ArrayList<DepResolution> resolutions = new ArrayList<>(); for (RawDependency rawDep : unit.Dependencies) { DepResolution res = rs.resolveRawDep(rawDep); resolutions.add(res); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Deps resolved"); } if (!(unit.getProject() instanceof JDKProject)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Adding JDK dep"); } if (unit.Repo.equals(ScanCommand.ANDROID_CORE_REPO)) { } else if (unit.Repo.equals(ScanCommand.ANDROID_SDK_REPO)) { resolutions.add(new DepResolution(null, ResolvedTarget.androidCore())); }else if (unit.Data.containsKey("Android")) { resolutions.add(new DepResolution(null, ResolvedTarget.androidCore())); resolutions.add(new DepResolution(null, ResolvedTarget.androidSDK())); } else { resolutions.add(new DepResolution(null, ResolvedTarget.jdk())); } } else { if (!unit.Repo.equals(JDKProject.JDK_REPO)) { resolutions.add(new DepResolution(null, ResolvedTarget.jdk())); } } JSONUtil.writeJSON(resolutions); }

Target:
public void Execute() { SourceUnit unit = null; try { Reader r; if (!StringUtils.isEmpty(debugUnitFile)) { LOGGER.debug("Reading source unit JSON data from {}", debugUnitFile); r = Files.newBufferedReader(FileSystems.getDefault().getPath(debugUnitFile)); } else { r = new InputStreamReader(System.in); } unit = new Gson().fromJson(r, SourceUnit.class); r.close(); } catch (IOException e) { LOGGER.error("Failed to read source unit data", e); System.exit(1); } LOGGER.info("Resolving dependencies of {}", unit.Name); Resolver rs = new Resolver(unit.getProject(), unit); LOGGER.debug("Resolving deps"); final ArrayList<DepResolution> resolutions = new ArrayList<>(); for (RawDependency rawDep : unit.Dependencies) { DepResolution res = rs.resolveRawDep(rawDep); resolutions.add(res); } LOGGER.debug("Deps resolved"); if (!(unit.getProject() instanceof JDKProject)) { LOGGER.debug("Adding JDK dep"); if (unit.Repo.equals(ScanCommand.ANDROID_CORE_REPO)) { } else if (unit.Repo.equals(ScanCommand.ANDROID_SDK_REPO)) { resolutions.add(new DepResolution(null, ResolvedTarget.androidCore())); } else if (unit.Data.containsKey("Android")) { resolutions.add(new DepResolution(null, ResolvedTarget.androidCore())); resolutions.add(new DepResolution(null, ResolvedTarget.androidSDK())); } else { resolutions.add(new DepResolution(null, ResolvedTarget.jdk())); } } else { if (!unit.Repo.equals(JDKProject.JDK_REPO)) { resolutions.add(new DepResolution(null, ResolvedTarget.jdk())); } } JSONUtil.writeJSON(resolutions); }
Source:
public Iterator<Setting> getIterator() { if (lastResolvedEObject == null || leftReferences == null) { final Set<Setting> settings = Collections.emptySet(); return settings.iterator(); } EStructuralFeature feature; if (getDomainModelReference() == null) { feature = getDomainModelEFeature(); } else { feature = getDomainModelReference().getIterator().next().getEStructuralFeature(); } final EStructuralFeature listFeature = feature; if (!EReference.class.isInstance(listFeature)) { final Set<Setting> settings = Collections.emptySet(); return settings.iterator(); } if (!lastResolvedEObject.eClass().getEAllStructuralFeatures().contains(listFeature)) { final List<Setting> settings = Collections.emptyList(); return settings.iterator(); } final int numElems = 1 + resolvedColumns.size(); return new Iterator<EStructuralFeature.Setting>() { int returnedElements = 0; @Override public boolean hasNext() { return numElems > returnedElements; } @Override public Setting next() { Setting result = null; if (returnedElements == 0) { result = ((InternalEObject) lastResolvedEObject).eSetting(listFeature); } else { final Iterator<Setting> iterator = resolvedColumns.get(returnedElements - 1).getIterator(); if (iterator.hasNext()) { result = iterator.next(); } } returnedElements++; return result; } @Override public void remove() { } }; }

Target:
public Iterator<Setting> getIterator() { if (lastResolvedEObject == null || leftReferences == null) { final Set<Setting> settings = Collections.emptySet(); return settings.iterator(); } EStructuralFeature feature; if (getDomainModelReference() == null) { feature = getDomainModelEFeature(); } else { feature = getDomainModelReference().getIterator().next().getEStructuralFeature(); } final EStructuralFeature listFeature = feature; if (!EReference.class.isInstance(listFeature)) { final Set<Setting> settings = Collections.emptySet(); return settings.iterator(); } if (!lastResolvedEObject.eClass().getEAllStructuralFeatures().contains(listFeature)) { final List<Setting> settings = Collections.emptyList(); return settings.iterator(); } final int numElems = 1 + resolvedColumns.size(); return new Iterator<EStructuralFeature.Setting>() { int returnedElements = 0; @Override public boolean hasNext() { return numElems > returnedElements; } @Override public Setting next() { Setting result = null; if (returnedElements == 0) { result = ((InternalEObject) lastResolvedEObject).eSetting(listFeature); } else { final Iterator<Setting> iterator = resolvedColumns.get(returnedElements - 1).getIterator(); if (iterator.hasNext()) { result = iterator.next(); } else { throw new NoSuchElementException(String.format( "The iterator has %1$s but %2$s already has been returned!", numElems, returnedElements)); } } returnedElements++; return result; } @Override public void remove() { } }; }
Source:
private void read(SelectionKey key, Transmission transmission) throws IOException { long startTimeToReadInMs = time.milliseconds(); try { long bytesRead = transmission.read(); if (bytesRead == -1) { close(key); return; } metrics.selectorBytesReceived.update(bytesRead); metrics.selectorBytesReceivedCount.inc(bytesRead); if (transmission.getNetworkReceive().getReceivedBytes().isReadComplete()) { this.completedReceives.add(transmission.getNetworkReceive()); transmission.clearReceive(); } } finally { long readTime = time.milliseconds() - startTimeToReadInMs; logger.trace("SocketServer time spent on read per key = {}", transmission.getConnectionId(), readTime); } }

Target:
private void read(SelectionKey key, Transmission transmission) throws IOException { long startTimeToReadInMs = time.milliseconds(); try { boolean readComplete = transmission.read(); if (readComplete) { this.completedReceives.add(transmission.getNetworkReceive()); transmission.clearReceive(); } } finally { long readTime = time.milliseconds() - startTimeToReadInMs; logger.trace("SocketServer time spent on read per key = {}", transmission.getConnectionId(), readTime); } }
Source:
private boolean checkReplicationLocations(String[] replicationPaths) { for (String replicationPath : replicationPaths) { if (!Files.exists(Paths.get(replicationPath))) { throw new ReplicationDestinationUnavailableException(String.format("Unable to find replication destination %s", replicationPath)); } } return true; }

Target:
private void checkReplicationLocations(String[] replicationPaths) throws ReplicationDestinationUnavailableException { for (String replicationPath : replicationPaths) { if (!Files.exists(Paths.get(replicationPath))) { String errorMsg = String.format("Unable to find replication destination %s", replicationPath); throw new ReplicationDestinationUnavailableException(errorMsg); } } }
Source:
void acceptVisitor(Visitor v) { for (SelectInfo selectInfo : selectInfos) { selectInfo.getExpression().accept(v); } }

Target:
void acceptVisitor(Visitor v) { for (int i = 0; i < selectInfos.size(); i++) { final SelectInfo selectInfo = selectInfos.get(i); selectInfo.getExpression().accept(v); } }
Source:
public ConfigPropertiesProcessor(Path outputDir, String fileName) { this.outputDir = outputDir; this.fileName = fileName == null ? "default" : fileName; }

Target:
public ConfigPropertiesProcessor(Path outputDir, String fileName) { this.outputDir = outputDir; this.fileName = fileName == null ? "cluster" : fileName; }
Source:
public void testCreateContainer() throws Exception { boolean created = false; while (!created) { privateContainer = (CONTAINER_PREFIX + new SecureRandom().nextInt()); try { created = getApi().createContainer(privateContainer, withMetadata(ImmutableMultimap.of("foo", "bar"))); } catch (UndeclaredThrowableException e) { HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); if (htpe.getResponse().getStatusCode() == 409) continue; throw e; } } Set<ContainerProperties> response = getApi().listContainers(includeMetadata()); assert null != response; long containerCount = response.size(); assertTrue(containerCount >= 1); ListBlobsResponse list = getApi().listBlobs(privateContainer); assertEquals(list.getUrl(), URI.create(String.format("<LINK_0>", view.unwrap( AzureBlobApiMetadata.CONTEXT_TOKEN).getIdentity(), privateContainer))); }

Target:
public void testCreateContainer() throws Exception { boolean created = false; while (!created) { privateContainer = CONTAINER_PREFIX + new SecureRandom().nextInt(); try { created = getApi().createContainer(privateContainer, withMetadata(ImmutableMultimap.of("foo", "bar"))); } catch (UndeclaredThrowableException e) { HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); if (htpe.getResponse().getStatusCode() == 409) continue; throw e; } } Set<ContainerProperties> response = getApi().listContainers(includeMetadata()); assert null != response; long containerCount = response.size(); assertTrue(containerCount >= 1); ListBlobsResponse list = getApi().listBlobs(privateContainer); assertEquals(list.getUrl(), URI.create(String.format("<LINK_0>", view.unwrap( AzureBlobApiMetadata.CONTEXT_TOKEN).getIdentity(), privateContainer))); }
Source:
public void test_clientAttribute_overClientConfig() { ClientConfig clientConfig = new ClientConfig(); clientConfig.setAttribute(key, value); assertEquals(value, clientConfig.getAttributes().get(key)); assertNull(clientConfig.getAttributes().get(nonExistingKey)); }

Target:
public void test_clientAttribute_overClientConfig() { ClientConfig clientConfig = new ClientConfig(); clientConfig.setAttribute(key, value); assertEquals(value, clientConfig.getAttributes().get(key)); assertEquals(1, clientConfig.getAttributes().size()); assertNull(clientConfig.getAttributes().get(nonExistingKey)); }
Source:
public void addStatisticsToMonitor(Statistics stats) { monitor.addListener(this); monitor.addStatistics(stats); StatisticDescriptor[] descriptors = stats.getType().getStatistics(); for (StatisticDescriptor d : descriptors) { String name = d.getName(); Number value = stats.get(d); if (name.equals(StatsKey.VM_GC_STATS_COLLECTIONS)) { collections += value.longValue(); } else if (name.equals(StatsKey.VM_GC_STATS_COLLECTION_TIME)) { collectionTime += value.longValue(); } } }

Target:
public void addStatisticsToMonitor(Statistics stats) { monitor.addListener(this); monitor.addStatistics(stats); StatisticDescriptor[] descriptors = stats.getType().getStatistics(); for (StatisticDescriptor d : descriptors) { String name = d.getName(); Number value = stats.get(d); if (value == null) { continue; } if (name.equals(StatsKey.VM_GC_STATS_COLLECTIONS)) { collections.put(stats.getUniqueId(), value); } else if (name.equals(StatsKey.VM_GC_STATS_COLLECTION_TIME)) { collectionTime.put(stats.getUniqueId(), value); } } }
Source:
public Status read(String table, String endpoint, Set<String> fields, HashMap<String, ByteIterator> result) { int responseCode; try { responseCode = httpGet(urlPrefix + endpoint, result); } catch (Exception e) { responseCode = handleExceptions(e, urlPrefix + endpoint, HttpMethod.GET); } if (logEnabled) { System.out.println(new StringBuilder("GET Request: ").append(urlPrefix).append(endpoint) .append(" | Response Code: ").append(responseCode).toString()); } return getStatus(responseCode); }

Target:
public Status read(String table, String endpoint, Set<String> fields, HashMap<String, ByteIterator> result) { int responseCode; try { responseCode = httpGet(urlPrefix + endpoint, result); } catch (Exception e) { responseCode = handleExceptions(e, urlPrefix + endpoint, HttpMethod.GET); } if (logEnabled) { System.err.println(new StringBuilder("GET Request: ").append(urlPrefix).append(endpoint) .append(" | Response Code: ").append(responseCode).toString()); } return getStatus(responseCode); }
Source:
public void testGetCollections() throws Exception { chain = new OperationChain("test-chain"); chain.add(GetCollectionsOperation.ID).set("searchTerm", COLLECTION_NAME + 1); PaginableDocumentModelListImpl collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertEquals(1, collectionsList.size()); DocumentModel collection = collectionsList.get(0); assertEquals(COLLECTION_NAME + 1, collection.getName()); assertEquals(COLLECTION_DESCRIPTION, collection.getPropertyValue("dc:description")); chain = new OperationChain("test-chain-2"); chain.add(GetCollectionsOperation.ID).set("searchTerm", COLLECTION_NAME.subSequence(0, 6)); collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertEquals(listCollections.size(), collectionsList.size()); chain = new OperationChain("test-chain-3"); chain.add(GetCollectionsOperation.ID).set("searchTerm", "NonExistenting"); collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertEquals(0, collectionsList.size()); }

Target:
public void testGetCollections() throws Exception { chain = new OperationChain("test-chain"); chain.add(GetCollectionsOperation.ID).set("searchTerm", COLLECTION_NAME + 1); PaginableDocumentModelListImpl collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertNotNull(collectionsList); assertEquals(1, collectionsList.size()); DocumentModel collection = collectionsList.get(0); assertEquals(COLLECTION_NAME + 1, collection.getName()); assertEquals(COLLECTION_DESCRIPTION, collection.getPropertyValue("dc:description")); chain = new OperationChain("test-chain-2"); chain.add(GetCollectionsOperation.ID) .set("searchTerm", COLLECTION_NAME.substring(0, COLLECTION_NAME.length() - 3)); collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertNotNull(collectionsList); assertEquals(listCollections.size(), collectionsList.size()); chain = new OperationChain("test-chain-3"); chain.add(GetCollectionsOperation.ID).set("searchTerm", "NonExistenting"); collectionsList = (PaginableDocumentModelListImpl) service.run(ctx, chain); assertNotNull(collectionsList); assertEquals(0, collectionsList.size()); }
Source:
protected IStrategoTerm getFlowSpecTransferFunctions(ILanguageComponent component) { IStrategoTerm transferFunctions = flowSpecTransferFunctionCache.get(component); if (transferFunctions != null) { return transferFunctions; } FileObject tfs = resourceService.resolve(component.location(), TRANSFER_FUNCTIONS_FILE); try { transferFunctions = termFactory .parseFromString(IOUtils.toString(tfs.getContent().getInputStream(), StandardCharsets.UTF_8)); } catch (ParseError | IOException e) { logger.error("Could not read transfer functions file for {}", component); throw new MetaborgRuntimeException("Could not read transfer functions file", e); } flowSpecTransferFunctionCache.put(component, transferFunctions); return transferFunctions; }

Target:
protected Optional<TFFileInfo> getFlowSpecTransferFunctions(ILanguageComponent component) { TFFileInfo transferFunctions = flowSpecTransferFunctionCache.get(component); if (transferFunctions != null) { return Optional.of(transferFunctions); } FileObject tfs = resourceService.resolve(component.location(), TRANSFER_FUNCTIONS_FILE); try { IStrategoTerm sTerm = termFactory.parseFromString( IOUtils.toString(tfs.getContent().getInputStream(), StandardCharsets.UTF_8)); ITerm term = strategoTerms.fromStratego(sTerm); transferFunctions = TFFileInfo.match().match(term, PersistentUnifier.Immutable.of()).orElseThrow(() -> new ParseException("Parse error on reading the transfer function file")); } catch (ParseError | ParseException | IOException e) { logger.error("Could not read transfer functions file for {}", component); return Optional.empty(); } logger.debug("Caching flowspec transfer functions for language {}", component); flowSpecTransferFunctionCache.put(component, transferFunctions); return Optional.of(transferFunctions); }
Source:
private static FormFillFailure _error(FormValidation.Kind kind, Throwable e, String message) { if (e==null) return _errorWithMarkup(Util.escape(message),kind); return _errorWithMarkup(Util.escape(message)+ " <a href='#' class='showDetails'>" + Messages.FormValidation_Error_Details() + "</a><pre style='display:none'>" + Util.escape(Functions.printThrowable(e)) + "</pre>",kind ); }

Target:
private static FormFillFailure _error(FormValidation.Kind kind, Throwable e, String message) { if (e == null) { return _errorWithMarkup(Util.escape(message), kind); } return _errorWithMarkup(Util.escape(message) + " <a href='#' class='showDetails'>" + Messages.FormValidation_Error_Details() + "</a><pre style='display:none'>" + Util.escape(Functions.printThrowable(e)) + "</pre>", kind ); }
Source:
public SimpleUri addNode(Node node, String suggestedUri) { SimpleUri nodeUri = new SimpleUri("engine:" + suggestedUri); nodes.put(nodeUri, node); return nodeUri; }

Target:
public SimpleUri addNode(Node node, String suggestedUri) { Preconditions.checkNotNull(node, "node cannot be null!"); Preconditions.checkNotNull(suggestedUri, "suggestedUri cannot be null!"); SimpleUri nodeUri = new SimpleUri("engine:" + suggestedUri); if (nodeMap.containsKey(nodeUri)) { int i = 2; while (nodeMap.containsKey(new SimpleUri(nodeUri.toString() + i))) { i++; } nodeUri = new SimpleUri(nodeUri.toString() + i); } node.setUri(nodeUri); nodeMap.put(nodeUri, node); return nodeUri; }
Source:
public void testCreateWithUnsupportedConnectorThrowsWhenNotNull() { List<TableElement> inputColumns = ImmutableList.of( new ColumnDefinition(identifier("a"), "DATE", emptyList(), Optional.empty(), true), new ColumnDefinition(identifier("b"), "VARCHAR", emptyList(), Optional.empty(), false), new ColumnDefinition(identifier("c"), "VARBINARY", emptyList(), Optional.empty(), false)); CreateTable statement = new CreateTable(QualifiedName.of("test_table"), inputColumns, true, ImmutableList.of(), Optional.empty()); getFutureValue(new CreateTableTask().internalExecute(statement, metadata, new AllowAllAccessControl(), testSession, emptyList())); }

Target:
public void testCreateWithUnsupportedConnectorThrowsWhenNotNull() { List<TableElement> inputColumns = ImmutableList.of( new ColumnDefinition(identifier("a"), "DATE", true, emptyList(), Optional.empty()), new ColumnDefinition(identifier("b"), "VARCHAR", false, emptyList(), Optional.empty()), new ColumnDefinition(identifier("c"), "VARBINARY", false, emptyList(), Optional.empty())); CreateTable statement = new CreateTable( QualifiedName.of("test_table"), inputColumns, true, ImmutableList.of(), Optional.empty()); getFutureValue(new CreateTableTask().internalExecute(statement, metadata, new AllowAllAccessControl(), testSession, emptyList())); }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { Map<String, String> properties = tableSinkConfig.getProperties().getProperties(); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableSinkConfig.getName()), "Dataset name must be given."); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableSinkConfig.getRowField()), "Field to be used as rowkey must be given."); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { validateInputAndOutputSchemaFields(inputSchema); boolean rowFieldPresent = false; for (Schema.Field field : inputSchema.getFields()) { if (!field.getSchema().getType().isSimpleType()) { throw new IllegalArgumentException( String.format("Field '%s' is not of simple type, All fields for table sink should of simple type", field.getName())); } if (field.getName().equals(tableSinkConfig.getRowField())) { rowFieldPresent = true; } } if (!rowFieldPresent) { throw new IllegalArgumentException( String.format("Row field key : '%s' is not present in the input schema", tableSinkConfig.getRowField())); } } pipelineConfigurer.createDataset(tableSinkConfig.getName(), Table.class.getName(), DatasetProperties.builder() .addAll(properties) .build()); }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); Map<String, String> properties; if (tableSinkConfig.getProperties() == null) { properties = new HashMap<>(); } else { properties = tableSinkConfig.getProperties().getProperties(); } Preconditions.checkArgument(!Strings.isNullOrEmpty(tableSinkConfig.getName()), "Dataset name must be given."); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableSinkConfig.getRowField()), "Field to be used as rowkey must be given."); Schema outputSchema = SchemaValidator.validateOutputSchemaAndInputSchemaIfPresent(tableSinkConfig.getSchemaStr(), tableSinkConfig.getRowField(), pipelineConfigurer); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); pipelineConfigurer.createDataset(tableSinkConfig.getName(), Table.class.getName(), DatasetProperties.builder() .addAll(properties) .build()); }
Source:
public Map<String, Long> materializePositions(final EventType eventType, final Subscription subscription) throws ServiceUnavailableException { final SubscriptionBase.InitialPosition position = subscription.getReadFrom(); if (position == SubscriptionBase.InitialPosition.CURSORS) { final List<SubscriptionCursorWithoutToken> etInitialCursors = subscription.getInitialCursors().stream() .filter(c -> c.getEventType().equals(eventType.getName())) .collect(Collectors.toList()); return getSubscriptionTopicInitPositions(eventType.getTopic(), etInitialCursors); } else { try (final Consumer<String, String> consumer = kafkaFactory.getConsumer()) { final org.apache.kafka.common.TopicPartition[] kafkaTPs = consumer .partitionsFor(eventType.getTopic()) .stream() .map(p -> new org.apache.kafka.common.TopicPartition(eventType.getTopic(), p.partition())) .toArray(org.apache.kafka.common.TopicPartition[]::new); consumer.assign(Arrays.asList(kafkaTPs)); if (position == SubscriptionBase.InitialPosition.BEGIN) { consumer.seekToBeginning(kafkaTPs); } else if (position == SubscriptionBase.InitialPosition.END) { consumer.seekToEnd(kafkaTPs); } else { throw new IllegalArgumentException("Bad offset specification " + position + " for topic " + eventType.getTopic()); } return Stream.of(kafkaTPs).collect(Collectors.toMap( tp -> String.valueOf(tp.partition()), consumer::position)); } catch (final Exception e) { throw new ServiceUnavailableException("Error occurred when fetching partitions offsets", e); } } }

Target:
public Map<String, Long> materializePositions(final EventType eventType, final Subscription subscription) throws ServiceUnavailableException { final SubscriptionBase.InitialPosition position = subscription.getReadFrom(); if (position == SubscriptionBase.InitialPosition.CURSORS) { final List<SubscriptionCursorWithoutToken> etInitialCursors = subscription.getInitialCursors().stream() .filter(c -> c.getEventType().equals(eventType.getName())) .collect(Collectors.toList()); return getSubscriptionTopicInitPositions(eventType.getTopic(), etInitialCursors); } else { try (final Consumer<String, String> consumer = kafkaFactory.getConsumer()) { final org.apache.kafka.common.TopicPartition[] kafkaTPs = consumer .partitionsFor(eventType.getTopic()) .stream() .map(p -> new org.apache.kafka.common.TopicPartition(eventType.getTopic(), p.partition())) .toArray(org.apache.kafka.common.TopicPartition[]::new); consumer.assign(Arrays.asList(kafkaTPs)); if (position == SubscriptionBase.InitialPosition.BEGIN) { consumer.seekToBeginning(kafkaTPs); } else if (position == SubscriptionBase.InitialPosition.END) { consumer.seekToEnd(kafkaTPs); } return Stream.of(kafkaTPs).collect(Collectors.toMap( tp -> String.valueOf(tp.partition()), consumer::position)); } catch (final Exception e) { throw new ServiceUnavailableException("Error occurred when fetching partitions offsets", e); } } }
Source:
public void info(String message, Object... args) { final String errorMessage = MessageFormatter.arrayFormat(message, args).getMessage(); logger.info("{}", errorMessage); System.out.println(errorMessage); }

Target:
public void info(String message, Object... args) { String infoMessage = MessageFormatter.arrayFormat(message, args).getMessage(); logger.info("{}", infoMessage); System.out.println(infoMessage); }
Source:
public static Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("<LINK_0>", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = factory.newDocumentBuilder(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); return dBuilder.parse(inputStream); }

Target:
public static Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("<LINK_0>", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = factory.newDocumentBuilder(); try (InputStream inputStream = new ByteArrayInputStream(xml.getBytes())) { return dBuilder.parse(inputStream); } }
Source:
public static int signalStrengthForRequestSize(int requestSize) { return requestSize == 0 ? 0 : Math.min(15, (int) Math.floor(Math.log(requestSize) / LOG_2) + 1); }

Target:
public static int signalStrengthForRequestSize(int requestSize) { if(requestSize <= 0) return 0; else if (requestSize >= 16384) return 15; else return Math.min(15, MathHelper.log2(requestSize) + 1); }
Source:
public static Thread[] findThreadsByName(final String threadName, final String threadGroupName) { if (threadName == null) { throw new IllegalArgumentException("The threadName must not be null"); } if (threadGroupName == null) { throw new IllegalArgumentException("The threadGroupName must not be null"); } final ThreadGroup[] threadGroups = findThreadGroupsByName(threadGroupName); if(threadGroups.length == 0) { return EMPTY_THREAD_ARRAY; } final Thread[] threads = findThreadsByName(threadName); if(threads.length == 0) { return EMPTY_THREAD_ARRAY; } final List<Thread> matchedThreads = new ArrayList<Thread>(); for (int i = 0; i < threads.length; i++) { final Thread thread = threads[i]; if(thread != null && ArrayUtils.contains(threadGroups, thread.getThreadGroup())) { matchedThreads.add(thread); } } return matchedThreads.toArray(new Thread[matchedThreads.size()]); }

Target:
public static Collection<Thread> findThreadsByName(final String threadName, final String threadGroupName) { if (threadName == null) { throw new IllegalArgumentException("The thread name must not be null"); } if (threadGroupName == null) { throw new IllegalArgumentException("The thread group name must not be null"); } final Collection<Thread> result = new ArrayList<Thread>(); for(final ThreadGroup group : selectThreadGroups(new NamePredicate(threadGroupName))) { result.addAll(selectThreads(group, false, new NamePredicate(threadName))); } return Collections.unmodifiableCollection(result); }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiLifecycleHelper = IUiLifecycleHelper.Factory.getInstance(getActivity(), callback); uiLifecycleHelper.onCreate(savedInstanceState); Context context = getActivity().getBaseContext(); socialPref = new PrefManager(context, PrefManager.Pref.FEATURES); pref = new PrefManager(context, PrefManager.Pref.LOGIN); profile = pref.getCurrentUserProfile(); if (config.isUserProfilesEnabled() && profile != null && profile.username != null) { getAccountTask = new GetAccountTask(getActivity(), profile.username) { @Override protected void onSuccess(@NonNull Account account) throws Exception { profileImage = account.getProfileImage(); if (null != imageView) { EventBus.getDefault().post(new ProfilePhotoFetchedEvent(profileImage)); } } }; getAccountTask.setTaskProcessCallback(null); getAccountTask.execute(); } EventBus.getDefault().register(this); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiLifecycleHelper = IUiLifecycleHelper.Factory.getInstance(getActivity(), callback); uiLifecycleHelper.onCreate(savedInstanceState); Context context = getActivity().getBaseContext(); socialPref = new PrefManager(context, PrefManager.Pref.FEATURES); pref = new PrefManager(context, PrefManager.Pref.LOGIN); profile = pref.getCurrentUserProfile(); if (config.isUserProfilesEnabled() && profile != null && profile.username != null) { getAccountTask = new GetAccountTask(getActivity(), profile.username); getAccountTask.setTaskProcessCallback(null); getAccountTask.execute(); } EventBus.getDefault().register(this); }