问:
How does Flexible Search query translate to SQL query in Hybris?
As far as I know, Hybris uses FlexibleSearchQuery to query data. So to query the database, I need to translate FlexibleSearchQuery into SQL. I still do not know how Hybris does it.Can you help me understand?

I have stack trace code as follows:

I see: TranslatedQuery tQuery(class: FlexibleSearch method: executeSearch) = this.cacheKey.tq (class: FlexibleSearchCacheUnit method: compute).

So, Where does this.cacheKey.tq value come from?

```PreparedStatementImpl   executeQuery

public ResultSet executeQuery() throws SQLException {
        if (this.isLoggingActivated()) {
            long startTime = System.currentTimeMillis();

            ResultSet var5;
            try {
                var5 = this.wrapResultSet(this.prepStmtPassthru.executeQuery());
            } catch (SQLException var9) {
                this.getConnection().notifyError(var9);
                this.getConnection().logError(var9, "error executing query");
                throw var9;
            } finally {
                this.connection.getDataSource().getLogUtils().logElapsed(Thread.currentThread().getId(), this.connection.getConnectionID(), startTime, "statement", this.preparedQueryWithoutStackTrace, this.assembleQueryFromPreparedStatement());
            }

            return var5;
        } else {
            try {
                return this.wrapResultSet(this.prepStmtPassthru.executeQuery());
            } catch (SQLException var11) {
                this.getConnection().notifyError(var11);
                this.getConnection().logError(var11, "error executing query");
                throw var11;
            }
        }
    }

FlexibleSearchExecutor  execute

public SearchResult execute(int start, int count, boolean dontNeedTotal, TranslatedQuery translatedQuery, List<Class<?>> resultClasses, Map values, PK languagePK, int prefetchSize, Set<PK> prefetchLanguages) {
        ConversionMetaInformation conversionResult = this.convertResultClasses(resultClasses);
        ExecutableQuery executableQuery = this.getExecutableQuery(translatedQuery, values, languagePK);
        JDBCValueMappings jdbcVM = JDBCValueMappings.getInstance();
        LimitStatementBuilder limitBuilder = this.limitStatementFactory.getLimitStatementBuilder(executableQuery, start, count);
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String query = null;

        SearchResult result;
        try {
            String errorMessageSecondPart;
            try {
                connection = this.tenant.getDataSource().getConnection();
                if (this.isNeedTotalAndCountIsZero(count, dontNeedTotal)) {
                    int totalCount = jdbcVM.getTotalCountFromCountQuery(connection, executableQuery.getCountSQL(), executableQuery.getCountValueList());
                    result = SQLSearchResultFactory.createCountOnlyResult(totalCount, start, count, executableQuery.getSQL(), executableQuery.getValueList());
                } else {
                    query = limitBuilder.getModifiedStatement();
                    statement = connection.prepareStatement(query);
                    jdbcVM.fillStatement(statement, limitBuilder.getModifiedStatementValues());
                    long t1 = 0L;
                    long t2 = 0L;
                    long t3 = 0L;
                    long t4 = 0L;
                    if (LOG.isDebugEnabled()) {
                        t1 = System.currentTimeMillis();
                    }

                    resultSet = statement.executeQuery();
                    if (LOG.isDebugEnabled()) {
                        t2 = System.currentTimeMillis();
                    }

                    int _start = limitBuilder.getOriginalStart();
                    int _count = limitBuilder.getOriginalCount();
                    if (limitBuilder.hasDbEngineLimitSupport()) {
                        _start = 0;
                        _count = -1;
                    }

                    if (LOG.isDebugEnabled()) {
                        t3 = System.currentTimeMillis();
                    }

                    RowFetchResult rowFetchResult = jdbcVM.getQueryResults(resultSet, conversionResult.getConvertedClasses(), _start, _count);
                    if (LOG.isDebugEnabled()) {
                        t4 = System.currentTimeMillis();
                    }

                    int totalCount = dontNeedTotal ? rowFetchResult.rows.size() : jdbcVM.getTotalCount(resultSet, rowFetchResult, start, count, connection, executableQuery, limitBuilder.hasDbEngineLimitSupport());
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(this.getInfoForLogging(executableQuery.getSQL(), limitBuilder.getModifiedStatement(), conversionResult.getConvertedClasses(), executableQuery.getValueList(), ", original range=[" + limitBuilder.getOriginalStart() + "," + limitBuilder.getOriginalCount() + "], rowcount=" + totalCount + ", query=" + (t2 - t1) / 1000L + "ms, fetch=" + (t4 - t3) / 1000L + "ms"));
                    }

                    result = SQLSearchResultFactory.createCacheable(new CacheableResultHolder(rowFetchResult, prefetchSize, prefetchLanguages, conversionResult), totalCount, start, count, limitBuilder.getModifiedStatement(), executableQuery.getValueList());
                }
            } catch (IllegalArgumentException var35) {
                errorMessageSecondPart = Config.getBoolean("flexible.search.exception.show.query.details", false) ? var35.getMessage() + " query = '" + executableQuery.getSQL() + "', values = " + executableQuery.getValueList() : "enable the property 'flexible.search.exception.show.query.details' for more details";
                throw new FlexibleSearchException(var35, "wrong flexible search parameter - " + errorMessageSecondPart, 0);
            } catch (SQLException var36) {
                errorMessageSecondPart = Config.getBoolean("flexible.search.exception.show.query.details", false) ? var36.getMessage() + " query = '" + query + "', values = " + executableQuery.getValueList() : "enable the property 'flexible.search.exception.show.query.details' for more details";
                throw new FlexibleSearchException(var36, "SQL search error - " + errorMessageSecondPart, 0);
            }
        } finally {
            Utilities.tryToCloseJDBC(connection, statement, resultSet);
        }

        return result;
    }

FlexibleSearch  executeSearch

protected SearchResult executeSearch(TranslatedQuery tQuery, Map values, PK langPK, List<Class<?>> resultClasses, boolean dontNeedTotal, int start, int count, int prefetchSize, Set<PK> prefetchLanguages, boolean doExecuteQuery) throws FlexibleSearchException {
        return doExecuteQuery ? this.fsExecutor.execute(start, count, dontNeedTotal, tQuery, resultClasses, values, langPK, prefetchSize, prefetchLanguages) : this.fsExecutor.simulate(start, count, tQuery, values, langPK);
    }

FlexibleSearchCacheUnit compute

public final Object compute() throws FlexibleSearchException {
        this.usedCachedResult = false;
        StandardSearchResult ret = (StandardSearchResult)this.fs.executeSearch(this.cacheKey.tq, this.values, this.cacheKey.langPK, Arrays.asList(this.cacheKey.resultClasses), this.cacheKey.hasModifier(1), this.cacheKey.start, this.cacheKey.count, this.prefetchSize, this.prefetchLanguages, this.cacheKey.hasModifier(2));
        ret.setUnitHash(System.identityHashCode(this));
        return ret;
    }

AbstractCacheUnit   privateGetNoLock

private final Object privateGetNoLock() throws Exception {
        Object ret = this.value;
        if (this.isValueUnknown(ret)) {
            ret = this.compute();
            this.value = ret;
        }

        return ret;
    }

AbstractCacheUnit   privateGet

private final Object privateGet() throws Exception {
        return this.getTransactionAwareCache().isForceExclusiveComputation(this) ? this.privateGetSynchronized() : this.privateGetNoLock();
    }

AbstractCacheUnit   get

public final Object get() throws Exception {
        if (!this.useCache()) {
            return this.computeUncached();
        } else {
            TransactionAwareCache transactionAwareCache = this.getTransactionAwareCache();
            boolean success = false;
            AbstractCacheUnit valueUnit = transactionAwareCache.getOrAddUnit(this);
            Object ret = valueUnit.value;

            try {
                ret = this.isValueUnknown(ret) ? valueUnit.privateGet() : ret;
                success = true;
            } catch (CacheValueLoadException var9) {
                if (var9.getCause() instanceof Exception) {
                    throw (Exception)var9.getCause();
                }

                throw var9;
            } finally {
                if (!success) {
                    transactionAwareCache.removeUnit(valueUnit);
                }

            }

            return ret;
        }
    }

FlexibleSearchCacheUnit myGet

public final StandardSearchResult myGet() throws Exception {
        StandardSearchResult ret = (StandardSearchResult)this.get();
        ret.setFromCache(this.usedCachedResult);
        return ret;
    }

FlexibleSearch  search

public SearchResult search(SessionContext _ctx, String query, Map values, List resultClasses, boolean failOnUnknownFields, boolean dontNeedTotal, int start, int count) throws FlexibleSearchException {
        TranslatedQuery tQuery = null;
        int prefetchSize = this.getSearchPrefetchSize(_ctx);
        if (LOG.isDebugEnabled()) {
            LOG.debug(this.getSearchDebug(_ctx, query, resultClasses, failOnUnknownFields, dontNeedTotal, start, count, prefetchSize));
        }

        boolean doExecuteQuery = !this.disableExecution(_ctx);
        SessionContext localCtx = null;

        SearchResult var22;
        try {
            if (_ctx != null) {
                localCtx = JaloSession.getCurrentSession(this.getTenant()).createLocalSessionContext(_ctx);
                localCtx.setAttribute("disableExecution", Boolean.FALSE);
            }

            PK langPK = this.getSearchLangPK(localCtx);
            tQuery = this.translate(localCtx, this.getRestrictionPrincipal(localCtx), query, values != null ? values.size() : 0, langPK != null, failOnUnknownFields, this.disableRestrictions(localCtx), this.disablePrincipalGroupRestrictions(localCtx), values);
            Map _values = tQuery.removeUnusedValues(this.translatePathValueKeys(localCtx, tQuery.getValueKeys(), new CaseInsensitiveParameterMap(values != null ? values : Collections.EMPTY_MAP)));
            Set<PK> queryTCs = tQuery.getTypePKs();
            Set<Integer> beanTCs = new HashSet(queryTCs.size() * 4);
            PersistenceManager pm = this.getTenant().getPersistenceManager();
            Iterator var19 = queryTCs.iterator();

            while(var19.hasNext()) {
                PK typePK = (PK)var19.next();
                beanTCs.addAll(pm.getBeanTypeCodes(typePK));
            }

            if (beanTCs.isEmpty()) {
                throw new JaloInvalidParameterException("empty bean typcode list ( typePKs = " + tQuery.getTypePKs() + ", query = " + tQuery.getSQLTemplate() + " )", 0);
            }

            try {
                if (!this.isCachingDisabled(localCtx)) {
                    int ttl = this.getTTL(localCtx);
                    FlexibleSearch.FlexibleSearchCacheKey cacheKey = this.createCacheKey(resultClasses, dontNeedTotal, start, count, tQuery, doExecuteQuery, langPK, _values, beanTCs, ttl);
                    FlexibleSearchCacheUnit cacheUnit = this.createCacheUnit(prefetchSize, WrapperFactory.getPrefetchLanguages(localCtx), _values, cacheKey);
                    var22 = this.wrapSearchResult(cacheUnit.myGet());
                    return var22;
                }

                var22 = this.wrapSearchResult(this.executeSearch(tQuery, _values, langPK, resultClasses, dontNeedTotal, start, count, prefetchSize, WrapperFactory.getPrefetchLanguages(localCtx), doExecuteQuery));
            } catch (FlexibleSearchException var28) {
                throw var28;
            } catch (Exception var29) {
                throw new FlexibleSearchException(var29, var29.getMessage(), 0);
            }
        } catch (FlexibleSearchException var30) {
            LOG.error("Flexible search error occured...");
            if (tQuery == null) {
                LOG.error("Query translation was not successful.");
            }

            throw var30;
        } catch (JaloItemNotFoundException var31) {
            throw new JaloInternalException(var31, "cannot get type by translated query type pk", 0);
        } finally {
            if (localCtx != null) {
                JaloSession.getCurrentSession(this.getTenant()).removeLocalSessionContext();
            }

        }

        return var22;
    }

FlexibleSearch  search

public SearchResult search(String query, Map values, List resultClasses, boolean failOnUnknownFields, boolean dontNeedTotal, int start, int count) throws FlexibleSearchException {
        return this.search(JaloSession.hasCurrentSession() ? this.getSession().getSessionContext() : null, query, values, resultClasses, failOnUnknownFields, dontNeedTotal, start, count);
    }

DefaultFlexibleSearchService$2  execute

    private <T> de.hybris.platform.jalo.SearchResult<T> getJaloResult(final FlexibleSearchQuery query) {
        return (de.hybris.platform.jalo.SearchResult)this.getSessionService().executeInLocalView(new SessionExecutionBody() {
            public de.hybris.platform.jalo.SearchResult<T> execute() {
                DefaultFlexibleSearchService.this.getQueryPreprocessorRegistry().executeAllPreprocessors(query);
                Map queryParams = (Map)DefaultFlexibleSearchService.this.toPersistenceLayer(query.getQueryParameters());

                try {
                    return FlexibleSearch.getInstance().search(query.getQuery(), queryParams, this.convertModelClassList(query), query.isFailOnUnknownFields(), !query.isNeedTotal(), query.getStart(), query.getCount());
                } catch (FlexibleSearchException var3) {
                    throw new de.hybris.platform.servicelayer.search.exceptions.FlexibleSearchException(var3.getMessage(), var3);
                }
            }

            private List<Class> convertModelClassList(FlexibleSearchQuery queryx) {
                List<Class> resultClassList = new ArrayList(queryx.getResultClassList().size());
                Iterator var4 = queryx.getResultClassList().iterator();

                while(var4.hasNext()) {
                    Class modelClass = (Class)var4.next();
                    resultClassList.add(DefaultFlexibleSearchService.this.getModelService().getModelTypeClass(modelClass));
                }

                return resultClassList;
            }
        });
    }

DefaultFlexibleSearchService$2  execute

DefaultSessionService   executeInLocalView

public Object executeInLocalView(SessionExecutionBody body) {
        Object var3;
        try {
            this.getOrCreateCurrentJaloSession().createLocalSessionContext();
            var3 = body.execute();
        } finally {
            this.getOrCreateCurrentJaloSession().removeLocalSessionContext();
        }

        return var3;
    }

DefaultFlexibleSearchService    getJaloResult

private <T> de.hybris.platform.jalo.SearchResult<T> getJaloResult(final FlexibleSearchQuery query) {
        return (de.hybris.platform.jalo.SearchResult)this.getSessionService().executeInLocalView(new SessionExecutionBody() {
            public de.hybris.platform.jalo.SearchResult<T> execute() {
                DefaultFlexibleSearchService.this.getQueryPreprocessorRegistry().executeAllPreprocessors(query);
                Map queryParams = (Map)DefaultFlexibleSearchService.this.toPersistenceLayer(query.getQueryParameters());

                try {
                    return FlexibleSearch.getInstance().search(query.getQuery(), queryParams, this.convertModelClassList(query), query.isFailOnUnknownFields(), !query.isNeedTotal(), query.getStart(), query.getCount());
                } catch (FlexibleSearchException var3) {
                    throw new de.hybris.platform.servicelayer.search.exceptions.FlexibleSearchException(var3.getMessage(), var3);
                }
            }

            private List<Class> convertModelClassList(FlexibleSearchQuery queryx) {
                List<Class> resultClassList = new ArrayList(queryx.getResultClassList().size());
                Iterator var4 = queryx.getResultClassList().iterator();

                while(var4.hasNext()) {
                    Class modelClass = (Class)var4.next();
                    resultClassList.add(DefaultFlexibleSearchService.this.getModelService().getModelTypeClass(modelClass));
                }

                return resultClassList;
            }
        });
    }

DefaultFlexibleSearchService    search

public <T> SearchResult<T> search(FlexibleSearchQuery query) {
        ServicesUtil.validateParameterNotNull(query, "The 'query' is null!");
        de.hybris.platform.jalo.SearchResult<T> jaloResult = this.getJaloResult(query);
        if (jaloResult.getCount() == 0) {
            return this.createEmptyResult(jaloResult);
        } else {
            return jaloResult instanceof StandardSearchResult ? this.wrapOrConvert(query, (StandardSearchResult)jaloResult, () -> {
                return this.convert(jaloResult);
            }) : this.convert(jaloResult);
        }
    }

DefaultPagedFlexibleSearchService   search

public <T> SearchPageData<T> search(final String query, final Map<String, ?> queryParams, final PageableData pageableData)
    {
        validateParameterNotNull(query, "query cannot be null");
        validateParameterNotNull(pageableData, "pageableData cannot be null");
        Assert.isTrue(pageableData.getCurrentPage() >= 0, "pageableData current page must be zero or greater");
        Assert.isTrue(pageableData.getPageSize() > 0, "pageableData page size must be greater than zero");

        final FlexibleSearchQuery searchQuery = new FlexibleSearchQuery(query);
        if (queryParams != null && !queryParams.isEmpty())
        {
            searchQuery.addQueryParameters(queryParams);
        }

        searchQuery.setNeedTotal(true);
        searchQuery.setStart(pageableData.getCurrentPage() * pageableData.getPageSize());
        searchQuery.setCount(pageableData.getPageSize());

        final SearchResult<T> searchResult = getFlexibleSearchService().search(searchQuery);

        // Create the paged search result
        final SearchPageData<T> result = createSearchPageData();
        result.setResults(searchResult.getResult());
        result.setPagination(createPagination(pageableData, searchResult));
        // Note: does not set sorts

        return result;
    }

DefaultPagedFlexibleSearchService   search

public <T> SearchPageData<T> search(final List<SortQueryData> sortQueries, final String defaultSortCode,
            final Map<String, ?> queryParams, final PageableData pageableData)
    {
        validateParameterNotNull(sortQueries, "sortQueries cannot be null");
        validateParameterNotNull(defaultSortCode, "defaultSortCode cannot be null");
        validateParameterNotNull(pageableData, "pageableData cannot be null");
        Assert.isTrue(!sortQueries.isEmpty(), "sortQueries must not be empty");
        Assert.isTrue(pageableData.getCurrentPage() >= 0, "pageableData current page must be zero or greater");
        Assert.isTrue(pageableData.getPageSize() > 0, "pageableData page size must be greater than zero");

        // Work out which sort and query to use
        final SortQueryData selectedSortQuery = findSortQueryData(sortQueries, pageableData.getSort(), defaultSortCode);

        // Execute the query
        final SearchPageData<T> searchPageData = search(selectedSortQuery.getQuery(), queryParams, pageableData);

        // Specify which sort was used
        searchPageData.getPagination().setSort(selectedSortQuery.getSortCode());
        searchPageData.setSorts(createSorts(sortQueries, selectedSortQuery.getSortCode()));
        return searchPageData;
    }

DefaultCustomerAccountDao   findOrdersByCustomerAndStore

public SearchPageData<OrderModel> findOrdersByCustomerAndStore(final CustomerModel customerModel, final BaseStoreModel store,
            final OrderStatus[] status, final PageableData pageableData)
    {
        validateParameterNotNull(customerModel, "Customer must not be null");
        validateParameterNotNull(store, "Store must not be null");

        final Map<String, Object> queryParams = new HashMap<String, Object>();
        queryParams.put("customer", customerModel);
        queryParams.put("store", store);

        String filterClause = StringUtils.EMPTY;
        if (CollectionUtils.isNotEmpty(getFilterOrderStatusList()))
        {
            queryParams.put("filterStatusList", getFilterOrderStatusList());
            filterClause = FILTER_ORDER_STATUS;
        }

        final List<SortQueryData> sortQueries;

        if (ArrayUtils.isNotEmpty(status))
        {
            queryParams.put("statusList", Arrays.asList(status));
            sortQueries = Arrays.asList(
                    createSortQueryData("byDate",
                            createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY_AND_STATUS, filterClause, SORT_ORDERS_BY_DATE)),
                    createSortQueryData("byOrderNumber",
                            createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY_AND_STATUS, filterClause, SORT_ORDERS_BY_CODE)));
        }
        else
        {
            sortQueries = Arrays
                    .asList(
                            createSortQueryData("byDate",
                                    createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY, filterClause, SORT_ORDERS_BY_DATE)),
                            createSortQueryData("byOrderNumber",
                                    createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY, filterClause, SORT_ORDERS_BY_CODE)));
        }
        }

        return getPagedFlexibleSearchService().search(sortQueries, "byDate", queryParams, pageableData);
    }

DefaultCustomerAccountService   getOrderList

public SearchPageData<OrderModel> getOrderList(final CustomerModel customerModel, final BaseStoreModel store,
            final OrderStatus[] status, final PageableData pageableData)
    {
        validateParameterNotNull(customerModel, "Customer model cannot be null");
        validateParameterNotNull(store, "Store must not be null");
        validateParameterNotNull(pageableData, "PageableData must not be null");
        return getCustomerAccountDao().findOrdersByCustomerAndStore(customerModel, store, status, pageableData);
    }

DefaultOrderFacade  getPagedOrderHistoryForStatuses

public SearchPageData<OrderHistoryData> getPagedOrderHistoryForStatuses(final PageableData pageableData,
            final OrderStatus... statuses)
    {
        final CustomerModel currentCustomer = (CustomerModel) getUserService().getCurrentUser();
        final BaseStoreModel currentBaseStore = getBaseStoreService().getCurrentBaseStore();
        final SearchPageData<OrderModel> orderResults = getCustomerAccountService().getOrderList(currentCustomer, currentBaseStore,
                statuses, pageableData);

        return convertPageData(orderResults, getOrderHistoryConverter());
    }

AccountPageController   orders
public String orders(@RequestParam(value = "page", defaultValue = "0") final int page,
            @RequestParam(value = "show", defaultValue = "Page") final ShowMode showMode,
            @RequestParam(value = "sort", required = false) final String sortCode, final Model model) throws CMSItemNotFoundException
    {
        // Handle paged search results
        final PageableData pageableData = createPageableData(page, 5, sortCode, showMode);
        final SearchPageData<OrderHistoryData> searchPageData = vinOrderFacade.getPagedOrderHistoryForStatuses(pageableData);
        populateModel(model, searchPageData, showMode);

        storeCmsPageInModel(model, getContentPageForLabelOrId(ORDER_HISTORY_CMS_PAGE));
        setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORDER_HISTORY_CMS_PAGE));
        model.addAttribute(BREADCRUMBS_ATTR, accountBreadcrumbBuilder.getBreadcrumbs("text.account.orderHistory"));
        model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW);
        model.addAttribute("isASM", assistedServiceFacade.isAssistedServiceAgentLoggedIn());
        return getViewForPage(model);
    }
```

答:
FlexibleSearchService this service is having API TranslationResult translate(FlexibleSearchQuery arg0) which you can use to convert your FlexibleSearchQuery to SQL Query.

For example :

```<code>private static final Logger LOG = Logger.getLogger(ExampleClass.class);

@Resource
private FlexibleSearchService flexibleSearchService

......

FlexibleSearchQuery query = new FlexibleSearchQuery(query_string);
TranslationResult result = flexibleSearchService.translate(query);
LOG.info("SQL Query : " + result.getSQLQuery());
LOG.info("SQL Query Parameter : " + result.getSQLQueryParameters());
</code>```

For more details, you can check its implementation in DefaultFlexibleSearchService class or check this

Body:
As far as I know, Hybris uses FlexibleSearchQuery to query data. So to query the database, I need to translate FlexibleSearchQuery into SQL. I still do not know how Hybris does it.Can you help me understand?

I have stack trace code as follows:

I see: TranslatedQuery tQuery(class: FlexibleSearch method: executeSearch) = this.cacheKey.tq (class: FlexibleSearchCacheUnit method: compute).

So, Where does this.cacheKey.tq value come from?

PreparedStatementImpl   executeQuery

public ResultSet executeQuery() throws SQLException {
        if (this.isLoggingActivated()) {
            long startTime = System.currentTimeMillis();

            ResultSet var5;
            try {
                var5 = this.wrapResultSet(this.prepStmtPassthru.executeQuery());
            } catch (SQLException var9) {
                this.getConnection().notifyError(var9);
                this.getConnection().logError(var9, "error executing query");
                throw var9;
            } finally {
                this.connection.getDataSource().getLogUtils().logElapsed(Thread.currentThread().getId(), this.connection.getConnectionID(), startTime, "statement", this.preparedQueryWithoutStackTrace, this.assembleQueryFromPreparedStatement());
            }

            return var5;
        } else {
            try {
                return this.wrapResultSet(this.prepStmtPassthru.executeQuery());
            } catch (SQLException var11) {
                this.getConnection().notifyError(var11);
                this.getConnection().logError(var11, "error executing query");
                throw var11;
            }
        }
    }

FlexibleSearchExecutor  execute

public SearchResult execute(int start, int count, boolean dontNeedTotal, TranslatedQuery translatedQuery, List<Class<?>> resultClasses, Map values, PK languagePK, int prefetchSize, Set<PK> prefetchLanguages) {
        ConversionMetaInformation conversionResult = this.convertResultClasses(resultClasses);
        ExecutableQuery executableQuery = this.getExecutableQuery(translatedQuery, values, languagePK);
        JDBCValueMappings jdbcVM = JDBCValueMappings.getInstance();
        LimitStatementBuilder limitBuilder = this.limitStatementFactory.getLimitStatementBuilder(executableQuery, start, count);
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String query = null;

        SearchResult result;
        try {
            String errorMessageSecondPart;
            try {
                connection = this.tenant.getDataSource().getConnection();
                if (this.isNeedTotalAndCountIsZero(count, dontNeedTotal)) {
                    int totalCount = jdbcVM.getTotalCountFromCountQuery(connection, executableQuery.getCountSQL(), executableQuery.getCountValueList());
                    result = SQLSearchResultFactory.createCountOnlyResult(totalCount, start, count, executableQuery.getSQL(), executableQuery.getValueList());
                } else {
                    query = limitBuilder.getModifiedStatement();
                    statement = connection.prepareStatement(query);
                    jdbcVM.fillStatement(statement, limitBuilder.getModifiedStatementValues());
                    long t1 = 0L;
                    long t2 = 0L;
                    long t3 = 0L;
                    long t4 = 0L;
                    if (LOG.isDebugEnabled()) {
                        t1 = System.currentTimeMillis();
                    }

                    resultSet = statement.executeQuery();
                    if (LOG.isDebugEnabled()) {
                        t2 = System.currentTimeMillis();
                    }

                    int _start = limitBuilder.getOriginalStart();
                    int _count = limitBuilder.getOriginalCount();
                    if (limitBuilder.hasDbEngineLimitSupport()) {
                        _start = 0;
                        _count = -1;
                    }

                    if (LOG.isDebugEnabled()) {
                        t3 = System.currentTimeMillis();
                    }

                    RowFetchResult rowFetchResult = jdbcVM.getQueryResults(resultSet, conversionResult.getConvertedClasses(), _start, _count);
                    if (LOG.isDebugEnabled()) {
                        t4 = System.currentTimeMillis();
                    }

                    int totalCount = dontNeedTotal ? rowFetchResult.rows.size() : jdbcVM.getTotalCount(resultSet, rowFetchResult, start, count, connection, executableQuery, limitBuilder.hasDbEngineLimitSupport());
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(this.getInfoForLogging(executableQuery.getSQL(), limitBuilder.getModifiedStatement(), conversionResult.getConvertedClasses(), executableQuery.getValueList(), ", original range=[" + limitBuilder.getOriginalStart() + "," + limitBuilder.getOriginalCount() + "], rowcount=" + totalCount + ", query=" + (t2 - t1) / 1000L + "ms, fetch=" + (t4 - t3) / 1000L + "ms"));
                    }

                    result = SQLSearchResultFactory.createCacheable(new CacheableResultHolder(rowFetchResult, prefetchSize, prefetchLanguages, conversionResult), totalCount, start, count, limitBuilder.getModifiedStatement(), executableQuery.getValueList());
                }
            } catch (IllegalArgumentException var35) {
                errorMessageSecondPart = Config.getBoolean("flexible.search.exception.show.query.details", false) ? var35.getMessage() + " query = '" + executableQuery.getSQL() + "', values = " + executableQuery.getValueList() : "enable the property 'flexible.search.exception.show.query.details' for more details";
                throw new FlexibleSearchException(var35, "wrong flexible search parameter - " + errorMessageSecondPart, 0);
            } catch (SQLException var36) {
                errorMessageSecondPart = Config.getBoolean("flexible.search.exception.show.query.details", false) ? var36.getMessage() + " query = '" + query + "', values = " + executableQuery.getValueList() : "enable the property 'flexible.search.exception.show.query.details' for more details";
                throw new FlexibleSearchException(var36, "SQL search error - " + errorMessageSecondPart, 0);
            }
        } finally {
            Utilities.tryToCloseJDBC(connection, statement, resultSet);
        }

        return result;
    }

FlexibleSearch  executeSearch

protected SearchResult executeSearch(TranslatedQuery tQuery, Map values, PK langPK, List<Class<?>> resultClasses, boolean dontNeedTotal, int start, int count, int prefetchSize, Set<PK> prefetchLanguages, boolean doExecuteQuery) throws FlexibleSearchException {
        return doExecuteQuery ? this.fsExecutor.execute(start, count, dontNeedTotal, tQuery, resultClasses, values, langPK, prefetchSize, prefetchLanguages) : this.fsExecutor.simulate(start, count, tQuery, values, langPK);
    }

FlexibleSearchCacheUnit compute

public final Object compute() throws FlexibleSearchException {
        this.usedCachedResult = false;
        StandardSearchResult ret = (StandardSearchResult)this.fs.executeSearch(this.cacheKey.tq, this.values, this.cacheKey.langPK, Arrays.asList(this.cacheKey.resultClasses), this.cacheKey.hasModifier(1), this.cacheKey.start, this.cacheKey.count, this.prefetchSize, this.prefetchLanguages, this.cacheKey.hasModifier(2));
        ret.setUnitHash(System.identityHashCode(this));
        return ret;
    }

AbstractCacheUnit   privateGetNoLock

private final Object privateGetNoLock() throws Exception {
        Object ret = this.value;
        if (this.isValueUnknown(ret)) {
            ret = this.compute();
            this.value = ret;
        }

        return ret;
    }

AbstractCacheUnit   privateGet

private final Object privateGet() throws Exception {
        return this.getTransactionAwareCache().isForceExclusiveComputation(this) ? this.privateGetSynchronized() : this.privateGetNoLock();
    }

AbstractCacheUnit   get

public final Object get() throws Exception {
        if (!this.useCache()) {
            return this.computeUncached();
        } else {
            TransactionAwareCache transactionAwareCache = this.getTransactionAwareCache();
            boolean success = false;
            AbstractCacheUnit valueUnit = transactionAwareCache.getOrAddUnit(this);
            Object ret = valueUnit.value;

            try {
                ret = this.isValueUnknown(ret) ? valueUnit.privateGet() : ret;
                success = true;
            } catch (CacheValueLoadException var9) {
                if (var9.getCause() instanceof Exception) {
                    throw (Exception)var9.getCause();
                }

                throw var9;
            } finally {
                if (!success) {
                    transactionAwareCache.removeUnit(valueUnit);
                }

            }

            return ret;
        }
    }

FlexibleSearchCacheUnit myGet

public final StandardSearchResult myGet() throws Exception {
        StandardSearchResult ret = (StandardSearchResult)this.get();
        ret.setFromCache(this.usedCachedResult);
        return ret;
    }

FlexibleSearch  search

public SearchResult search(SessionContext _ctx, String query, Map values, List resultClasses, boolean failOnUnknownFields, boolean dontNeedTotal, int start, int count) throws FlexibleSearchException {
        TranslatedQuery tQuery = null;
        int prefetchSize = this.getSearchPrefetchSize(_ctx);
        if (LOG.isDebugEnabled()) {
            LOG.debug(this.getSearchDebug(_ctx, query, resultClasses, failOnUnknownFields, dontNeedTotal, start, count, prefetchSize));
        }

        boolean doExecuteQuery = !this.disableExecution(_ctx);
        SessionContext localCtx = null;

        SearchResult var22;
        try {
            if (_ctx != null) {
                localCtx = JaloSession.getCurrentSession(this.getTenant()).createLocalSessionContext(_ctx);
                localCtx.setAttribute("disableExecution", Boolean.FALSE);
            }

            PK langPK = this.getSearchLangPK(localCtx);
            tQuery = this.translate(localCtx, this.getRestrictionPrincipal(localCtx), query, values != null ? values.size() : 0, langPK != null, failOnUnknownFields, this.disableRestrictions(localCtx), this.disablePrincipalGroupRestrictions(localCtx), values);
            Map _values = tQuery.removeUnusedValues(this.translatePathValueKeys(localCtx, tQuery.getValueKeys(), new CaseInsensitiveParameterMap(values != null ? values : Collections.EMPTY_MAP)));
            Set<PK> queryTCs = tQuery.getTypePKs();
            Set<Integer> beanTCs = new HashSet(queryTCs.size() * 4);
            PersistenceManager pm = this.getTenant().getPersistenceManager();
            Iterator var19 = queryTCs.iterator();

            while(var19.hasNext()) {
                PK typePK = (PK)var19.next();
                beanTCs.addAll(pm.getBeanTypeCodes(typePK));
            }

            if (beanTCs.isEmpty()) {
                throw new JaloInvalidParameterException("empty bean typcode list ( typePKs = " + tQuery.getTypePKs() + ", query = " + tQuery.getSQLTemplate() + " )", 0);
            }

            try {
                if (!this.isCachingDisabled(localCtx)) {
                    int ttl = this.getTTL(localCtx);
                    FlexibleSearch.FlexibleSearchCacheKey cacheKey = this.createCacheKey(resultClasses, dontNeedTotal, start, count, tQuery, doExecuteQuery, langPK, _values, beanTCs, ttl);
                    FlexibleSearchCacheUnit cacheUnit = this.createCacheUnit(prefetchSize, WrapperFactory.getPrefetchLanguages(localCtx), _values, cacheKey);
                    var22 = this.wrapSearchResult(cacheUnit.myGet());
                    return var22;
                }

                var22 = this.wrapSearchResult(this.executeSearch(tQuery, _values, langPK, resultClasses, dontNeedTotal, start, count, prefetchSize, WrapperFactory.getPrefetchLanguages(localCtx), doExecuteQuery));
            } catch (FlexibleSearchException var28) {
                throw var28;
            } catch (Exception var29) {
                throw new FlexibleSearchException(var29, var29.getMessage(), 0);
            }
        } catch (FlexibleSearchException var30) {
            LOG.error("Flexible search error occured...");
            if (tQuery == null) {
                LOG.error("Query translation was not successful.");
            }

            throw var30;
        } catch (JaloItemNotFoundException var31) {
            throw new JaloInternalException(var31, "cannot get type by translated query type pk", 0);
        } finally {
            if (localCtx != null) {
                JaloSession.getCurrentSession(this.getTenant()).removeLocalSessionContext();
            }

        }

        return var22;
    }

FlexibleSearch  search

public SearchResult search(String query, Map values, List resultClasses, boolean failOnUnknownFields, boolean dontNeedTotal, int start, int count) throws FlexibleSearchException {
        return this.search(JaloSession.hasCurrentSession() ? this.getSession().getSessionContext() : null, query, values, resultClasses, failOnUnknownFields, dontNeedTotal, start, count);
    }

DefaultFlexibleSearchService$2  execute

    private <T> de.hybris.platform.jalo.SearchResult<T> getJaloResult(final FlexibleSearchQuery query) {
        return (de.hybris.platform.jalo.SearchResult)this.getSessionService().executeInLocalView(new SessionExecutionBody() {
            public de.hybris.platform.jalo.SearchResult<T> execute() {
                DefaultFlexibleSearchService.this.getQueryPreprocessorRegistry().executeAllPreprocessors(query);
                Map queryParams = (Map)DefaultFlexibleSearchService.this.toPersistenceLayer(query.getQueryParameters());

                try {
                    return FlexibleSearch.getInstance().search(query.getQuery(), queryParams, this.convertModelClassList(query), query.isFailOnUnknownFields(), !query.isNeedTotal(), query.getStart(), query.getCount());
                } catch (FlexibleSearchException var3) {
                    throw new de.hybris.platform.servicelayer.search.exceptions.FlexibleSearchException(var3.getMessage(), var3);
                }
            }

            private List<Class> convertModelClassList(FlexibleSearchQuery queryx) {
                List<Class> resultClassList = new ArrayList(queryx.getResultClassList().size());
                Iterator var4 = queryx.getResultClassList().iterator();

                while(var4.hasNext()) {
                    Class modelClass = (Class)var4.next();
                    resultClassList.add(DefaultFlexibleSearchService.this.getModelService().getModelTypeClass(modelClass));
                }

                return resultClassList;
            }
        });
    }

DefaultFlexibleSearchService$2  execute

DefaultSessionService   executeInLocalView

public Object executeInLocalView(SessionExecutionBody body) {
        Object var3;
        try {
            this.getOrCreateCurrentJaloSession().createLocalSessionContext();
            var3 = body.execute();
        } finally {
            this.getOrCreateCurrentJaloSession().removeLocalSessionContext();
        }

        return var3;
    }

DefaultFlexibleSearchService    getJaloResult

private <T> de.hybris.platform.jalo.SearchResult<T> getJaloResult(final FlexibleSearchQuery query) {
        return (de.hybris.platform.jalo.SearchResult)this.getSessionService().executeInLocalView(new SessionExecutionBody() {
            public de.hybris.platform.jalo.SearchResult<T> execute() {
                DefaultFlexibleSearchService.this.getQueryPreprocessorRegistry().executeAllPreprocessors(query);
                Map queryParams = (Map)DefaultFlexibleSearchService.this.toPersistenceLayer(query.getQueryParameters());

                try {
                    return FlexibleSearch.getInstance().search(query.getQuery(), queryParams, this.convertModelClassList(query), query.isFailOnUnknownFields(), !query.isNeedTotal(), query.getStart(), query.getCount());
                } catch (FlexibleSearchException var3) {
                    throw new de.hybris.platform.servicelayer.search.exceptions.FlexibleSearchException(var3.getMessage(), var3);
                }
            }

            private List<Class> convertModelClassList(FlexibleSearchQuery queryx) {
                List<Class> resultClassList = new ArrayList(queryx.getResultClassList().size());
                Iterator var4 = queryx.getResultClassList().iterator();

                while(var4.hasNext()) {
                    Class modelClass = (Class)var4.next();
                    resultClassList.add(DefaultFlexibleSearchService.this.getModelService().getModelTypeClass(modelClass));
                }

                return resultClassList;
            }
        });
    }

DefaultFlexibleSearchService    search

public <T> SearchResult<T> search(FlexibleSearchQuery query) {
        ServicesUtil.validateParameterNotNull(query, "The 'query' is null!");
        de.hybris.platform.jalo.SearchResult<T> jaloResult = this.getJaloResult(query);
        if (jaloResult.getCount() == 0) {
            return this.createEmptyResult(jaloResult);
        } else {
            return jaloResult instanceof StandardSearchResult ? this.wrapOrConvert(query, (StandardSearchResult)jaloResult, () -> {
                return this.convert(jaloResult);
            }) : this.convert(jaloResult);
        }
    }

DefaultPagedFlexibleSearchService   search

public <T> SearchPageData<T> search(final String query, final Map<String, ?> queryParams, final PageableData pageableData)
    {
        validateParameterNotNull(query, "query cannot be null");
        validateParameterNotNull(pageableData, "pageableData cannot be null");
        Assert.isTrue(pageableData.getCurrentPage() >= 0, "pageableData current page must be zero or greater");
        Assert.isTrue(pageableData.getPageSize() > 0, "pageableData page size must be greater than zero");

        final FlexibleSearchQuery searchQuery = new FlexibleSearchQuery(query);
        if (queryParams != null && !queryParams.isEmpty())
        {
            searchQuery.addQueryParameters(queryParams);
        }

        searchQuery.setNeedTotal(true);
        searchQuery.setStart(pageableData.getCurrentPage() * pageableData.getPageSize());
        searchQuery.setCount(pageableData.getPageSize());

        final SearchResult<T> searchResult = getFlexibleSearchService().search(searchQuery);

        // Create the paged search result
        final SearchPageData<T> result = createSearchPageData();
        result.setResults(searchResult.getResult());
        result.setPagination(createPagination(pageableData, searchResult));
        // Note: does not set sorts

        return result;
    }

DefaultPagedFlexibleSearchService   search

public <T> SearchPageData<T> search(final List<SortQueryData> sortQueries, final String defaultSortCode,
            final Map<String, ?> queryParams, final PageableData pageableData)
    {
        validateParameterNotNull(sortQueries, "sortQueries cannot be null");
        validateParameterNotNull(defaultSortCode, "defaultSortCode cannot be null");
        validateParameterNotNull(pageableData, "pageableData cannot be null");
        Assert.isTrue(!sortQueries.isEmpty(), "sortQueries must not be empty");
        Assert.isTrue(pageableData.getCurrentPage() >= 0, "pageableData current page must be zero or greater");
        Assert.isTrue(pageableData.getPageSize() > 0, "pageableData page size must be greater than zero");

        // Work out which sort and query to use
        final SortQueryData selectedSortQuery = findSortQueryData(sortQueries, pageableData.getSort(), defaultSortCode);

        // Execute the query
        final SearchPageData<T> searchPageData = search(selectedSortQuery.getQuery(), queryParams, pageableData);

        // Specify which sort was used
        searchPageData.getPagination().setSort(selectedSortQuery.getSortCode());
        searchPageData.setSorts(createSorts(sortQueries, selectedSortQuery.getSortCode()));
        return searchPageData;
    }

DefaultCustomerAccountDao   findOrdersByCustomerAndStore

public SearchPageData<OrderModel> findOrdersByCustomerAndStore(final CustomerModel customerModel, final BaseStoreModel store,
            final OrderStatus[] status, final PageableData pageableData)
    {
        validateParameterNotNull(customerModel, "Customer must not be null");
        validateParameterNotNull(store, "Store must not be null");

        final Map<String, Object> queryParams = new HashMap<String, Object>();
        queryParams.put("customer", customerModel);
        queryParams.put("store", store);

        String filterClause = StringUtils.EMPTY;
        if (CollectionUtils.isNotEmpty(getFilterOrderStatusList()))
        {
            queryParams.put("filterStatusList", getFilterOrderStatusList());
            filterClause = FILTER_ORDER_STATUS;
        }

        final List<SortQueryData> sortQueries;

        if (ArrayUtils.isNotEmpty(status))
        {
            queryParams.put("statusList", Arrays.asList(status));
            sortQueries = Arrays.asList(
                    createSortQueryData("byDate",
                            createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY_AND_STATUS, filterClause, SORT_ORDERS_BY_DATE)),
                    createSortQueryData("byOrderNumber",
                            createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY_AND_STATUS, filterClause, SORT_ORDERS_BY_CODE)));
        }
        else
        {
            sortQueries = Arrays
                    .asList(
                            createSortQueryData("byDate",
                                    createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY, filterClause, SORT_ORDERS_BY_DATE)),
                            createSortQueryData("byOrderNumber",
                                    createQuery(FIND_ORDERS_BY_CUSTOMER_STORE_QUERY, filterClause, SORT_ORDERS_BY_CODE)));
        }
        }

        return getPagedFlexibleSearchService().search(sortQueries, "byDate", queryParams, pageableData);
    }

DefaultCustomerAccountService   getOrderList

public SearchPageData<OrderModel> getOrderList(final CustomerModel customerModel, final BaseStoreModel store,
            final OrderStatus[] status, final PageableData pageableData)
    {
        validateParameterNotNull(customerModel, "Customer model cannot be null");
        validateParameterNotNull(store, "Store must not be null");
        validateParameterNotNull(pageableData, "PageableData must not be null");
        return getCustomerAccountDao().findOrdersByCustomerAndStore(customerModel, store, status, pageableData);
    }

DefaultOrderFacade  getPagedOrderHistoryForStatuses

public SearchPageData<OrderHistoryData> getPagedOrderHistoryForStatuses(final PageableData pageableData,
            final OrderStatus... statuses)
    {
        final CustomerModel currentCustomer = (CustomerModel) getUserService().getCurrentUser();
        final BaseStoreModel currentBaseStore = getBaseStoreService().getCurrentBaseStore();
        final SearchPageData<OrderModel> orderResults = getCustomerAccountService().getOrderList(currentCustomer, currentBaseStore,
                statuses, pageableData);

        return convertPageData(orderResults, getOrderHistoryConverter());
    }

AccountPageController   orders
public String orders(@RequestParam(value = "page", defaultValue = "0") final int page,
            @RequestParam(value = "show", defaultValue = "Page") final ShowMode showMode,
            @RequestParam(value = "sort", required = false) final String sortCode, final Model model) throws CMSItemNotFoundException
    {
        // Handle paged search results
        final PageableData pageableData = createPageableData(page, 5, sortCode, showMode);
        final SearchPageData<OrderHistoryData> searchPageData = vinOrderFacade.getPagedOrderHistoryForStatuses(pageableData);
        populateModel(model, searchPageData, showMode);

        storeCmsPageInModel(model, getContentPageForLabelOrId(ORDER_HISTORY_CMS_PAGE));
        setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORDER_HISTORY_CMS_PAGE));
        model.addAttribute(BREADCRUMBS_ATTR, accountBreadcrumbBuilder.getBreadcrumbs("text.account.orderHistory"));
        model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW);
        model.addAttribute("isASM", assistedServiceFacade.isAssistedServiceAgentLoggedIn());
        return getViewForPage(model);
    }

Body:
FlexibleSearchService this service is having API TranslationResult translate(FlexibleSearchQuery arg0) which you can use to convert your FlexibleSearchQuery to SQL Query.

For example :

private static final Logger LOG = Logger.getLogger(ExampleClass.class);

@Resource
private FlexibleSearchService flexibleSearchService

......

FlexibleSearchQuery query = new FlexibleSearchQuery(query_string);
TranslationResult result = flexibleSearchService.translate(query);
LOG.info("SQL Query : " + result.getSQLQuery());
LOG.info("SQL Query Parameter : " + result.getSQLQueryParameters());

For more details, you can check its implementation in DefaultFlexibleSearchService class or check this


来源: stackexchange

问:
R iteratively select and remove values from a vector
I want ot iteratively select a number of values from a vector (based on a coin-toss decision probability) and remove them from that vector, then in the next loop of iteration, I again want to select (following coin-toss) values from the remaining vector values. Until I will reach the point that my vector is empty. Following is the solution in my mind but at the end I get stuck with one non-selected value in the vector:

```<code>vector <- c("item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10")
  for (i in 1:10) {
    #select values from the vector based on coin-toss probability, so that roughly half of the items get selected
  selected <- sample(vector, replace = F, size = length(vector)/2)
  print(slected)
  # Do some operation with slected values

  # remove the selcted values from the original vector
  vector <- vector[!vector%in%selected]
  print(vector)
  # as we are in loop this will keep happening until we are done selecting all of the elements in the vector.
  }

NOTE: I don't want to select any value twice!
</code>```

Can anybody guide me what can be a better solution for this.

EDIT: Can there be a coin-toss based selection, where I don't give the size explicitly. For example, for every value in the vector we calculate a probability of selection and if it is higher than 0.5 then that value get selected and not otherwise.

I want to do it this way because I want to iterate over this vector 1000 of times and I expect to get different results based on different kind of selection in every iteration.

答:
Here's a different solution. Notice that the most important change is the use of ceiling in defining the sample size.

```<code>x <- c("item1", "item2", "item3", "item4", "item5", "item6", "item7",
       "item8", "item9", "item10")

while(length(x) > 0) {
  selected <- sample(x, replace = FALSE, size = ceiling(length(x)/2))
  cat("selected:", selected, "\n")
  x <- x[!x %in% selected]
  cat("remaining:", x, "\n\n")
}

selected: item5 item3 item8 item10 item4
remaining: item1 item2 item6 item7 item9

selected: item1 item2 item9
remaining: item6 item7

selected: item6
remaining: item7

selected: item7
remaining:
</code>```

I also used a while loop instead of OP's for loop since that makes more sense conceptually.

Regarding OP's comments:

You can also try something like the following where you don't define the sample size that is being selected. Note however, that this can easily lead to some cases where no or all elements are selected, even though the probabiliy for each element is 0.5:

```<code>x <- c("item1", "item2", "item3", "item4", "item5", "item6", "item7",
       "item8", "item9", "item10")
while(length(x) > 0) {
  selected <- x[sample(c(TRUE, FALSE), size = length(x), replace = TRUE)]
  cat("selected:", selected, "\n")
  x <- x[!x %in% selected]
  cat("remaining:", x, "\n\n")
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want ot iteratively select a number of values from a vector (based on a coin-toss decision probability) and remove them from that vector, then in the next loop of iteration, I again want to select (following coin-toss) values from the remaining vector values. Until I will reach the point that my vector is empty. Following is the solution in my mind but at the end I get stuck with one non-selected value in the vector:

vector <- c("item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10")
  for (i in 1:10) {
    #select values from the vector based on coin-toss probability, so that roughly half of the items get selected
  selected <- sample(vector, replace = F, size = length(vector)/2)
  print(slected)
  # Do some operation with slected values

  # remove the selcted values from the original vector
  vector <- vector[!vector%in%selected]
  print(vector)
  # as we are in loop this will keep happening until we are done selecting all of the elements in the vector.
  }

NOTE: I don't want to select any value twice!

Can anybody guide me what can be a better solution for this.

EDIT: Can there be a coin-toss based selection, where I don't give the size explicitly. For example, for every value in the vector we calculate a probability of selection and if it is higher than 0.5 then that value get selected and not otherwise.

I want to do it this way because I want to iterate over this vector 1000 of times and I expect to get different results based on different kind of selection in every iteration.

Body:
Here's a different solution. Notice that the most important change is the use of ceiling in defining the sample size.

x <- c("item1", "item2", "item3", "item4", "item5", "item6", "item7",
       "item8", "item9", "item10")

while(length(x) > 0) {
  selected <- sample(x, replace = FALSE, size = ceiling(length(x)/2))
  cat("selected:", selected, "\n")
  x <- x[!x %in% selected]
  cat("remaining:", x, "\n\n")
}

selected: item5 item3 item8 item10 item4
remaining: item1 item2 item6 item7 item9

selected: item1 item2 item9
remaining: item6 item7

selected: item6
remaining: item7

selected: item7
remaining:

I also used a while loop instead of OP's for loop since that makes more sense conceptually.

Regarding OP's comments:

You can also try something like the following where you don't define the sample size that is being selected. Note however, that this can easily lead to some cases where no or all elements are selected, even though the probabiliy for each element is 0.5:

x <- c("item1", "item2", "item3", "item4", "item5", "item6", "item7",
       "item8", "item9", "item10")
while(length(x) > 0) {
  selected <- x[sample(c(TRUE, FALSE), size = length(x), replace = TRUE)]
  cat("selected:", selected, "\n")
  x <- x[!x %in% selected]
  cat("remaining:", x, "\n\n")
}


问:
mongoDB spring-boot custom query in uppercase, with LIKE
I need to search the items by their names via spring boot on a db implemented by mongodb. For a normal SQL database I would've done as follows:

```<code>@Query("SELECT * FROM customer WHERE UPPER(name) LIKE UPPER(CONCAT('%', :name, '%'))")
List<Customer> findByName(@Param("name") String name);
</code>```

Yet it does not accept a normal 'SELECT' query, because it is a NoSQL database. Thus I need to query this collection by using JSON format, yet I have no idea of the implementation on spring-boot.. This is my first time using mongodb too.

Going through the posts on stackoverflow, I have found an example such as:

@Query("{'name':?0}")

And on this site there are examples. Also here there is an explanation of the query above. Yet still I have no idea how to convert the former query I have pasted above into a "json based query".

Note: I am extending MongoRepository on my repository.

Note2: The above query is case sensitive, that's the reason I am trying to query in upper case along with converting the column data into upper case.

UPDATE

```<code>@Query(" { $text: { $search: ?0 , $caseSensitive: false } }")
</code>```

works perfectly(I had to index my collection by launching this command:db.customerCollection.createIndex({name: "text"}) ) to ignore case sensitivity, but I still need to implement 'LIKE'; because when I search 'user', it is able to find 'UsEr' etc. But if I search 'se', it doesn't bring me any result. Any help will be appreciated!

Thank you for your time!

答:
I have resolved my issue by using $regex and writing the query as:

```<code>@Query(" { companyName: { $regex : '(?i)?0'}  } }")
</code>```

I would've never guessed to spend that much time for such a simple thing. But I am glad that it is resolved anyway !

[ref]

Body:
I need to search the items by their names via spring boot on a db implemented by mongodb. For a normal SQL database I would've done as follows:

@Query("SELECT * FROM customer WHERE UPPER(name) LIKE UPPER(CONCAT('%', :name, '%'))")
List<Customer> findByName(@Param("name") String name);

Yet it does not accept a normal 'SELECT' query, because it is a NoSQL database. Thus I need to query this collection by using JSON format, yet I have no idea of the implementation on spring-boot.. This is my first time using mongodb too.

Going through the posts on stackoverflow, I have found an example such as:

@Query("{'name':?0}")

And on this site there are examples. Also here there is an explanation of the query above. Yet still I have no idea how to convert the former query I have pasted above into a "json based query".

Note: I am extending MongoRepository on my repository.

Note2: The above query is case sensitive, that's the reason I am trying to query in upper case along with converting the column data into upper case.

UPDATE

@Query(" { $text: { $search: ?0 , $caseSensitive: false } }")

works perfectly(I had to index my collection by launching this command:db.customerCollection.createIndex({name: "text"}) ) to ignore case sensitivity, but I still need to implement 'LIKE'; because when I search 'user', it is able to find 'UsEr' etc. But if I search 'se', it doesn't bring me any result. Any help will be appreciated!

Thank you for your time!

Body:
I have resolved my issue by using $regex and writing the query as:

@Query(" { companyName: { $regex : '(?i)?0'}  } }")

I would've never guessed to spend that much time for such a simple thing. But I am glad that it is resolved anyway !

[ref]


问:
php's file_get_contents provokes crash
I am having some trouble with PHP's file_get_contents function.

My setup is basically as follows:
-> From a php page (let's call it a.php), a POST request is sent to another php page (b.php) through file_get_contents.

-> b.php does some stuff with the POST input and then sends another POST request through file_get_contents to itself (b.php)

->This is repeated a couple of times (for example 4 times), so basically it looks like this:

a.php -> POST request through file_get_contents -> b.php -> POST request through file_get_contents -> b.php -> POST request through file_get_contents -> b.php -> POST request through file_get_contents -> b.php

At the last post request to b.php, the script echoes something to the "poster", he adds something to it etc. etc. all the way back to a.php.

For clarity's sake: in production all those php files will be on different servers, and each server has an added value in the process.

For testing however, all pages are on the same server (and I add "?server=x" to the URL so that the same file uses a different database at every "call").

This works like a charm :) ... Unless there are more than 5 file_get_contents are "active" simultaneously ...
This works fine:
a.php->b.php->b.php->b.php->b.php
This doesn't:
a.php->b.php->b.php->b.php->b.php->b.php
As a matter of fact it crashes my server (not responding to ANY http requests anymore), and only restarting Apache "deblocks" it.
The same happens when I load the working "circuit" a.php->b.php->b.php->b.php->b.php different times from the browser.

Error in the Apache error log:

```<code>failed to open stream: HTTP request failed!
</code>```

I thought it might be related to the POST size being too large, but sending a HUGE POST request through the a.php->b.php->b.php->b.php->b.php circuit works just fine ....

So it looks like somehow only 5 simultaneous file_get_contents are allowed ...

Anyone's got some ideas ?

EDIT: As mentioned below, it looks like the real problem is a deadlock, which will not happen in PRD since there will be no "loop" on the same server ... I solved this issue by using CURL instead with a timeout. When a deadlock risks to occur, the curl requests simply time out without freezing the server.
I'm still interested however to get an answer to this question: How can I check/reconfigure the amount of simultaneous requests in Apache2? It's not in the conf file afaik.
Thanks !!!

答: I would suggest using CURL instead of file_get_contents in this case - although I've never had an issue with this except(!) when using sessions since they lock the process up till the session closes. </p>

Title: php's file_get_contents provokes crash

Body:
I am having some trouble with PHP's file_get_contents function.

My setup is basically as follows:
-> From a php page (let's call it a.php), a POST request is sent to another php page (b.php) through file_get_contents.

-> b.php does some stuff with the POST input and then sends another POST request through file_get_contents to itself (b.php)

->This is repeated a couple of times (for example 4 times), so basically it looks like this:

a.php -> POST request through file_get_contents -> b.php -> POST request through file_get_contents -> b.php -> POST request through file_get_contents -> b.php -> POST request through file_get_contents -> b.php

At the last post request to b.php, the script echoes something to the "poster", he adds something to it etc. etc. all the way back to a.php.

For clarity's sake: in production all those php files will be on different servers, and each server has an added value in the process.

For testing however, all pages are on the same server (and I add "?server=x" to the URL so that the same file uses a different database at every "call").

This works like a charm :) ... Unless there are more than 5 file_get_contents are "active" simultaneously ...
This works fine:
a.php->b.php->b.php->b.php->b.php
This doesn't:
a.php->b.php->b.php->b.php->b.php->b.php
As a matter of fact it crashes my server (not responding to ANY http requests anymore), and only restarting Apache "deblocks" it.
The same happens when I load the working "circuit" a.php->b.php->b.php->b.php->b.php different times from the browser.

Error in the Apache error log:

failed to open stream: HTTP request failed!

I thought it might be related to the POST size being too large, but sending a HUGE POST request through the a.php->b.php->b.php->b.php->b.php circuit works just fine ....

So it looks like somehow only 5 simultaneous file_get_contents are allowed ...

Anyone's got some ideas ?

EDIT: As mentioned below, it looks like the real problem is a deadlock, which will not happen in PRD since there will be no "loop" on the same server ... I solved this issue by using CURL instead with a timeout. When a deadlock risks to occur, the curl requests simply time out without freezing the server.
I'm still interested however to get an answer to this question: How can I check/reconfigure the amount of simultaneous requests in Apache2? It's not in the conf file afaik.
Thanks !!!


问:
Transaction is alternating Timeouts
I am using jboss 5.1.x, EJB3.0

I have MDB which listens to JMS queue. when the MDB taking a message, it dispatch a msg via TCP to some modem.
sometimes that Modem doesnt response when the server is waiting for an answer:

```<code>      byte[] byteData = receive(is);
</code>```

coz I cant set timeout on InputStream.

so thanks to the EJB container the transaction timeout(which is there by default) rolling back the operation and then a retry executed again.

this mechanism by default works fine for me, the problem is:

Sometimes the transaction never timed out, and after long time I get the following
msg in the console:

```<code>  15:18:22,578 WARN  [arjLoggerI18N] [com.arjuna.ats.arjuna.coordinator.TransactionReaper_18] - TransactionReaper::check timeout    for TX a6b2232:5f8:4d3591c6:76 in state  RUN
  15:18:22,578 WARN  [arjLoggerI18N] [com.arjuna.ats.arjuna.coordinator.BasicAction_58] - Abort of action id a6b2232:5f8:4d3591c6:76 invoked while multiple threads active within it.
  15:18:22,578 WARN  [arjLoggerI18N] [com.arjuna.ats.arjuna.coordinator.CheckedAction_2] - CheckedAction::check - atomic action a6b2232:5f8:4d3591c6:76 aborting with 1 threads active!
   15:18:22,578 WARN  [arjLoggerI18N] [com.arjuna.ats.arjuna.coordinator.TransactionReaper_7] - TransactionReaper::doCancellations worker Thread[Thread-10,5,jboss] successfully canceled TX a6b2232:5f8:4d3591c6:76
</code>```

Any idea what's wrong? and why sometimes it work and sometimes it doesnt?

thanks,

ray.

答:
JBossAS that uses the Arjuna's Transaction Manager. In EJB3 interceptor chain would begin to unroll and eventually hit the transaction manager interceptors whose job it is to abort the transaction.

For MDB's you can annote it with @ActivationConfigProperty(propertyName="transactionTimeout" value="1500")

For other beans you can have @TransactionTimeout(1500) at class level or method level.

When the transaction manager detects that the transaction has timed out and then aborts it from within an asynchronous thread (different from the thread running in method), but it never sends an interrupt to the currently running thread.

Therefore resulting in : invoked while multiple threads active within it ... aborting with 1 threads active!

Edit :

```<code>//---

ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();

while (root.getParent() != null)
  root = root.getParent();

findAllThread(root,0);

//---

public static findAllThread(ThreadGroup threadGroup, int level){

    int actCount = threadGroup.activeCount();
    Thread[] threads = new Thread[actCount*2];
    actCount = threadGroup.enumerate(threads, false);

    for (int i=0; i<actCount; i++) {
        Thread thread = threads[i];
        thread.interrupt();
    }

    int groupCount = threadGroup.activeGroupCount();
    ThreadGroup[] groups = new ThreadGroup[numGroups*2];
    groupCount = threadGroup.enumerate(groups, false);

    for (int i=0; i<groupCount; i++)
        findAllThread(groups[i], level+1);

//---
</code>```

It will list other active threads also like Reference Handler, Finalizer, Signal Dispatcher etc.

ContentLicense: CC BY-SA 2.5

Title: Transaction is alternating Timeouts

Body:
I am using jboss 5.1.x, EJB3.0

I have MDB which listens to JMS queue. when the MDB taking a message, it dispatch a msg via TCP to some modem.
sometimes that Modem doesnt response when the server is waiting for an answer:

      byte[] byteData = receive(is);

coz I cant set timeout on InputStream.

so thanks to the EJB container the transaction timeout(which is there by default) rolling back the operation and then a retry executed again.

this mechanism by default works fine for me, the problem is:

Sometimes the transaction never timed out, and after long time I get the following
msg in the console:

  15:18:22,578 WARN  [arjLoggerI18N] [com.arjuna.ats.arjuna.coordinator.TransactionReaper_18] - TransactionReaper::check timeout    for TX a6b2232:5f8:4d3591c6:76 in state  RUN
  15:18:22,578 WARN  [arjLoggerI18N] [com.arjuna.ats.arjuna.coordinator.BasicAction_58] - Abort of action id a6b2232:5f8:4d3591c6:76 invoked while multiple threads active within it.
  15:18:22,578 WARN  [arjLoggerI18N] [com.arjuna.ats.arjuna.coordinator.CheckedAction_2] - CheckedAction::check - atomic action a6b2232:5f8:4d3591c6:76 aborting with 1 threads active!
   15:18:22,578 WARN  [arjLoggerI18N] [com.arjuna.ats.arjuna.coordinator.TransactionReaper_7] - TransactionReaper::doCancellations worker Thread[Thread-10,5,jboss] successfully canceled TX a6b2232:5f8:4d3591c6:76

Any idea what's wrong? and why sometimes it work and sometimes it doesnt?

thanks,

ray.

Body:
JBossAS that uses the Arjuna's Transaction Manager. In EJB3 interceptor chain would begin to unroll and eventually hit the transaction manager interceptors whose job it is to abort the transaction.

For MDB's you can annote it with @ActivationConfigProperty(propertyName="transactionTimeout" value="1500")

For other beans you can have @TransactionTimeout(1500) at class level or method level.

When the transaction manager detects that the transaction has timed out and then aborts it from within an asynchronous thread (different from the thread running in method), but it never sends an interrupt to the currently running thread.

Therefore resulting in : invoked while multiple threads active within it ... aborting with 1 threads active!

Edit :

//---

ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();

while (root.getParent() != null)
  root = root.getParent();

findAllThread(root,0);

//---

public static findAllThread(ThreadGroup threadGroup, int level){

    int actCount = threadGroup.activeCount();
    Thread[] threads = new Thread[actCount*2];
    actCount = threadGroup.enumerate(threads, false);

    for (int i=0; i<actCount; i++) {
        Thread thread = threads[i];
        thread.interrupt();
    }

    int groupCount = threadGroup.activeGroupCount();
    ThreadGroup[] groups = new ThreadGroup[numGroups*2];
    groupCount = threadGroup.enumerate(groups, false);

    for (int i=0; i<groupCount; i++)
        findAllThread(groups[i], level+1);

//---

It will list other active threads also like Reference Handler, Finalizer, Signal Dispatcher etc.


问:
Temporal Table Constraints
I've been looking into temporal tables recently and I've applied them successfully to one of my tables. I need to apply it to other tables in the database so I ran a script to which was like the example below. However when running it on my 2nd table I get a

Msg 2714, Level 16, State 5, Line 1 There is already an object named
  'DF_ValidFrom' in the database.

The article below seems to imply you can use the same constraint across the Product and Location and tables. Anyone got any experience in altering existing tables to temporal tables?

```<code>ALTER TABLE Product
ADD
    SysStartTime datetime2 (2) GENERATED ALWAYS AS ROW START HIDDEN
        constraint DF_ValidFrom DEFAULT DATEADD(second, -1, SYSUTCDATETIME())
    , SysEndTime datetime2 (2)  GENERATED ALWAYS AS ROW END HIDDEN
        constraint DF_ValidTo DEFAULT '9999.12.31 23:59:59.99'
    , PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime);

ALTER TABLE Product
    SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.ProductHistory));

ALTER TABLE [Location]
ADD
    SysStartTime datetime2 (2) GENERATED ALWAYS AS ROW START HIDDEN
        constraint DF_ValidFrom DEFAULT DATEADD(second, -1, SYSUTCDATETIME())
    , SysEndTime datetime2 (2)  GENERATED ALWAYS AS ROW END HIDDEN
        constraint DF_ValidTo DEFAULT '9999.12.31 23:59:59.99'
    , PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime);

ALTER TABLE [Location]
    SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.LocationHistory));
</code>```

Full article is here
https://learn.microsoft.com/en-us/sql/relational-databases/tables/temporal-table-usage-scenarios

Thanks in advance for any help.

答:
For perfectly work just add constraint with different name.
This will help you to run execute your script properly.
We did in our project for almost 50 tables.</p>

Title: Temporal Table Constraints

Body:
I've been looking into temporal tables recently and I've applied them successfully to one of my tables. I need to apply it to other tables in the database so I ran a script to which was like the example below. However when running it on my 2nd table I get a

Msg 2714, Level 16, State 5, Line 1 There is already an object named
  'DF_ValidFrom' in the database.

The article below seems to imply you can use the same constraint across the Product and Location and tables. Anyone got any experience in altering existing tables to temporal tables?

ALTER TABLE Product
ADD
    SysStartTime datetime2 (2) GENERATED ALWAYS AS ROW START HIDDEN
        constraint DF_ValidFrom DEFAULT DATEADD(second, -1, SYSUTCDATETIME())
    , SysEndTime datetime2 (2)  GENERATED ALWAYS AS ROW END HIDDEN
        constraint DF_ValidTo DEFAULT '9999.12.31 23:59:59.99'
    , PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime);

ALTER TABLE Product
    SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.ProductHistory));

ALTER TABLE [Location]
ADD
    SysStartTime datetime2 (2) GENERATED ALWAYS AS ROW START HIDDEN
        constraint DF_ValidFrom DEFAULT DATEADD(second, -1, SYSUTCDATETIME())
    , SysEndTime datetime2 (2)  GENERATED ALWAYS AS ROW END HIDDEN
        constraint DF_ValidTo DEFAULT '9999.12.31 23:59:59.99'
    , PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime);

ALTER TABLE [Location]
    SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.LocationHistory));

Full article is here
https://learn.microsoft.com/en-us/sql/relational-databases/tables/temporal-table-usage-scenarios

Thanks in advance for any help.


问:
Prevent submit on Enter but allow Enter for newLine in TextArea
Is it possible to prevent the enter key from submitting forms, but allowing the enter key to work inside input. (E.g. textArea newline)?

I tried so far:

e.preventDefault()

e.stopPropagation()

Both on the form tag onkeyup="if (e.keyCode == 13))"

This does prevent submission of the form on enter key, but it also prevents the enter key from working inside formfields completely.
What I want to achieve is, that when I press the enter key inside a TextArea, that it creates a newLine but when I hit enter in a input type="text"that it doesn't submit the form.

Using JSF 2.3

JQuery solution is also ok.

答:
Get keypress event then check if specialClass is not :focus and check the pressed key (13 = Enter key)

$(document).keypress(function(e) {
  if(!$(".specialClass").is(":focus")){
    e.preventDefault();
    if(e.which == 13) {
        console.log('You pressed enter!');
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
  <textarea name="text" class="specialClass">Text</textarea><br>
  <input type="submit">
</form></code>```

Body:
Get keypress event then check if specialClass is not :focus and check the pressed key (13 = Enter key)

$(document).keypress(function(e) {
  if(!$(".specialClass").is(":focus")){
    e.preventDefault();
    if(e.which == 13) {
        console.log('You pressed enter!');
    }
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
  <textarea name="text" class="specialClass">Text</textarea><br>
  <input type="submit">
</form>

ContentLicense: CC BY-SA 4.0


问:
Laravel migration - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
I am trying to run a migration for a table inventories that I have created with this migration:

Schema::create('inventories', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('remote_id')->unsigned();
    $table->integer('local_id')->unsigned();
    $table->string('local_type');
    $table->string('url')->nullable()->unique();
    $table->timestamps();
});
```

<p>I am trying to add a run a migration where I am adding a foreign key to the table:</p>

<pre class="lang-php prettyprint-override"><code>Schema::table('inventories', function (Blueprint $table) {
    $table->foreign('local_id')->references('id')->on('contents')->onDelete('cascade');
});
</code>```

But, I am getting an error when I try to run the migration:

[Illuminate\Database\QueryException]

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
  update a child row: a foreign key constraint fails (middleton

  .#sql-5d6_162a, CONSTRAINT inventories_local_id_foreign FOREIGN
  KEY (local_id) REFERENCES contents (id) ON DELETE CASCADE     )
  (SQL: alter table inventories add constraint
  inventories_local_id_foreign foreign key (local_id) references
  contents (id) on delete cascade)

[PDOException]

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
  update a child row: a foreign key constraint fails (middleton

  .#sql-5d6_162a, CONSTRAINT inventories_local_id_foreign FOREIGN
  KEY (local_id) REFERENCES contents (id) ON DELETE CASCADE     )

What am I doing wrong?

答:
You probably have some records in the inventories table with local_id that does not have corresponding id in the contents table, hence the error. You could solve it by one of the two ways:

Run the migration with foreign_key_checks turned off. This will disabled the foreign key constraints for the existing rows (if that's what you want). It's documented here

Insert only those records that have corresponding id field in contents table. You can use INSERT INTO.. WHERE EXISTS query to filter the records out, and insert only those records.

Body:
I am trying to run a migration for a table inventories that I have created with this migration:

Schema::create('inventories', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('remote_id')->unsigned();
    $table->integer('local_id')->unsigned();
    $table->string('local_type');
    $table->string('url')->nullable()->unique();
    $table->timestamps();
});

I am trying to add a run a migration where I am adding a foreign key to the table:

Schema::table('inventories', function (Blueprint $table) {
    $table->foreign('local_id')->references('id')->on('contents')->onDelete('cascade');
});

But, I am getting an error when I try to run the migration:

[Illuminate\Database\QueryException]

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
  update a child row: a foreign key constraint fails (middleton

  .#sql-5d6_162a, CONSTRAINT inventories_local_id_foreign FOREIGN
  KEY (local_id) REFERENCES contents (id) ON DELETE CASCADE     )
  (SQL: alter table inventories add constraint
  inventories_local_id_foreign foreign key (local_id) references
  contents (id) on delete cascade)

[PDOException]

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
  update a child row: a foreign key constraint fails (middleton

  .#sql-5d6_162a, CONSTRAINT inventories_local_id_foreign FOREIGN
  KEY (local_id) REFERENCES contents (id) ON DELETE CASCADE     )

What am I doing wrong?


问:
How does PHP 'foreach' actually work?
Let me prefix this by saying that I know what foreach is, does and how to use it. This question concerns how it works under the bonnet, and I don't want any answers along the lines of "this is how you loop an array with foreach".

For a long time I assumed that foreach worked with the array itself. Then I found many references to the fact that it works with a copy of the array, and I have since assumed this to be the end of the story. But I recently got into a discussion on the matter, and after a little experimentation found that this was not in fact 100% true.

Let me show what I mean. For the following test cases, we will be working with the following array:

```<code>$array = array(1, 2, 3, 4, 5);
</code>```

Test case 1:

```<code>foreach ($array as $item) {
  echo "$item\n";
  $array[] = $item;
}
print_r($array);

/* Output in loop:    1 2 3 4 5
   $array after loop: 1 2 3 4 5 1 2 3 4 5 */
</code>```

This clearly shows that we are not working directly with the source array - otherwise the loop would continue forever, since we are constantly pushing items onto the array during the loop. But just to be sure this is the case:

Test case 2:

```<code>foreach ($array as $key => $item) {
  $array[$key + 1] = $item + 2;
  echo "$item\n";
}

print_r($array);

/* Output in loop:    1 2 3 4 5
   $array after loop: 1 3 4 5 6 7 */
</code>```

This backs up our initial conclusion, we are working with a copy of the source array during the loop, otherwise we would see the modified values during the loop. But...

If we look in the manual, we find this statement:

When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array.

Right... this seems to suggest that foreach relies on the array pointer of the source array. But we've just proved that we're not working with the source array, right? Well, not entirely.

Test case 3:

```<code>// Move the array pointer on one to make sure it doesn't affect the loop
var_dump(each($array));

foreach ($array as $item) {
  echo "$item\n";
}

var_dump(each($array));

/* Output
  array(4) {
    [1]=>
    int(1)
    ["value"]=>
    int(1)
    [0]=>
    int(0)
    ["key"]=>
    int(0)
  }
  1
  2
  3
  4
  5
  bool(false)
*/
</code>```

So, despite the fact that we are not working directly with the source array, we are working directly with the source array pointer - the fact that the pointer is at the end of the array at the end of the loop shows this. Except this can't be true - if it was, then test case 1 would loop forever.

The PHP manual also states:

As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.

Well, let's find out what that "unexpected behavior" is (technically, any behavior is unexpected since I no longer know what to expect).

Test case 4:

```<code>foreach ($array as $key => $item) {
  echo "$item\n";
  each($array);
}

/* Output: 1 2 3 4 5 */
</code>```

Test case 5:

```<code>foreach ($array as $key => $item) {
  echo "$item\n";
  reset($array);
}

/* Output: 1 2 3 4 5 */
</code>```

...nothing that unexpected there, in fact it seems to support the "copy of source" theory.

The Question

What is going on here? My C-fu is not good enough for me to able to extract a proper conclusion simply by looking at the PHP source code, I would appreciate it if someone could translate it into English for me.

It seems to me that foreach works with a copy of the array, but sets the array pointer of the source array to the end of the array after the loop.

Is this correct and the whole story?

If not, what is it really doing?

Is there any situation where using functions that adjust the array pointer (each(), reset() et al.) during a foreach could affect the outcome of the loop?

答:
PHP foreach loop can be used with Indexed arrays, Associative arrays and Object public variables.

In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy of the array rather than the original one. This is demonstrated in the below example:

```<code><?php
$numbers = [1,2,3,4,5,6,7,8,9]; # initial values for our array
echo '```', print_r($numbers, true), '```', '<hr />';
foreach($numbers as $index => $number){
    $numbers[$index] = $number + 1; # this is making changes to the origial array
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # showing data from the copied array
}
echo '<hr />', '```', print_r($numbers, true), '```'; # shows the original values (also includes the newly added values).
</code>```

Besides this, php does allow to use iterated values as a reference to the original array value as well. This is demonstrated below:

```<code><?php
$numbers = [1,2,3,4,5,6,7,8,9];
echo '```', print_r($numbers, true), '```';
foreach($numbers as $index => &$number){
    ++$number; # we are incrementing the original value
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # this is showing the original value
}
echo '<hr />';
echo '```', print_r($numbers, true), '```'; # we are again showing the original value
</code>```

Note: It does not allow original array indexes to be used as references.

Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples

Title: How does PHP 'foreach' actually work?

Body:
Let me prefix this by saying that I know what foreach is, does and how to use it. This question concerns how it works under the bonnet, and I don't want any answers along the lines of "this is how you loop an array with foreach".

For a long time I assumed that foreach worked with the array itself. Then I found many references to the fact that it works with a copy of the array, and I have since assumed this to be the end of the story. But I recently got into a discussion on the matter, and after a little experimentation found that this was not in fact 100% true.

Let me show what I mean. For the following test cases, we will be working with the following array:

$array = array(1, 2, 3, 4, 5);

Test case 1:

foreach ($array as $item) {
  echo "$item\n";
  $array[] = $item;
}
print_r($array);

/* Output in loop:    1 2 3 4 5
   $array after loop: 1 2 3 4 5 1 2 3 4 5 */

This clearly shows that we are not working directly with the source array - otherwise the loop would continue forever, since we are constantly pushing items onto the array during the loop. But just to be sure this is the case:

Test case 2:

foreach ($array as $key => $item) {
  $array[$key + 1] = $item + 2;
  echo "$item\n";
}

print_r($array);

/* Output in loop:    1 2 3 4 5
   $array after loop: 1 3 4 5 6 7 */

This backs up our initial conclusion, we are working with a copy of the source array during the loop, otherwise we would see the modified values during the loop. But...

If we look in the manual, we find this statement:

When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array.

Right... this seems to suggest that foreach relies on the array pointer of the source array. But we've just proved that we're not working with the source array, right? Well, not entirely.

Test case 3:

// Move the array pointer on one to make sure it doesn't affect the loop
var_dump(each($array));

foreach ($array as $item) {
  echo "$item\n";
}

var_dump(each($array));

/* Output
  array(4) {
    [1]=>
    int(1)
    ["value"]=>
    int(1)
    [0]=>
    int(0)
    ["key"]=>
    int(0)
  }
  1
  2
  3
  4
  5
  bool(false)
*/

So, despite the fact that we are not working directly with the source array, we are working directly with the source array pointer - the fact that the pointer is at the end of the array at the end of the loop shows this. Except this can't be true - if it was, then test case 1 would loop forever.

The PHP manual also states:

As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.

Well, let's find out what that "unexpected behavior" is (technically, any behavior is unexpected since I no longer know what to expect).

Test case 4:

foreach ($array as $key => $item) {
  echo "$item\n";
  each($array);
}

/* Output: 1 2 3 4 5 */

Test case 5:

foreach ($array as $key => $item) {
  echo "$item\n";
  reset($array);
}

/* Output: 1 2 3 4 5 */

...nothing that unexpected there, in fact it seems to support the "copy of source" theory.

The Question

What is going on here? My C-fu is not good enough for me to able to extract a proper conclusion simply by looking at the PHP source code, I would appreciate it if someone could translate it into English for me.

It seems to me that foreach works with a copy of the array, but sets the array pointer of the source array to the end of the array after the loop.

Is this correct and the whole story?

If not, what is it really doing?

Is there any situation where using functions that adjust the array pointer (each(), reset() et al.) during a foreach could affect the outcome of the loop?

Body:
PHP foreach loop can be used with Indexed arrays, Associative arrays and Object public variables.

In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy of the array rather than the original one. This is demonstrated in the below example:

<?php
$numbers = [1,2,3,4,5,6,7,8,9]; # initial values for our array
echo '<pre>', print_r($numbers, true), '</pre>', '<hr />';
foreach($numbers as $index => $number){
    $numbers[$index] = $number + 1; # this is making changes to the origial array
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # showing data from the copied array
}
echo '<hr />', '<pre>', print_r($numbers, true), '</pre>'; # shows the original values (also includes the newly added values).

Besides this, php does allow to use iterated values as a reference to the original array value as well. This is demonstrated below:

<?php
$numbers = [1,2,3,4,5,6,7,8,9];
echo '<pre>', print_r($numbers, true), '</pre>';
foreach($numbers as $index => &$number){
    ++$number; # we are incrementing the original value
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # this is showing the original value
}
echo '<hr />';
echo '<pre>', print_r($numbers, true), '</pre>'; # we are again showing the original value

Note: It does not allow original array indexes to be used as references.

Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples


问:
c++ language oops
Why do we declare constructor's as public?

答: If you don't you will not be able to construct the object from other objects.</p>

Title: c++ language oops


问:
Unknown host in Java RMI
I'm working on a Java RMI distribuited system and I have 2 VMs running ubuntu on my local machine (ubuntu- (master) IP = 192.168.101.131 and ubuntu- (slave) IP = 92.168.101.137). Can I run my bankServer.jar on both VMs (within a tomcat). The ubuntu- (master) database automatically replicates on ubuntu- (slave). So far so good. Server mentions (in portuguese) that is running in the default port 1099.

```<code>Cubuntu@ubuntu:/var/www/html/classes$ java -cp ./code/:jar/serverBanco.jar -
Dja.rmi.server.codebase=file:jar/computeInterfaces.jar -
Djava.rmi.server.hostname=192.168.101.131 -
Djava.security.policy=file:jar/all.policy bank.BankServer
Default RMI Port = 1099
Servidor iniciado...
</code>```

Now when running the client on my local machine my program first ping the host to see if he is online and, if ok, binds to it the registry like so:

```<code>InetAddress inet = null;
     InetAddress inet2 = null;
     String rmi_adress;
        //ping
        inet = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 101, (byte) 137 });
        System.out.println("Enviando Ping Request para host: " + inet);
        System.out.println(inet.isReachable(5000) ? "Resposta: Host online" : "Resposta: Host offline");

        inet2 = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 101, (byte) 131 });
        System.out.println("Enviando Ping Request para host: " + inet2);
        System.out.println(inet2.isReachable(5000) ? "Resposta: Host online" : "Resposta: Host offline");

        try {
            registry = LocateRegistry.getRegistry("rmi://127.0.0.1/BankServer");
            if (inet.isReachable(5000)) {
                rmi_adress = "rmi://192.168.101.137/BankServer";
                registry = LocateRegistry.getRegistry(rmi_adress);
                System.out.println("RMI Port set to " + rmi_adress);
                bank = (OperationsInterface) registry.lookup(rmi_adress);
            }else {
                rmi_adress =  "rmi://192.168.101.131/BankServer";
                registry = LocateRegistry.getRegistry(rmi_adress);
                System.out.println("RMI Port set to " + rmi_adress);
                bank = (OperationsInterface) registry.lookup(rmi_adress);
            }
</code>```

But when running the client it can not recognize the host. This is the exception I'm getting:

```<code>Enviando Ping Request para host: /192.168.101.137
Resposta: Host online
Enviando Ping Request para host: /192.168.101.131
Resposta: Host online
RMI Port set to rmi://192.168.101.137/BankServer
Exception in thread "main" java.rmi.UnknownHostException: Unknown host:
rmi://192.168.101.137/BankServer; nested exception is:
    Java.net.UnknownHostException: rmi://192.168.101.137/BankServer
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:616)
    at
sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
    at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:342)
    at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
    at atm.ATM.main(ATM.java:52)
Caused by: java.net.UnknownHostException: rmi://192.168.101.137/BankServer
    at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at...
</code>```

Now what could be happening here? Any help is appreciated.

答: You should try to remove rmi:// when you get the registry

Title: Unknown host in Java RMI

Body:
I'm working on a Java RMI distribuited system and I have 2 VMs running ubuntu on my local machine (ubuntu- (master) IP = 192.168.101.131 and ubuntu- (slave) IP = 92.168.101.137). Can I run my bankServer.jar on both VMs (within a tomcat). The ubuntu- (master) database automatically replicates on ubuntu- (slave). So far so good. Server mentions (in portuguese) that is running in the default port 1099.

Cubuntu@ubuntu:/var/www/html/classes$ java -cp ./code/:jar/serverBanco.jar -
Dja.rmi.server.codebase=file:jar/computeInterfaces.jar -
Djava.rmi.server.hostname=192.168.101.131 -
Djava.security.policy=file:jar/all.policy bank.BankServer
Default RMI Port = 1099
Servidor iniciado...

Now when running the client on my local machine my program first ping the host to see if he is online and, if ok, binds to it the registry like so:

InetAddress inet = null;
     InetAddress inet2 = null;
     String rmi_adress;
        //ping
        inet = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 101, (byte) 137 });
        System.out.println("Enviando Ping Request para host: " + inet);
        System.out.println(inet.isReachable(5000) ? "Resposta: Host online" : "Resposta: Host offline");

        inet2 = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 101, (byte) 131 });
        System.out.println("Enviando Ping Request para host: " + inet2);
        System.out.println(inet2.isReachable(5000) ? "Resposta: Host online" : "Resposta: Host offline");

        try {
            registry = LocateRegistry.getRegistry("rmi://127.0.0.1/BankServer");
            if (inet.isReachable(5000)) {
                rmi_adress = "rmi://192.168.101.137/BankServer";
                registry = LocateRegistry.getRegistry(rmi_adress);
                System.out.println("RMI Port set to " + rmi_adress);
                bank = (OperationsInterface) registry.lookup(rmi_adress);
            }else {
                rmi_adress =  "rmi://192.168.101.131/BankServer";
                registry = LocateRegistry.getRegistry(rmi_adress);
                System.out.println("RMI Port set to " + rmi_adress);
                bank = (OperationsInterface) registry.lookup(rmi_adress);
            }

But when running the client it can not recognize the host. This is the exception I'm getting:

Enviando Ping Request para host: /192.168.101.137
Resposta: Host online
Enviando Ping Request para host: /192.168.101.131
Resposta: Host online
RMI Port set to rmi://192.168.101.137/BankServer
Exception in thread "main" java.rmi.UnknownHostException: Unknown host:
rmi://192.168.101.137/BankServer; nested exception is:
    Java.net.UnknownHostException: rmi://192.168.101.137/BankServer
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:616)
    at
sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
    at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:342)
    at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
    at atm.ATM.main(ATM.java:52)
Caused by: java.net.UnknownHostException: rmi://192.168.101.137/BankServer
    at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at...

Now what could be happening here? Any help is appreciated.