text:
Q: Method with REQUIRES_NEW called from REQUIRES_NEW causes NullPointerException in TransactionalInterceptorRequiresNew I'm having a hard time understanding what is wrong with my code...
There is a @Singleton EJB:
@Singleton
public class MailJobScheduler {

    @Inject
    private NewJobSchedulerBA newJobSchedulerBA;

    @Schedule(hour = "*", minute = "*", second = "*/10")
    public void doCheckForLongRunningJobs() {
        try {
            LOG.info("Checking for long running mail jobs...");
            newJobSchedulerBA.checkForLongRunningJobs(mailJobDAO);
        } catch (Exception e) {
            LOG.error("Unknown error while checking for long running mail jobs", e);
        }
    }
}

It just calls a method from NewJobSchedulerBA. This is the implementation:
    @Override
    @Transactional(Transactional.TxType.REQUIRES_NEW)
    public <T extends AbstractAsyncJobBE> void checkForLongRunningJobs(JobDAO<T> jobDAO) {
        JobDAO.LongRunningJobs longRunningJobs = jobDAO.findLongRunningJobs();
        longRunningJobs.getJobs().stream()
            .filter(job -> !job.wasWarningMailSent())
            .forEach(job -> {
                LOG.info("Found long running job: {}", job);
                // the update is done inside a new transaction, so if something goes wrong with updating
                // one job entity the other updates might still succeed
                jobMonitoringBA.markJobAsBeingNotified(job);
                jobMonitoringBA.sendWarningMail(job, longRunningJobs.getWarningTime());
            });
    }

It's inside a CDI bean and annotated with REQUIRES_NEW, so if anything goes wrong inside it I don't want my scheduler to expunge the timer.
This in turn calls JobMonitoringBA.markJobAsBeingNotified(...) (which is also a CDI bean):
    @Override
    @Transactional(Transactional.TxType.REQUIRES_NEW)
    public void markJobAsBeingNotified(AbstractAsyncJobBE job) {
        LOG.info("Updating job...");
        job = this.entityManager.merge(job);
        job.setWasWarningMailSent(true);
        LOG.info("Done");
    }

The idea here is that when a single job cannot be updated (because of, e.g., an OptimisticLockException, then the other jobs should still getting updated.
When I force an OptimisticLockException, then I get this log output:
[2021-07-23T12:11:10.001+0200] [Payara 4.1] [INFO] [] [com.bmw.swhrl.job.processor.scheduler.MailJobScheduler] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070001] [levelValue: 800] [[
  Checking for long running mail jobs...]]

[2021-07-23T12:11:10.002+0200] [Payara 4.1] [INFO] [] [com.bmw.swhrl.dao.impl.AbstractJobDAOImpl] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070002] [levelValue: 800] [[
  Finding long running jobs...]]

[2021-07-23T12:11:10.002+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070002] [levelValue: 800] [[
  [EL Finer]: connection: 2021-07-23 12:11:10.002--ServerSession(1144457050)--Thread(Thread[__ejb-thread-pool4,5,main])--client acquired: 223416353
]]

[2021-07-23T12:11:10.003+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070003] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:10.003--UnitOfWork(60223483)--Thread(Thread[__ejb-thread-pool4,5,main])--TX binding to tx mgr, status=STATUS_ACTIVE
]]

[2021-07-23T12:11:10.003+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070003] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:10.003--ClientSession(223416353)--Thread(Thread[__ejb-thread-pool4,5,main])--acquire unit of work: 60223483
]]

[2021-07-23T12:11:10.003+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070003] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:10.003--UnitOfWork(60223483)--Thread(Thread[__ejb-thread-pool4,5,main])--begin unit of work flush
]]

[2021-07-23T12:11:10.003+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070003] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:10.003--UnitOfWork(60223483)--Thread(Thread[__ejb-thread-pool4,5,main])--end unit of work flush
]]

[2021-07-23T12:11:10.003+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070003] [levelValue: 800] [[
  [EL Fine]: sql: 2021-07-23 12:11:10.003--ServerSession(1144457050)--Connection(128547665)--Thread(Thread[__ejb-thread-pool4,5,main])--SELECT ID, job_name, num_jobs_per_execution, warning_time_in_seconds FROM swhrl.job_type_configuration WHERE (job_name = ?)
    bind => [MailJobBE]
]]

[2021-07-23T12:11:10.005+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070005] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:10.005--UnitOfWork(60223483)--Thread(Thread[__ejb-thread-pool4,5,main])--begin unit of work flush
]]

[2021-07-23T12:11:10.005+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070005] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:10.005--UnitOfWork(60223483)--Thread(Thread[__ejb-thread-pool4,5,main])--end unit of work flush
]]

[2021-07-23T12:11:10.005+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070005] [levelValue: 800] [[
  [EL Fine]: sql: 2021-07-23 12:11:10.005--ServerSession(1144457050)--Connection(1207842220)--Thread(Thread[__ejb-thread-pool4,5,main])--SELECT id, bcc_recipients, content, created_by, created_date, job_failure_reason, job_result, job_status, recipients, stages, start_date, stop_date, subject, version, was_warning_mail_sent, job_id FROM swhrl.mail_job WHERE ((job_status = ?) AND (start_date < ?))
    bind => [STARTED, 2021-07-23 11:56:10.004]
]]

[2021-07-23T12:11:10.010+0200] [Payara 4.1] [INFO] [] [com.bmw.swhrl.dao.impl.AbstractJobDAOImpl] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070010] [levelValue: 800] [[
  Found 1 jobs]]

[2021-07-23T12:11:10.011+0200] [Payara 4.1] [INFO] [] [com.bmw.swhrl.job.processor.control.impl.NewJobSchedulerBAImpl] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070011] [levelValue: 800] [[
  Found long running job: MailJobBE[ id=1 ]]]

[2021-07-23T12:11:10.011+0200] [Payara 4.1] [INFO] [] [com.bmw.swhrl.job.processor.control.impl.JobMonitoringBAImpl] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070011] [levelValue: 800] [[
  Updating job...]]

[2021-07-23T12:11:10.012+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070012] [levelValue: 800] [[
  [EL Finer]: connection: 2021-07-23 12:11:10.012--ServerSession(1144457050)--Thread(Thread[__ejb-thread-pool4,5,main])--client acquired: 2016554542
]]

[2021-07-23T12:11:10.012+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070012] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:10.012--UnitOfWork(613966548)--Thread(Thread[__ejb-thread-pool4,5,main])--TX binding to tx mgr, status=STATUS_ACTIVE
]]

[2021-07-23T12:11:10.013+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070013] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:10.013--ClientSession(2016554542)--Thread(Thread[__ejb-thread-pool4,5,main])--acquire unit of work: 613966548
]]

[2021-07-23T12:11:10.017+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035070017] [levelValue: 800] [[
  [EL Fine]: sql: 2021-07-23 12:11:10.017--ServerSession(1144457050)--Connection(1633715874)--Thread(Thread[__ejb-thread-pool4,5,main])--SELECT id, bcc_recipients, content, created_by, created_date, job_failure_reason, job_result, job_status, recipients, stages, start_date, stop_date, subject, version, was_warning_mail_sent, job_id FROM swhrl.mail_job WHERE (id = ?)
    bind => [1]
]]

[2021-07-23T12:11:50.863+0200] [Payara 4.1] [INFO] [] [com.bmw.swhrl.job.processor.control.impl.JobMonitoringBAImpl] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035110863] [levelValue: 800] [[
  Done]]

[2021-07-23T12:11:50.863+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035110863] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:50.863--UnitOfWork(613966548)--Thread(Thread[__ejb-thread-pool4,5,main])--TX beforeCompletion callback, status=STATUS_ACTIVE
]]

[2021-07-23T12:11:50.864+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035110864] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:50.864--UnitOfWork(613966548)--Thread(Thread[__ejb-thread-pool4,5,main])--begin unit of work commit
]]

[2021-07-23T12:11:50.880+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035110880] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:50.88--ClientSession(2016554542)--Thread(Thread[__ejb-thread-pool4,5,main])--TX beginTransaction, status=STATUS_ACTIVE
]]

[2021-07-23T12:11:50.881+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035110881] [levelValue: 800] [[
  [EL Fine]: sql: 2021-07-23 12:11:50.881--ClientSession(2016554542)--Connection(1452902274)--Thread(Thread[__ejb-thread-pool4,5,main])--UPDATE swhrl.mail_job SET was_warning_mail_sent = ?, version = ? WHERE ((id = ?) AND (version = ?))
    bind => [true, 4, 1, 3]
]]

[2021-07-23T12:11:50.886+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035110886] [levelValue: 800] [[
  [EL Warning]: 2021-07-23 12:11:50.884--UnitOfWork(613966548)--Thread(Thread[__ejb-thread-pool4,5,main])--Local Exception Stack:
Exception [EclipseLink-5006] (Eclipse Persistence Services - 2.6.4.qualifier): org.eclipse.persistence.exceptions.OptimisticLockException
Exception Description: The object [MailJobBE[ id=1 ]] cannot be updated because it has changed or been deleted since it was last read.
Class> com.bmw.swhrl.entities.domain.MailJobBE Primary Key> 1
    at org.eclipse.persistence.exceptions.OptimisticLockException.objectChangedSinceLastReadWhenUpdating(OptimisticLockException.java:144)
    ...

[2021-07-23T12:11:50.887+0200] [Payara 4.1] [WARNING] [] [javax.enterprise.resource.jta.com.sun.enterprise.transaction] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035110887] [levelValue: 900] [[
  DTX5014: Caught exception in beforeCompletion() callback:
javax.persistence.OptimisticLockException: Exception [EclipseLink-5006] (Eclipse Persistence Services - 2.6.4.qualifier): org.eclipse.persistence.exceptions.OptimisticLockException
Exception Description: The object [MailJobBE[ id=1 ]] cannot be updated because it has changed or been deleted since it was last read.
Class> com.bmw.swhrl.entities.domain.MailJobBE Primary Key> 1
    at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl$1.handleException(EntityManagerSetupImpl.java:743)
    ...

[2021-07-23T12:11:50.890+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035110890] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:50.89--UnitOfWork(613966548)--Thread(Thread[__ejb-thread-pool4,5,main])--TX afterCompletion callback, status=ROLLEDBACK
]]

[2021-07-23T12:11:50.890+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035110890] [levelValue: 800] [[
  [EL Finer]: transaction: 2021-07-23 12:11:50.89--UnitOfWork(613966548)--Thread(Thread[__ejb-thread-pool4,5,main])--release unit of work
]]

[2021-07-23T12:11:50.890+0200] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035110890] [levelValue: 800] [[
  [EL Finer]: connection: 2021-07-23 12:11:50.89--ClientSession(2016554542)--Thread(Thread[__ejb-thread-pool4,5,main])--client released
]]

[2021-07-23T12:12:16.311+0200] [Payara 4.1] [WARNING] [] [com.bmw.swhrl.job.processor.control.impl.NewJobSchedulerBAImpl] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035136311] [levelValue: 900] [[
  Error while trying to send warning message for job: [MailJobBE, id=1, error=Managed bean with Transactional annotation and TxType of REQUIRES_NEW encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.]]]

[2021-07-23T12:12:25.409+0200] [Payara 4.1] [SEVERE] [] [com.bmw.swhrl.job.processor.scheduler.MailJobScheduler] [tid: _ThreadID=116 _ThreadName=__ejb-thread-pool4] [timeMillis: 1627035145409] [levelValue: 1000] [[
  Unknown error while checking for long running mail jobs
javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRES_NEW encountered exception during commit java.lang.NullPointerException
    at org.glassfish.cdi.transaction.TransactionalInterceptorRequiresNew.transactional(TransactionalInterceptorRequiresNew.java:122)
    ...
Caused by: java.lang.NullPointerException
    at org.glassfish.cdi.transaction.TransactionalInterceptorRequiresNew.transactional(TransactionalInterceptorRequiresNew.java:111)
    ... 51 more
]]

Here I don't understand the NullPointerException. Following the log outputs for the transaction, one can see that a new transaction (A) is created when entering checkForLongRunningJobs() and another one (B) when entering markJobAsBeingNotified(). The latter transaction B is rolled back, but then no log output occurs for transaction A.
The NullPointerException is thrown when the TransactionalInterceptorRequiresNew tries to get the status of the transaction:
if(getTransactionManager().getTransaction().getStatus() == Status.STATUS_MARKED_ROLLBACK) {
   getTransactionManager().rollback();
} else {
   getTransactionManager().commit();
}

Does anyone know why the transaction is suddenly null. Does the transaction manager returns transaction B, which has been finished?
EDIT:
When I try to, e.g., update an entity after the forEach() inside checkForLongRunningJobs(), an exception is thrown that says that a transaction is required. So after the process returns from markJobAsBeingNotified(), the transaction created for checkForLongRunningJobs() is gone.

A: I think I got it: It's the OptimisticLockException that messes thinks up.
Here is a code snippet for TransactionalInterceptorRequiresNew:
try {
    proceed = proceed(ctx);
} finally {
    try {
        TransactionManager tm = getTransactionManager();
        if (tm instanceof TransactionManagerHelper) {
           ((TransactionManagerHelper)tm).postInvokeTx(false,true);
        }
        // Exception handling for proceed method call above can set TM/TRX as setRollbackOnly
        if(getTransactionManager().getTransaction().getStatus() == Status.STATUS_MARKED_ROLLBACK) {
            getTransactionManager().rollback();
        } else {
            getTransactionManager().commit(); // <---- OptimisticLockException is thrown
        }
    } catch (Exception exception) {
        String messageString =
                "Managed bean with Transactional annotation and TxType of REQUIRES_NEW " +
                        "encountered exception during commit " +
                        exception;
        _logger.log(java.util.logging.Level.FINE, CDI_JTA_MBREQNEWCT, exception);
        throw new TransactionalException(messageString, exception);  <---- new Exception is thrown
    }
    if (suspendedTransaction != null) {
        try {
            getTransactionManager().resume(suspendedTransaction); <---- suspended transaction is not resumed
        } catch (Exception exception) {
            String messageString =
                    "Managed bean with Transactional annotation and TxType of REQUIRED " +
                            "encountered exception during resume " +
                            exception;
            _logger.log(java.util.logging.Level.FINE, CDI_JTA_MBREQNEWRT, exception);
            throw new TransactionalException(messageString, exception);
        }
    }

It is thrown when getTransactionManager().commit() is called. This exception is catched and a new TransactionalException is thrown. But the suspended transaction is not resumed, so when control returns to checkForLongRunningJobs() the transaction in this context was not resumed and a NullPointerException is thrown when the method returns and the interceptor tries to get the status of the transaction.
Is this an intended behaviour? How is the exception handling supposed to be done in case of an OptimisticLockException?


text:
Q: How Can I plot scatter plot for each category in seperate graph I am fairly new to R and What I'd like to do is to scatter plot by category. I have a data set with 5 category (Item_nbr) and 19 variables. I want to have scatter plot for each category separately not in the same graph with different color. I mean generate 5 scatter plot. My data is :
Date         Units  avgdir  Item_nbr   tmax
1/1/2012       0     0.5      1         50
1/1/2012       2     0.2      2         40
1/1/2012       3     0.1      3         60
1/1/2012       10    0.7      4         70
1/1/2012        5    0.2      5         80
1/2/2012        6    0.8      1         90
1/2/2012        11   0.8      2         40
1/2/2012        12   0.8      3         70
1/2/2012        9    0.8      4         60
1/2/2012        8    0.8      5         70
............

Now How can I 5 scatter plot to plot units column in each of them.

A: Simplest solution:
for(i in unique(data$Item_nbr))
  plot(Units ~ avgdir, data[data$Item_nbr == i, ])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display data in Liferay Search Container from different database tables : Liferay I have been using search container in liferay to display data from a table. Works well!!
here is a snippet of code:
<%
List<testapp> pendingApprovals = ActionClass.getPendingLeaveApplications();
%>
<liferay-ui:search-container delta="20" emptyResultsMessage="No Results Found">
    <liferay-ui:search-container-results total="<%= pendingApprovals.size() %>"
       results="<%= ListUtil.subList(pendingApprovals , searchContainer.getStart(), searchContainer.getEnd()) %>" />

    <liferay-ui:search-container-row keyProperty = "empId" modelVar="search"
        className="com.test.mis.portal.model.testapp">
        <liferay-ui:search-container-column-text name='Leave Duration' value = '<%=String.valueOf(search.getLeaveDuration())%>'   href="" />
    </liferay-ui:search-container-row>

    <liferay-ui:search-iterator/>
</liferay-ui:search-container>

Using the above code I display data from the testapp table based on some condition.
In the same code I would like to add a row and display data. The data for this row should come from another table. In short I want to display data using search container from two different database tables.
Is it possible to do? My requirement is such that data comes from two different tables
EDITED SECTION WITH REQUIREMENT
I have Employee table with some fields
I have another table Leave with some Fields.
empId is in Leave table which maps to Employee table.
I have a search container whicg displays the data from the Leave table only if the leave is pending
I want to display only those fields from Employee table which match with Leave table and satisfy the above condition.

A: There might be many ways, here I list a few which come to my mind readily:

*

*one way is to modify the TestAppImpl model generated through ServiceBuilder to include your dependency something like this:
public class TestAppImpl extends TestAppBaseImpl {

    private List<OtherTableData> otherTableDataList;

    private OtherTableData otherTableData;

    // if want to retrieve a list of rows
    public List<OtherTableData> getOtherTableDataList() {

        // call a custom method created in the OtherTableDataLocalService
        // testAppId variable is available to TestAppImpl
        List<OtherTableData> otherDataList = OtherTableDataLocalServiceUtil.getOtherDataListByTestAppId(testAppId);

        return otherDataList;
    }

    // if want to retrieve just one row
    public OtherTableData getOtherTableData() {

        // call a custom method created in the OtherTableDataLocalService
        // testAppId variable is available to TestAppImpl
        OtherTableData otherData = OtherTableDataLocalServiceUtil.getOtherDataByTestAppId(testAppId);

        return otherData;
    }
}

You would have to rebuild your service after the above change.
Now in the JSP you just can use:
<liferay-ui:search-container-column-text name='Other table data name' value='<%=search.getOtherTableData().getName() %>' href="" />

*Or else if you don't want to change the TestAppImpl then in the JSP you can use:
<liferay-ui:search-container-column-text>

<%
List<OtherTableData> otherDataList = OtherTableDataLocalServiceUtil.getOtherDataListByTestAppId(search.getTestAppId());

for (OtherTableData tempData : otherDataList) {
%>

    <%=tempData.getName() %>
    <%=tempData.getDescription() %>
    <%=tempData.getData() %>

<%
}
%>

</liferay-ui:search-container-column-text>

*A variation of point-2 above:
<liferay-ui:search-container-column-jsp
    name="otherDataFetch"
    path="/html/portlet/testApp/other_data.jsp"
/>

And in the other_data.jsp we can have the following code:
<%
ResultRow row = (ResultRow)request.getAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW);

TestApp search = (TestApp) row.getObject();

List<OtherTableData> otherDataList = OtherTableDataLocalServiceUtil.getOtherDataListByTestAppId(search.getTestAppId());

for (OtherTableData tempData : otherDataList) {
%>

    <%=tempData.getName() %>
    <%=tempData.getDescription() %>
    <%=tempData.getData() %>

<%
}
%>

Hope this is what you were looking for or else atleast it may give you a hint to go forward.

A: Your problem here has 2 faces:

*

*Being able to retrieve Data from tables Leave and Employee, by using the employeeId Foreign key. You don't need a custom query for that, and it's a pretty trivial task, I'm just pointing it out.

*Displaying in the search container, data that cannot be retrieved from one Data/ Table. As you can see, the 'liferay-ui:search-container-row' attribute named 'className' which ca take the valu of one Class name. About this, I can see 2 approaches:

a) Retrieve results per Leave table, and filter out by employee ID and pending status. Then in each row, use the employeeId to get back again the Employee instance (by EmployeeLocalServiceUtil. getEmployee(empId)), then get Employye attributes, like employee Name etc. This will need to get your hands dirty on the jsp file
b) Create a custom Class (say EmployeePendingLeaves), and use it as the searchContainer's model class. Don't include it in your database model. Just create a function that scans the Employee and Leave tables, and creates a  EmployeePendingLeaves instance for each result row. it should have a variable/attribute for each of the row's columns


text:
Q: Add Next/previous buttons pagination How would I add next/previous buttons to this snippet. I actually don't want the numbers.
var itemsPerPage = 4;

var $entries = $("#entries");
var $list = $entries.children("ul:first");
$list.children().eq(itemsPerPage).nextAll().andSelf().hide();

var $pagination = $("

").each(function () {
    var itemsTotal = $list.children().size();
    var pages = Math.ceil(itemsTotal / itemsPerPage);
    for (var i = 1; i <= pages; i += 1) {
        $(this).append("
" + i + "
");
    }
}).appendTo($entries);
$pagination.children("li:first").addClass("selected");
$pagination.children().click(function () {
    if ($(this).is(".selected")) {
        return;
    }
    var page = $(this).index() + 1;
    var firstToShow = (page - 1) * itemsPerPage;
    var lastToShow = page * itemsPerPage;
    $list.children().hide().slice(firstToShow, lastToShow).slideDown('slow');
    $(this).addClass("selected").siblings(".selected").removeClass("selected");
});

A: Without numbers (the page variable needs to become global in order to be able to manage which page you're currently on):
$(document).ready(function () {

    var page = 1;
    var itemsPerPage = 4;
    var prev = "<<";
    var next = ">>";

    var $entries = $("#entries");
    var $list = $entries.children("ul:first");
    $list.children().eq(itemsPerPage).nextAll().andSelf().hide();

    var $pagination = $("

").each(function () {
        var itemsTotal = $list.children().size();
        var pages = Math.ceil(itemsTotal / itemsPerPage);
        $(this).append("
" + prev + "
");
        $(this).append("
" + next + "
");
    }).appendTo($entries);
    $pagination.children("li:first").hide();
    $pagination.children().click(function () {

        if ($(this).text() == prev)
            page = page - 1;
        else if ($(this).text() == next)
            page = page + 1;

        var firstToShow = (page - 1) * itemsPerPage;
        var lastToShow = page * itemsPerPage;
        $list.children().hide().slice(firstToShow, lastToShow).slideDown('slow');
        $($(this).parent().find("li")[page]).addClass("selected").siblings(".selected").removeClass("selected");

        if (page == 1)
            $(this).parent().find("li:first").hide();
        else
            $(this).parent().find("li:first").show();
        if (page == Math.ceil($list.children().size() / itemsPerPage))
            $(this).parent().find("li:last").hide();
        else
            $(this).parent().find("li:last").show();
    });
});

With numbers (which page you're currently on can continue to be managed via the .selected class):
$(document).ready(function () {

    var itemsPerPage = 4;
    var prev = "<<";
    var next = ">>";

    var $entries = $("#entries");
    var $list = $entries.children("ul:first");
    $list.children().eq(itemsPerPage).nextAll().andSelf().hide();

    var $pagination = $("

").each(function () {
        var itemsTotal = $list.children().size();
        var pages = Math.ceil(itemsTotal / itemsPerPage);
        $(this).append("
" + prev + "
");
        for (var i = 1; i <= pages; i += 1) {
            $(this).append("
" + i + "
");
        }
        $(this).append("
" + next + "
");
    }).appendTo($entries);
    $pagination.children("li:first").hide();
    $pagination.children("li:eq(1)").addClass("selected");
    $pagination.children().click(function () {

        if ($(this).is(".selected")) { return; }

        var page;
        var selectedNode = $(this).parent().find(".selected");
        if ($(this).text() == prev)
            page = selectedNode.index() - 1;
        else if ($(this).text() == next)
            page = selectedNode.index() + 1;
        else
            page = $(this).index();

        var firstToShow = (page - 1) * itemsPerPage;
        var lastToShow = page * itemsPerPage;
        $list.children().hide().slice(firstToShow, lastToShow).slideDown('slow');
        $($(this).parent().find("li")[page]).addClass("selected").siblings(".selected").removeClass("selected");

        if (page == 1)
            $(this).parent().find("li:first").hide();
        else
            $(this).parent().find("li:first").show();
        if (page == Math.ceil($list.children().size() / itemsPerPage))
            $(this).parent().find("li:last").hide();
        else
            $(this).parent().find("li:last").show();
    });
});


text:
Q: Error Position: 27 Return: 1730 - ORA-01730: invalid number of column names specified I need help in creating a view in PeopleSoft using PeopleTools Application Designer. When running the view SQL below in ORACLE SQL Developer, it selects perfectly fine but when I create it as view in App Designer I get the error below:

Error: UM_7902_VW - SQL Error. Error Position: 27  Return: 1730 - ORA-01730: invalid number of column names specified.

Here is my sql:
SELECT A.EMPLID, B.NAME, A.ADM_APPL_NBR, C.ADMIN_FUNCTION, A.STDNT_CAR_NBR,
A.ACAD_CAREER, D.APPL_PROG_NBR, D.ADMIT_TERM, C.CHECKLIST_CD, E.DESCRSHORT,
C.CHECKLIST_STATUS, C.STATUS_DT, C.DUE_DT AS C_DUE_DT, C.COMM_COMMENTS,
C.SEQ_3C, F.CHKLST_ITEM_CD,
G.DESCR, F.ITEM_STATUS, F.STATUS_DT, F.DUE_DT AS F_DUE_DT, F.RESPONSIBLE_ID
FROM PS_ADM_APPL_DATA A
JOIN PS_PERSON_NAME B ON B.EMPLID = A.EMPLID
JOIN PS_PERSON_CHECKLST C ON C.COMMON_ID = A.EMPLID
JOIN PS_ADM_APPL_PROG D ON D.EMPLID = A.EMPLID
AND D.EMPLID = A.EMPLID
AND D.ACAD_CAREER= A.ACAD_CAREER
AND D.STDNT_CAR_NBR= A.STDNT_CAR_NBR
AND D.ADM_APPL_NBR= A.ADM_APPL_NBR
AND D.EFFDT =
(SELECT MAX(D2.EFFDT) FROM PS_ADM_APPL_PROG D2
WHERE D.EMPLID = D2.EMPLID
AND D.ACAD_CAREER = D2.ACAD_CAREER
AND D.STDNT_CAR_NBR = D2.STDNT_CAR_NBR
AND D.ADM_APPL_NBR = D2.ADM_APPL_NBR
AND D.APPL_PROG_NBR = D2.APPL_PROG_NBR
AND D2.EFFDT <= SYSDATE)
AND D.EFFSEQ =
(SELECT MAX(D3.EFFSEQ) FROM PS_ADM_APPL_PROG D3
WHERE D.EMPLID = D3.EMPLID
AND D.ACAD_CAREER = D3.ACAD_CAREER
AND D.STDNT_CAR_NBR = D3.STDNT_CAR_NBR
AND D.ADM_APPL_NBR = D3.ADM_APPL_NBR
AND D.APPL_PROG_NBR = D3.APPL_PROG_NBR
AND D.EFFDT <= D3.EFFDT)
JOIN PS_CS_CHKLST_TBL E ON E.CHECKLIST_CD = C.CHECKLIST_CD
AND E.EFFDT = (SELECT MAX(E2.EFFDT) FROM PS_CS_CHKLST_TBL E2 WHERE
E2.INSTITUTION = E.INSTITUTION AND E2.CHECKLIST_CD = E.CHECKLIST_CD)
AND E.EFF_STATUS = 'A'
JOIN PS_PERSON_CHK_ITEM  F ON F.COMMON_ID = C.COMMON_ID
AND F.SEQ_3C = C.SEQ_3C
JOIN PS_SCC_CKLSITM_TBL  G ON G.CHKLST_ITEM_CD = F.CHKLST_ITEM_CD
AND G.EFF_STATUS = 'A'
AND G.EFFDT = (SELECT MAX(G2.EFFDT) FROM PS_SCC_CKLSITM_TBL  G2 WHERE
G2.CHKLST_ITEM_CD = G.CHKLST_ITEM_CD)
JOIN PS_TERM_TBL H ON H.INSTITUTION = E.INSTITUTION
AND H.ACAD_CAREER = A.ACAD_CAREER

I would appreciate any help i can get. Thanks!

A: In App Designer when modeling the record: do you have an equal amount of fields in the record definition as you have in your select SQL?
These must match, otherwise this error appears when building in App Designer.

A: It looks as if you took create view some_view (col1, col2, ..., coln) as from one of its previous incarnations, modified the select statement you posted (added or removed some columns) and - once you stick it together - number of columns doesn't match any more.
The simplest way out of it is to let Oracle do it, i.e. don't name columns:
create view some_view as
  select <your select goes here>

Though, pay attention to column names select returns; you can't have something like
select max(some_value),  --> this - must have an alias
       my_name

because columns query returns must have their aliases.


text:
Q: Fatal error in Buddypress, "Call to undefined function bp_get_settings_slug()" I am developing a website using Buddypress and after creating the register page, when someone wants to sign up, after typing the info and press the sign up button, this error appears:

Fatal error: Call to undefined function bp_get_settings_slug() in /home/yeboah2/public_html/winderrands/wp-content/plugins/buddypress/bp-core/bp-core-filters.php on line 1072

Instead of redirecting the new user to the activation page, it doesn't, that error shows up but on the users page. I see the new user created but the user can't activate his/her account.
this is where the error generated from...
// Who is the email going to?
    $recipient = $email->get( 'to' );
    if ( $recipient ) {
        $recipient = array_shift( $recipient );
        $user_obj  = $recipient->get_user( 'search-email' );

        $tokens['recipient.email'] = $recipient->get_address();
        $tokens['recipient.name']  = $recipient->get_name();

        if ( ! $user_obj && $tokens['recipient.email'] ) {
            $user_obj = get_user_by( 'email', $tokens['recipient.email'] );
        }

        if ( $user_obj ) {
            $tokens['recipient.username'] = $user_obj->user_login;
            if ( bp_is_active( 'settings' ) && empty( $tokens['unsubscribe'] ) ) {
                $tokens['unsubscribe'] = esc_url( sprintf(
                    '%s%s/notifications/',
                    bp_core_get_user_domain( $user_obj->ID ),
                    bp_get_settings_slug()
                ) );
            }
        }
    }


text:
Q: What additional factors need to be considered when calculating voltage drop? Considering the following formulas for voltage drop, what additional factors need to be included and how can resistance be derived to thoroughly calculate theoretical voltage drop for multiple scenarios?
For example, cables run in steel conduit will need to be treated differently than cables run in 'free space' (this falls under resistance but is additional to cable resistance). The National Electric Code contains resistance & impedance data but only for specific scenarios and cable ratings.
How can one cover all necessary factors in the absence of raw data in order to produce an accurate result? Or, how can one obtain the data if it exists?

*

*DC:
Vd = \$2IRL\$

*Single phase:
Vd = \$2IZL\$

*Three phase:
Vd = \$\sqrt{3}ZL\$

A: Two additional factors that should be considered are the power factor of the load and the L/R for the cable. The effect of steel conduit is related to cable inductance. The major electrical equipment manufacturers such as ABB, Allen-Bradley, Eaton, Schneider Electric and Siemens may have helpful information. There are online voltage drop calculators. Some major electric utilities may have information. There may be handbooks published by IEEE or others. NFPA's guide to the NEC may have something.
For 50 for 60 Hz, frequency should not be an issue, but it might be for 400 Hz and would certainly be for higher frequency.
I use the following:


text:
Q: Trying to find the highest grade of a student using Loops So I am working on a homework right now, but am having trouble trying to figure out a working program
for my homework's objective. How it works is I input my class' names, their student IDs(numbers only), and their grade for a subject. The final should be to show the student's name, ID, and their highest grade in the subject.
        static void Main(string[] args)
        {
            int counter = 0;
            int number = 0;
            int bestGrade = 0;
            int studentid = 0;

                for (counter = 0; counter < 10; counter++)
                {
                    Console.WriteLine("Please enter student name: ");
                    studentname = Convert.ToString(Console.ReadLine());
                    Console.WriteLine("Please enter student ID no.: ");
                    studentid = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Please enter student's FoP Prelim Grade: ");
                    grade = Convert.ToInt32(Console.ReadLine());

                if (grade > bestGrade)
                    {
                          bestGrade = grade;
                    }
                }

            Console.WriteLine("{0}, Student ID: {1}, Has the highest grade of {3}", studentname, studentid, number);
        }

I apologize if my codes seem messy, and thank you in advance!

A: If you are just trying to print out the Name, ID, and score for the student with the highest score, you can do that by storing all of the parameters in separate arrays. E.g., names in a string array, IDs and scores in int arrays. All of them will have the same array length, and thus you can iterate through the score array to find the largest score and then print the Name & ID using that index in your Console.WriteLine statement.

A: If you want to use the easiest way, you can store the values in variables like this:
static void Main(string[] args)
{
    int bestGrade = 0;
    int bestStudentid = 0;
    string bestStudentname = "";

    for (var counter = 0; counter < 10; counter++)
    {
        Console.WriteLine("Please enter student name: ");
        var studentname = Console.ReadLine();
        Console.WriteLine("Please enter student ID no.: ");
        var studentid = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Please enter student's FoP Prelim Grade: ");
        var grade = Convert.ToInt32(Console.ReadLine());

        if (counter == 0)
        {
            bestGrade = grade;
        }
        else
        {
            if (grade > bestGrade)
            {
                bestGrade = grade;
                bestStudentid = studentid;
                bestStudentname = studentname;
            }
        }
    }

    Console.WriteLine($"{bestStudentname}, Student ID: {bestStudentid}, Has the highest grade of {bestGrade}");
}

If you want to store everything, you have to save them in a list or array and print it with the index of the largest grade.


text:
Q: Get "y" position of container on Flutter I want to get a 'y' position of container, widget, stack etc. When it's displayed on center of screen, I want to change from image (video preview image) to video file. How can I do?
I found the screen height. I calculated the screen center. I couldn't find to container place.
I created such a sample, but the item doesnt stand in the center. Possible I have made an algorithm error here?
class _DedectCenterState extends State<DedectCenter> {

Size _wSize;
int listSize = 4;
List<GlobalKey> _key = [];

ScrollController _sController;

_scrollListener() {
 print("scrolling : " + _sController.offset.toString());

 setState(() {
   getPosition();
});}

@override
void initState() {

for(int i=0; i < listSize; i++) {
  _key[i] = new GlobalKey();
}

_sController = ScrollController();

_sController.addListener(_scrollListener);
super.initState();
}

void getPosition(){

double _wCenterTop = (_wSize.height / 2) - 150.0;
double _wCenterBottom = (_wSize.height / 2) + 150.0;

print("center bottom: " + _wCenterBottom.toString());
print("center top: " + _wCenterTop.toString());

for(int i=0; i < listSize; i++) {

  //add key to your widget, which position you need to find
  RenderBox box = _key[i].currentContext.findRenderObject();
  Offset position = box.localToGlobal(Offset.zero); //this is global position
  double y = position.dy; //this is y - I think it's what you want

   print("key $i y position: " + y.toString());

  if(y < _wCenterTop && y > _wCenterBottom) print("key $i center: " + y.toString());
 }}

Widget build(BuildContext context) {
 _wSize = MediaQuery.of(context).size;

return new Scaffold(
  appBar: null,
  body: new ListView(
    controller: _sController,
  children: <Widget>[
    Row(
      children: <Widget>[
        Column(
          children: <Widget>[
            Container(
              key: _key[0],
              margin: EdgeInsets.only(top:100.0),
              height: 140.0,
                width: _wSize.width,
                child: new Image.asset('assets/images/physical/a1.png'),
            )],)],
    ),
    Row(
      children: <Widget>[
        Column(
          children: <Widget>[
            Container(
              key: _key[1],
              margin: EdgeInsets.only(top:100.0),
              height: 140.0,
              width: _wSize.width,
              child: new Image.asset('assets/images/physical/a2.png'),
  ),],)],
),
    Row(
      children: <Widget>[
        Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(top:100.0),
              key: _key[2],
              height: 140.0,
              width: _wSize.width,
                child: new Image.asset('assets/images/physical/a3.png'),
            ),],)],),
     Row(
      children: <Widget>[
        Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(top:100.0),
              key: _key[3],
              width: _wSize.width,
                height: 140.0,
                child: new Image.asset('assets/images/physical/a4.png'),
            ),
          ],
        )
      ],),]));}}

A: class _DetectCenterState extends State<DetectCenter> {

Size _wSize;
int listSize = 4;
List<GlobalKey> _key = [];

ScrollController _sController;

_scrollListener() {
 print("scrolling : " + _sController.offset.toString());

 setState(() {
   getPosition();
});}

@override
void initState() {

for(int i=0; i < listSize; i++) {
  _key.add(new GlobalKey());
}

_sController = ScrollController();

_sController.addListener(_scrollListener);
super.initState();
}

void getPosition(){

double _wCenterTop = (_wSize.height / 2) - 150.0;
double _wCenterBottom = (_wSize.height / 2) + 150.0;

print("center bottom: " + _wCenterBottom.toString());
print("center top: " + _wCenterTop.toString());

for(int i=0; i < listSize; i++) {

  //add key to your widget, which position you need to find
  RenderBox box = _key[i].currentContext.findRenderObject();
  Offset position = box.localToGlobal(Offset.zero); //this is global position
  double y = position.dy; //this is y - I think it's what you want

   print("key $i y position: " + y.toString());

  if(y < _wCenterTop && y > _wCenterBottom) print("key $i center: " + y.toString());
 }}

Widget build(BuildContext context) {
 _wSize = MediaQuery.of(context).size;

return new Scaffold(
  appBar: null,
  body: new ListView(
    controller: _sController,
  children: <Widget>[
    Row(
      children: <Widget>[
        Column(
          children: <Widget>[
            Container(
              key: _key[0],
              margin: EdgeInsets.only(top:100.0),
              height: 140.0,
                width: _wSize.width,
                child: new Image.asset('assets/images/physical/a1.png'),
            )],)],
    ),
    Row(
      children: <Widget>[
        Column(
          children: <Widget>[
            Container(
              key: _key[1],
              margin: EdgeInsets.only(top:100.0),
              height: 140.0,
              width: _wSize.width,
              child: new Image.asset('assets/images/physical/a2.png'),
  ),],)],
),
    Row(
      children: <Widget>[
        Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(top:100.0),
              key: _key[2],
              height: 140.0,
              width: _wSize.width,
                child: new Image.asset('assets/images/physical/a3.png'),
            ),],)],),
     Row(
      children: <Widget>[
        Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(top:100.0),
              key: _key[3],
              width: _wSize.width,
                height: 140.0,
                child: new Image.asset('assets/images/physical/a4.png'),
            ),
          ],
        )
      ],),]));}}

A: You can use GlobalKey for getting size or position of widget
GlobalKey key = GlobalKey(); // declare a global key

add key to your widget, whose position you need to find
Container(
   key: key,
   ...
);

get the position using a renderbox
RenderBox box = key.currentContext.findRenderObject() as RenderBox;
Offset position = box.localToGlobal(Offset.zero); //this is global position
double y = position.dy; //this is y - I think it's what you want


text:
Q: Distinguishing what domain the request comes from I have one API and two different domain. How can I check which domain host triggered api request?
Example:

*

*API: example.API.com

*Domain1: example.Domain1.com

*Domain2: example.Domain2.com

and I want to know which domain call my API?
I used C# for my code, maybe there is a ready way to solve my problem but if not then maybe some advice on how to approach the problem?
I try code.
string host = _httpContextAccessor.HttpContext?.Request.Headers.Referer.FirstOrDefault();

This code gives me the full url of the client, but I don't know if that's a good way because
this can be null.


text:
Q: Knockoutjs checkbox changed event I have some checkboxes bound to an array in my model. This works great, when you check a box the array is updated accordingly.
However when the value has changed i wish to call a method on my model to filter the results given the new values. I have tried hooking up the change event but this seems to have the values prior to the change rather than after the change.
I have illustrated my issue in a jsfiddle http://jsfiddle.net/LpKSe/ which might make this make more sense.
For completeness my code is repeated here.
JS
function SizeModel() {
    var self = this;
    self.sizes = ko.observableArray(["small", "medium", "large"]);
    self.sizes2 = ko.observableArray(["small", "medium", "large"]);
    self.getResults = function(e) {
        alert(self.sizes());
    };
    self.getResults2 = function(e) {
        alert(self.sizes2());
    };
}

$(document).ready(function() {
    sizeModel = new SizeModel();

    ko.applyBindings(sizeModel);
});

Html

Size
  <input type="checkbox" value="small"  data-bind=" checked: sizes, event:{change: getResults}"/>
  Small
  <input type="checkbox"  value="medium" data-bind=" checked: sizes, event:{change: getResults}"   />
  Medium
  <input type="checkbox"  value="large" data-bind=" checked: sizes, event:{change: getResults}"  />
  Large

Size
 <input type="checkbox" value="small"  data-bind=" checked: sizes2, event:{click: getResults2}"/>
 Small
 <input type="checkbox"  value="medium" data-bind=" checked: sizes2, event:{click: getResults2}"   />
 Medium
 <input type="checkbox"  value="large" data-bind=" checked: sizes2, event:{click: getResults2}"  />
 Large

A: You don't need the change event.  If you subscribe to the observableArray you will be notified when it changes, and be passed the updated array: http://jsfiddle.net/jearles/LpKSe/53/
function SizeModel() {
    var self = this;
    self.sizes = ko.observableArray(["3", "2", "1"]);
    self.sizes.subscribe(function(updated) {
        alert(updated);
    });
}

A: In your fiddle you're missing commas in your data-bind-s, here's a fixed example: http://jsfiddle.net/4aau4/1/
Re the problem - it might be either a KnockoutJS-related problem (i.e. it updates the observableArray after the change event is fired), or something similar to what I stucked on some time ago: Checkboxes are being checked before click handler is even called
EDIT:
What a tough Sunday, I think I'm still not awake :)
Take a look at this snippet: http://jsfiddle.net/4aau4/2/ - it looks like DOM is properly updated and it's ko.observableArray that lags behind. ($('input:checked').length says how many checkboxes are actualy checked).


text:
Q: Pass id of component in setter method to ManagedBean Well, i have a generic setter method in my ManagedBean. This generic method should add the value of a property with the component id into a "Map", see bellow my component in XHTML page:
<h:outputLabel value="Data Fechamento: " />
                    <p:calendar pattern="dd/MM/yyyy" required="true"
                        requiredMessage="A Data de Fechamento é obrigatória"
                        value="#{relatorioMB.param}">
                    </p:calendar>

Inside my ManagedBean see the setter method "setParam()":
public void setParam(Object value){
    String compId = "dataFechamento"; //here should be a generic form to get component id
    AppContext.getInstance().addAttribute(compId, value);
    }

All components in my XHTML page will call "setParam()" and ADD a new attribute to "AppContext" class. How can i do it ?
EDIT 1
I tried use getCurrentComponent in setter method, but it return the "panelGrid" (parent) and not Calendar.
UIComponent ui = UIComponent.getCurrentComponent(FacesContext.getCurrentInstance());

A: You could create a handler bean that would take all the params and put them into an array. There you could call setParam() for each element in the array using a loop.
An example of this would be:
On your page if you need information from an inputText:
<h:inputText id="id" value="#{Handler.id}"></h:inputText>

This sets the value on the handler as a field that you can work with.
Then when you have a button call an action from your handler like:
<h:commandButton action="#{Handler.doAction}" />

Then it is as simple as calling a method from the handler!
Hope this helps!


text:
Q: React renderizado de variables en componente Tengo una variable let "contador" en el componente con un valor inicial por ejemplo : "0", okey bueno, ahora en un "useEffect" renderizo un estado de cualquier variable de "useState" para mostrar un nuevo resultado. pero dentro del componente hay una condición que si se cumple la variable contador cambia a "1". Y, he hay, El problema la variable contador vuelve a "0" por que el componente se renderiza completamente para mostrar el nuevo resultado del UseState... y la variable contador ya no vale "1" si no vuelve a tener el mismo valor inicial osea "0".
Como hago para que las variables que tenga en un componente no vuelvan a tener el valor inicial al momento de un renderizado a causa de una de useState que cambio gracias un useEffect...


text:
Q: Issue with Enterprise build and UUID usage As you know Apple recently deprecated the usage of UDID. So my solution to this was

*

*Generate CFUUID

*Save it to keychain

*Re-access the keychain item there after.

This has been working good. But, for some reason we recently saw that with the installation of an enterprise build we are getting a different UUID(Which was supposed to be stored on keychain with our unique access key).
Did any one come across such situation? Here is the code to create the UUID and store it onto keychain..
+ (NSString *)registerUUIDWithKeyChain
{
CFUUIDRef udid = CFUUIDCreate(NULL);
NSString *uuidString = (NSString *) CFUUIDCreateString(NULL, udid);

KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"UniqueApp" accessGroup:nil];

NSString *userName = @"UniqueAppName";
NSString *password = uuidString;

[keychainItem setObject:userName forKey:(id)kSecAttrAccount];
[keychainItem setObject:password forKey:(id)kSecValueData];

[keychainItem release];

return uuidString;

}

+ (NSString *)userUUID
{
    KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"UniqueApp" accessGroup:nil];

//Accesing the v_data was the only way. For some reason there is a runtime issue if we try to access it though "kSecValueData"
NSString *uuid = [keychainItem.keychainItemData objectForKey:@"v_Data"];

//Check if the app is installed for the first time on the device. If YES register the UUID in to the keychain.
//Also check if it is a reinstall by accessing the previous keyChainItem with our Identifier.
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"firstRun"] intValue] == 0 && !(uuid.length > 0))
{
    uuid = [UIDevice_Additions registerUUIDWithKeyChain];

    NSLog(@"\n First Time Registered UUID is %@", uuid);

    //after stuff done
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:@"firstRun"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [keychainItem release];
    return uuid;
}

[keychainItem release];
return uuid;
}

@end

A: Okie,
After battling with the issue for a day, I found what was triggering this.

*

*Keychain's are certificate dependent

*An enterprise build is created with a different certificate

*Hence, when the code tries to access your key from an enterprise build you will not find it and hence the code generates will generate a new one.

*Solution would be to create your Keychain so that it is globally accessible. You can change the accessGroup variable in the KeyChainWrapper init method.

Good Luck!

A: you may use MAC Addres instread of UUID
- (NSString *) macaddress
{
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;

    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;

    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }

    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }

    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!\n");
        return NULL;
    }

    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }

    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);

    return outstring;
}


text:
Q: Joomla to Wordpress migration from HTML files I know there exists tools that migrates Joomla to Wordpress at database level. But my problem is I don't have access to Joomla database anymore. I only have whole Joomla! 1.0.x site's local copy which was taken 2 years ago. Is it possible to migrate that posts to my Wordpress site?
Or should I copy-paste all content to a CSV file and use an Excel importer ?

A: If you don't have the DB, then you don't have the content. All of the content on a Joomla site is stored in the DB. If you only have the Joomla files, there is nothing to copy and paste in to a CSV.

A: Not specifically for Joomla , but I have made such a thing in the past several times while migrating from some Custom Cms's
It will depend on HOW BIG is your site and how much information you need to migrate (and it's complexity) but you can always go for HTML SCRAPPING / PARSING.
As from this point , GIYBF . And your Coding skills.
One of the best one IMHO is Simple HTML DOM ,and another that many recommend but I personally never used are htmlSQL  And phpquery .
But there are also a lot of Tutorials on google ( here also and EXAMPLE TUT) explaining how to do it , and also a lot of questions here on SE and a list of options (not PHP exclusive).
The other option (which is basically the same , but without libraries) , is going or REGEX , like in this very simple example..

A: Try using this script. http://azeemkhan.info/2008/joomla2wordpress-import-wizard-v3/ Note you will need to install an old version of wordpress first and THEN upgrade your wordpress version.
There's a useful guide on this here and info on utf-8 support here.
Hope this helps


text:
Q: redirect to different pages on selected radio button using button click The following image is a pop up that details risk warnings and then asks users to choose one of the two radio buttons. When 'I agree'(Submit) button is clicked, it should redirect to different pages based on which radio button is selected. The submit button has a jquery class.Can someone help me with a jquery code to check which radio button is selected and redirect to different pages?

The html is below,

           Disclaimer and Risk Warnings

             Please select the user type that applies to you

            <asp:RadioButtonList ID="RadioButtonList1" runat="server">
            <asp:ListItem>Private Clients</asp:ListItem>
            <asp:ListItem>Professional Intermediaries</asp:ListItem>
            </asp:RadioButtonList>

                <input id="AcceptButton" type="button" value="I Agree" class="close"  style="margin-left: 215px" />

The jquery class is below
              $('.window .close').click(function (e) {

                $.cookie("CamSession1", "CAM");
                if ($('#Private Clients').is(':checked')) {
                    window.location.replace("http://stackoverflow.com");
                }
                else if ($('#Professional Intermediaries').is(':checked')) {
                    window.location.replace("http://exchange.com");
                }
                e.preventDefault();
                $('#mask').hide();
                $('.window').hide();
            });

A: Try this
Html

           Disclaimer and Risk Warnings

             Please select the user type that applies to you

            <input type="radio" name="rdotnc" id="rdo1" />Private Clients
            <input type="radio" name="rdotnc" id="rdo2"/>Professional Intermediaries
            </asp:RadioButtonList>

                <input id="AcceptButton" type="button" value="I Agree" class="close"  style="margin-left: 215px" />

Javascript
$('.window .close').click(function (e) {
                //$.cookie("CamSession1", "CAM");
                if ($('#rdo1').is(':checked')) {
                    window.location.replace("http://www.stackoverflow.com");
                }
                else if ($('#rdo2').is(':checked')) {
                    window.location.replace("http://www.exchange.com");
                }
                $('#mask').hide();
                $('.window').hide();
            });

Check fiddle here


text:
Q: Elasticsearch 5 | filter nested object and nested aggregation count elasticsearch 5.2
I want to filter my items by the nested object state.id = 101 and an aggregation count for all the items by state.id. There are items with the state ids 101, 102 and 103.
The aggregation count is now limited to state.id 101. I want the only get the items with state.id = 101 and the aggregation count for all state ids.
How can i do this?
GET index/items/_search
{
  "query": {
        "nested" : {
            "path" : "state",
            "query": {
              "bool": {
                "filter": {
                  "term": { "state.id": 101 }
                }
              }
            }
        }
  },
     "aggs" : {
        "state" : {
            "nested" : {
                "path" : "state"
            },
            "aggs" : {
                "count" : { "terms" : { "field" : "state.id" } }
            }
        }
    }
}

A: You need to use post_filter instead of query: (Oh and use POST instead of GET when sending a payload)
POST index/items/_search
{
   "post_filter": {                         <--- change this
      "nested": {
         "path": "state",
         "query": {
            "bool": {
               "filter": {
                  "term": {
                     "state.id": 101
                  }
               }
            }
         }
      }
   },
   "aggs": {
      "state": {
         "nested": {
            "path": "state"
         },
         "aggs": {
            "count": {
               "terms": {
                  "field": "state.id"
               }
            }
         }
      }
   }
}

If you want to further narrow the nested aggregation, you can also add a filter:
POST index/items/_search
{
   "post_filter": {
      "nested": {
         "path": "state",
         "query": {
            "bool": {
               "filter": {
                  "term": {
                     "state.id": 101
                  }
               }
            }
         }
      }
   },
   "aggs": {
      "narrow": {
         "filter": {
            "nested": {
               "path": "state",
               "query": {
                  "bool": {
                     "filter": {
                        "term": {
                           "state.id": 101
                        }
                     }
                  }
               }
            }
         },
         "aggs": {
            "state": {
               "nested": {
                  "path": "state"
               },
               "aggs": {
                  "count": {
                     "terms": {
                        "field": "state.id"
                     }
                  }
               }
            }
         }
      }
   }
}


text:
Q: Navbar using Bootstrap not EXPANDING Hello all I've looked everywhere and can't seem to find the answer. My navbar is not able to expand at all listed where projects is.
http://www.wonsahm.com
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">

<link href="bootstrap.css" rel ="stylesheet">
<link href="bootstrap.js" rel="stylesheet">
<link rel="stylesheet" href="bootstrap.min.js">

<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<link href="navbar.css" rel="stylesheet">

About Me

      Projects

Action

Another action

Something else here

Separated link

One more separated link

A: You don't have Jquery included on the page. Use Google Chrome tools (F12) and read the console errors.

Uncaught Error: Bootstrap's JavaScript requires jQuery

This needs including before you include bootstrap.min.js. There might be more problems after this one is resolved but this will certainly help you make head way.
It also appears that navbar.css is missing.


text:
Q: Bind slices of observable array to different elements I have a knockout observable array having a few objects in it.
Now each of the object has a property called group. I would like to know if we can bind the items of this array to different elements depending on their groups.
For example, An observable array has 5 items in it. In bracket I'm showing their groups.

*

*Item1 (group1)

*Item2 (group1)

*Item3 (group2)

*Item4 (group2)

*Item5 (group3)
We can bind all 5 items to a table or UL but what I want is to be able to have 3 different tables/UL because 3 distinct groups are identified as group1, group2 and group3.
So, first table/UL should bind Item1 & Item2.
Second table/ul should bind Item3 & Item4.
Third table/UL should bind Item5.
Considering the array populates dynamically so we can not keep the fixed number of tables/UL elements to bind.
Thanks!

A: Say your items look like this:
var Item = function(name, group) {
  this.name = name;
  this.group = group;
}

And they're in an observable array:
var items = ko.observableArray([
  new Item("Item1", "group1"),
  new Item(/* ... */),
  /* et cetera */
]);

To create an object with all items sorted by group, create a computed:
var itemsByGroup = ko.computed(function() {
  return items().reduce(function(result, item) {
    if (!result[item.group]) {
      result[item.group] = [];
    }

    result[item.group].push(item);

    return result;
  }, {});
});

You need to create a computed 2-dimensional array to use the knockout foreach binding.
var itemGroups = ko.computed(function() {
  return Object.keys(itemGroups())
    .map(function(key) { return itemGroups()[key]});
});

Now, you can create your lists using HTML markup like so:

    </ul

If you want to add group labels and such, you can return an object with a label property and the items in an items array. Experiment with it using the fiddle below:

var Item = function(name, group) {
  this.name = name;
  this.group = group;
}

var items = ko.observableArray([
  new Item("1", "A"),
  new Item("2", "A"),
  new Item("3", "B"),
  new Item("4", "C")
]);

var itemsByGroup = ko.computed(function() {
  return items().reduce(function(result, item) {
    if (!result[item.group]) {
      result[item.group] = [];
    }

    result[item.group].push(item);

    return result;
  }, {});
});

var groupedArray = ko.computed(function() {
  var grouped = itemsByGroup();
  return Object.keys(grouped)
    .map(function(key) {
      return grouped[key]
    });
});

ko.applyBindings({
  groupedArray: groupedArray
});

        </ul


text:
Q: R programming code correction When i run the code below this is the error I get, "Error in if (mm[[j]] == mm[[j + 1]]) { :
  missing value where TRUE/FALSE needed "
Any ideas on how to fix this
m <- matrix(c(1:5,NA,7,7,NA),
nrow=3,ncol=3,byrow=T)
print(m)
for ( i in 1:dim(m)[[1]] ) {
mm <- sort(m[i,],na.last=c(NA,NA,T)[[i]])
for ( j in 1:(length(mm)-1) ) {
if ( mm[[j]]==mm[[j+1]] ) {
cat(i,j,mm[[j]],fill=T)
}
}
}

A: Try wrapping isTRUE() around your if-condition:
for ( i in 1:dim(m)[[1]] ) {
  mm <- sort(m[i,],na.last=c(NA,NA,T)[[i]])
  for ( j in 1:(length(mm)-1) ) {
    if ( isTRUE(mm[[j]]==mm[[j+1]]) ) {
      cat(i,j,mm[[j]],fill=T)
    }
  }
}

Output:
3 1 7


text:
Q: Application backgrounding in Xamarin.Mac How do I achieve Application backgrounding in Xamarin.Mac. I want something that work similar as android services:

Android Services - A Service is an application component that can perform long-running operations in the background, and it does not
  provide a user interface. Another application component can start a
  service, and it continues to run in the background even if the user
  switches to another application. Additionally, a component can bind to
  a service to interact with it and even perform interprocess
  communication (IPC). For example, a service can handle network
  transactions, play music, perform file I/O, or interact with a content
  provider, all from the background. ~Android.com

Thanks in Advance.

A: The proper way is to install your application as a LaunchAgent (instance-per-user) or a LaunchDaemon (instance-per-machine) using launchd, and the 'application type' setting (within "Xamarin Studio" or "Visual Studio for Mac" project options dialog) should be set to "Executable" instead of "Executable with a UI" (or similar.)
As a "LaunchAgent" you have the option of interacting with the desktop, and your code runs under the context of each logged in user instead of a system process account. You will not see a tile in the 'dock bar' (unless you allocate an NSApp), and you only see a 'status menu bar' if you explicitly call a Mac API to make it happen. Additionally, launchd will periodically check for and launch your process, ensuring that it is always running.) There is no requirement that you use any Cocoa/Mac APIs to implement an agent/daemon, you could run any console app under launchd and the above would still remain true.
Integration with launchd is non-trivial, but well documented for the macOS platform, and it applies equally to Xamarin.Mac-developed applications as it does any other platform/tool-chain (Java, C++, Obj-C, SWift, ...), if I had to guess learning how to use launchd is a 2-4 hour investment for most devs.
Because Xamarin.Mac does not itself have explicit support for launchd (and IMO should not) you will also be tasked with calling launchctl yourself. As a seasoned .NET developer I find that wrapping all of the 'launchctl ugliness' inside an "installer class" works well (then you only need to run installutil to install/uninstall your agent/service/application.) These installer classes can also be implemented to work on Windows and Linux, meaning cross-platform installs only ever require the use of installutil.
Separately, you can set particular properties in your app bundle Info.plist, but this is not necessary. However, most will find editing the existing plist easier than integrating with launchd. It's worth noting that one behavioral difference is that editing the plist to include either LSBackgroundOnly or LSUIElement doesn't guarantee your application is running, but using launchctl will.
HTH
References

*

*Creating Launch Daemons and Agents Article on Apple.com

*How to Create a Background Running Cocoa Application on StackOverflow.com

*launchd Article on Wikipedia.org

*launchctl Manual Page on Apple.com

*LSBackgroundOnly Reference on Apple.com

*LSUIElement Reference on Apple.com

*installutil Reference on Microsoft.com (applies to Mono/Xamarin Linux/Mac platforms as well, though Windows uses its own 'Service Control Manager (SCM)' APIs instead of launchctl.)


text:
Q: nest queries and pass their results as alias to SUM So, I'm running two queries that returns me the X amount of items per month through a year.
the 1st query gives me the following result

the 'no column name' would be the months, so I have no data in august, november and december.
The second query, gives me the following

only August and Setpember has data.
What I'm trying to figure out is how can I sum both tables to get the 100% value, then define each % (corretivas x preventivas).
In my research, I assume I have to nest the queries, but I just can't reach the logic to get me near the wanted result.
this is my queries so far
select month(workOrderDate), COUNT(*) as preventivas from WorkOrder WHERE
workOrderDescription = 'preventiva'
AND YEAR(workOrderDate) = 2018
AND lastUpdateData IS NOT NULL
AND WorkType = '02'
group BY MONTH(workOrderDate)
ORDER BY MONTH(workOrderDate)

select MONTH(workOrderDate), COUNT(*) AS corretivas from WorkOrder WHERE
YEAR(workOrderDate) = 2018
AND workOrderDescription = 'CORRETIVA'
AND lastUpdateData IS NOT NULL
GROUP BY MONTH(workOrderDate)
ORDER BY MONTH(workOrderDate)

The expected result would be

and so on
Would anybody helpe me with this?

A: You want conditional aggregation  :
SELECT MONTH(wo.workOrderDate), COUNT(*) AS total,
       (SUM(CASE WHEN wo.WorkType = '02' AND wo.orkOrderDescription = 'preventiva' THEN 1 ELSE 0 END) * 1.0 / COUNT(*)) * 100 AS preventiva,
       (SUM(CASE WHEN wo.orkOrderDescription = 'CORRETIVA' THEN 1 ELSE 0 END) * 1.0 / COUNT(*)) * 100 AS CORRETIVA
FROM WorkOrder wo
WHERE YEAR(wo.workOrderDate) = 2018 AND wo.lastUpdateData IS NOT NULL
GROUP BY MONTH(wo.workOrderDate);


text:
Q: Create relationship table for one-row relationships? I have the following structure:
-- Table Users ---
-  User1
-  User2
-  User3

-- Table Roles ---
-  Role1
-  Role2
-  Role3
-  Role4

Every user has to have one row, not more or less. Should i create a new table, eg. `user_roles" and store the users role in there, like:
-- Table user_roles --
-  user_id = User1     role_id = Role2
-  user_id = User2     role_id = Role1
-  user_id = User3     role_id = Role4

Or, should I store the users role in the Users table? Since there will always only be one role for each user, I see no reason why not to keep it in the Users table. Am I thinking correctly or should it be in a separate table? Very simple question, but I've wondered for long. In the past I have kept the "key" in the Users table.

A: To enforce that every use has to have exactly one role, you should add a role_id to the users table, make it not null and reference the roles table
create table roles
(
  id integer primary key,
  role_name varchar(50) not null
);

create table users
(
   id integer not null primary key,
   username varchar(50) not null,
   role_id integer not null,
   ... other columns ...
);
alter table users
   add constraint fk_users_rol
   foreign key (role_id) references roles(id);

A: If the specification will not change, you can store the RoleID in the user table. For the sake of expansion, in case you want to support more roles per user in future, you may have the UserRoles table. For now:
Users(UserID, UserName, ..... RoleID);


text:
Q: Double chars are inserted in my input field when handling keypress event I am trying to update my value Attribute in input Element of type text through typing.But I got double chars in the input text the first time I press a key. Why?
html code
<input type="text" name="" value="" id="click">

JavaScript code
const input= document.getElementById('click');
var char= '';
input.addEventListener('keypress',function(e){
    var x= e.which || e.keyCode;
    char+= String.fromCharCode(x);
    input.setAttribute('value',char);
});

const input= document.getElementById('click');
var char= '';
input.addEventListener('keypress',function(e){
    var x= e.which || e.keyCode;
    char+= String.fromCharCode(x);
    input.setAttribute('value',char);
});
<input type="text" name="" value="" id="click">

A: keypress is causing this to happen. It's firing after the character has already been initially added to the input box. You can fix this by using e.preventDefault()
Note this will have a strange affect on the cursor since it's not being set to after the current character any longer and you're simply appending data to the input box. The cursor will remain static.

const input= document.getElementById('click');
var char= '';
input.addEventListener('keypress',function(e){
    e.preventDefault();
    var x= e.which || e.keyCode;
    char += String.fromCharCode(x);
    input.setAttribute('value',char);

});
<input type="text" name="" value="" id="click">

Alternatively and more preferably, you can use the new input event listener, which fires immediately on box input:

const input= document.getElementById('click');
var char= '';
input.addEventListener('input',function(e){
    var x= e.which || e.keyCode;
    char += String.fromCharCode(x);
    input.setAttribute('value',char);

});
<input type="text" name="" value="" id="click">


text:
Q: vsts extension making database calls I'm investigating building a VSTS Extension that can call an external SQL database passing a task ID, display the results in a task, and pass back an update if needed back to the SQL database. I have been looking for a while for a microsoft help doc that will answer this question but have not had any luck. Is it possible to interact with an external SQL database using a VSTS Extension? If so, is there any documentation out there that I missed?

A: There isn't the built-in api to do with database in VSTS extension, the VSTS extension uses Data storage to store data.
Anyway, you just need to do it directly with some libraries, for example:
var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close;

Related thread: How to connect to SQL Server database from JavaScript in the browser?
The better way is that you can build a API project (e.g. web api) to do with database (need to be accessible from internet), then you can call that API with necessary data in you VSTS extension.


text:
Q: Average Age from DOB Field - MySQL / PHP I wasn't sure how I could calculate the average age of my contacts who all exist in a mysql table with a DOB date field such as YYYY-MM-DD.
Is there a way to do with with a MySQL call (please note I am using cakephp but that shouldn't be an issue)
Thanks

A: You can determine age by using DATEDIFF():
DATEDIFF(TO_DAYS(NOW()), TO_DAYS(DOB))

The average is found in MySQL using AVG():
AVG(Column)

So combine those:
SELECT AVG(DATEDIFF(TO_DAYS(NOW()), TO_DAYS(DOB))) as `Average` FROM Contacts;

Note that this returns the average age in days, not years. To obtain years you can average the years part of each date:
SELECT AVG(DATEDIFF(YEAR(NOW()), YEAR(DOB))) as `Average` FROM Contacts;

Or as @TimDearborn suggested, divide the day average by 365.242199.

A: Here is your answer
SELECT AVG(TIMESTAMPDIFF(YEAR, DOB, CURDATE())) AS `Average` FROM Contacts WHERE DOB IS NOT NULL;

A: You don't really need to do a datediff if you're using Bailey Parker's second method.  Just subtract the years and take the avg.
SELECT AVG(YEAR(NOW())-YEAR(dob)) as `Average` FROM users;


text:
Q: How to split merged cell in BIRT I am trying to split a merged cell in BIRT Designer but there is no option to split.
I found that, this doesn't have solution at https://bugs.eclipse.org/bugs/show_bug.cgi?id=166197
Please help me to solve this.
Thanks,
Jayanth.

A: This works as expected. Perhaps you made the same mistake as the poster in the mentioned link. You have to select the cell, not its content.
Once you have the cell selected, right-click and you can choose "Split Cell" from the context menu.
To select the cell, the easiest way is to use the breadcrumb bar (which is disabled by default, you can enable it with the mysterious symbol to the right of the zoom level list-box), and right-click the cell in the breadcrumb bar.
Another option is to move the cell's content somewhere else (temporarily) in order to empty the cell. Then split the cell, and move the content back into it.
Note 1: One would expect that it's possible to split the cell from the context menu in the Outline view, but no...
Note 2: You cannot modify the structure of a report item referenced from a library.


text:
Q: Javascript item method of Select HTML:
<select id="mySelect">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
</select>

Javascript:
var x=document.getElementById("mySelect");
alert(x.options.item(1).text);
alert(x.options[1].text);

Here we are getting the text of option.
What is the difference between
x.options.item(1).text

and
x.options[1].text

as both are yielding same result.

A: SELECT element has a collection of options.
When you do options[i] you're actually accessing collection directly (e.g. array).
When you do options.item(i) you're accessing same thing but through API.
Second way is recommended because if underlying implementation of collection changes you might get exceptions. That's why there is an API.
API spec:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionsCollection

A: The options collection returns a collection of all the options in a dropdown list.
x.options.item(index)       //Returns the element from the collection with the specified index

x.options[index]            // will returns element from collection with specified collection .index is an integer specifies the element to retrieve (starts at 0)

So .text will return the same in both the cases
Here is a list of methods of collection Select options Collection
[index]                 An integer that specifies the element to retrieve (starts at 0)
[add(element[,index])]  Adds an option element into the collection at the specified index. If no index is specified, it inserts the option element at the end of the collection
item(index)             Returns the element from the collection with the specified index
namedItem(name)         Returns the element from the collection with the specified name (name or id attribute)
remove(index)           Removes the element with the specified index from the collection

A: The options object here is actually an OptionsCollection instance which inherits from HTMLCollection; as such it exposes a few properties and methods, such as:

*

*length

*item(index)

*namedItem(name)
Besides that it can also be dereferenced as an array, i.e. options[i] is the same as options.item(i). The same trick can be applied to methods like getElementsByClassName() and friends.


text:
Q: How can I find and concatenate files that have varying characters but whose root is listed in a text file? So I'm trying to concatenate files that have slightly varying prefixes and suffixes but have the same root. But I want to do it for all the "roots" listed in a text file.
So far I have been able to do this but by one root at a time which works fine:
#works
find directory/ -type f -name '*ftsW*.fna' -exec cat {} \; > new_directory/ftsW.fna

However, when I try to loop through all the roots listed in the 'roots.txt' file, i get empty files of all the roots listed in the txt file.
#outputs empty files

filename='roots.txt'
filenames=`cat $filename`
for a in $filenames
do find directory/ -type f -name '*$a*.fna' -exec cat {} \; > new_directory/$a.fna
done

Does anyone know I can fix this code? Thank you!

A: When you're running in the loop you write the first file to your destination, then you overwrite your dest with the next file, and then overwrite it again, etc.   So you only end up with your last file.   Try this:
cat $(find directory/ -type f -name '*$a*.fna') > new_directory/$a.fna

Which will cat all the files at once.


text:
Q: Display messages in my custom theme, Drupal 7 I just made a theme for my user pass page like this article:
create custom theme
But there is no messages to displayed any more in my user-password.tpl.php
I print $messages in my theme but not displayed.

A: Maybe I understand this wrong, but I guess you mean the System Messages e.g. "Edited Node successfully"?
I print messages above my main-content in my page.tpl.php:
<?php if ($messages): ?>

        <?php print $messages; ?>

<?php endif; ?>


text:
Q: Problems accessing type of Base class within a typescript mix-in I have some ES6 mixin code which looks like:
function DeserializableMixin(Base) {
  return class extends Base {
    deserialize(structure) {
      Object.assign(this, JSON.parse(JSON.stringify(structure)));
      return this;
    }
    clone() {
      const c = this.constructor;
      return new c().deserialize(this);
    }
  };
}

and this works with existing code like this:
class FooEntity {}

class DeFoo extends DeserializableMixin(FooEntity) {}

const df = new DeFoo();
const x = df.deserialize({ bar: 43 });
const y = df.clone();

I would like to port this mixin to TS and based on the docs at: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-mix-in-classes it seemed reasonably straightforward.
I would like deserialize to be somewhat type safe and take a Partial<Base> rather thanPartial<any> or Partial<{}> so that the IDE/compiler can pickup deserializations which do not match the shape of the Base class.
likewise I don't want to use Partial<this> as this causes functions on the derived class (e.g. clone() and deserialize()) to be allowed as a valid part of the structure.
What I want to write is this:
export type Constructor<T> = new(...args : any[]) => T;

export function DeserializableMixin<T extends Constructor<{}>>(Base : T) {
  return class extends Base {
    deserialize(structure : Partial<Base> ) {
      Object.assign(this, JSON.parse(JSON.stringify(structure)));

      return this;
    }

    clone() {
      const c = this.constructor as Constructor<this>;

      return new c().deserialize(this as Base);
    }
  };
}

But typescript does not allow me to use Base as a class type, even though it does allow me to use it in the extends clause.
The only way I have come close to it is by doing the following:
export function DeserializableMixin<P, T extends Constructor<{}>>(Base : T, proto : P) {
  return class extends Base {
    deserialize(structure : Partial<P> ) {
      Object.assign(this, JSON.parse(JSON.stringify(structure)));

      return this;
    }

    clone() {
      const c = this.constructor as Constructor<this>;

      return new c().deserialize(this as any as P);
    }
  };
}

which requires me to use the mixin like this:
class Foo {
  bar : number;
  baz : string;
};

class DeFoo extends DeserializableMixin(Foo, Foo.prototype) {}

const df = new DeFoo();
const x = df.deserialize({bar: 43})
const y = df.clone();

which does the job but seems a bit stupid to me. Is there a less convoluted way of doing this?
EDIT
I have subsequently found that even this is not enough. It is fine if the use of the mix-in remains in the same module as which the mix-in is defined, but if I export type definitions for this and use it in another module things such as:
const df = new DeFoo();
const df2 = df.clone();

do not work as intended as df2 will have an any type. Note that if it is done in the same module (the module the mix-in is defined) df2 will have the type DeFoo.
In order to work around this I have added yet more seemingly redundant code.
export function DeserializableMixin<P, T extends Constructor<{}>>(Base : T, proto : P) {
  return class extends Base {
    deserialize<E>(this : E, structure : Partial<P> ) : E {
      Object.assign(this, JSON.parse(JSON.stringify(structure)));

      return this;
    }

    clone<E>(this : E) : E {
      const c = this.constructor as any;

      return new c().deserialize(this as any as P);
    }
  };
}


text:
Q: snmpwalk command did return different number of variable bindings I run the command below in my linux environment.
snmpwalk -t 10000000 -v2c -cpublic localhost:161 1 >abc.txt
The problem is i always get different number of variable bindings!! What is happening? Any solution?


text:
Q: Should a sprint planning meeting be held before the previous sprint has ended? I am currently working in a team where we are doing the planning aprox halfway through the previous sprint.
We start a 2 week sprint on a Monday, and the following Tuesday (1 week later) we have a planning meeting for the following sprint to start in a weeks time. We also conduct a weekly backlog grooming meeting where we prepare stories for planning.

*

*Is this normal? My scrum master says this is a common method and widely used.

*Is there any source of information for the case of holding the planning during the previous sprint?

*Does anyone have an opinion on the pros/cons of doing this?

I agree that it seems unusual, but I need some good reasons for doing it. I can't bring this up only knowing the negatives. Is there any justification for doing the planning before the end of a sprint?

A:
Is this normal? My scrum master says this is a common method and widely used.

No. He is incorrect. One sprint ends with a sprint review meeting. Then, the next sprint begins with a sprint planning meeting. Another meeting that happens during a sprint is a Product Backlog Refinement (aka Grooming) meeting.

Is there any source of information for the case of holding the planning during the previous sprint?

There appears to be no source of such information, other than your Scrum Master.

Does anyone have an opinion on the pros/cons of doing this?

Yes. It wastes time for at least two reasons:

*

*It takes up time, during the sprint, when other work (such as perhaps backlog refinement) could be done.

*The planning that is accomplished in that meeting may need to be re-planned at the beginning of the next sprint.

...I need some pros, some good reasons for doing it. I can't bring this up only knowing the negatives.

Really, there are only negatives.

A: That approach is quite unusual for several reasons.
Firstly, you don't know how the remainder of the sprint will go. It is quite possible some work will be incomplete and may need to be considered for the next sprint.
Secondly, the whole idea of Scrum is to get feedback from the stakeholders at the end of sprint showcase and feed this in to planning. If you have already decided on the content of the next sprint it implies you do not care what the stakeholders say.
I coached a team recently that had been doing planning 2-3 days before the end of the sprint. They had encountered numerous problems including having to carry over unfinished work and being forced to re-plan after the showcase. After we moved the planning sessions to the beginning of the sprint these problems went away.

A: In order to prevent long planning meetings I would suggest doing timeboxed "Backlog refinement meetings" during the sprint. Depending on the Sprint lenght and the uncertainty of the product backlog I would schedule one short session each week, unless you are doing one week Sprints.
The actual sprint commitment still only happens in the Sprint planning meeting, which starts after the previous Sprint ends.
But having the extra "estimation and planning" meetings during the Sprint will make the life of PO easier, the backlog more clear and the planning meetings shorter. Although not part of the official Scrum I can advocate for doing "Backlog refinement meetings" during each Sprint.


text:
Q: background color change material design Using material design lite i am trying to make the menu's background black and the front white.
But the background color is only becoming black just for those place where the menu have content, other places it is default color !
Have A LOOK HERE ---
https://codepen.io/anon/pen/pbKVko

        Chris

            Dashboard
            Cost & Sales
            Budget
            Analysis

How can i make the whole menu's background black and the text color white !
this is my css --
      #left_menu{
          background-color: black;
          color: white;
      }

anyone knows how to solve this issue !

A: This should do.
.mdl-layout__drawer {
    background: #000;
    color: #fff; // for the header of that menu
}
.mdl-layout__drawer .mdl-navigation .mdl-navigation__link:hover {
   color: #fff; // links
}


text:
Q: Linphone Push Notification I am using linphone open source to make a call in my application.
I met a problem while using linphone service.
The situation is that UserA calls UserB while UserB is not using the application. So, UserB does not receive this call and the server returns call error to UserA.
Bit, I want the UserB to still receive a call from UserA anyway.
Please help me resolve this problem.

A: Solution: instruct UserB to install and use the Linphone application.


text:
Q: node.js: serve static web, match request url //*/web/ to file system /web/ I use node.js in a simple way to serve a static web.
...
app.use(express.static('./build'));
http.createServer(app).listen(port, ipaddress);
...

This serves the files 1:1 (with index.html as default resource), e.g.
//server/a.html -> ./build/a.html
//server/bbb/x.html -> ./build/bbb/x.html
//server/ccc/ -> ./build/index.html

But now, I need to be able to remove 'one level' of the request url, but it shall serve still the same web, e.g.
//server/aaaa/a.html -> ./build/a.html
//server/bbbb/a.html -> ./build/a.html
//server/xxxx/bbb/x.html -> ./build/bbb/x.html
//server/yyy/ccc/ -> ./build/ccc/index.html

So I need a wildcard matching in the request url. I tried this:
app.use('/\*', express.static('./build'));
http.createServer(app).listen(port, ipaddress);

But with no luck. No more page is accessible. What is wrong?
[Edited to show that the server should serve index.html as default resource]

A: Depending on your application, you might put express.static() on separate Router instances that are mounted on your app. For example:
var routerA = new express.Router();
// You could also reuse the same static file handler since they
// are all using the same root path
routerA.use(express.static('./build'));
// and other `routerA` route handlers ...

var routerB = new express.Router();
routerB.use(express.static('./build'));
// and other `routerB` route handlers ...

// etc.

However if you don't have your application broken up like this already, you could also specify multiple routes like:
app.use(['aaaa', 'bbbb', 'xxxx'], express.static('./build'));

Or if nothing else, you could just use a custom middleware, calling the static file handler manually (although this is kind of a hack, as it was what separate, mounted Routers were designed to help solve):
var staticHandler = express.static('./build');
app.use(function(req, res, next) {
  var m = /^\/[^/]+(\/.+)$/.exec(req.url);
  if (m) {
    // Temporarily override the `req.url` so that the path
    // concatenation will happen correctly
    var oldUrl = req.url;
    req.url = m[1];
    staticHandler(req, res, function(err) {
      // Reverting the to the original `req.url` allows
      // route handlers to match the request if a file
      // was not found
      req.url = oldUrl;
      next(err);
    });
  } else
    next();
});

app.get('/aaa/foo', function(req, res) {
  res.end('hello from /aaa/foo!');
});

A: My final solution is:
// serve all files from ./web directory regardless of first element in url
app.get('/:leveltoremove/*', function(req, res) {
  var path = req.params[0] ? req.params[0] : 'index.html';
  res.sendfile(path, {root: './web'});
});

http.createServer(app).listen(port, ipaddress);


text:
Q: What is the reason I can't connect a Seagate Personal Cloud device to a Switch I have a Seagate Personal Cloud, a consumer NAS device with minimal instructions or documentation which expects to be connected via an ethernet cable to a wireless router so that it can be found on a local network.
I don't have access to a router but I do have a switch. However, I can't find the device on the other computers attached to the switch and, asking Seagate's support people online, I'm told that it isn't possible to do what I want.
My question (as a networking non-professional) is: why not? What is the difference, as far as the NAS is concerned, between being attached to a router and being attached to a switch?
The switch is a 3com OfficeConnect dual speed switch, and its status lights report traffic of some sort to and from the port it's connected to. In other respects it seems to be working: e.g. I can print to a network printer attached to it.


text:
Q: Dice rolling sum and 7-card probability questions

*

*We are playing with fair fifty-sided dice numbered 1–50. Suppose we roll three of them. What is the probability that the sum of the numbers on the dice is 37?

*What is the probability that a seven-card poker hand contains a seven-card straight?

For the first question, I am not sure of an easy way to calculate this other than to enumerate all possibilities. Is there a simpler solution?
For the second question, my answer was $\frac{6\cdot{4 \choose 1}^7}{52 \choose 7}$, since out of all possible combinations, for any straight, we can choose any of the 4 suited cards, and there are 6 possible straights (beginning with A, 1, 2 ... or 6). However, the answer has $\frac{8\cdot{4 \choose 1}^7}{52 \choose 7}$, and I'm not sure why.

A: For 1) because 37 is less than 50 , we can just use stars and bars.
The number of sequences of $k$ natural numbers that sum to $n$ is given by
$$N = \binom{n-1}{k-1}$$
so $$P = \frac{\binom{36}{2}}{50^3}$$

A: As to the first part, you can do it with generating functions.  The number of ways to get a sum of $37$ is the coefficient of $x^{37}$ in $$(x+x^2+x^3+\cdots+x^{50})^3=\left(\frac{x-x^{51}}{1-x}\right)^3=x^3(1-x^{50})^3(1-x)^{-3}$$  Now, since we are only interested in the coefficient of $x^{37}$ we can ignore the middle term in the last expression, and we see that the answer is the coefficient of $x^{34}$ in the power series for $(1-x)^{-3}$, or $$\frac{(-3)(-4)\cdots(-36)}{34!}=\frac{36!}{2!34!}=\frac{36\cdot35}2=\boxed{630}$$


text:
Q: A question about a positive continuous function
Suppose $f \in C[0, 1]$ satisfies following properties:
1)$f(0) = f(1) = 0$
2)$\forall x \in (0, 1)$ $f(x) > 0$
Do there always exist such $c$ and $d$ in $(0, 1)$ that $f(c) = f(d) = d - c$?

I  have tried to consider the function $g(x) = \max\{t \in [0, 1]|f(t) = f(x)\} - x - f(x)$ which is strictly positive in $0$ and negative in the point of largest point of maximum. Thus if that function were always continuous, our problem would have been solved. Unfortunately, it isn't.

A: This is a particular case of Toeplitz's conjecture, which if the argument below is correct, is way simpler than the cases in which the conjecture is known to be true. the conjecture asks for the existence of a non-degenerate square inscribed in any simple closed curve of the plane.
In our case the simple closed curve is formed by the graph of the function $f$ and the segment $[0,1]\times \{0\}$.

Let's extend $f(x)$ to a function on $\mathbb{R}$ by defining it to be $0$ outside of $[0,1]$.
Define $g(x)=f(x+f(x))-f(x)$.
The function $g$ is continuous, since it is a composition of continuous functions.
It satisfies that $g(0)=f(f(0))-f(0)=0$ and $g(1)=f(1+f(1))-f(1)=f(1)-f(1)=0$.
Observe that also, if $x\in (0,1)$ and $x+f(x)\notin[0,1]$, then $g(x)\neq0$.
Therefore, if for some $x\in(0,1)$ we have $g(x)=0$, then $x+f(x)\in(0,1)$ and the points $c=x, d=x+f(x)$ satisfy that $f(c)=f(d)=d-c$.

To get a contradiction, assume that $g(x)>0$ on $(0,1)$.
Let $x_0\in(0,1)$ be the supremum of the points in which $f$ attains its maximum. Note that the set where $f$ attains its maximum is compact and contained in $(0,1)$.
Then $g(x_0)>0$ implies that $f(x_0+f(x_0))>f(x_0)>0$. Therefore, $x_0+f(x_0)\in(0,1)$ and $f$ attains on it a larger value than that on $x_0$. This is a contradiction. Therefore we cannot have $g(x)>0$ for $x\in(0,1)$.

Assume now that $g(x)<0$ for $x\in (0,1)$.
Pick any point $x_0\in (0,1)$. And without loss of generality we can assume that $x_0$ is the infimum of $\{x\in[0,1]:\ f(x)=f(x_0)\}\subset (0,1)$. By assumption $g(x_0)<0$ and therefore $f(x_0+f(x_0))<f(x_0)$.
Consider the set $K_0=\{x\in[0,1]:\ x+f(x)\geq x_0\}$. This set is non-empty (contains $x_0$) compact, contained in $(0,1)$. Observe that it must contain some points $<x_0$, otherwise it will force $f(x_0)=0$, which is not allowed.
Let $x_1=\inf K_0<x_0$. Then $x_1+f(x_1)=x_0$. Since $g(x_1)<0$ we have that $f(x_0)=f(x_1+f(x_1))<f(x_1)$. But then, by continuity, there must be a point in $(0,x_1)$ where $f$ takes the value $f(x_0)$. This is a contradiction with the choice of $x_0$.

Since assuming $g(x)>0$ on $(0,1)$ and assuming $g(x)<0$ on $(0,1)$ are both impossible, we must have $g(x)=0$ for some point in $c\in(0,1)$. Then define $d=c+f(c)$ and we will have $f(c)=f(d)=d-c$.