问:
Update property doesn't seem to work
I have a datatable with dialog forms nested in a tabView tag....
each row of the datatable has buttons for editing and displaying data in Dialog form...but when i click on the edit or display button, it doesn't fill the form...And i don't know what's wrong with the update property....

I tried also to update the datatable after a create and update process by setting an update property in the forms commanButton but it seems that something is missing...

I also visited this link...update-form-on-hcommandbutton-action
and it doesn't seem to work in my case...maybe because update property is not set corectly.
when i delete the tabView, layout and LayoutUnit tags, it works correctly

Here is my index.xhtml code:

```<code><h:body>
    <ui:composition template="/template.xhtml">
        <ui:define name="content">
            <f:view>
                    <p:tabView id="tout">
                        <p:tab title="Identite" id="test">
                            <p:layout style="min-width:400px;min-height:450px;" id="change">

                                <p:layoutUnit position="center" id="tester">
                                    /* this Dialog form is for creating a new Antecedent*/
                                    <p:dialog showEffect="drop" hideEffect="drop" id="creation" widgetVar="creation" header="Enregistrer locataire">
                                        <h:form id="creer">
                                            <center>
                                                <p:panelGrid columns="4">

                                                    <p:outputLabel value="DateDiagnostic:" for="dateDiagnostic" />
                                                    <p:inputText id="dateDiagnostic" value="#{antecedentMBean.antecedent.dateDiagnostic}" title="DateDiagnostic" >
                                                        <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                    </p:inputText>
                                                    <p:outputLabel value="DateGuerison:" for="dateGuerison" />
                                                    <p:inputText id="dateGuerison" value="#{antecedentMBean.antecedent.dateGuerison}" title="DateGuerison" >
                                                        <f:convertDateTime pattern="MM/dd/yyyy" />
                                                    </p:inputText>
                                                    <p:outputLabel value="Allergies:" for="allergies" />
                                                    <p:inputText id="allergies" value="#{antecedentMBean.antecedent.allergies}" title="Allergies" />
                                                    <p:outputLabel value="Therapie:" for="therapie" />
                                                    <p:inputText id="therapie" value="#{antecedentMBean.antecedent.therapie}" title="Therapie" />

                                                </p:panelGrid>
                                                <p:panelGrid columns="1">
                                                    <p:outputLabel value="Diagnostique:" for="diagnostique" />

                                                    <p:inputTextarea id="diagnostique" value="#{antecedentMBean.antecedent.diagnostique}" title="Diagnostique" autoResize="false" rows="6" cols="83"/>
                                                </p:panelGrid>
                                                <hr/>
                                            </center>
                                            <center>
                                                <p:button icon="fa fa-close" value="Fermer" onclick="PF('creation').hide();
                                                        return false" />
                                                <p:commandButton icon="fa fa-trash" id="effacer" value="Effacer" type="reset"/>
                                                <p:commandButton icon="fa fa-save" value="Enregistrer" action="#{antecedentMBean.createAntecedent()}"
                                                        update=":formulaire:tbl"          oncomplete="PF('creation').hide()" />
                                            </center>
                                        </h:form>
                                    </p:dialog>

                                    <h:form id="formulaire">
                                    /* this Dialog form is for etiting */
                                        <p:dialog showEffect="size" id="modif" hideEffect="size" widgetVar="modif" header="Modification">
                                            <p:outputPanel id="repere" style="text-align:center;">
                                                <center>
                                                    <p:panelGrid columns="4">

                                                        <p:outputLabel value="DateDiagnostic:" for="dateDiagnostic" />
                                                        <p:inputText id="dateDiagnostic" value="#{antecedentMBean.antecedent.dateDiagnostic}" title="DateDiagnostic" >
                                                            <f:convertDateTime pattern="MM/dd/yyyy" />
                                                        </p:inputText>
                                                        <p:outputLabel value="DateGuerison:" for="dateGuerison" />
                                                        <p:inputText id="dateGuerison" value="#{antecedentMBean.antecedent.dateGuerison}" title="DateGuerison" >
                                                            <f:convertDateTime pattern="MM/dd/yyyy" />
                                                        </p:inputText>
                                                        <p:outputLabel value="Allergies:" for="allergies" />
                                                        <p:inputText id="allergies" value="#{antecedentMBean.antecedent.allergies}" title="Allergies" />
                                                        <p:outputLabel value="Therapie:" for="therapie" />
                                                        <p:inputText id="therapie" value="#{antecedentMBean.antecedent.therapie}" title="Therapie" />

                                                    </p:panelGrid>
                                                    <p:panelGrid columns="1">
                                                        <p:outputLabel value="Diagnostique:" for="diagnostique" />

                                                        <p:inputTextarea id="diagnostique" value="#{antecedentMBean.antecedent.diagnostique}" title="Diagnostique" autoResize="false" rows="6" cols="83"/>
                                                    </p:panelGrid>
                                                    <hr/>
                                                </center>
                                                <center>
                                                    <p:button icon="fa fa-close" value="Fermer" onclick="PF('modif').hide();
                                                            return false" />
                                                    <p:commandButton icon="fa fa-trash" id="effacer" value="Effacer" type="reset"/>
                                                    <p:commandButton icon="fa fa-pencil" value="Modifier" action="#{antecedentMBean.updateAntecedent()}"
                                                                     update=":formulaire:tbl"  onclick="PF('modif').hide()" />
                                                </center>
                                            </p:outputPanel>
                                        </p:dialog>
                                        /* this Dialog form is for displaying a row details */
                                        <p:dialog showEffect="size" hideEffect="size" id="voir" widgetVar="voir" header="Modification">
                                            <p:outputPanel id="view" style="text-align:center;">
                                                <center>
                                                    <p:panelGrid columns="4">
                                                        <p:outputLabel value="IdAntecedent:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.idAntecedent}" title="IdAntecedent"/>
                                                        <p:outputLabel value="DateDiagnostic:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.dateDiagnostic}" title="DateDiagnostic">
                                                            <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                        </h:outputText>
                                                        <p:outputLabel value="DateGuerison:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.dateGuerison}" title="DateGuerison">
                                                            <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                        </h:outputText>
                                                        <p:outputLabel value="Allergies:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.allergies}" title="Allergies"/>
                                                        <p:outputLabel value="Therapie:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.therapie}" title="Therapie"/>
                                                        <p:outputLabel value="Diagnostique:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.diagnostique}" title="Diagnostique"/>
                                                        <p:outputLabel value="CreerPar:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.creerPar}" title="CreerPar"/>
                                                        <p:outputLabel
                                                           <p:outputLabel value="DateCreer:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.dateCreer}" title="DateCreer">
                                                            <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                        </h:outputText>
                                                        <p:outputLabel value="MajPar:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.majPar}" title="MajPar"/>
                                                        <p:outputLabel value="DateMaj:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.dateMaj}" title="DateMaj">
                                                            <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                        </h:outputText>
                                                        <p:outputLabel value="IdPatient:"/>
                                                        <h:outputText value="#{antecedentMBean.antecedent.idPatient.prenom}" title="IdPatient"/>
                                                    </p:panelGrid>
                                                    <hr/>
                                                </center>
                                                <p:button icon="fa fa-close" value="Fermer" onclick="PF('voir').hide();
                                                            return false" />
                                            </p:outputPanel>
                                        </p:dialog>

                                        /* this commandButton display the create form */
                                        <p:commandButton icon="fa fa-plus" value="Creer"
                                                         onclick="PF('creation').show()"/>

                                        /* Here is my dataTable */
                                        <p:dataTable id="tbl" value="#{antecedentMBean.listAllAntecedents()}" var="item"
                                                     emptyMessage="Aucun Antecedent trouvee" widgetVar="AntecedentTable"
                                                     paginator="true" paginatorTemplate="{CurrentPageReport}
                                                     {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink}
                                                     {LastPageLink} {RowsPerPageDropdown} " paginatorPosition="top" rowsPerPageTemplate="5,10"
                                                     >

                                            <f:facet name="header">
                                                Liste des Patients
                                            </f:facet>

                                            <p:column>
                                                <f:facet name="header">
                                                    <h:outputText value="IdAntecedent"/>
                                                </f:facet>
                                                <h:outputText value="#{item.idAntecedent}"/>
                                            </p:column>
                                            <p:column>
                                                <f:facet name="header">
                                                    <h:outputText value="DateDiagnostic"/>
                                                </f:facet>
                                                <h:outputText value="#{item.dateDiagnostic}">
                                                    <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                </h:outputText>
                                            </p:column>
                                            <p:column>
                                                <f:facet name="header">
                                                    <h:outputText value="DateGuerison"/>
                                                </f:facet>
                                                <h:outputText value="#{item.dateGuerison}">
                                                    <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                </h:outputText>
                                            </p:column>
                                            <p:column>
                                                <f:facet name="header">
                                                    <h:outputText value="Allergies"/>
                                                </f:facet>
                                                <h:outputText value="#{item.allergies}"/>
                                            </p:column>
                                            <p:column>
                                                <f:facet name="header">
                                                    <h:outputText value="Therapie"/>
                                                </f:facet>
                                                <h:outputText value="#{item.therapie}"/>
                                            </p:column>
                                            <p:column>
                                                <f:facet name="header">
                                                    <h:outputText value="Diagnostique"/>
                                                </f:facet>
                                                <h:outputText value="#{item.diagnostique}"/>
                                            </p:column>

                                            <p:column headerText="Action" style="width:18%" exportable="false">
                                                <div class="ui-g">
                                                    <div class="ui-g-4">
                                                    /* Here are the buttons for editing*/
                                                        <p:commandButton icon="fa fa-pencil" update=":formulaire:repere" oncomplete="PF('modif').show()">
                                                            <f:setPropertyActionListener value="#{item}" target="#{antecedentMBean.antecedent}" />
                                                        </p:commandButton>
                                                    </div>
                                                    <div class="ui-g-4">
                                                    /* Here are the buttons for deleting*/
                                                        <p:commandButton icon="fa fa-trash" style="background-color: red" type="button" onclick="PF('cd').show()" />

                                                        <p:confirmDialog message="Voulez vous vraiment supprimer cet enregistrer?"
                                                                         header="Suppression en cours" severity="alert"
                                                                         widgetVar="cd" global="true" showEffect="bounce" hideEffect="bounce">
                                                            <p:commandButton value="Oui" action="#{antecedentMBean.deleteAntecedent()}"
                                                                             oncomplete="PF('cd').hide()" icon="ui-icon-check">
                                                                <f:setPropertyActionListener target="#{antecedentMBean.antecedent}" value="#{item}"/>
                                                            </p:commandButton>
                                                            <p:commandButton value="Non" onclick="PF('cd').hide();" type="button" icon="ui-icon-close"/>
                                                        </p:confirmDialog>
                                                    </div>
                                                    <div class="ui-g-4">
                                                    /* Here are the buttons for displaying*/
                                                        <p:commandButton icon="fa fa-binoculars" update=":formulaire:view"     oncomplete="PF('voir').show()">
                                                            <f:setPropertyActionListener value="#{item}" target="#{antecedentMBean.antecedent}" />
                                                        </p:commandButton>
                                                    </div>
                                                </div>
                                            </p:column>

                                        </p:dataTable>

                                    </h:form>
                                </p:layoutUnit>
                            </p:layout>
                        </p:tab>
                    </p:tabView>
            </f:view>
        </ui:define>
    </ui:composition>
</h:body>
</code>```

An here is my managedbean:
    package managedbeans;

```<code>import entities.Operation;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import sessions.OperationFacadeLocal;

Named(value = "operationMBean")
@ViewScoped
public class OperationMBean implements Serializable{

@EJB
private OperationFacadeLocal operationFacade;
private List<Operation> operationList;
private Operation operation;
private Date date = new Date();

public OperationFacadeLocal getOperationFacade() {
    return operationFacade;
}

public void setOperationFacade(OperationFacadeLocal operationFacade) {
    this.operationFacade = operationFacade;
}

public List<Operation> getOperationList() {
    return operationList;
}

public void setOperationList(List<Operation> operationList) {
    this.operationList = operationList;
}

public Operation getOperation() {
    return operation;
}

public void setOperation(Operation operation) {
    this.operation = operation;
}

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

 public List<Operation> createOperation(){
    operation.setDateCree(getDate());
    operation.setDateMaj(getDate());
    operationFacade.create(operation);
    operationList = operationFacade.findAll();
    return operationList;
}

public List<Operation> updateOperation(){
    operation.setDateMaj(getDate());
    operationFacade.edit(operation);
    operationList = operationFacade.findAll();
    return operationList;
}

public List<Operation> deleteOperation(){
    operationFacade.remove(operation);
    operationList = operationFacade.findAll();
    return operationList;
}

/**
 * Creates a new instance of OperationMBean
 */
public OperationMBean() {
}

}
</code>```

I'm using PrimeFaces 6.1 Netbeans 8.2 Glassfish 4.1
Hope i've been clear in my question
Thanks in advance!!!

答:
I solve this problem by using WidgetVar instead of id in the update property like this:

```<code><p:commandButton update="widgetVar(element_widgetVar)" />
</code>```

Thanks to Stackoverflow

Title: Update property doesn't seem to work

Body:
I have a datatable with dialog forms nested in a tabView tag....
each row of the datatable has buttons for editing and displaying data in Dialog form...but when i click on the edit or display button, it doesn't fill the form...And i don't know what's wrong with the update property....

I tried also to update the datatable after a create and update process by setting an update property in the forms commanButton but it seems that something is missing...

I also visited this link...update-form-on-hcommandbutton-action
and it doesn't seem to work in my case...maybe because update property is not set corectly.
when i delete the tabView, layout and LayoutUnit tags, it works correctly

Here is my index.xhtml code:

<h:body>
    <ui:composition template="/template.xhtml">
        <ui:define name="content">
            <f:view>

                                    /* this Dialog form is for creating a new Antecedent*/

                                        <h:form id="creer">

                                                        <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />

                                                        <f:convertDateTime pattern="MM/dd/yyyy" />

                                        </h:form>

                                    <h:form id="formulaire">
                                    /* this Dialog form is for etiting */

                                                            <f:convertDateTime pattern="MM/dd/yyyy" />

                                                            <f:convertDateTime pattern="MM/dd/yyyy" />

                                        /* this Dialog form is for displaying a row details */

                                                        <h:outputText value="#{antecedentMBean.antecedent.idAntecedent}" title="IdAntecedent"/>

                                                        <h:outputText value="#{antecedentMBean.antecedent.dateDiagnostic}" title="DateDiagnostic">
                                                            <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                        </h:outputText>

                                                        <h:outputText value="#{antecedentMBean.antecedent.dateGuerison}" title="DateGuerison">
                                                            <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                        </h:outputText>

                                                        <h:outputText value="#{antecedentMBean.antecedent.allergies}" title="Allergies"/>

                                                        <h:outputText value="#{antecedentMBean.antecedent.therapie}" title="Therapie"/>

                                                        <h:outputText value="#{antecedentMBean.antecedent.diagnostique}" title="Diagnostique"/>

                                                        <h:outputText value="#{antecedentMBean.antecedent.creerPar}" title="CreerPar"/>
                                                        <p:outputLabel

                                                        <h:outputText value="#{antecedentMBean.antecedent.dateCreer}" title="DateCreer">
                                                            <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                        </h:outputText>

                                                        <h:outputText value="#{antecedentMBean.antecedent.majPar}" title="MajPar"/>

                                                        <h:outputText value="#{antecedentMBean.antecedent.dateMaj}" title="DateMaj">
                                                            <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                        </h:outputText>

                                                        <h:outputText value="#{antecedentMBean.antecedent.idPatient.prenom}" title="IdPatient"/>

                                        /* this commandButton display the create form */

                                        /* Here is my dataTable */
                                        <p:dataTable id="tbl" value="#{antecedentMBean.listAllAntecedents()}" var="item"
                                                     emptyMessage="Aucun Antecedent trouvee" widgetVar="AntecedentTable"
                                                     paginator="true" paginatorTemplate="{CurrentPageReport}
                                                     {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink}
                                                     {LastPageLink} {RowsPerPageDropdown} " paginatorPosition="top" rowsPerPageTemplate="5,10"
                                                     >

                                            <f:facet name="header">
                                                Liste des Patients
                                            </f:facet>

                                                <f:facet name="header">
                                                    <h:outputText value="IdAntecedent"/>
                                                </f:facet>
                                                <h:outputText value="#{item.idAntecedent}"/>

                                                <f:facet name="header">
                                                    <h:outputText value="DateDiagnostic"/>
                                                </f:facet>
                                                <h:outputText value="#{item.dateDiagnostic}">
                                                    <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                </h:outputText>

                                                <f:facet name="header">
                                                    <h:outputText value="DateGuerison"/>
                                                </f:facet>
                                                <h:outputText value="#{item.dateGuerison}">
                                                    <f:convertDateTime pattern="MM/dd/yyyy HH:mm:ss" />
                                                </h:outputText>

                                                <f:facet name="header">
                                                    <h:outputText value="Allergies"/>
                                                </f:facet>
                                                <h:outputText value="#{item.allergies}"/>

                                                <f:facet name="header">
                                                    <h:outputText value="Therapie"/>
                                                </f:facet>
                                                <h:outputText value="#{item.therapie}"/>

                                                <f:facet name="header">
                                                    <h:outputText value="Diagnostique"/>
                                                </f:facet>
                                                <h:outputText value="#{item.diagnostique}"/>

                                                    /* Here are the buttons for editing*/

                                                            <f:setPropertyActionListener value="#{item}" target="#{antecedentMBean.antecedent}" />

                                                    /* Here are the buttons for deleting*/

                                                                <f:setPropertyActionListener target="#{antecedentMBean.antecedent}" value="#{item}"/>

                                                    /* Here are the buttons for displaying*/

                                                            <f:setPropertyActionListener value="#{item}" target="#{antecedentMBean.antecedent}" />

                                    </h:form>

            </f:view>
        </ui:define>
    </ui:composition>
</h:body>

An here is my managedbean:
    package managedbeans;

import entities.Operation;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import sessions.OperationFacadeLocal;

Named(value = "operationMBean")
@ViewScoped
public class OperationMBean implements Serializable{

@EJB
private OperationFacadeLocal operationFacade;
private List<Operation> operationList;
private Operation operation;
private Date date = new Date();

public OperationFacadeLocal getOperationFacade() {
    return operationFacade;
}

public void setOperationFacade(OperationFacadeLocal operationFacade) {
    this.operationFacade = operationFacade;
}

public List<Operation> getOperationList() {
    return operationList;
}

public void setOperationList(List<Operation> operationList) {
    this.operationList = operationList;
}

public Operation getOperation() {
    return operation;
}

public void setOperation(Operation operation) {
    this.operation = operation;
}

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

 public List<Operation> createOperation(){
    operation.setDateCree(getDate());
    operation.setDateMaj(getDate());
    operationFacade.create(operation);
    operationList = operationFacade.findAll();
    return operationList;
}

public List<Operation> updateOperation(){
    operation.setDateMaj(getDate());
    operationFacade.edit(operation);
    operationList = operationFacade.findAll();
    return operationList;
}

public List<Operation> deleteOperation(){
    operationFacade.remove(operation);
    operationList = operationFacade.findAll();
    return operationList;
}

/**
 * Creates a new instance of OperationMBean
 */
public OperationMBean() {
}

}

I'm using PrimeFaces 6.1 Netbeans 8.2 Glassfish 4.1
Hope i've been clear in my question
Thanks in advance!!!

Body:
I solve this problem by using WidgetVar instead of id in the update property like this:

<p:commandButton update="widgetVar(element_widgetVar)" />

Thanks to Stackoverflow


来源: stackexchange

问:
MongoDB aggregation filter
I'm trying to select some data from a mongodb collection in python, here are some example data :

```<code>[{"id":1, "planned_timestamp":1512728425, "executed_timestamp":0, "owner":1, "action_type": "read", "action_params":"book A"},
{"id":2, "planned_timestamp":1512728430, "executed_timestamp":0, "owner":1, "action_type": "read", "action_params":"book B"},
{"id":3, "planned_timestamp":1512728435, "executed_timestamp":0, "owner":2, "action_type": "read", "action_params":"book C"}]
</code>```

I want to select all task that has "executed_timestamp":0, "planned_timestamp" lower than the timestamp variable and I would like to have the results as follows:

```<code>[{"owner":1, "tasks": [{"id":1,"planned_timestamp":1512728425,"action_type": "read","action_params":"book A"},{"id":1,"planned_timestamp":1512728430,"action_type": "read","action_params":"book B"}]},
{"owner":2, "tasks": [{"id":3,"planned_timestamp":1512728435,"action_type": "read","action_params":"book C"}]}]
</code>```

My current request with pymongo is :

```<code>r = db.task_queue.aggregate(
       [
         { "$group" : { "_id" : "$agent_id", "tasks": { "$push": "$$ROOT" } } }
       ]
    )
</code>```

答:
What is agent_id?

What you need is $match. Try this.

```<code>timestamp = 1500000000

r = db.task_queue.aggregate(
        [
            {"$match": {"$and": [
                {
                    "executed_timestamp": {"$eq": 0},
                    "planned_timestamp": {"$lte": timestamp}
                }
            ]}},
            {"$group" : { "_id" : "$owner", "tasks": { "$push": "$$ROOT" } } },
            {"$project":
            {
                "_id": 0,
                "owner": "$_id.owner",
                "tasks": 1
            }}
        ]
    )
</code>```

ContentLicense: CC BY-SA 3.0

Title: MongoDB aggregation filter

Body:
I'm trying to select some data from a mongodb collection in python, here are some example data :

[{"id":1, "planned_timestamp":1512728425, "executed_timestamp":0, "owner":1, "action_type": "read", "action_params":"book A"},
{"id":2, "planned_timestamp":1512728430, "executed_timestamp":0, "owner":1, "action_type": "read", "action_params":"book B"},
{"id":3, "planned_timestamp":1512728435, "executed_timestamp":0, "owner":2, "action_type": "read", "action_params":"book C"}]

I want to select all task that has "executed_timestamp":0, "planned_timestamp" lower than the timestamp variable and I would like to have the results as follows:

[{"owner":1, "tasks": [{"id":1,"planned_timestamp":1512728425,"action_type": "read","action_params":"book A"},{"id":1,"planned_timestamp":1512728430,"action_type": "read","action_params":"book B"}]},
{"owner":2, "tasks": [{"id":3,"planned_timestamp":1512728435,"action_type": "read","action_params":"book C"}]}]

My current request with pymongo is :

r = db.task_queue.aggregate(
       [
         { "$group" : { "_id" : "$agent_id", "tasks": { "$push": "$$ROOT" } } }
       ]
    )

Body:
What is agent_id?

What you need is $match. Try this.

timestamp = 1500000000

r = db.task_queue.aggregate(
        [
            {"$match": {"$and": [
                {
                    "executed_timestamp": {"$eq": 0},
                    "planned_timestamp": {"$lte": timestamp}
                }
            ]}},
            {"$group" : { "_id" : "$owner", "tasks": { "$push": "$$ROOT" } } },
            {"$project":
            {
                "_id": 0,
                "owner": "$_id.owner",
                "tasks": 1
            }}
        ]
    )


问:
MVVM Combobox binding
I have a combobox that doesn't seem to be updated it's view model.

On the view I have

```<code><ComboBox Grid.Row="0"
           Grid.Column="1"
           ToolTip="Current rank of the officer"
           ItemsSource="{Binding Path=RanksAvailable}"
           DisplayMemberPath="Name"
           SelectedValuePath="Name"
           SelectedValue="{Binding Path=SelectedRank, Mode=TwoWay}"/>
</code>```

in the view model I have

```<code>    public List<Rank> RanksAvailable {get; set;}
    private Rank _selectedRank;

    public Rank SelectedRank
    {
        get { return _selectedRank; }
        set
        {
            if (_selectedRank != value)
            {
                _selectedRank = value;
                this.isDirty = true;
                RaisePropertyChanged("SelectedRank");
            }
        }
    }
</code>```

the combobox is being populated alright, I just can't seem to get a value out of it.

答:
The problem is you are using SelectedValuePath="Name" just remove it and it will work.

Your ComboBox will become-

```<code><ComboBox Grid.Row="0"
           Grid.Column="1"
           ToolTip="Current rank of the officer"
           ItemsSource="{Binding Path=RanksAvailable}"
           DisplayMemberPath="Name"
           SelectedValue="{Binding Path=SelectedRank, Mode=TwoWay}"/>
</code>```

ContentLicense: CC BY-SA 2.5

Title: MVVM Combobox binding

Body:
I have a combobox that doesn't seem to be updated it's view model.

On the view I have

<ComboBox Grid.Row="0"
           Grid.Column="1"
           ToolTip="Current rank of the officer"
           ItemsSource="{Binding Path=RanksAvailable}"
           DisplayMemberPath="Name"
           SelectedValuePath="Name"
           SelectedValue="{Binding Path=SelectedRank, Mode=TwoWay}"/>

in the view model I have

    public List<Rank> RanksAvailable {get; set;}
    private Rank _selectedRank;

    public Rank SelectedRank
    {
        get { return _selectedRank; }
        set
        {
            if (_selectedRank != value)
            {
                _selectedRank = value;
                this.isDirty = true;
                RaisePropertyChanged("SelectedRank");
            }
        }
    }

the combobox is being populated alright, I just can't seem to get a value out of it.

Body:
The problem is you are using SelectedValuePath="Name" just remove it and it will work.

Your ComboBox will become-

<ComboBox Grid.Row="0"
           Grid.Column="1"
           ToolTip="Current rank of the officer"
           ItemsSource="{Binding Path=RanksAvailable}"
           DisplayMemberPath="Name"
           SelectedValue="{Binding Path=SelectedRank, Mode=TwoWay}"/>


问:
Getting current time minus 10 minutes in epoch with milliseconds
I would like to have a python3 script which gets the current time - 10 minutes and it converts it to epoch time in milliseconds

The problem is that I have no idea how to start.

something witch in bash looks like this:

```<code>$(( $(date -d '-10 minutes' +%s%N)/1000000 )))
</code>```

答:
You can use datetime.datetime and datetime.timedelta to achieve that:

```<code>import datetime

current_time = datetime.datetime.now()  # use datetime.datetime.utcnow() for UTC time
ten_minutes_ago = current_time - datetime.timedelta(minutes=10)

ten_minutes_ago_epoch_ts = int(ten_minutes_ago.timestamp() * 1000)  # in miliseconds
</code>```

Body:
I would like to have a python3 script which gets the current time - 10 minutes and it converts it to epoch time in milliseconds

The problem is that I have no idea how to start.

something witch in bash looks like this:

$(( $(date -d '-10 minutes' +%s%N)/1000000 )))

Body:
You can use datetime.datetime and datetime.timedelta to achieve that:

import datetime

current_time = datetime.datetime.now()  # use datetime.datetime.utcnow() for UTC time
ten_minutes_ago = current_time - datetime.timedelta(minutes=10)

ten_minutes_ago_epoch_ts = int(ten_minutes_ago.timestamp() * 1000)  # in miliseconds


问:
How to validate the radio button inside ng-repeat?
I have the below code for student's assignment status marking. My problem is it is not necessary that all students should be marked. The user might mark some might not. Now  how to validate that at least one user must be marked else there should be some validation message displayed.

Thanks in advance!

```<code><div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Complete</th>
                        <th>Incomplete</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="record in studentRecord.AssignmentStatus">
                        <td>{{record.Name}}</td>
                        <td><input type="radio" value=Complete ng-model="record.Status" /></td>
                        <td><input type="radio" value=Incomplete ng-model="record.Status" /></td>
                    </tr>
                </tbody>
            </table>
            <button class="btn btn-primary pull-right" ng-click="updateAssignment(studentRecord)">Submit</button>
        </div>
</code>```

答:
This advice seems good but has a problem. We can not put ng-required in the case of radio button inside ng-repeat. As you can see in your fiddle, It is asking for both radio button to be selected which is not possible. That trick is generally not good in the case where we want either thing to be selected inside ng-repeat. –

I disagree with glandrum101 (the author of the statements above).
Well while that might be true, you can add some code in the controller to make this work.

controller:

```<code>Just put this code in the controller and use it with ng-change:

vm.setTrueFalseRadioState = setTrueFalseRadioState;

function setTrueFalseRadioState(answer) {
  angular.forEach(vm.AssignmentStatus, function(a) {
    if (a.Status !== answer.Status) {
      a.Status = false;
    }
  });
}
</code>```

html:

```<code><input type="radio" id="myChoice_{{$index + 1}}" name="response" ng-required="!record.Status" ng-change="studentRecord.setTrueFalseRadioState(record)" value="true" ng-model="record.Status" />
</code>```

I made a sample plunker to demonstrate this

Body:
I have the below code for student's assignment status marking. My problem is it is not necessary that all students should be marked. The user might mark some might not. Now  how to validate that at least one user must be marked else there should be some validation message displayed.

Thanks in advance!

                        Name
                        Complete
                        Incomplete

                        {{record.Name}}
                        <input type="radio" value=Complete ng-model="record.Status" />
                        <input type="radio" value=Incomplete ng-model="record.Status" />

            <button class="btn btn-primary pull-right" ng-click="updateAssignment(studentRecord)">Submit</button>

Body:
This advice seems good but has a problem. We can not put ng-required in the case of radio button inside ng-repeat. As you can see in your fiddle, It is asking for both radio button to be selected which is not possible. That trick is generally not good in the case where we want either thing to be selected inside ng-repeat. –

I disagree with glandrum101 (the author of the statements above).
Well while that might be true, you can add some code in the controller to make this work.

controller:

Just put this code in the controller and use it with ng-change:

vm.setTrueFalseRadioState = setTrueFalseRadioState;

function setTrueFalseRadioState(answer) {
  angular.forEach(vm.AssignmentStatus, function(a) {
    if (a.Status !== answer.Status) {
      a.Status = false;
    }
  });
}

html:

<input type="radio" id="myChoice_{{$index + 1}}" name="response" ng-required="!record.Status" ng-change="studentRecord.setTrueFalseRadioState(record)" value="true" ng-model="record.Status" />

I made a sample plunker to demonstrate this


问:
Debian 8: Restarting apache2 failed
I'm trying to Configure timezone for PHP and after setting  that, I have a set of commands to execute provided,

```<code>cd /etc/apache2/mods-enabled/
ln -s ../mods-available/rewrite.load .
ln -s ../mods-available/headers.load .
ln -s ../mods-available/expires.load .
ln -s ../mods-available/ssl.load .
ln -s ../mods-available/ssl.conf .
ln -s ../mods-available/php5* .
ln -s ../mods-available/socache_shmcb.load .

/etc/init.d/apache2 restart
</code>```

When I run the last command with sudo, I get the following error,

```<code>[....] Restarting apache2 (via systemctl): apache2.serviceJob for apache2.service failed. See 'systemctl status apache2.service' and 'journalctl -xn' for details.
 failed!
</code>```

When I type in the terminal,

```<code>systemctl status apache2.service
</code>```

I get the output of,

```<code>● apache2.service - LSB: Apache2 web server
   Loaded: loaded (/etc/init.d/apache2)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─forking.conf
   Active: failed (Result: exit-code) since Fri 2017-12-08 12:57:08 CET; 5min ago
  Process: 23298 ExecStop=/etc/init.d/apache2 stop (code=exited, status=0/SUCCESS)
  Process: 23587 ExecStart=/etc/init.d/apache2 start (code=exited, status=1/FAILURE)
</code>```

What should I do in this case?

Upadte

The output of the command of sudo cat /var/log/apache2/error.log is provided,

```<code>[Fri Dec 08 11:58:17.392972 2017] [mpm_event:notice] [pid 12892:tid 140108409681792] AH00489: Apache/2.4.10 (Debian) configured -- resuming normal operations
[Fri Dec 08 11:58:17.393055 2017] [core:notice] [pid 12892:tid 140108409681792] AH00094: Command line: '/usr/sbin/apache2'
[Fri Dec 08 11:58:36.585248 2017] [mpm_event:notice] [pid 12892:tid 140108409681792] AH00493: SIGUSR1 received.  Doing graceful restart
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
[Fri Dec 08 11:58:36.588582 2017] [mpm_event:notice] [pid 12892:tid 140108409681792] AH00489: Apache/2.4.10 (Debian) configured -- resuming normal operations
[Fri Dec 08 11:58:36.588590 2017] [core:notice] [pid 12892:tid 140108409681792] AH00094: Command line: '/usr/sbin/apache2'
[Fri Dec 08 11:58:39.747035 2017] [mpm_event:notice] [pid 12892:tid 140108409681792] AH00491: caught SIGTERM, shutting down
[Fri Dec 08 11:58:40.816350 2017] [mpm_prefork:notice] [pid 15087] AH00163: Apache/2.4.10 (Debian) configured -- resuming normal operations
[Fri Dec 08 11:58:40.816435 2017] [core:notice] [pid 15087] AH00094: Command line: '/usr/sbin/apache2'
[Fri Dec 08 11:58:42.228275 2017] [mpm_prefork:notice] [pid 15087] AH00169: caught SIGTERM, shutting down
[Fri Dec 08 11:58:43.344556 2017] [mpm_prefork:notice] [pid 15186] AH00163: Apache/2.4.10 (Debian) configured -- resuming normal operations
[Fri Dec 08 11:58:43.344605 2017] [core:notice] [pid 15186] AH00094: Command line: '/usr/sbin/apache2'
[Fri Dec 08 12:40:45.121960 2017] [mpm_prefork:notice] [pid 15186] AH00169: caught SIGTERM, shutting down
</code>```

The output of command /usr/sbin/apache2 is provided,

```<code>[Fri Dec 08 13:30:36.877713 2017] [core:warn] [pid 23750] AH00111: Config variable ${APACHE_LOCK_DIR} is not defined
[Fri Dec 08 13:30:36.879775 2017] [core:warn] [pid 23750] AH00111: Config variable ${APACHE_PID_FILE} is not defined
[Fri Dec 08 13:30:36.879827 2017] [core:warn] [pid 23750] AH00111: Config variable ${APACHE_RUN_USER} is not defined
[Fri Dec 08 13:30:36.879865 2017] [core:warn] [pid 23750] AH00111: Config variable ${APACHE_RUN_GROUP} is not defined
[Fri Dec 08 13:30:36.879905 2017] [core:warn] [pid 23750] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
apache2: Syntax error on line 140 of /etc/apache2/apache2.conf: Could not open configuration file /etc/apache2/mods-enabled/php5.load: No such file or directory
</code>```

答: You haven't properly enabled the PHP 5 module by the looks of it. Try running a2enmod php5, if it fails you might not have the module installed, in which case try: apt-get install libapache2-mod-php5 and then a2enmod php5 again.

Title: Debian 8: Restarting apache2 failed

Body:
I'm trying to Configure timezone for PHP and after setting  that, I have a set of commands to execute provided,

cd /etc/apache2/mods-enabled/
ln -s ../mods-available/rewrite.load .
ln -s ../mods-available/headers.load .
ln -s ../mods-available/expires.load .
ln -s ../mods-available/ssl.load .
ln -s ../mods-available/ssl.conf .
ln -s ../mods-available/php5* .
ln -s ../mods-available/socache_shmcb.load .

/etc/init.d/apache2 restart

When I run the last command with sudo, I get the following error,

[....] Restarting apache2 (via systemctl): apache2.serviceJob for apache2.service failed. See 'systemctl status apache2.service' and 'journalctl -xn' for details.
 failed!

When I type in the terminal,

systemctl status apache2.service

I get the output of,

● apache2.service - LSB: Apache2 web server
   Loaded: loaded (/etc/init.d/apache2)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─forking.conf
   Active: failed (Result: exit-code) since Fri 2017-12-08 12:57:08 CET; 5min ago
  Process: 23298 ExecStop=/etc/init.d/apache2 stop (code=exited, status=0/SUCCESS)
  Process: 23587 ExecStart=/etc/init.d/apache2 start (code=exited, status=1/FAILURE)

What should I do in this case?

Upadte

The output of the command of sudo cat /var/log/apache2/error.log is provided,

[Fri Dec 08 11:58:17.392972 2017] [mpm_event:notice] [pid 12892:tid 140108409681792] AH00489: Apache/2.4.10 (Debian) configured -- resuming normal operations
[Fri Dec 08 11:58:17.393055 2017] [core:notice] [pid 12892:tid 140108409681792] AH00094: Command line: '/usr/sbin/apache2'
[Fri Dec 08 11:58:36.585248 2017] [mpm_event:notice] [pid 12892:tid 140108409681792] AH00493: SIGUSR1 received.  Doing graceful restart
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
[Fri Dec 08 11:58:36.588582 2017] [mpm_event:notice] [pid 12892:tid 140108409681792] AH00489: Apache/2.4.10 (Debian) configured -- resuming normal operations
[Fri Dec 08 11:58:36.588590 2017] [core:notice] [pid 12892:tid 140108409681792] AH00094: Command line: '/usr/sbin/apache2'
[Fri Dec 08 11:58:39.747035 2017] [mpm_event:notice] [pid 12892:tid 140108409681792] AH00491: caught SIGTERM, shutting down
[Fri Dec 08 11:58:40.816350 2017] [mpm_prefork:notice] [pid 15087] AH00163: Apache/2.4.10 (Debian) configured -- resuming normal operations
[Fri Dec 08 11:58:40.816435 2017] [core:notice] [pid 15087] AH00094: Command line: '/usr/sbin/apache2'
[Fri Dec 08 11:58:42.228275 2017] [mpm_prefork:notice] [pid 15087] AH00169: caught SIGTERM, shutting down
[Fri Dec 08 11:58:43.344556 2017] [mpm_prefork:notice] [pid 15186] AH00163: Apache/2.4.10 (Debian) configured -- resuming normal operations
[Fri Dec 08 11:58:43.344605 2017] [core:notice] [pid 15186] AH00094: Command line: '/usr/sbin/apache2'
[Fri Dec 08 12:40:45.121960 2017] [mpm_prefork:notice] [pid 15186] AH00169: caught SIGTERM, shutting down

The output of command /usr/sbin/apache2 is provided,

[Fri Dec 08 13:30:36.877713 2017] [core:warn] [pid 23750] AH00111: Config variable ${APACHE_LOCK_DIR} is not defined
[Fri Dec 08 13:30:36.879775 2017] [core:warn] [pid 23750] AH00111: Config variable ${APACHE_PID_FILE} is not defined
[Fri Dec 08 13:30:36.879827 2017] [core:warn] [pid 23750] AH00111: Config variable ${APACHE_RUN_USER} is not defined
[Fri Dec 08 13:30:36.879865 2017] [core:warn] [pid 23750] AH00111: Config variable ${APACHE_RUN_GROUP} is not defined
[Fri Dec 08 13:30:36.879905 2017] [core:warn] [pid 23750] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
apache2: Syntax error on line 140 of /etc/apache2/apache2.conf: Could not open configuration file /etc/apache2/mods-enabled/php5.load: No such file or directory


问:
iPhone - how may I check if a date is Monday?
I'm trying to find if a date is Monday.

To do this I proceed this way :

```<code>#define kDateAndHourUnitsComponents NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// for test and debug purpose
NSDateComponents* b = [calendar components:kDateAndHourUnitsComponents fromDate:retDate];
int a=[[calendar components:kDateAndHourUnitsComponents fromDate:theDate] weekday];
// -----------

if ([[calendar components:kDateAndHourUnitsComponents fromDate:theDate] weekday] == EKMonday) DoThis....
</code>```

But this doesn't work... a and b does not contain anything useful (a equals 2147483647),

I also wonder what can be the use of [calendar components:NSWeekdayCalendarUnit fromDate:retDate] that is not useful anymore in that case...

I also found this that confirms the process :
How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?

What did I miss ?

答:
Here ya go, this works and returns days via ints: 7 = Sat, 1 = Sun, 2 = Mon...

OBJECTIVE C

```<code>NSDate* curDate = [NSDate date];
int dayInt = [[[NSCalendar currentCalendar] components: NSWeekdayCalendarUnit fromDate: curDate] weekday];
</code>```

SWIFT 4.2

Build up the date you want to check what day of the week it is

```<code>let dateComponents = DateComponents(
    year: 2019,
    month: 2 /*FEB*/,
    day: 23 /*23rd day of that month */
)
</code>```

get the current calendar.

```<code>let cal = Calendar.current
</code>```

now use the calendar to check if the build up date is a valid date

```<code>guard let date = cal.date(from: dateComponents ) else {
    // The date you build up wasn't a valid day on the calendar
    return
}

//Now that your date is validated, get the day of the week

let weekdayIndex = cal.component(.weekday, from: date)
</code>```

You'll notice that the 'weekdayIndex' is an integer. If you want to make it a string, you can do something like this:

```<code>if let weekdayName = DateFormatter().weekdaySymbols?[ weekdayIndex - 1] {
    print("The weekday for your date is :: \(weekdayName)")
}
</code>```

Instead of building your own date, you are of course allowed to use let date = Date() instead to get what the current day of the week is

Body:
I'm trying to find if a date is Monday.

To do this I proceed this way :

#define kDateAndHourUnitsComponents NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// for test and debug purpose
NSDateComponents* b = [calendar components:kDateAndHourUnitsComponents fromDate:retDate];
int a=[[calendar components:kDateAndHourUnitsComponents fromDate:theDate] weekday];
// -----------

if ([[calendar components:kDateAndHourUnitsComponents fromDate:theDate] weekday] == EKMonday) DoThis....

But this doesn't work... a and b does not contain anything useful (a equals 2147483647),

I also wonder what can be the use of [calendar components:NSWeekdayCalendarUnit fromDate:retDate] that is not useful anymore in that case...

I also found this that confirms the process :
How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?

What did I miss ?

Body:
Here ya go, this works and returns days via ints: 7 = Sat, 1 = Sun, 2 = Mon...

OBJECTIVE C

NSDate* curDate = [NSDate date];
int dayInt = [[[NSCalendar currentCalendar] components: NSWeekdayCalendarUnit fromDate: curDate] weekday];

SWIFT 4.2

Build up the date you want to check what day of the week it is

let dateComponents = DateComponents(
    year: 2019,
    month: 2 /*FEB*/,
    day: 23 /*23rd day of that month */
)

get the current calendar.

let cal = Calendar.current

now use the calendar to check if the build up date is a valid date

guard let date = cal.date(from: dateComponents ) else {
    // The date you build up wasn't a valid day on the calendar
    return
}

//Now that your date is validated, get the day of the week

let weekdayIndex = cal.component(.weekday, from: date)

You'll notice that the 'weekdayIndex' is an integer. If you want to make it a string, you can do something like this:

if let weekdayName = DateFormatter().weekdaySymbols?[ weekdayIndex - 1] {
    print("The weekday for your date is :: \(weekdayName)")
}

Instead of building your own date, you are of course allowed to use let date = Date() instead to get what the current day of the week is

ContentLicense: CC BY-SA 4.0


问:
Plugin not working with JQuery-3.1.0
I am trying to create an image cropper using cropit plugin

```<code><!DOCTYPE html>
    <html>
      <head>
        <title>cropit</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/cropit@0.5.1/dist/jquery.cropit.js"></script>

        <style>
          .cropit-preview {
            background-color: #f8f8f8;
            background-size: cover;
            border: 1px solid #ccc;
            border-radius: 3px;
            margin-top: 7px;
            width: 250px;
            height: 250px;
          }

          .cropit-preview-image-container {
            cursor: move;
          }

          .image-size-label {
            margin-top: 10px;
          }

          input, .export {
            display: block;
          }

          button {
            margin-top: 10px;
          }
        </style>
      </head>
      <body>
        <div class="image-editor">
          <input type="file" class="cropit-image-input">
          <div class="cropit-preview"></div>
          <div class="image-size-label">
            Resize image
          </div>
          <input type="range" class="cropit-image-zoom-input">
          <button class="rotate-ccw">Rotate counterclockwise</button>
          <button class="rotate-cw">Rotate clockwise</button>

          <button class="export">Export</button>
        </div>

        <script>
          $(function() {
            $('.image-editor').cropit({
              imageState: {
                src: 'http://lorempixel.com/500/400/',
              },
            });

            $('.rotate-cw').click(function() {
              $('.image-editor').cropit('rotateCW');
            });
            $('.rotate-ccw').click(function() {
              $('.image-editor').cropit('rotateCCW');
            });

            $('.export').click(function() {
              var imageData = $('.image-editor').cropit('export');
              window.open(imageData);
            });
          });
        </script>
      </body>
    </html>
</code>```

This code works fine without any problem. But, if I replace the current version (2.0.0) with latest version (3.1.0), then the browsed image will not be loaded.
i.e, if we replace:

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</code>```

with

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</code>```

then the image will not be loaded. I can't use the jQuery old version because I am already using the latest version for other plugins.

答:
Just include the migrate plugin given below to solve the problem.

```<code><script src="https://code.jquery.com/jquery-migrate-3.0.1.js"></script>
</code>```

Source

Title: Plugin not working with JQuery-3.1.0

Body:
I am trying to create an image cropper using cropit plugin

<!DOCTYPE html>

        <title>cropit</title>

          <input type="file" class="cropit-image-input">

            Resize image

          <input type="range" class="cropit-image-zoom-input">
          <button class="rotate-ccw">Rotate counterclockwise</button>
          <button class="rotate-cw">Rotate clockwise</button>

          <button class="export">Export</button>

This code works fine without any problem. But, if I replace the current version (2.0.0) with latest version (3.1.0), then the browsed image will not be loaded.
i.e, if we replace:

with

then the image will not be loaded. I can't use the jQuery old version because I am already using the latest version for other plugins.

Body:
Just include the migrate plugin given below to solve the problem.

<script src="https://code.jquery.com/jquery-migrate-3.0.1.js"></script>

Source


问:
Get ARFrame from ARKit scene
I am new to iPhone app development (but experienced developer in other languages) and I am making an ARKit application in which I need to track an image's position and display a rectangle around this image.

I could do it in C++ with OpenCV and make the appropriate "bridging" classes to be able to call this code from swift. Now, I need to get the images from ARKit and pass them to this function.

How do I suscribe a function which handles the ARFrames from the ARKit scene? I found that I could get some ARFrame from sceneView.session.currentFrame but I did not find how to make a function that would be called for each frame (or each time my function has ended and is ready to receive the next frame).

Also, I discovered the Vision Framework but it seems to only be able to track an element on which the user tapped. Is that right or is there a combination of predefined functions which could be used to this purpose?

答:
You can get each captured frame by the camera with the session(:didUpdate:) method from the ARSessionDelegate protocol. Note that this method might be useful even if you don't use the provided ARFrame; for instance, I use it to "poll" if there's any virtual content added currently visible.

Regarding the tracking image question, I believe you could create an ARAnchor or SCNNode and position it over the image and ARKit would track it

Title: Get ARFrame from ARKit scene


问:
Is there an API for Mozilla for updating signed addons?
I have a signed addon that I use personally but would like to experiment with making it distributable via AMO. I have already uploaded the initial version through the Developer Hub, and I'm now hoping to be able to include an automated release through a CI pipeline.

I've been investigating how to do this for a while now, having found this article and API doc but haven't had much luck. I'm definitely able to connect with my JWT properly, as I get either a 301 (I assume this is because the API described in the article has been changed in the last two years) but then a 400 when I follow the redirects.

Every request returns Missing "upload" key in multipart file data. I believe this is to do with the endpoint being a PUT but expecting a multipart form (all my research points to this being supported by POST only). I've tried several different approaches, both with cURL and with various Python libraries - including PyCurl to try and use the multipart in a POST request and override only the method to PUT - but just don't seem to be getting anywhere.

I haven't been able to find any recent documentation on this, as the older articles imply it's a deprecated API but the newer docs don't seem to have the answers I'm looking for. Issues like this one suggest it's still possible, and I've seen mention of web-ext but I think I'm just missing how to put the pieces together.

My request is:

```<code>    curl -XPUT https://addons.mozilla.org/api/v3/addons/{myId}/versions/0.2 -F 'upload=../toolbox.api' -H 'Authorization: JWT <myToken>' -v -L
</code>```

Has anyone tried to do this and have any advice on how to move forward? Or conversely know that it's definitely not possible?

Thanks in advance!

答:
You can use the node.js based command web-ext to sign extensions from command line.

Like with the curl approach you obtain the issuer/secret, then use those as given arguments or environment variables:

```<code>web-ext sign --api-key=$AMO_JWT_ISSUER --api-secret=$AMO_JWT_SECRET
</code>```

If you need to use a proxy:

```<code>web-ext sign --api-key=... --api-secret=... --api-proxy=https://yourproxy:6000
</code>```

Please see the linked article for details (and its other features).

Body:
I have a signed addon that I use personally but would like to experiment with making it distributable via AMO. I have already uploaded the initial version through the Developer Hub, and I'm now hoping to be able to include an automated release through a CI pipeline.

I've been investigating how to do this for a while now, having found this article and API doc but haven't had much luck. I'm definitely able to connect with my JWT properly, as I get either a 301 (I assume this is because the API described in the article has been changed in the last two years) but then a 400 when I follow the redirects.

Every request returns Missing "upload" key in multipart file data. I believe this is to do with the endpoint being a PUT but expecting a multipart form (all my research points to this being supported by POST only). I've tried several different approaches, both with cURL and with various Python libraries - including PyCurl to try and use the multipart in a POST request and override only the method to PUT - but just don't seem to be getting anywhere.

I haven't been able to find any recent documentation on this, as the older articles imply it's a deprecated API but the newer docs don't seem to have the answers I'm looking for. Issues like this one suggest it's still possible, and I've seen mention of web-ext but I think I'm just missing how to put the pieces together.

My request is:

    curl -XPUT https://addons.mozilla.org/api/v3/addons/{myId}/versions/0.2 -F 'upload=../toolbox.api' -H 'Authorization: JWT <myToken>' -v -L

Has anyone tried to do this and have any advice on how to move forward? Or conversely know that it's definitely not possible?

Thanks in advance!

Body:
You can use the node.js based command web-ext to sign extensions from command line.

Like with the curl approach you obtain the issuer/secret, then use those as given arguments or environment variables:

web-ext sign --api-key=$AMO_JWT_ISSUER --api-secret=$AMO_JWT_SECRET

If you need to use a proxy:

web-ext sign --api-key=... --api-secret=... --api-proxy=https://yourproxy:6000

Please see the linked article for details (and its other features).


问:
TypeError: '<' not supported between instances of 'float' and 'function'
I am trying to create a very simple virus-cure simulation. I created two files (infection.py and medicine.py), one simulating a virus and one simulating a very simplified cure. The first program works perfectly fine on its own. It is returning a list containing the amount of viruses for each time unit. The second program has the first program imported and is supossed to create some kind of cure. I mostly use predefined functions from program 1, and I redefined simulate().

To understand this program: 'The Cure' starts after timestep = 100, this is after the virus has been diagnosed. The virus can only reproduce if it is resistant to the cure, in other words, if the virus contains 'AAA'. A virus can die, reproduce and mutate. A mutation can sometimes result in resistancy.

Everything should be working (in theory?), however I get the same error message over and over again when running program 2: TypeError: '<' not supported between instances of 'float' and 'function'. I know what it means, but it says the error comes from a function predefined in program 1. But program 1 has no difficulty running this function whatsoever. I tried storing the value of random.random() and then using it, but this did not work. This is my code:

PROGRAM 1

```<code>import random

def generateVirus(length):
    return ''.join([random.choice(['A', 'G', 'T', 'C']) for i in range(length)])

def mutate(virus):
    rand = random.randint(0, len(virus)-1)
    return virus[:rand] + random.choice([i for i in 'AGTC' if i != virus[rand]]) + virus[rand+1:]

def kill(viruses, mortalityProb):
    return [survivors for survivors in viruses if random.random() > mortalityProb]

def reproduce(viruses, mutationProb, reproductionProb):
    nextgen = []
    for i in viruses:
        nextgen.append(i)
        if random.random() < reproductionProb:
            if random.random() < mutationProb:
                nextgen.append(mutate(i))
            else:
                nextgen.append(i)
    return nextgen

def reproductionProbability(viruses, maxReproductionProb, maxPopulation):
    return (1 - (len(viruses) / maxPopulation)) * maxReproductionProb

def simulate(viruses, mortalityProb, mutationProb, maxReproductionProb,
    maxPopulation, timesteps = 500):
    pop_size = []
    while timesteps > -1:
        survivors = kill(viruses, mortalityProb)
        reproductionProb = reproductionProbability(survivors, maxReproductionProb, maxPopulation)
        viruses = reproduce(survivors, mutationProb, reproductionProb)
        pop_size.append(len(viruses))
        timesteps -= 1
    return pop_size

print(simulate(['GCTCC', 'CCGG', 'AACCGG', 'CCCTATAGG'], 0.05, 0.1, 0.07, 1000))
</code>```

PROGRAM 2

```<code>import infection

def isResistent(virus):
    if virus.find('AAA') > -1:
        return True
    else:
        return False

def simulate(viruses, mortalityProb, mutationProb, maxReproductionProb, maxPopulation, timesteps = 500):
    activation_cure = 400
    while timesteps > -1:
        survivors = infection.kill(viruses, mortalityProb)
        for virus in viruses:
            if timesteps < activation_cure and isResistent(virus):
                reproductionProb = infection.reproductionProbability
                infection.reproduce(viruses, mutationProb, reproductionProb)
        timesteps -= 1
    return len(viruses)

def experiment(numberOfPatients):
    cured = 0
    viruses = []
    for i in range(10):
        viruses.append(infection.generateVirus(16))
    for i in range(numberOfPatients):
        remaining_virus = simulate(viruses, 0.05, 0.1, 0.07, 1000)
        if remaining_virus[len(remaining_virus)-1] == 0:
            cured += 1
    return cured

print(experiment(5))
</code>```

COMPLETE ERROR MESSAGE

```<code>File "C:\something\workspace\infection.py", line 17, in reproduce
if random.random() < reproductionProb:
TypeError: '<' not supported between instances of 'float' and 'function'
</code>```

答:
The error message is clear: This line (line 17) is the problem:

```<code> if random.random() < reproductionProb
</code>```

random.random() is a float and reproductionProb a function handle. You cannot compare a float with a function.

```<code>reproductionProb = infection.reproductionProbability
</code>```

is the call where you are passing a function handle instead of a float.

Also you need to make sure to encapsulate your main function as:

```<code>if __name__=='__main__':
</code>```

If you import your file this prevents the main function of the imported file being called.

Body:
I am trying to create a very simple virus-cure simulation. I created two files (infection.py and medicine.py), one simulating a virus and one simulating a very simplified cure. The first program works perfectly fine on its own. It is returning a list containing the amount of viruses for each time unit. The second program has the first program imported and is supossed to create some kind of cure. I mostly use predefined functions from program 1, and I redefined simulate().

To understand this program: 'The Cure' starts after timestep = 100, this is after the virus has been diagnosed. The virus can only reproduce if it is resistant to the cure, in other words, if the virus contains 'AAA'. A virus can die, reproduce and mutate. A mutation can sometimes result in resistancy.

Everything should be working (in theory?), however I get the same error message over and over again when running program 2: TypeError: '<' not supported between instances of 'float' and 'function'. I know what it means, but it says the error comes from a function predefined in program 1. But program 1 has no difficulty running this function whatsoever. I tried storing the value of random.random() and then using it, but this did not work. This is my code:

PROGRAM 1

import random

def generateVirus(length):
    return ''.join([random.choice(['A', 'G', 'T', 'C']) for i in range(length)])

def mutate(virus):
    rand = random.randint(0, len(virus)-1)
    return virus[:rand] + random.choice([i for i in 'AGTC' if i != virus[rand]]) + virus[rand+1:]

def kill(viruses, mortalityProb):
    return [survivors for survivors in viruses if random.random() > mortalityProb]

def reproduce(viruses, mutationProb, reproductionProb):
    nextgen = []
    for i in viruses:
        nextgen.append(i)
        if random.random() < reproductionProb:
            if random.random() < mutationProb:
                nextgen.append(mutate(i))
            else:
                nextgen.append(i)
    return nextgen

def reproductionProbability(viruses, maxReproductionProb, maxPopulation):
    return (1 - (len(viruses) / maxPopulation)) * maxReproductionProb

def simulate(viruses, mortalityProb, mutationProb, maxReproductionProb,
    maxPopulation, timesteps = 500):
    pop_size = []
    while timesteps > -1:
        survivors = kill(viruses, mortalityProb)
        reproductionProb = reproductionProbability(survivors, maxReproductionProb, maxPopulation)
        viruses = reproduce(survivors, mutationProb, reproductionProb)
        pop_size.append(len(viruses))
        timesteps -= 1
    return pop_size

print(simulate(['GCTCC', 'CCGG', 'AACCGG', 'CCCTATAGG'], 0.05, 0.1, 0.07, 1000))

PROGRAM 2

import infection

def isResistent(virus):
    if virus.find('AAA') > -1:
        return True
    else:
        return False

def simulate(viruses, mortalityProb, mutationProb, maxReproductionProb, maxPopulation, timesteps = 500):
    activation_cure = 400
    while timesteps > -1:
        survivors = infection.kill(viruses, mortalityProb)
        for virus in viruses:
            if timesteps < activation_cure and isResistent(virus):
                reproductionProb = infection.reproductionProbability
                infection.reproduce(viruses, mutationProb, reproductionProb)
        timesteps -= 1
    return len(viruses)

def experiment(numberOfPatients):
    cured = 0
    viruses = []
    for i in range(10):
        viruses.append(infection.generateVirus(16))
    for i in range(numberOfPatients):
        remaining_virus = simulate(viruses, 0.05, 0.1, 0.07, 1000)
        if remaining_virus[len(remaining_virus)-1] == 0:
            cured += 1
    return cured

print(experiment(5))

COMPLETE ERROR MESSAGE

File "C:\something\workspace\infection.py", line 17, in reproduce
if random.random() < reproductionProb:
TypeError: '<' not supported between instances of 'float' and 'function'

Body:
The error message is clear: This line (line 17) is the problem:

 if random.random() < reproductionProb

random.random() is a float and reproductionProb a function handle. You cannot compare a float with a function.

reproductionProb = infection.reproductionProbability

is the call where you are passing a function handle instead of a float.

Also you need to make sure to encapsulate your main function as:

if __name__=='__main__':

If you import your file this prevents the main function of the imported file being called.


问:
What is the rationale for limitations on pointer arithmetic or comparison?
In C/C++, addition or subtraction on pointer is defined only if the resulting pointer lies within the original pointed complete object. Moreover, comparison of two pointers can only be performed if the two pointed objects are subobjects of a unique complete object.

What are the reasons of such limitations?

I supposed that segmented memory model (see here §1.2.1) could be one of the reasons but since compilers can actually define a total order on all pointers as demonstrated by this answer, I am doubting this.

答:
You only prove that the restriction could be removed - but miss that it would come with a cost (in terms of memory and code) - which was contrary to the goals of C.

Specifically the difference needs to have a type, which is ptrdiff_t, and one would assume it is similar to size_t.

In a segmented memory model you (normally) indirectly have a limitation on the sizes of objects - assuming that the answers in: What's the real size of `size_t`, `uintptr_t`, `intptr_t` and `ptrdiff_t` type on 16-bit systems using segmented addressing mode? are correct.

Thus at least for differences removing that restriction would not only add extra instructions to ensure a total order - for an unimportant corner case (as in other answer), but also spend double the amount of memory for differences etc.

C was designed to be more minimalistic and not to force compiler to spend memory and code on such cases. (In those days memory limitations mattered more.)

Obviously there are also other benefits - like the possibility to detect errors when mixing pointers from different arrays. Similarly as mixing iterators for two different containers is undefined in C++ (with some minor exceptions) - and some debug-implementations detect such errors.


问:
Chain Laravel traits/scopes
I would like to chain 2 global scopes which are accessible through traits I made.

```<code>trait ActivatedTrait
{
    public static function bootActivatedTrait()
    {
        static::addGlobalScope(new ActivatedScope);
    }

    public static function withInactive()
    {
        $instance = new static;
        return $instance->newQueryWithoutScope(new ActivatedScope);
    }
}

trait PublishedTrait
{
    public static function bootPublishedTrait()
    {
        static::addGlobalScope(new PublishedScope);
    }

    public static function withUnpublished()
    {
        $instance = new static;
        return $instance->newQueryWithoutScope(new PublishedScope);
    }
}
</code>```

When I call my model like this, it works

```<code>MyModel::withInactive()
MyModel::withUnpublished()
</code>```

But this doesn't

```<code>MyModel::withInactive()->withUnpublished()
</code>```

EDIT

For some reason, this code worked under Laravel 4.2, but I switched to 5.5 and now it broke.

EDIT 2

If I make local scopes like scopeWithInactive() and scopeWithUnpublished() I can chain them just fine.

答:
Since I was new to the project, I didn't quite understand what was being done since I didn't have the needed insight after that part broke after upgrade. What I did was:

Eliminate traits, added normal L 5.5 global scopes (this one fetches only active items with each request)

```<code>class ActivatedScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('content.is_active', 1);
    }
}
</code>```

Booted them up in model

```<code>protected static function boot()
{
    parent::boot();
    static::addGlobalScope(new ActivatedScope());
    static::addGlobalScope(new PublishedScope());
}
</code>```

And added local scopes which would cancel the effect of it:

```<code>public function scopeWithInactive($query)
{
    return $query->withoutGlobalScope(ActivatedScope::class);
}
</code>```

This enabled me to do this:

```<code>Item::all() // <- only active and published items

Item::withInactive()->get() // <- published items which are either active or inactive

Item.:withInactive()->withUnpublished()->get() // <- all items from DB
</code>```

NOTE

My initial question was wrong as there is no point in "chaining" anything here since global scopes are applied to the model automatically. If I use 2 global scopes, both are applied. So it was a matter of chaining functions which would disable the effect of global scope.

Title: Chain Laravel traits/scopes

Body:
I would like to chain 2 global scopes which are accessible through traits I made.

trait ActivatedTrait
{
    public static function bootActivatedTrait()
    {
        static::addGlobalScope(new ActivatedScope);
    }

    public static function withInactive()
    {
        $instance = new static;
        return $instance->newQueryWithoutScope(new ActivatedScope);
    }
}

trait PublishedTrait
{
    public static function bootPublishedTrait()
    {
        static::addGlobalScope(new PublishedScope);
    }

    public static function withUnpublished()
    {
        $instance = new static;
        return $instance->newQueryWithoutScope(new PublishedScope);
    }
}

When I call my model like this, it works

MyModel::withInactive()
MyModel::withUnpublished()

But this doesn't

MyModel::withInactive()->withUnpublished()

EDIT

For some reason, this code worked under Laravel 4.2, but I switched to 5.5 and now it broke.

EDIT 2

If I make local scopes like scopeWithInactive() and scopeWithUnpublished() I can chain them just fine.

Body:
Since I was new to the project, I didn't quite understand what was being done since I didn't have the needed insight after that part broke after upgrade. What I did was:

Eliminate traits, added normal L 5.5 global scopes (this one fetches only active items with each request)

class ActivatedScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('content.is_active', 1);
    }
}

Booted them up in model

protected static function boot()
{
    parent::boot();
    static::addGlobalScope(new ActivatedScope());
    static::addGlobalScope(new PublishedScope());
}

And added local scopes which would cancel the effect of it:

public function scopeWithInactive($query)
{
    return $query->withoutGlobalScope(ActivatedScope::class);
}

This enabled me to do this:

Item::all() // <- only active and published items

Item::withInactive()->get() // <- published items which are either active or inactive

Item.:withInactive()->withUnpublished()->get() // <- all items from DB

NOTE

My initial question was wrong as there is no point in "chaining" anything here since global scopes are applied to the model automatically. If I use 2 global scopes, both are applied. So it was a matter of chaining functions which would disable the effect of global scope.


问:
Calling function without use touching textarea?
I have 3 values where user can customize banner (color/image/border color) and those changes are added to textarea below (output is HTML).

So far i manage to get it working with button but problem is that with every change user has to press it (to see how it looks) and if i use something like onClick or onChange it will somehow update with previous change and not current change (this happens duo color picker as code is put in front and not on end (i think)).

```<code><textarea name="html_code" class="form-control" id="html_code"rows="2" cols="40"></textarea>
<input type="button" class="btn btn-info" value="Preview Banner" onclick="get_text();" />

<script type="text/javascript">
    function get_text() {
    $("#preview").html($("#html_code").val());
     }
   </script>
</code>```

So my question is, how could i make function start when text change in textarea without user editing something in it. (if something like that is even possible to achieve in this way). Thanks for suggestions :)

答:
So my question is, how could i make function start when text change in
  textarea without user editing something in it.

Use change event on textarea (or input if user copy-paste value in it)

```<code>$("#html_code").on( "change input", function(){
    $("#preview").html( $(this).val() );
})
</code>```

Body:
I have 3 values where user can customize banner (color/image/border color) and those changes are added to textarea below (output is HTML).

So far i manage to get it working with button but problem is that with every change user has to press it (to see how it looks) and if i use something like onClick or onChange it will somehow update with previous change and not current change (this happens duo color picker as code is put in front and not on end (i think)).

<textarea name="html_code" class="form-control" id="html_code"rows="2" cols="40"></textarea>
<input type="button" class="btn btn-info" value="Preview Banner" onclick="get_text();" />

So my question is, how could i make function start when text change in textarea without user editing something in it. (if something like that is even possible to achieve in this way). Thanks for suggestions :)

Body:
So my question is, how could i make function start when text change in
  textarea without user editing something in it.

Use change event on textarea (or input if user copy-paste value in it)

$("#html_code").on( "change input", function(){
    $("#preview").html( $(this).val() );
})


问:
Will an XML sitemap make affect my website's PCI compliance?
I have an ecommerce website that's PCI compliant, and the website does not have an XML sitemap. The previous webmaster stated that he removed the sitemap because it caused the website to fail PCI validation testing. (We use the McAfee SECURE service for automated testing.)  I'd like to restore the sitemap for SEO, but I don't want to jeopardize our compliance.

Assuming that my new sitemap only includes relevant product/information link information, do I have anything to worry about?

答: Create an account on Webmaster tools and if you encounter problems search the help, this should not be a problem.</p>


问:
Read excel (xlsx) file in java using Apoche POI (getting weird numbers)
I have to open a testdate for a schoolproject. This testdate is a excel(xlsx) file that includes number, letter, date and time. But with the code below it reads the excel file, but i get weird numbers like 42538.0 and 1.153481443E9. after date.

```<code>public class Page4_Controller implements Initializable {

    @FXML
    private Button button1;

    public void Button1Action(ActionEvent event) throws IOException {
        //Initialize excel file
        FileChooser fc = new FileChooser();
        fc.getExtensionFilters().addAll(
                new ExtensionFilter("Excel Files", "*.xlsx"));
        File selectedFile = fc.showOpenDialog(null);

        // Read file
        readXLSXFile(selectedFile.getAbsolutePath());
    }

    public static void readXLSXFile(String excelFilePath) throws IOException {
        FileInputStream fys = new FileInputStream(new File(excelFilePath));

        //Create workbook instance that refers to .xlsx file
        XSSFWorkbook wb = new XSSFWorkbook(fys);

        //Create a sheet object to retrive the sheet
        XSSFSheet sheet = wb.getSheetAt(0);

        //That is for evalueate the cell type
        FormulaEvaluator forlulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
        DataFormatter df = new DataFormatter();

        //Default data for database (comes later)
        //String airport = sheet.getRow(1).getCell(1).getStringCellValue();
        //Date date = sheet.getRow(2).getCell(1).getDateCellValue();

        for (Row row : sheet) {
            for (Cell cell : row) {
                switch (forlulaEvaluator.evaluateInCell(cell).getCellType()) {
                    //If cell is a numeric format
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        System.out.print(df.formatCellValue(cell) + "\t");
                        break;
                    //If cell is a string format
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getRichStringCellValue() + "\t");
                        break;
                }

            }
            System.out.println();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

}
</code>```

答: This is the excel file that I have to read in java

Body:
I have to open a testdate for a schoolproject. This testdate is a excel(xlsx) file that includes number, letter, date and time. But with the code below it reads the excel file, but i get weird numbers like 42538.0 and 1.153481443E9. after date.

public class Page4_Controller implements Initializable {

    @FXML
    private Button button1;

    public void Button1Action(ActionEvent event) throws IOException {
        //Initialize excel file
        FileChooser fc = new FileChooser();
        fc.getExtensionFilters().addAll(
                new ExtensionFilter("Excel Files", "*.xlsx"));
        File selectedFile = fc.showOpenDialog(null);

        // Read file
        readXLSXFile(selectedFile.getAbsolutePath());
    }

    public static void readXLSXFile(String excelFilePath) throws IOException {
        FileInputStream fys = new FileInputStream(new File(excelFilePath));

        //Create workbook instance that refers to .xlsx file
        XSSFWorkbook wb = new XSSFWorkbook(fys);

        //Create a sheet object to retrive the sheet
        XSSFSheet sheet = wb.getSheetAt(0);

        //That is for evalueate the cell type
        FormulaEvaluator forlulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
        DataFormatter df = new DataFormatter();

        //Default data for database (comes later)
        //String airport = sheet.getRow(1).getCell(1).getStringCellValue();
        //Date date = sheet.getRow(2).getCell(1).getDateCellValue();

        for (Row row : sheet) {
            for (Cell cell : row) {
                switch (forlulaEvaluator.evaluateInCell(cell).getCellType()) {
                    //If cell is a numeric format
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        System.out.print(df.formatCellValue(cell) + "\t");
                        break;
                    //If cell is a string format
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getRichStringCellValue() + "\t");
                        break;
                }

            }
            System.out.println();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

}


问:
Python: Finding a substring in a string, but returning True or False instead of the index position
I need to check if a substring is part of a specific string. The substring is 'AAA' and if it is found in the given string, it must return True. If it isn't in the string, it must return False

```<code>def isResistent(virus):
    gen = "AAA"
    if gen in virus:
        print("True")
    else:
        print("False")

isResistent('GCAAGCTGGTCGTGAAAGCT')
</code>```

It returns True or False, but besides True or False it first gives the index number or something. When I run the program several times it returns:

Output:

```<code>2
True

1
True

2
True

4
True

0
True
</code>```

Is it possible to only print True or False?

答:
Your function should just return 'AAA' in virus.

```<code>def isResistent(virus):
    return 'AAA' in virus

>>> isResistent('GCAAGCTGGTCGTGAAAGCT')
True
</code>```

Body:
I need to check if a substring is part of a specific string. The substring is 'AAA' and if it is found in the given string, it must return True. If it isn't in the string, it must return False

def isResistent(virus):
    gen = "AAA"
    if gen in virus:
        print("True")
    else:
        print("False")

isResistent('GCAAGCTGGTCGTGAAAGCT')

It returns True or False, but besides True or False it first gives the index number or something. When I run the program several times it returns:

Output:

2
True

1
True

2
True

4
True

0
True

Is it possible to only print True or False?

Body:
Your function should just return 'AAA' in virus.

def isResistent(virus):
    return 'AAA' in virus

>>> isResistent('GCAAGCTGGTCGTGAAAGCT')
True


问:
Permission issues when deploying docker image in OpenShift/Minishift
This question relates to the local version of OpenShift, Minishift. I am runnning on MacOS.

I am attempting to deploy an application called Mountebank from docker hub, here is the source:

https://hub.docker.com/r/andyrbell/mountebank/

The DockerFile goes as follows:

```<code>FROM alpine:3.6
EXPOSE 2525
CMD ["mb"]
ENV NODE_VERSION=6.10.3-r1

RUN apk update \
  && apk add --no-cache nodejs=${NODE_VERSION} \
  && apk add --no-cache nodejs-npm=${NODE_VERSION}

ENV MOUNTEBANK_VERSION=1.13.0

RUN npm install -g mountebank@${MOUNTEBANK_VERSION} --production \
  && npm cache clean \
  && rm -rf /tmp/npm*
</code>```

I can run the Mountebank image within a container locally on MacOS fine.

When I install the image inside Minishift and attempt to start a pod, I get the following error:

```<code>    /usr/lib/node_modules/mountebank/node_modules/q/q.js:155
    throw e;
    ^
    Error: EACCES: permission denied, open 'mb.pid'
    at Error (native)
    at Object.fs.openSync (fs.js:641:18)
    at Object.fs.writeFileSync (fs.js:1347:33)
    at /usr/lib/node_modules/mountebank/bin/mb:176:16
    at _fulfilled (/usr/lib/node_modules/mountebank/node_modules/q/q.js:854:54)
    at self.promiseDispatch.done (/usr/lib/node_modules/mountebank/node_modules/q/q.js:883:30)
    at Promise.promise.promiseDispatch (/usr/lib/node_modules/mountebank/node_modules/q/q.js:816:13)
    at /usr/lib/node_modules/mountebank/node_modules/q/q.js:624:44
    at runSingle (/usr/lib/node_modules/mountebank/node_modules/q/q.js:137:13)
    at flush (/usr/lib/node_modules/mountebank/node_modules/q/q.js:125:13)
</code>```

I am assuming this is related to permission issues under which my pod is running in Minishift, but am unaware how to go about changing them.

Any help is appreciated,

Many thanks

答:
OK, so here's how I fixed my issues. I moved the location where the mb.pid and mb.log files were going to be stored. They were initially stored at root, which caused problems when the image was hosted within Minishift:

```<code>FROM alpine:3.6

EXPOSE 2525

CMD mb --pidfile /tmp/mb.pid --logfile /tmp/mb.log

ENV NODE_VERSION=6.10.3-r1

RUN apk update \
&& apk add --no-cache nodejs=${NODE_VERSION} \
&& apk add --no-cache nodejs-npm=${NODE_VERSION}

ENV MOUNTEBANK_VERSION=1.13.0

RUN npm install -g mountebank@${MOUNTEBANK_VERSION} --production \
&& npm cache clean \
&& rm -rf /tmp/npm*
</code>```

Notice the --pidfile --logfile storing the files in /tmp/

Body:
This question relates to the local version of OpenShift, Minishift. I am runnning on MacOS.

I am attempting to deploy an application called Mountebank from docker hub, here is the source:

https://hub.docker.com/r/andyrbell/mountebank/

The DockerFile goes as follows:

FROM alpine:3.6
EXPOSE 2525
CMD ["mb"]
ENV NODE_VERSION=6.10.3-r1

RUN apk update \
  && apk add --no-cache nodejs=${NODE_VERSION} \
  && apk add --no-cache nodejs-npm=${NODE_VERSION}

ENV MOUNTEBANK_VERSION=1.13.0

RUN npm install -g mountebank@${MOUNTEBANK_VERSION} --production \
  && npm cache clean \
  && rm -rf /tmp/npm*

I can run the Mountebank image within a container locally on MacOS fine.

When I install the image inside Minishift and attempt to start a pod, I get the following error:

    /usr/lib/node_modules/mountebank/node_modules/q/q.js:155
    throw e;
    ^
    Error: EACCES: permission denied, open 'mb.pid'
    at Error (native)
    at Object.fs.openSync (fs.js:641:18)
    at Object.fs.writeFileSync (fs.js:1347:33)
    at /usr/lib/node_modules/mountebank/bin/mb:176:16
    at _fulfilled (/usr/lib/node_modules/mountebank/node_modules/q/q.js:854:54)
    at self.promiseDispatch.done (/usr/lib/node_modules/mountebank/node_modules/q/q.js:883:30)
    at Promise.promise.promiseDispatch (/usr/lib/node_modules/mountebank/node_modules/q/q.js:816:13)
    at /usr/lib/node_modules/mountebank/node_modules/q/q.js:624:44
    at runSingle (/usr/lib/node_modules/mountebank/node_modules/q/q.js:137:13)
    at flush (/usr/lib/node_modules/mountebank/node_modules/q/q.js:125:13)

I am assuming this is related to permission issues under which my pod is running in Minishift, but am unaware how to go about changing them.

Any help is appreciated,

Many thanks

Body:
OK, so here's how I fixed my issues. I moved the location where the mb.pid and mb.log files were going to be stored. They were initially stored at root, which caused problems when the image was hosted within Minishift:

FROM alpine:3.6

EXPOSE 2525

CMD mb --pidfile /tmp/mb.pid --logfile /tmp/mb.log

ENV NODE_VERSION=6.10.3-r1

RUN apk update \
&& apk add --no-cache nodejs=${NODE_VERSION} \
&& apk add --no-cache nodejs-npm=${NODE_VERSION}

ENV MOUNTEBANK_VERSION=1.13.0

RUN npm install -g mountebank@${MOUNTEBANK_VERSION} --production \
&& npm cache clean \
&& rm -rf /tmp/npm*

Notice the --pidfile --logfile storing the files in /tmp/


问:
Rxjava2 how to return cached values if time does't come out
I have a question. I have simple Observable.

```<code>public interface CitiesApi {
    @GET("location/cities")
    Observable<List<City>> getCities(@Query("country") String countryId);
}
</code>```

Also I have class(manager), which save data from this observable and turn it over to activity or presenter.

```<code>public class Manager {

    @Inject
    CitiesApi mCitiesApi;

    private Date mDate;
    private List<City> mCities;

    public Observable<List<City>> getObservable() {
        return mCitiesApi.getCities("123");
    }
}
</code>```

Question: When i subscribe on this observable, and

current time - last subscribe time < 10 min(or other range, it doesn't
  matter...)

I want to call onNext with old data. But if time difference > 10 i want to download data from web (return original observable). I don't want to use retrofit cache, cause i could change this list manually.

答:
You Observable must llok like that:</p>

```<code>public Observable<List<City>> getObservable() {

if (cacheTime > 10){ //If cached data time is greater than 10min, you make your network call.
        return mCitiesApi.getCities("123");
} else{
    return Observable.just(getChachedData("123")) //Where getChachedData is a method that return a list of your cached data.
}
}
</code>```

Body:
I have a question. I have simple Observable.

public interface CitiesApi {
    @GET("location/cities")
    Observable<List<City>> getCities(@Query("country") String countryId);
}

Also I have class(manager), which save data from this observable and turn it over to activity or presenter.

public class Manager {

    @Inject
    CitiesApi mCitiesApi;

    private Date mDate;
    private List<City> mCities;

    public Observable<List<City>> getObservable() {
        return mCitiesApi.getCities("123");
    }
}

Question: When i subscribe on this observable, and

current time - last subscribe time < 10 min(or other range, it doesn't
  matter...)

I want to call onNext with old data. But if time difference > 10 i want to download data from web (return original observable). I don't want to use retrofit cache, cause i could change this list manually.

Body:
You Observable must llok like that:

public Observable<List<City>> getObservable() {

if (cacheTime > 10){ //If cached data time is greater than 10min, you make your network call.
        return mCitiesApi.getCities("123");
} else{
    return Observable.just(getChachedData("123")) //Where getChachedData is a method that return a list of your cached data.
}
}