问:
Hibernate Envers - Audited Entity can't recover ID from empty audited table relation
I need some help on Hibernate Envers. I have the following scenario:

I have a Entity in Hibernate/JPA and this Entity has a normal configuration:

```<code>    package com.algar.fsw.siscos.model;

/**
 * TbUsuario generated by hbm2java
 */
@Entity
@Table(name = "SCCTB023_USUARIO")
@Audited
@AuditTable("SCCTB047_USUARIO_ADTRA")
public class Usuario implements java.io.Serializable {

    @Id
    @Column(name = "NU_USUARIO", nullable = false, scale = 0)
    @NotNull
    private Long id;

    @Column(name = "NO_USUARIO", nullable = false, length = 50)
    @NotNull
    @Length(max = 50)
    private String nome;

    @Column(name = "NO_LOGIN", unique = true, nullable = false, length = 16)
    @NotNull
    @Length(max = 16)
    private String login;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "NU_PERFIL", nullable = false)
    private Perfil perfil = new Perfil();

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "usuario" , cascade = CascadeType.ALL)
    private List<UsuarioGrupo> usuariosGrupos = new ArrayList<UsuarioGrupo>();

    public Usuario() {
    }

    public Usuario(Long id ) {
        this.id = id;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getLogin() {
        return login;
    }
    public void setLogin(String login) {
        this.login = login;
    }

    public Perfil getPerfil() {
        return perfil;
    }
    public void setPerfil(Perfil perfil) {
        this.perfil = perfil;
    }

    public List<UsuarioGrupo> getUsuariosGrupos() {
        return usuariosGrupos;
    }
    public void setUsuariosGrupos(List<UsuarioGrupo> usuariosGrupos) {
        this.usuariosGrupos = usuariosGrupos;
    }
}
</code>```

And, this Entity has a relation with this Entity:

```<code>package com.algar.fsw.siscos.model;

@Entity
@Table(name = "SCCTB018_PERFIL")
@Audited
@AuditTable("SCCTB042_PERFIL_ADTRA")
public class Perfil implements java.io.Serializable {

    @Id
    @Column(name = "NU_PERFIL", nullable = false, scale = 0)
    @NotNull
    private Long id;

    @Column(name = "NO_PERFIL", nullable = false, length = 30)
    @NotNull
    @Enumerated(EnumType.STRING)
    private PerfilEnum perfilEnum;

    @Column(name = "IC_ATIVO", nullable = false, precision = 1, scale = 0)
    private boolean ativo = true;

    @Column(name = "NU_NIVEL", nullable = false, precision = 1, scale = 0)
    private Long nivel;

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return perfilEnum.toString();
    }

    public boolean isAtivo() {
        return ativo;
    }
    public void setAtivo(boolean ativo) {
        this.ativo = ativo;
    }

    public Long getNivel() {
        return nivel;
    }

    public void setNivel(Long nivel) {
        this.nivel = nivel;
    }

    public PerfilEnum getPerfilEnum() {
        return perfilEnum;
    }

    public void setPerfilEnum(PerfilEnum perfilEnum) {
        this.perfilEnum = perfilEnum;
    }
}
</code>```

When I retrieve the Usuario information, everything is ok, but when I call the method getPerfil I receive a NoEntityFoundException because of the ID of the relation. The data exists only in the regular table, in the audited table the data does not exist because the Audited tables were created after the data already exists in the original table so no records were putted on audited table . I need to recover only the ID, I don't need the data from Perfil. So, if I call getPerfil, the only thing I need is the ID information.

Does anyone know a workaround or some solution for this kind of problem?

The reason I need this is because of an WEB application that has a screen that shows the changes in some Entity, showing the values: date_created, property_changed, value_before and value_after. So I'm constructing the logic to compare the revisions manually in java.

Please, could anyone help me?

Thanks

答:
I had similar issue and the only solution (workaround) that helped me was to manual insert all data prior to envers as initial revision 1 with zero timestamp (1970-01-01). For your case it would be something like this:</p>

```<code>INSERT INTO REVINFO(REV, REVTSTMP) VALUES(1, 0);

INSERT INTO SCCTB047_USUARIO_ADTRA
(REV, REVTYPE, NU_USUARIO, NO_USUARIO, NO_LOGIN, NU_PERFIL)
SELECT 1, 0, NU_USUARIO, NO_USUARIO, NO_LOGIN, NU_PERFIL FROM SCCTB023_USUARIO;

INSERT INTO SCCTB042_PERFIL_ADTRA
(REV, REVTYPE, NU_PERFIL, NO_PERFIL, IC_ATIVO, NU_NIVEL)
SELECT 1, 0, NU_PERFIL, NO_PERFIL, IC_ATIVO, NU_NIVEL FROM SCCTB018_PERFIL;
</code>```

Body:
I need some help on Hibernate Envers. I have the following scenario:

I have a Entity in Hibernate/JPA and this Entity has a normal configuration:

    package com.algar.fsw.siscos.model;

/**
 * TbUsuario generated by hbm2java
 */
@Entity
@Table(name = "SCCTB023_USUARIO")
@Audited
@AuditTable("SCCTB047_USUARIO_ADTRA")
public class Usuario implements java.io.Serializable {

    @Id
    @Column(name = "NU_USUARIO", nullable = false, scale = 0)
    @NotNull
    private Long id;

    @Column(name = "NO_USUARIO", nullable = false, length = 50)
    @NotNull
    @Length(max = 50)
    private String nome;

    @Column(name = "NO_LOGIN", unique = true, nullable = false, length = 16)
    @NotNull
    @Length(max = 16)
    private String login;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "NU_PERFIL", nullable = false)
    private Perfil perfil = new Perfil();

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "usuario" , cascade = CascadeType.ALL)
    private List<UsuarioGrupo> usuariosGrupos = new ArrayList<UsuarioGrupo>();

    public Usuario() {
    }

    public Usuario(Long id ) {
        this.id = id;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getLogin() {
        return login;
    }
    public void setLogin(String login) {
        this.login = login;
    }

    public Perfil getPerfil() {
        return perfil;
    }
    public void setPerfil(Perfil perfil) {
        this.perfil = perfil;
    }

    public List<UsuarioGrupo> getUsuariosGrupos() {
        return usuariosGrupos;
    }
    public void setUsuariosGrupos(List<UsuarioGrupo> usuariosGrupos) {
        this.usuariosGrupos = usuariosGrupos;
    }
}

And, this Entity has a relation with this Entity:

package com.algar.fsw.siscos.model;

@Entity
@Table(name = "SCCTB018_PERFIL")
@Audited
@AuditTable("SCCTB042_PERFIL_ADTRA")
public class Perfil implements java.io.Serializable {

    @Id
    @Column(name = "NU_PERFIL", nullable = false, scale = 0)
    @NotNull
    private Long id;

    @Column(name = "NO_PERFIL", nullable = false, length = 30)
    @NotNull
    @Enumerated(EnumType.STRING)
    private PerfilEnum perfilEnum;

    @Column(name = "IC_ATIVO", nullable = false, precision = 1, scale = 0)
    private boolean ativo = true;

    @Column(name = "NU_NIVEL", nullable = false, precision = 1, scale = 0)
    private Long nivel;

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return perfilEnum.toString();
    }

    public boolean isAtivo() {
        return ativo;
    }
    public void setAtivo(boolean ativo) {
        this.ativo = ativo;
    }

    public Long getNivel() {
        return nivel;
    }

    public void setNivel(Long nivel) {
        this.nivel = nivel;
    }

    public PerfilEnum getPerfilEnum() {
        return perfilEnum;
    }

    public void setPerfilEnum(PerfilEnum perfilEnum) {
        this.perfilEnum = perfilEnum;
    }
}

When I retrieve the Usuario information, everything is ok, but when I call the method getPerfil I receive a NoEntityFoundException because of the ID of the relation. The data exists only in the regular table, in the audited table the data does not exist because the Audited tables were created after the data already exists in the original table so no records were putted on audited table . I need to recover only the ID, I don't need the data from Perfil. So, if I call getPerfil, the only thing I need is the ID information.

Does anyone know a workaround or some solution for this kind of problem?

The reason I need this is because of an WEB application that has a screen that shows the changes in some Entity, showing the values: date_created, property_changed, value_before and value_after. So I'm constructing the logic to compare the revisions manually in java.

Please, could anyone help me?

Thanks

Body:
I had similar issue and the only solution (workaround) that helped me was to manual insert all data prior to envers as initial revision 1 with zero timestamp (1970-01-01). For your case it would be something like this:

INSERT INTO REVINFO(REV, REVTSTMP) VALUES(1, 0);

INSERT INTO SCCTB047_USUARIO_ADTRA
(REV, REVTYPE, NU_USUARIO, NO_USUARIO, NO_LOGIN, NU_PERFIL)
SELECT 1, 0, NU_USUARIO, NO_USUARIO, NO_LOGIN, NU_PERFIL FROM SCCTB023_USUARIO;

INSERT INTO SCCTB042_PERFIL_ADTRA
(REV, REVTYPE, NU_PERFIL, NO_PERFIL, IC_ATIVO, NU_NIVEL)
SELECT 1, 0, NU_PERFIL, NO_PERFIL, IC_ATIVO, NU_NIVEL FROM SCCTB018_PERFIL;


来源: stackexchange

问:
How to check if my iPhone app is hacked/cracked?
I'm wondering if there are some ways to check if my application is hacked?

I mean, I don't really want to prevent my application from hacking, but I would like to list all iPhone (UUID) that use my hacked application.

答: Check out mtiks. They do free piracy monitoring, but you'll have to re-release your app to the appstore. If you don't have anything setup currently, you're not going to be able to tell who's using it.</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
How to properly use dictionary collection?
Here is my code:

```<code>class className: Codable {
    let comments: [String: String, String:String]
}
</code>```

I am getting the following errors:

Expected ']' in dictionary type

Expected declaration

Consecutive declarations on a line muse be separated by ';'

From Swift docs it is done this way (I think):

```<code>let comments: [String: String]
</code>```

But for me it won't work because my comments in mongoose.Schema is defined as below (in the server):

```<code>comments: [{
    identifier: String,
    text: String
}]
</code>```

I defined comments collection to push it to the server for testing as below (it worked):

```<code>var comments = ["identifier" : "SomeRandomText", "text": "SomeRandomText"]
</code>```

Now my question is, how can I define the comments in my class that extends Codable to match my comments in the server?

答:
It should be an array of documents, so probably something like this should work:

```<code>class className: Codable {
    let comments: [{String: String, String:String}]
}
</code>```

And the collection for testing the same:

```<code>var comments = [{"identifier" : "SomeRandomText", "text": "SomeRandomText"}]
</code>```

Body:
Here is my code:

class className: Codable {
    let comments: [String: String, String:String]
}

I am getting the following errors:

Expected ']' in dictionary type

Expected declaration

Consecutive declarations on a line muse be separated by ';'

From Swift docs it is done this way (I think):

let comments: [String: String]

But for me it won't work because my comments in mongoose.Schema is defined as below (in the server):

comments: [{
    identifier: String,
    text: String
}]

I defined comments collection to push it to the server for testing as below (it worked):

var comments = ["identifier" : "SomeRandomText", "text": "SomeRandomText"]

Now my question is, how can I define the comments in my class that extends Codable to match my comments in the server?

Body:
It should be an array of documents, so probably something like this should work:

class className: Codable {
    let comments: [{String: String, String:String}]
}

And the collection for testing the same:

var comments = [{"identifier" : "SomeRandomText", "text": "SomeRandomText"}]


问:
iText 7.0.5 - Forms - NullPointerException when adding a lot of tables with form fields
I used Bruno's example (https://developers.itextpdf.com/examples/form-examples/clone-create-fields-table) to add form fields to tables in a newly created document. The example itself works without any problems, but if I want to create 50 tables I get the following exception:

```<code>Exception in thread "main" java.lang.NullPointerException
    at com.itextpdf.kernel.pdf.PdfDictionary.get(PdfDictionary.java:552)
    at com.itextpdf.kernel.pdf.PdfDictionary.getAsArray(PdfDictionary.java:156)
    at com.itextpdf.kernel.pdf.PdfPage.getAnnotations(PdfPage.java:743)
    at com.itextpdf.kernel.pdf.annot.PdfAnnotation.getPage(PdfAnnotation.java:427)
    at com.itextpdf.forms.fields.PdfFormField.regenerateField(PdfFormField.java:1781)
    at com.itextpdf.forms.fields.PdfFormField.setValue(PdfFormField.java:1043)
    at com.itextpdf.forms.fields.PdfFormField.setValue(PdfFormField.java:1004)
    at com.itextpdf.forms.fields.PdfFormField.setValue(PdfFormField.java:999)
    at com.itextpdf.forms.fields.PdfFormField.createText(PdfFormField.java:469)
    at com.itextpdf.forms.fields.PdfFormField.createText(PdfFormField.java:410)
    at com.itextpdf.forms.fields.PdfFormField.createText(PdfFormField.java:391)
    at CreateFormInTable$MyCellRenderer.draw(CreateFormInTable.java:62)
    at com.itextpdf.layout.renderer.TableRenderer.drawChildren(TableRenderer.java:1023)
    at com.itextpdf.layout.renderer.AbstractRenderer.draw(AbstractRenderer.java:458)
    at com.itextpdf.layout.renderer.TableRenderer.draw(TableRenderer.java:948)
    at com.itextpdf.layout.renderer.DocumentRenderer.flushSingleRenderer(DocumentRenderer.java:138)
    at com.itextpdf.layout.renderer.RootRenderer.processRenderer(RootRenderer.java:349)
    at com.itextpdf.layout.renderer.RootRenderer.shrinkCurrentAreaAndProcessRenderer(RootRenderer.java:338)
    at com.itextpdf.layout.renderer.RootRenderer.addChild(RootRenderer.java:236)
    at com.itextpdf.layout.RootElement.add(RootElement.java:109)
    at com.itextpdf.layout.Document.add(Document.java:143)
    at CreateFormInTable.manipulatePdf(CreateFormInTable.java:45)
    at CreateFormInTable.main(CreateFormInTable.java:25)
</code>```

I use Java 1.8.0_121 on Windows 8 Enterprise.

The modified manipulatePdf method looks like this:

```<code>protected void manipulatePdf(String dest) throws Exception {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);

    for (int i = 0; i < 50; i++) {
        System.out.println(i);
        Table table = new Table(2);
        Cell cell;
        cell = new Cell().add("Name:");
        table.addCell(cell);
        cell = new Cell();
        cell.setNextRenderer(new MyCellRenderer(cell, "name" + i));
        table.addCell(cell);
        cell = new Cell().add("Address");
        table.addCell(cell);
        cell = new Cell();
        cell.setNextRenderer(new MyCellRenderer(cell, "address" + i));
        table.addCell(cell);
        doc.add(table);
    }
    doc.close();
}
</code>```

The complete example that produces the NPE can be found here: https://github.com/trettstadtnlb/itext-table-form-fields

Has anyone experienced this kind of behaviour or can confirm that this is a bug?

答:
It is easy to reproduce this behavior in iText 7.0.x using much less content:

```<code>PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

PdfTextFormField field = PdfFormField.createText(pdfDoc, new Rectangle(100, 100, 300, 20), "name", "");
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
form.addField(field);

doc.close();
</code>```

The problem behind this is that for a form field (widget) without an associated page, iText tries to determine the page that widget is on by iterating all document pages and looking up their respective annotation arrays. And it already does so during createText, while setting the field value (and updating widget appearances)...

In the code above, though, the previous newly created pages, at least the first one, has already been flushed to the writer and de-initialized in memory. Thus, the loop over the pages tries to retrieve a value from a de-initialized page dictionary, i.e. from a null Map, hence the NullPointerException.

Whether this is a bug in iText or merely an anti-pattern, I don't know.

Inspired by @SamuelHuylebroeck's comment I tried both the OP's original code and the simplified code above with immediateFlush set to false. Indeed, this prevents the exception and the result of the simplified code looks ok. The result of the OP's original code, though, is not as he expects it, the table is built across four pages but all the fields turns up on the last page!

So, in case of form elements created directly (i.e. not via events) setting immediateFlush to false may be considered a work-around (but not a fix as the early flushing is an important feature of iText). The general case of form creation is broken, though, unless someone can point out that the code here is an iText 7 anti-pattern and can show how it should be done.

Body:
I used Bruno's example (https://developers.itextpdf.com/examples/form-examples/clone-create-fields-table) to add form fields to tables in a newly created document. The example itself works without any problems, but if I want to create 50 tables I get the following exception:

Exception in thread "main" java.lang.NullPointerException
    at com.itextpdf.kernel.pdf.PdfDictionary.get(PdfDictionary.java:552)
    at com.itextpdf.kernel.pdf.PdfDictionary.getAsArray(PdfDictionary.java:156)
    at com.itextpdf.kernel.pdf.PdfPage.getAnnotations(PdfPage.java:743)
    at com.itextpdf.kernel.pdf.annot.PdfAnnotation.getPage(PdfAnnotation.java:427)
    at com.itextpdf.forms.fields.PdfFormField.regenerateField(PdfFormField.java:1781)
    at com.itextpdf.forms.fields.PdfFormField.setValue(PdfFormField.java:1043)
    at com.itextpdf.forms.fields.PdfFormField.setValue(PdfFormField.java:1004)
    at com.itextpdf.forms.fields.PdfFormField.setValue(PdfFormField.java:999)
    at com.itextpdf.forms.fields.PdfFormField.createText(PdfFormField.java:469)
    at com.itextpdf.forms.fields.PdfFormField.createText(PdfFormField.java:410)
    at com.itextpdf.forms.fields.PdfFormField.createText(PdfFormField.java:391)
    at CreateFormInTable$MyCellRenderer.draw(CreateFormInTable.java:62)
    at com.itextpdf.layout.renderer.TableRenderer.drawChildren(TableRenderer.java:1023)
    at com.itextpdf.layout.renderer.AbstractRenderer.draw(AbstractRenderer.java:458)
    at com.itextpdf.layout.renderer.TableRenderer.draw(TableRenderer.java:948)
    at com.itextpdf.layout.renderer.DocumentRenderer.flushSingleRenderer(DocumentRenderer.java:138)
    at com.itextpdf.layout.renderer.RootRenderer.processRenderer(RootRenderer.java:349)
    at com.itextpdf.layout.renderer.RootRenderer.shrinkCurrentAreaAndProcessRenderer(RootRenderer.java:338)
    at com.itextpdf.layout.renderer.RootRenderer.addChild(RootRenderer.java:236)
    at com.itextpdf.layout.RootElement.add(RootElement.java:109)
    at com.itextpdf.layout.Document.add(Document.java:143)
    at CreateFormInTable.manipulatePdf(CreateFormInTable.java:45)
    at CreateFormInTable.main(CreateFormInTable.java:25)

I use Java 1.8.0_121 on Windows 8 Enterprise.

The modified manipulatePdf method looks like this:

protected void manipulatePdf(String dest) throws Exception {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);

    for (int i = 0; i < 50; i++) {
        System.out.println(i);
        Table table = new Table(2);
        Cell cell;
        cell = new Cell().add("Name:");
        table.addCell(cell);
        cell = new Cell();
        cell.setNextRenderer(new MyCellRenderer(cell, "name" + i));
        table.addCell(cell);
        cell = new Cell().add("Address");
        table.addCell(cell);
        cell = new Cell();
        cell.setNextRenderer(new MyCellRenderer(cell, "address" + i));
        table.addCell(cell);
        doc.add(table);
    }
    doc.close();
}

The complete example that produces the NPE can be found here: https://github.com/trettstadtnlb/itext-table-form-fields

Has anyone experienced this kind of behaviour or can confirm that this is a bug?

Body:
It is easy to reproduce this behavior in iText 7.0.x using much less content:

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

PdfTextFormField field = PdfFormField.createText(pdfDoc, new Rectangle(100, 100, 300, 20), "name", "");
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
form.addField(field);

doc.close();

The problem behind this is that for a form field (widget) without an associated page, iText tries to determine the page that widget is on by iterating all document pages and looking up their respective annotation arrays. And it already does so during createText, while setting the field value (and updating widget appearances)...

In the code above, though, the previous newly created pages, at least the first one, has already been flushed to the writer and de-initialized in memory. Thus, the loop over the pages tries to retrieve a value from a de-initialized page dictionary, i.e. from a null Map, hence the NullPointerException.

Whether this is a bug in iText or merely an anti-pattern, I don't know.

Inspired by @SamuelHuylebroeck's comment I tried both the OP's original code and the simplified code above with immediateFlush set to false. Indeed, this prevents the exception and the result of the simplified code looks ok. The result of the OP's original code, though, is not as he expects it, the table is built across four pages but all the fields turns up on the last page!

So, in case of form elements created directly (i.e. not via events) setting immediateFlush to false may be considered a work-around (but not a fix as the early flushing is an important feature of iText). The general case of form creation is broken, though, unless someone can point out that the code here is an iText 7 anti-pattern and can show how it should be done.


问:
cannot read property message of undefined
While trying to fetch the data from api using the angular's new httpclient, I get the error cannot read property message of undefined

```<code>// Here is my interface
export interface IMessage {
    Messages: Messages[];
}

interface Messages {
    id: number;
    messageContent: string;
    fromUserId: string;
    toUserId: string;
    productId?: number;
    parentMessageId?: number;
    subject: string;
    styleNumber?: string;
}
</code>```

//The method that calls this api

```<code>getAllMessages(): Observable<IMessage[]> {
    this.messageRepositoryService.getAllMessages()
    .subscribe(data => {
      console.log('data is =>', data[1].Messages); // here is error
      this.messages = data;
    },
    err => {
      console.log('Error occured while fetching country List');
    });
    return;
  }

  // in the service
getAllMessages(): Observable<IMessage[]> {
        return this.http.get<IMessage[]>(`${this.ROOT_URL}/list`);
    }
</code>```

To see how the response looks from the api, Here is the url http://52.70.78.117:7111/api/message/list

```<code>{"data":{"Messages":[{"Id":1,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message","StyleNumber":null},{"Id":2,"MessageContent":"test data","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message by Dev Team","StyleNumber":null},{"Id":3,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":4,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":5,"MessageContent":"testtesttesttest","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":6,"MessageContent":"testtesttesttest","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":7,"MessageContent":"testtesttesttest","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":8,"MessageContent":"Test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":9,"MessageContent":"Test Message","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":10,"MessageContent":"Test Message","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":11,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e58696b1c943-ade0-4026-b8ed-0f4a","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":12,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e586","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"96b1c943-ade0-4026-b8ed-0f4a6231e586","StyleNumber":null},{"Id":13,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e586","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"96b1c943-ade0-4026-b8ed-0f4a6231e586","StyleNumber":null},{"Id":14,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e586","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"96b1c943-ade0-4026-b8ed-0f4a6231e586","StyleNumber":null},{"Id":15,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e586","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"96b1c943-ade0-4026-b8ed-0f4a6231e586","StyleNumber":null},{"Id":16,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e586","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"96b1c943-ade0-4026-b8ed-0f4a6231e586","StyleNumber":null},{"Id":17,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"test","StyleNumber":null},{"Id":18,"MessageContent":"test message","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"test message","StyleNumber":null},{"Id":19,"MessageContent":"test data","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message by Dev Team","StyleNumber":null},{"Id":20,"MessageContent":"test message","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"test message","StyleNumber":null},{"Id":21,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"test mness","StyleNumber":null},{"Id":22,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"test ","StyleNumber":null},{"Id":25,"MessageContent":"test message","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"test message","StyleNumber":null},{"Id":28,"MessageContent":"test data tsn","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message by Dev Team","StyleNumber":null}],"Pagination":{"Page":1,"PageLength":20,"TotalRecords":20,"TotalPages":1},"MessageLimit":{"TotalMessageCount":5,"RemainingMessageCount":3}}}
</code>```

答:
try:

```<code>data.data.Messages[1]
</code>```

data is an object, not array. Messages is array.

Body:
While trying to fetch the data from api using the angular's new httpclient, I get the error cannot read property message of undefined

// Here is my interface
export interface IMessage {
    Messages: Messages[];
}

interface Messages {
    id: number;
    messageContent: string;
    fromUserId: string;
    toUserId: string;
    productId?: number;
    parentMessageId?: number;
    subject: string;
    styleNumber?: string;
}

//The method that calls this api

getAllMessages(): Observable<IMessage[]> {
    this.messageRepositoryService.getAllMessages()
    .subscribe(data => {
      console.log('data is =>', data[1].Messages); // here is error
      this.messages = data;
    },
    err => {
      console.log('Error occured while fetching country List');
    });
    return;
  }

  // in the service
getAllMessages(): Observable<IMessage[]> {
        return this.http.get<IMessage[]>(`${this.ROOT_URL}/list`);
    }

To see how the response looks from the api, Here is the url http://52.70.78.117:7111/api/message/list

{"data":{"Messages":[{"Id":1,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message","StyleNumber":null},{"Id":2,"MessageContent":"test data","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message by Dev Team","StyleNumber":null},{"Id":3,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":4,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":5,"MessageContent":"testtesttesttest","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":6,"MessageContent":"testtesttesttest","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":7,"MessageContent":"testtesttesttest","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":8,"MessageContent":"Test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":9,"MessageContent":"Test Message","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":10,"MessageContent":"Test Message","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":11,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e58696b1c943-ade0-4026-b8ed-0f4a","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"Test Message","StyleNumber":null},{"Id":12,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e586","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"96b1c943-ade0-4026-b8ed-0f4a6231e586","StyleNumber":null},{"Id":13,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e586","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"96b1c943-ade0-4026-b8ed-0f4a6231e586","StyleNumber":null},{"Id":14,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e586","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"96b1c943-ade0-4026-b8ed-0f4a6231e586","StyleNumber":null},{"Id":15,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e586","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"96b1c943-ade0-4026-b8ed-0f4a6231e586","StyleNumber":null},{"Id":16,"MessageContent":"96b1c943-ade0-4026-b8ed-0f4a6231e586","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"96b1c943-ade0-4026-b8ed-0f4a6231e586","StyleNumber":null},{"Id":17,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"test","StyleNumber":null},{"Id":18,"MessageContent":"test message","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"test message","StyleNumber":null},{"Id":19,"MessageContent":"test data","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message by Dev Team","StyleNumber":null},{"Id":20,"MessageContent":"test message","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"test message","StyleNumber":null},{"Id":21,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"test mness","StyleNumber":null},{"Id":22,"MessageContent":"test","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"test ","StyleNumber":null},{"Id":25,"MessageContent":"test message","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":1,"Subject":"test message","StyleNumber":null},{"Id":28,"MessageContent":"test data tsn","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message by Dev Team","StyleNumber":null}],"Pagination":{"Page":1,"PageLength":20,"TotalRecords":20,"TotalPages":1},"MessageLimit":{"TotalMessageCount":5,"RemainingMessageCount":3}}}

Body:
try:

data.data.Messages[1]

data is an object, not array. Messages is array.


问:
how to display pop up only 1 time in 1 day using javascript
i have a code like this. i want to showing that pop up only 1 time in 1 day.

```<code><script type="text/javascript">
    var popup = function() {
        window.open ("http://example.com", "Window","status=1,toolbar=1");
    }
</script>
<body onclick="popup()">    </body>
</code>```

that code will open pop up when i click anywhere on the page but it will always pop up a window everytime i click, so i want to make that pop up only showing 1 time in 1 day.

答:
You need to use LocalStorage of browser, to know what user see the popup and never show more once a day.

You can use:

```<code>localStorage.setItem('PopupName', 'true')
localStorage.getItem('PopupName') // that return true
</code>```

With this you can invoke a function that checks if that variable already exists in LocalStorage, and if it does not exist, execute the code that shows the popup and set a variable in LocalStorage like the example.

Body:
i have a code like this. i want to showing that pop up only 1 time in 1 day.

that code will open pop up when i click anywhere on the page but it will always pop up a window everytime i click, so i want to make that pop up only showing 1 time in 1 day.

Body:
You need to use LocalStorage of browser, to know what user see the popup and never show more once a day.

You can use:

localStorage.setItem('PopupName', 'true')
localStorage.getItem('PopupName') // that return true

With this you can invoke a function that checks if that variable already exists in LocalStorage, and if it does not exist, execute the code that shows the popup and set a variable in LocalStorage like the example.


问:
Is there any way to verify VS was installed successfully?
I was downloading Visual Studio 2017 and I went to work, when I came back my computer was shut down, and I don't know is the download was finished before it happened.

Is there any way to confirm that?

Sorry for the silly question.

答: Rerun the installer, if the installation was successful, it should look like this or with update instead of modify. Secondarily click on more and let the installer repair your installation.


答:
let comments: [String: String] is the correct way.

You want a Dictionary, whose keys are Strings and whose values are also Strings and that's what the above line declares.

If you check the type of your comments variable when declaring it with initial values (option click on the variable name), you'll see that its type is [String:String], which is just a shorthand notation for Dictionary<String,String>.

```<code>var comments = ["identifier" : "SomeRandomText", "text": "SomeRandomText"] //Here comments is of type [String:String]
</code>```

Title: How to properly use dictionary collection?

Body:
let comments: [String: String] is the correct way.

You want a Dictionary, whose keys are Strings and whose values are also Strings and that's what the above line declares.

If you check the type of your comments variable when declaring it with initial values (option click on the variable name), you'll see that its type is [String:String], which is just a shorthand notation for Dictionary<String,String>.

var comments = ["identifier" : "SomeRandomText", "text": "SomeRandomText"] //Here comments is of type [String:String]


问:
VueRouter is not defined
I have a laravel project and want use Vue.js for frontend. But i have never used
something more complicated than jquery. I can't run vue-router.

In my app.js

```<code>require('./bootstrap');
require('./vue-router');
require('./routes');

window.Vue = require('vue');
     const app = new Vue({
     el: '#app',
});
</code>```

Then i copy code vue-router from https://router.vuejs.org/en/installation.html

In my routes.js

```<code>const router = new VueRouter();

var App = Vue.extend({});

router.start(App, '#app');
</code>```

And when i try open page in console i see next : "VueRouter is not defined"

答:
You have to tell Vue to use VueRouter using the method Vue.use() first. So, do:

```<code>import VueRouter from 'vue-router'

# add this code
Vue.use(VueRouter)

var router = new VueRouter({
  routes: [
    {path: 'home', component: homeComponent}
  ]
})
</code>```

UPDATED:

First install vue-router using

```<code>npm install --save vue-router
</code>```

Then import and use it like

```<code>import VueRouter from 'vue-router'
</code>```

Then use it in vue

```<code>Vue.use(VueRouter)
</code>```

Then define your routes:

```<code>const routes = [
 {path: '/', component: SomeComponent}
]
</code>```

then initialize the router and pass it the routes

```<code>var router = new VueRouter({
  routes: routes,
  mode: 'history'
})
</code>```

Pass router to vuejs then profit :)

```<code>new Vue({
  el: '#root',
  router: router
})
</code>```

Title: VueRouter is not defined

Body:
I have a laravel project and want use Vue.js for frontend. But i have never used
something more complicated than jquery. I can't run vue-router.

In my app.js

require('./bootstrap');
require('./vue-router');
require('./routes');

window.Vue = require('vue');
     const app = new Vue({
     el: '#app',
});

Then i copy code vue-router from https://router.vuejs.org/en/installation.html

In my routes.js

const router = new VueRouter();

var App = Vue.extend({});

router.start(App, '#app');

And when i try open page in console i see next : "VueRouter is not defined"

Body:
You have to tell Vue to use VueRouter using the method Vue.use() first. So, do:

import VueRouter from 'vue-router'

# add this code
Vue.use(VueRouter)

var router = new VueRouter({
  routes: [
    {path: 'home', component: homeComponent}
  ]
})

UPDATED:

First install vue-router using

npm install --save vue-router

Then import and use it like

import VueRouter from 'vue-router'

Then use it in vue

Vue.use(VueRouter)

Then define your routes:

const routes = [
 {path: '/', component: SomeComponent}
]

then initialize the router and pass it the routes

var router = new VueRouter({
  routes: routes,
  mode: 'history'
})

Pass router to vuejs then profit :)

new Vue({
  el: '#root',
  router: router
})

ContentLicense: CC BY-SA 4.0


问:
AngularJS pass string to function by ng-click
I am trying to pass a string to a function through ng click, here's an example

HTML

 ng-click="test(STRING_TO_PASS)"

Controller

$scope.test = function(stringOne, stringTwo){
    valueOne = test(STRING_TO_PASS);
}

Edit -

Turns out I was thinking about this the wrong way... not really sure why I asked it, sorry guys!

答:
I think you want something like this.</p>

```<code>HTML

<a class="btn"> ng-click="test("StringOne","StringTwo")"</a>

Controller

$scope.test = function(stringOne, stringTwo){
    var valueOne = stringOne;
var valueTwo = stringTwo
}
</code>```

Body:
I think you want something like this.

HTML

<a class="btn"> ng-click="test("StringOne","StringTwo")"</a>

Controller

$scope.test = function(stringOne, stringTwo){
    var valueOne = stringOne;
var valueTwo = stringTwo
}


问:
Can adding a solution to TFS server cause WCF to break?
I am running on SP1 beta of 2010... it may or may not related to the beta.  But, in general, can adding a project to the codeplex TFS server somehow make WCF break when also inside an Azure project?

Seems to be the pattern for me.  Immediately upon launch I get a ServicePoint exception.  If I remove the app from source control everything works fine.

My project consists of

Azure WCF hello world application

VS2010 SP1 beta

Adding codeplex TFS reference causes exception

答:
Is it a CommunicationFaultedException? If it is, it is a bug when working with Azure 1.3 SDK projects that are checked into TFS. Make sure you have the Web.config file checked out (writeable).

If not, can you give any other information on on the ServicePoint execption?


问:
use subprocess in Python to use OpenSSL to print a PKCS7 certifcate to a file
There is plenty of code for OpenSSL/UNIX for Encrypting/Decrypting cert files.
I would like to know if there is some code I can put into Python 3.5 that will print and create an output file of that information. Here is the OpenSSL command that works wonderfully:

```<code>OpenSSL> pkcs7 -inform DER -n CERT.RSA -out CERT.TXT -noout -print_certs -text
</code>```

This converts the file so that I can easily read it. Try this for yourself in OpenSSL. I am not an expert in Python and I am trying to learn how to use my skills in Python for automation. Thank you for any input.

答:
Thank you to the ones that read my question. I figured it out. I hope that this helps someone.

PYTHON CODE:

```<code>subprocess.Popen(['openssl.exe', 'pkcs7', 'DER', '-in', InputFile, '-out', OutputFile,
    'print_certs', '-text'], stdout=None, stderr=None, shell=True)
</code>```

Body:
There is plenty of code for OpenSSL/UNIX for Encrypting/Decrypting cert files.
I would like to know if there is some code I can put into Python 3.5 that will print and create an output file of that information. Here is the OpenSSL command that works wonderfully:

OpenSSL> pkcs7 -inform DER -n CERT.RSA -out CERT.TXT -noout -print_certs -text

This converts the file so that I can easily read it. Try this for yourself in OpenSSL. I am not an expert in Python and I am trying to learn how to use my skills in Python for automation. Thank you for any input.

Body:
Thank you to the ones that read my question. I figured it out. I hope that this helps someone.

PYTHON CODE:

subprocess.Popen(['openssl.exe', 'pkcs7', 'DER', '-in', InputFile, '-out', OutputFile,
    'print_certs', '-text'], stdout=None, stderr=None, shell=True)


问:
How to slice different verb tenses word ending with -ed,-ing in a list?

So here is the sample list:

[work,worked,working,play,works,lotus]

I want to slice the -ed,-ing,-s form of work,the result should be like this:
 [work,play,lotus]

So,how can i achieve that with pure python code since the NLTK approach seemed to be inaccurate?

答:
You can simply do this:</p>

```<code>List = ['work','worked','working','play']

[item for item in List if not item.endswith(("ed", "ing"))]
</code>```

Body:
You can simply do this:

List = ['work','worked','working','play']

[item for item in List if not item.endswith(("ed", "ing"))]


问:
Kotlin: Fetching data from Firebase
I'm struggling to find an efficient way to fetch individual values from my Firebase Database. I'm coming from working with Swift. When using Swift to fetch data from Firebase, it was as simple as creating a dictionary and accessing the data through that and that allowed me to have access to that one value to do something with it. E.g

```<code>guard let dictionary = snapshot.value as? [String: AnyObject] else { return }
let username = dictionary["username"] as? String

if username == "Bob" {
  // do something
}
</code>```

I can only find documents and answers online that use for loops to loop through the snapshot in Kotlin. Is there a much for efficient way to do this? Here's all I can find online. Here's a snippet to get you started. I really appreciate it.

```<code>mReference.getReference("users").addListenerForSingleValueEvent(object : ValueEventListener {

    override fun onCancelled(p0: DatabaseError?) {
        TODO("not implemented")
    }

    override fun onDataChange(snapshot: DataSnapshot?) {
        val children = snapshot!!.children
        println("count: " + snapshot.children.count().toString())
    }

})
</code>```

答:
Otherwise, you can simplify loop. Like this</p>

```<code>//by using Iterable function

snapshot.children.filter {
                    children -> children.hasChild(targetUserKey)
                }.map {
                    children -> children.key
                }.first()
</code>```

Title: Kotlin: Fetching data from Firebase

Body:
I'm struggling to find an efficient way to fetch individual values from my Firebase Database. I'm coming from working with Swift. When using Swift to fetch data from Firebase, it was as simple as creating a dictionary and accessing the data through that and that allowed me to have access to that one value to do something with it. E.g

guard let dictionary = snapshot.value as? [String: AnyObject] else { return }
let username = dictionary["username"] as? String

if username == "Bob" {
  // do something
}

I can only find documents and answers online that use for loops to loop through the snapshot in Kotlin. Is there a much for efficient way to do this? Here's all I can find online. Here's a snippet to get you started. I really appreciate it.

mReference.getReference("users").addListenerForSingleValueEvent(object : ValueEventListener {

    override fun onCancelled(p0: DatabaseError?) {
        TODO("not implemented")
    }

    override fun onDataChange(snapshot: DataSnapshot?) {
        val children = snapshot!!.children
        println("count: " + snapshot.children.count().toString())
    }

})

Body:
Otherwise, you can simplify loop. Like this

//by using Iterable function

snapshot.children.filter {
                    children -> children.hasChild(targetUserKey)
                }.map {
                    children -> children.key
                }.first()


问:
Two rails apps sharing a model folder
I have two rails apps running off the same database, one which runs the client and one which provides an admin interface.

Both the apps have the exact same models defined save for small number of differences. Its tiresome for me to duplicate the vast majority of changes in the models on to both apps.

One way for two apps to use the same model info is to symlink the model folder from one app to the other, but I cant do that due to the few differences in code (e.g an extra validation on the client).

Is there a simple way I can move out the differences so I can keep the common code in one place?

答:
Why not doing it OOP way, e.g. creating a separate base class (in a separate directory) and then inheriting from it in both projects, so the differences are in the inherited class.

So, you have

```<code>class BaseModel < ActiveRecord::Base
</code>```

in "common" subdirectory, and then you have

```<code>class AdminBaseModel < Common::BaseModel
</code>```

in admin project and

```<code>class UserBaseModel < Common::BaseModel
</code>```

you might need

```<code>set_table_name "basemodel"
</code>```

so Rails knows which table to open.

Title: Two rails apps sharing a model folder

Body:
Why not doing it OOP way, e.g. creating a separate base class (in a separate directory) and then inheriting from it in both projects, so the differences are in the inherited class.

So, you have

class BaseModel < ActiveRecord::Base

in "common" subdirectory, and then you have

class AdminBaseModel < Common::BaseModel

in admin project and

class UserBaseModel < Common::BaseModel

you might need

set_table_name "basemodel"

so Rails knows which table to open.


问:
How to hot reload a namespace on file save in Leiningen REPL
When using the leiningen REPL, is there a way to make a file or ns automatically reload in the repl on file save. Currently I reload the ns by typing the following in the repl - (use 'sample.ns :reload-all).

However can I have it reload automatically on file save ?

答:
Most major editors support custom hotkey bindings and have a Clojure plugin that allows you to connect to the active REPL over the network (via "nREPL"). Personally, I use vim and therefore use vim-fireplace for this purpose.

This means you can have a custom hotkey for reloading whatever file you're editing as you edit it. From there, it's typically trivial to add a custom on-save hook that does the reloading.


问:
Angular help for showing data from API
Given the following JSON files:
https://drive.google.com/file/d/0Byt0rakzaB6bNXM0RW1ua3owY1U/view?usp=sharing
https://drive.google.com/file/d/0Byt0rakzaB6bdEhCSmFnZDBuZlU/view?usp=sharing

Create a responsive web page to display the data provided above.
Requirements:
The page is responsive on all mobile devices
Utilize Angular JS 1.X as the structure framework

That was the question . I have Coded like following to make them like the screenshot table. Data is showing in console. I can show the data in table like the required screenshot
.....................................................

```<code><script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("NHL_Goaltenders.json")
    .then(function(response) {
       $scope.myData1 = response;
       console.log(response);
      $http.get("NHL_Skaters.json").then(function(response){
         $scope.myData2 = response;
        console.log(response);
      });
    });
});
</script>

<div ng-app="myApp" ng-controller="myCtrl">
  <!-- <div ng-repeat="x in myData1">
    <p>{{ x.firstname}}</p> -->
<table border="1">

   <tr>

     <td>NAME</td>
     <td>TEAM</td>
     <td>GP</td>
     <td>G</td>
     <td>A</td>
     <td>PTS</td>
  </tr>

  <tr ng-repeat="x in myData1">

     <td>{{ x.Headers[0]}}</td>
     <td>{{ x.Headers[1]}}</td>
     <td>{{ x.Headers[2]}}</td>
     <td>{{ x.Headers[3]}}</td>
     <td>{{ x.Headers[4]}}</td>
     <td>{{ x.Headers[5]}}</td>
  </tr>
    <tr ng-repeat="x in myData1">

     <td>{{ x.Statistics[0][0]}}</td>
     <td>{{ x.Statistics[0]}}</td>
     <td>{{ x.Statistics[2]}}</td>
     <td>{{ x.Statistics[3]}}</td>
     <td>{{ x.Statistics[4]}}</td>
     <td>{{ x.Statistics[5]}}</td>
  </tr>
</table>

</div>
</code>```

答:
Here is one of the possible solutions: https://plnkr.co/edit/VahUhdPGF0BQAai9Lwl8?p=preview</p>

```<code>  <table border="1">
     <tr>
       <th ng-repeat="header in goaltenders.Headers">{{header}}</th>
    </tr>

    <tr ng-repeat="row in goaltenders.Statistics track by $index">
       <td ng-repeat="item in row track by $index">{{ item }}</td>
    </tr>
  </table>
</code>```

Title: Angular help for showing data from API

Body:
Given the following JSON files:
https://drive.google.com/file/d/0Byt0rakzaB6bNXM0RW1ua3owY1U/view?usp=sharing
https://drive.google.com/file/d/0Byt0rakzaB6bdEhCSmFnZDBuZlU/view?usp=sharing

Create a responsive web page to display the data provided above.
Requirements:
The page is responsive on all mobile devices
Utilize Angular JS 1.X as the structure framework

That was the question . I have Coded like following to make them like the screenshot table. Data is showing in console. I can show the data in table like the required screenshot
.....................................................

     NAME
     TEAM
     GP
     G
     A
     PTS

     {{ x.Headers[0]}}
     {{ x.Headers[1]}}
     {{ x.Headers[2]}}
     {{ x.Headers[3]}}
     {{ x.Headers[4]}}
     {{ x.Headers[5]}}

     {{ x.Statistics[0][0]}}
     {{ x.Statistics[0]}}
     {{ x.Statistics[2]}}
     {{ x.Statistics[3]}}
     {{ x.Statistics[4]}}
     {{ x.Statistics[5]}}

Body:
Here is one of the possible solutions: https://plnkr.co/edit/VahUhdPGF0BQAai9Lwl8?p=preview

  <table border="1">
     <tr>
       <th ng-repeat="header in goaltenders.Headers">{{header}}</th>
    </tr>

    <tr ng-repeat="row in goaltenders.Statistics track by $index">
       <td ng-repeat="item in row track by $index">{{ item }}</td>
    </tr>
  </table>


答:
You need to save the last-shown time-stamp in localstorage and compare the same with current time-stamp (after stripping off hours/min/sec/ms)

Demo (please check locally only)

 ```

Title: how to display pop up only 1 time in 1 day using javascript

Body:
You need to save the last-shown time-stamp in localstorage and compare the same with current time-stamp (after stripping off hours/min/sec/ms)

Demo (please check locally only)

<script type="text/javascript">
  var popup = function() {
    var lastShownTs = +localStorage.getItem("lastShown");
    var currentDate = new Date();
    currentDate.setHours(0, 0, 0, 0);
    var lastShown = null;
    if (!isNaN(lastShownTs)) {
      lastShown = new Date(lastShownTs);
      lastShown.setHours(0, 0, 0, 0);
    }
    if (lastShown == null || lastShown.getTime() != currentDate.getTime()) {
      window.open("http://example.com", "Window", "status=1,toolbar=1");
      localStorage.setItem("lastShown", currentDate.getTime());
    }
  }
</script>

<body onclick="popup()"> </body>


问:
Where is modify_ldt?
I am looking for the modify_ldt function (or constant for syscall) on ubuntu, but I can't find it's declaration anywhere. It's not in sys/types.h (as the man page suggests), nor in linux/ldt.h (doesn't exist) or linux/unistd.h as says here.

Where is it located?

答: As Karl already said, call system call directly. See here</p>

Title: Where is modify_ldt?


问:
My nav bar is covering up header
I tried to create a simple nav bar under which a welcome text as header will be available. But the nav bar is covering up the header. I tried fixing the problem by fixing the margins. But by doing that header is also moving along with the nav bar. So what should I do so that the nav bar doesn't cover up the header and remain in fixed position.

body {
  margin: 0;
  padding: 0;
  background: #2E4053;
  color: white;
  font-family: 'Raleway', sans-serif;
}

.welcome {
  height: 100px;
  margin: px; /* ? */
}

.welcome h1 {
  text-align: center;
  font-family: 'Berkshire Swash', cursive;
  color: white;
  padding: 26px;
  margin: 0 25%;
  border-bottom: 2px solid white;
}

.nav {
  height: 60px;
  width: 100%;
  background-color: lawngreen;
  position: fixed;
}

.search {
  float: right;
  margin-top: -52px;
  margin-right: 35px;
}

input {
  height: 20px;
  border-radius: 7px;
}

.nav ul {
  list-style: none;
  text-decoration: none;
}

.nav ul li a {
  text-decoration: none;
}

.nav ul li {
  display: inline-block;
  padding: 0px 20px;
  font-size: 25px;
  color: black;
  margin: 3px 50px;
  font-family: 'Boogaloo', cursive;
}

.nav ul li a:hover {
  text-decoration: line-through;
  color: blue;
  transition: 0.5s;
}

.search a i:hover {
  color: white;
  font-size: 33px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

<div class="nav">
  <ul>
    <li>About Me</li>
    <li>Contact</li>
    <li>Gallery</li>
    <li>Find Us</li>
  </ul>
  <div class="search">
    <input type="text" placeholder="Search">
    <i class="fa fa-search" style="font-
    size:30px;"></i>
  </div>
</div>

<div class="welcome">
  <h1>Welcome to My Travel Blog</h1>
</div></code>```

答:
You forgot to add margin in welcome class. Additionally, top:0 to fixed positioned .nav is also missing.

Here is the working solution

body {
margin: 0;
padding: 0;
background: #2E4053;
color: white;
font-family: 'Raleway', sans-serif;
}

.welcome {
height: 100px;
margin: 70px 0 0 0;
}

.welcome h1 {
text-align: center;
font-family: 'Berkshire Swash', cursive;
color: white;
padding: 26px;
margin: 0px 25%;
border-bottom: 2px solid white;
}

.nav {
height: 60px;
width: 100%;
background-color: lawngreen;
position: fixed;
top: 0;
}

.search {
float: right;
margin-top: -52px;
margin-right: 35px;
}

input {
height: 20px;
border-radius: 7px;
}

.nav ul {
list-style: none;
text-decoration: none;
}

.nav ul li a {
text-decoration: none;
}

.nav ul li {
display: inline-block;
padding: 0px 20px;
font-size: 25px;
color: black;
margin: 3px 50px;
font-family: 'Boogaloo', cursive;
}

.nav ul li a:hover {
text-decoration: line-through;
color: blue;
transition: 0.5s;
}

.search a i:hover {
color: white;
font-size: 33px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <meta charset="UTF-8">
  <title>My Travel Blog</title>
  <link rel="stylesheet" href="home.css">
  <link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth" rel="stylesheet">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">
</head>

<body>
  <div class="nav">
    <ul>
      <li>About Me</li>
      <li>Contact</li>
      <li>Gallery</li>
      <li>Find Us</li>
    </ul>
    <div class="search">
      <input type="text" placeholder="Search">

      <i class="fa fa-search" style="font-
    size:30px;"></i>
    </div>
  </div>
  <div class="welcome">
    <h1>Welcome to My Travel Blog</h1>
  </div>
</body></code>```

Title: My nav bar is covering up header

Body:
I tried to create a simple nav bar under which a welcome text as header will be available. But the nav bar is covering up the header. I tried fixing the problem by fixing the margins. But by doing that header is also moving along with the nav bar. So what should I do so that the nav bar doesn't cover up the header and remain in fixed position.

body {
  margin: 0;
  padding: 0;
  background: #2E4053;
  color: white;
  font-family: 'Raleway', sans-serif;
}

.welcome {
  height: 100px;
  margin: px; /* ? */
}

.welcome h1 {
  text-align: center;
  font-family: 'Berkshire Swash', cursive;
  color: white;
  padding: 26px;
  margin: 0 25%;
  border-bottom: 2px solid white;
}

.nav {
  height: 60px;
  width: 100%;
  background-color: lawngreen;
  position: fixed;
}

.search {
  float: right;
  margin-top: -52px;
  margin-right: 35px;
}

input {
  height: 20px;
  border-radius: 7px;
}

.nav ul {
  list-style: none;
  text-decoration: none;
}

.nav ul li a {
  text-decoration: none;
}

.nav ul li {
  display: inline-block;
  padding: 0px 20px;
  font-size: 25px;
  color: black;
  margin: 3px 50px;
  font-family: 'Boogaloo', cursive;
}

.nav ul li a:hover {
  text-decoration: line-through;
  color: blue;
  transition: 0.5s;
}

.search a i:hover {
  color: white;
  font-size: 33px;
}

<link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

About Me

Contact

Gallery

Find Us

    <input type="text" placeholder="Search">

Welcome to My Travel Blog

Body:
You forgot to add margin in welcome class. Additionally, top:0 to fixed positioned .nav is also missing.

Here is the working solution

body {
margin: 0;
padding: 0;
background: #2E4053;
color: white;
font-family: 'Raleway', sans-serif;
}

.welcome {
height: 100px;
margin: 70px 0 0 0;
}

.welcome h1 {
text-align: center;
font-family: 'Berkshire Swash', cursive;
color: white;
padding: 26px;
margin: 0px 25%;
border-bottom: 2px solid white;
}

.nav {
height: 60px;
width: 100%;
background-color: lawngreen;
position: fixed;
top: 0;
}

.search {
float: right;
margin-top: -52px;
margin-right: 35px;
}

input {
height: 20px;
border-radius: 7px;
}

.nav ul {
list-style: none;
text-decoration: none;
}

.nav ul li a {
text-decoration: none;
}

.nav ul li {
display: inline-block;
padding: 0px 20px;
font-size: 25px;
color: black;
margin: 3px 50px;
font-family: 'Boogaloo', cursive;
}

.nav ul li a:hover {
text-decoration: line-through;
color: blue;
transition: 0.5s;
}

.search a i:hover {
color: white;
font-size: 33px;
}

<head>
  <meta charset="UTF-8">
  <title>My Travel Blog</title>
  <link rel="stylesheet" href="home.css">
  <link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth" rel="stylesheet">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">
</head>

<body>
  <div class="nav">
    <ul>
      <li><a href="#me">About Me</a></li>
      <li><a href="#contact">Contact</a></li>
      <li><a href="#gallery">Gallery</a></li>
      <li><a href="#find">Find Us</a></li>
    </ul>
    <div class="search">
      <input type="text" placeholder="Search">

      <a href="https://google.com"><i class="fa fa-search" style="font-
    size:30px;"></i></a>
    </div>
  </div>
  <div class="welcome">
    <h1>Welcome to My Travel Blog</h1>
  </div>
</body>


问:
Filter the data according to time in PHP
There are different places available

if user wants to book the place he/she will provide the required start and end datetime

```<code>"needPlaceFrom" : "2017-12-04 09:00:00"
"needPlaceTo"   : "2017-12-04 10:00:00"
</code>```

The required place is already booked but available in required time

```<code>"bookedFrom" : "2017-12-04 11:00:00"
"bookedTo"   : "2017-12-04 12:00:00"

"bookedFrom" : "2017-12-04 07:00:00"
"bookedTo"   : "2017-12-04 08:00:00"
</code>```

I need to create a condition in which I show the place only when it is available

I am doing this,

```<code>if(needPlaceFrom < bookedFrom && needPlaceTo < bookedTo || needPlaceFrom > bookedFrom && needPlaceTo > bookedTo)
{
    //show data
}
</code>```

but the problem is that it is also showing me that place even when I am providing

```<code> "needPlaceFrom" : "2017-12-04 11:05:00"
</code>```

and the space is already booked from 11:00 - 12:00

答:
There was a problem in condition
this needs to be done like this</p>

```<code>if((needPlaceFrom < bookedFrom || needPlaceFrom > bookedTo) && (needPlaceTo < bookedFrom || needPlaceTo > bookedTo))
{
    //show data
}
</code>```

Body:
There are different places available

if user wants to book the place he/she will provide the required start and end datetime

"needPlaceFrom" : "2017-12-04 09:00:00"
"needPlaceTo"   : "2017-12-04 10:00:00"

The required place is already booked but available in required time

"bookedFrom" : "2017-12-04 11:00:00"
"bookedTo"   : "2017-12-04 12:00:00"

"bookedFrom" : "2017-12-04 07:00:00"
"bookedTo"   : "2017-12-04 08:00:00"

I need to create a condition in which I show the place only when it is available

I am doing this,

if(needPlaceFrom < bookedFrom && needPlaceTo < bookedTo || needPlaceFrom > bookedFrom && needPlaceTo > bookedTo)
{
    //show data
}

but the problem is that it is also showing me that place even when I am providing

 "needPlaceFrom" : "2017-12-04 11:05:00"

and the space is already booked from 11:00 - 12:00

Body:
There was a problem in condition
this needs to be done like this

if((needPlaceFrom < bookedFrom || needPlaceFrom > bookedTo) && (needPlaceTo < bookedFrom || needPlaceTo > bookedTo))
{
    //show data
}


问:
Correct way to implement container-element relationship in idiomatic Rust
I know why Rust doesn't like my code. However, I don't know what would be the idiomatic Rust approach to the problem.

I'm a C# programmer, and while I feel I understand Rust's system, I think my "old" approach to some problems don't work in Rust at all.

This code reproduces the problem I'm having, and it probably doesn't look like idiomatic Rust (or maybe it doesn't even look good in C# as well):

```<code>//a "global" container for the elements and some extra data
struct Container {
    elements: Vec<Element>,
    global_contextual_data: i32,
    //... more contextual data fields
}

impl Container {
   //this just calculates whatever I need based on the contextual data
   fn calculate_contextual_data(&self) -> i32 {
       //This function will end up using the elements vector and the other fields as well,
       //and will do some wacky maths with it.
       //That's why I currently have the elements stored in the container
   }
}

struct Element {
    element_data: i32,
    //other fields
}

impl Element {
    //I need to take a mutable reference to update element_data,
    //and a reference to the container to calculate something that needs
    //this global contextual data... including the other elements, as previously stated
    fn update_element_data(&mut self, some_data: i32, container: &Container) {
        self.element_data *= some_data + container.calculate_contextual_data() //do whatever maths I need
    }
}

fn main(){

    //let it be mutable so I can assign the elements later
    let mut container = Container {
        elements: vec![],
        global_contextual_data: 1
    };

    //build a vector of elements
    let elements = vec![
        Element {
            element_data: 5
        },
        Element {
            element_data: 7
        }
    ];

    //this works
    container.elements = elements;

    //and this works, but container is now borrowed as mutable
    for elem in container.elements.iter_mut() {
        elem.element_data += 1; //and while this works
        let some_data = 2;

        //i can't borrow it as immutable here and pass to the other function
        elem.update_element_data(some_data, &container);
    }
}
</code>```

I understand why elem.update_element_data(some_data, &container); won't work: I'm already borrowing it as mutable when I call iter_mut. Maybe each element should have a reference to the container? But then wouldn't I have more opportunities to break at borrow-checking?

I don't think it's possible to bring my old approach to this new system. Maybe I need to rewrite the whole thing. Can someone point me to the right direction? I've just started programming in Rust, and while the ownership system is making some sort of sense to me, the code I should write "around" it is still not that clear.

答:
I came across this question:
What's the Rust way to modify a structure within nested loops? which gave me insight into my problem.

I revisited the problem and boiled the problem down to the sharing of the vector by borrowing for writes and reads at the same time. This is just forbidden by Rust. I don't want to circumvent the borrow checker using unsafe. I was wondering, though, how much data should I copy?

My Element, which in reality is the entity of a game (I'm simulating a clicker game) has both mutable and immutable properties, which I broke apart.

```<code>struct Entity {
    type: EntityType,
    starting_price: f64,
    ...
    ...
    status: Cell<EntityStatus>
}
</code>```

Every time I need to change the status of an entity, I need to call get and set methods on the status field. EntityStatus derives Clone, Copy.

I could even put the fields directly on the struct and have them all be Cells but then it would be cumbersome to work with them (lots of calls to get and set), so I went for the more aesthetically pleasant approach.

By allowing myself to copy the status, edit and set it back, I could borrow the array immutably twice (.iter() instead of .iter_mut()).

I was afraid that the performance would be bad due to the copying, but in reality it was pretty good once I compiled with opt-level=3. If it gets problematic, I might change the fields to be Cells or come up with another approach.

Body:
I know why Rust doesn't like my code. However, I don't know what would be the idiomatic Rust approach to the problem.

I'm a C# programmer, and while I feel I understand Rust's system, I think my "old" approach to some problems don't work in Rust at all.

This code reproduces the problem I'm having, and it probably doesn't look like idiomatic Rust (or maybe it doesn't even look good in C# as well):

//a "global" container for the elements and some extra data
struct Container {
    elements: Vec<Element>,
    global_contextual_data: i32,
    //... more contextual data fields
}

impl Container {
   //this just calculates whatever I need based on the contextual data
   fn calculate_contextual_data(&self) -> i32 {
       //This function will end up using the elements vector and the other fields as well,
       //and will do some wacky maths with it.
       //That's why I currently have the elements stored in the container
   }
}

struct Element {
    element_data: i32,
    //other fields
}

impl Element {
    //I need to take a mutable reference to update element_data,
    //and a reference to the container to calculate something that needs
    //this global contextual data... including the other elements, as previously stated
    fn update_element_data(&mut self, some_data: i32, container: &Container) {
        self.element_data *= some_data + container.calculate_contextual_data() //do whatever maths I need
    }
}

fn main(){

    //let it be mutable so I can assign the elements later
    let mut container = Container {
        elements: vec![],
        global_contextual_data: 1
    };

    //build a vector of elements
    let elements = vec![
        Element {
            element_data: 5
        },
        Element {
            element_data: 7
        }
    ];

    //this works
    container.elements = elements;

    //and this works, but container is now borrowed as mutable
    for elem in container.elements.iter_mut() {
        elem.element_data += 1; //and while this works
        let some_data = 2;

        //i can't borrow it as immutable here and pass to the other function
        elem.update_element_data(some_data, &container);
    }
}

I understand why elem.update_element_data(some_data, &container); won't work: I'm already borrowing it as mutable when I call iter_mut. Maybe each element should have a reference to the container? But then wouldn't I have more opportunities to break at borrow-checking?

I don't think it's possible to bring my old approach to this new system. Maybe I need to rewrite the whole thing. Can someone point me to the right direction? I've just started programming in Rust, and while the ownership system is making some sort of sense to me, the code I should write "around" it is still not that clear.

Body:
I came across this question:
What's the Rust way to modify a structure within nested loops? which gave me insight into my problem.

I revisited the problem and boiled the problem down to the sharing of the vector by borrowing for writes and reads at the same time. This is just forbidden by Rust. I don't want to circumvent the borrow checker using unsafe. I was wondering, though, how much data should I copy?

My Element, which in reality is the entity of a game (I'm simulating a clicker game) has both mutable and immutable properties, which I broke apart.

struct Entity {
    type: EntityType,
    starting_price: f64,
    ...
    ...
    status: Cell<EntityStatus>
}

Every time I need to change the status of an entity, I need to call get and set methods on the status field. EntityStatus derives Clone, Copy.

I could even put the fields directly on the struct and have them all be Cells but then it would be cumbersome to work with them (lots of calls to get and set), so I went for the more aesthetically pleasant approach.

By allowing myself to copy the status, edit and set it back, I could borrow the array immutably twice (.iter() instead of .iter_mut()).

I was afraid that the performance would be bad due to the copying, but in reality it was pretty good once I compiled with opt-level=3. If it gets problematic, I might change the fields to be Cells or come up with another approach.


问:
How to change value field in html input tag using selenium in python
The following html tag:

```<code><input id="input-value" title="Search" type="text" value="">
</code>```

I want to change the value attribute from "" to "foo".

```<code><input id="input-value" title="Search" type="text" value="foo">
</code>```

I am trying this with send_keys() with no success.

```<code>ele = browser.find_element_by_id("input-value")
ele.send_keys("foo")
ele.send_keys(Keys.RETURN)`
</code>```

答:
To edit the value attribute and assign the value foo to it you can use the following code block which uses the JavascriptExecutor :

```<code>ele = browser.find_element_by_css_selector("input#input-value")
browser.execute_script("arguments[0].setAttribute('value','foo')", ele)
</code>```

Body:
The following html tag:

<input id="input-value" title="Search" type="text" value="">

I want to change the value attribute from "" to "foo".

<input id="input-value" title="Search" type="text" value="foo">

I am trying this with send_keys() with no success.

ele = browser.find_element_by_id("input-value")
ele.send_keys("foo")
ele.send_keys(Keys.RETURN)`

Body:
To edit the value attribute and assign the value foo to it you can use the following code block which uses the JavascriptExecutor :

ele = browser.find_element_by_css_selector("input#input-value")
browser.execute_script("arguments[0].setAttribute('value','foo')", ele)


问:
dynamically populate VoiceCommand PhraseList, Error VoiceCommandSet not found
I am looking for a way to dynamically populate my VCD file. I have a Code snippet from the Windows documentation that reads as follows:

```<code>Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinition.VoiceCommandSet commandSetEnUs;

if (Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager.
      InstalledCommandSets.TryGetValue(
        "AdventureWorksCommandSet_en-us", out commandSetEnUs))
{
  await commandSetEnUs.SetPhraseListAsync(
    "destination", new string[] {“London”, “Dallas”, “New York”, “Phoenix”});
}
</code>```

But, when I put this into my version of App.OnActivated() Visual Studio shows an error saying that VoiceCommandSet is not contained in "Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinition". My questions are:

Am I doing that in the wrong place? Do you know any example projects, that show how to do this properly? (I looked into Adventure Works, but didn't find these lines over there) Or am I missing some references, that I'm not aware of?

答:
```<code>public async Task UpdateDestinationPhraseList()
        {
            try
            {
                // Update the destination phrase list, so that Cortana voice commands can use destinations added by users.
                // When saving a trip, the UI navigates automatically back to this page, so the phrase list will be
                // updated automatically.
                VoiceCommandDefinition commandDefinitions;

                string countryCode = CultureInfo.CurrentCulture.Name.ToLower();
                if(countryCode.Length == 0)
                {
                    countryCode = "en-us";
                }

                if (VoiceCommandDefinitionManager.InstalledCommandDefinitions.TryGetValue("AdventureWorksCommandSet_" + countryCode, out commandDefinitions))
                {
                    List<string> destinations = new List<string>();
                    foreach (Model.Trip t in store.Trips)
                    {
                        destinations.Add(t.Destination);
                    }

                    await commandDefinitions.SetPhraseListAsync("destination", destinations);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Updating Phrase list for VCDs: " + ex.ToString());
            }
        }
</code>```

Body:
I am looking for a way to dynamically populate my VCD file. I have a Code snippet from the Windows documentation that reads as follows:

Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinition.VoiceCommandSet commandSetEnUs;

if (Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager.
      InstalledCommandSets.TryGetValue(
        "AdventureWorksCommandSet_en-us", out commandSetEnUs))
{
  await commandSetEnUs.SetPhraseListAsync(
    "destination", new string[] {“London”, “Dallas”, “New York”, “Phoenix”});
}

But, when I put this into my version of App.OnActivated() Visual Studio shows an error saying that VoiceCommandSet is not contained in "Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinition". My questions are:

Am I doing that in the wrong place? Do you know any example projects, that show how to do this properly? (I looked into Adventure Works, but didn't find these lines over there) Or am I missing some references, that I'm not aware of?


问:
Changing App name from .env file
I am trying to build multiple apps from same codebase using targets. I am using Fastlane, .env files to launch different builds. Build is uploading fine with different app_identifiers but I am not able to change app name through .env files

Following is my sample .env.target1 file:

```<code>SCHEME_NAME=SampleFastlaneTesting
BUNDLE_IDENTIFIER=com.*****.SampleFastlaneTesting
APP_NAME=“SampleFastlaneTesting”
</code>```

I am storing app name of each build using "APP_NAME" key. In deliver file
I am setting as follows:

```<code>name ENV[‘APP_NAME’]
</code>```

According to this link it should work but it is not updating when I launch the build. What am I doing wrong?

答:
It seems that you said the filename you are using is .env.target1. You can find how fastlane uses .env files here, so if you want to use that file you need to call fastlane with fastlane --env target1 <your lane>.

To actually update the name of your app that is shown on the home screen, you need to use the update_info_plist action. Edit your lane and include the following before running gym (or just place it at the beginning):

```<code>update_info_plist(
  plist_path: "path/to/Info.plist", # !!! Set to your Info.plist's path !!!
  display_name: ENV["APP_NAME"],
  app_identifier: ENV["BUNDLE_IDENTIFIER"]
)
</code>```

Title: Changing App name from .env file

Body:
I am trying to build multiple apps from same codebase using targets. I am using Fastlane, .env files to launch different builds. Build is uploading fine with different app_identifiers but I am not able to change app name through .env files

Following is my sample .env.target1 file:

SCHEME_NAME=SampleFastlaneTesting
BUNDLE_IDENTIFIER=com.*****.SampleFastlaneTesting
APP_NAME=“SampleFastlaneTesting”

I am storing app name of each build using "APP_NAME" key. In deliver file
I am setting as follows:

name ENV[‘APP_NAME’]

According to this link it should work but it is not updating when I launch the build. What am I doing wrong?

Body:
It seems that you said the filename you are using is .env.target1. You can find how fastlane uses .env files here, so if you want to use that file you need to call fastlane with fastlane --env target1 <your lane>.

To actually update the name of your app that is shown on the home screen, you need to use the update_info_plist action. Edit your lane and include the following before running gym (or just place it at the beginning):

update_info_plist(
  plist_path: "path/to/Info.plist", # !!! Set to your Info.plist's path !!!
  display_name: ENV["APP_NAME"],
  app_identifier: ENV["BUNDLE_IDENTIFIER"]
)


问:
How to unit test an apache camel cxfrs route?
I have a working cxfrs route. I can hit the rest service using SoapUi with a json object and get a response.

I wanted to write unit tests, and I though to use CamelTestSupport. My routebuilder configure() method looks something like this:

```<code>    from(cxfrsEndpoint)
        .recipientList(simple("direct:${header.operationName}"))
        .setHeader(Exchange.CONTENT_LENGTH, simple("-1"));

    from("direct:submitRequest")
        .bean("responseBean", "checkJson")
        .bean("responseBean", "createSuccessResponse");
</code>```

When I hit the url from SoapUi (http://localhost:8181/cxf/myContext/submitRequest) as a POST with an appropriate json string, I get a "success" json back. Cool.

In my unit test, I created an overriden createRouteBuilder method:

```<code>@Override
protected RouteBuilder createRouteBuilder() {

    MyRouteBuilder myRouteBuilder = new MyRouteBuilder();
    myRouteBuilder.setCxfrsEndpoint("direct:start");
    return myRouteBuilder;
}
</code>```

And then my unit test (I thought) would look something like this:

```<code>@Test
public void thisIsATest() throws Exception {

  MyRequest myRequest = new MyRequest();
  request.setSomeProperty("Some property value");

  ObjectMapper objectMapper = new ObjectMapper();
  String goodJsonRequest = objectMapper.writeValueAsString(request);

  String response = (String) template.requestBodyAndHeader(START_POINT, goodJsonRequest, "operationName", "submitRequest");
  assertNotNull(response);
  //Omitted: further assertions for content of the response json
}
</code>```

Well, when I execute the unit test, I get an unmarshalling exception with this as the cause:

```<code>Caused by: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '{' (code 123) in prolog; expected '<'
  at [row,col {unknown-source}]: [1,1]
  at com.ctc.wstx.sr.StreamScanner.throwUnexpectedChar(StreamScanner.java:647)
  at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2054)
  at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1131)
  at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:164)
  at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:415)
... 74 more
</code>```

It doesn't like my json string. What is the real service receiving?

On the real route, I enabled logging on the endpoint in the blueprint.xml like this:

```<code><!-- RouteBuilder declarations -->
<bean id="myRouteBuilder" class="com.mycompany.MyRouteBuilder">
  <property name="cxfrsEndpoint"  value="cxfrs:bean:cxfrsEndpoint?bindingStyle=SimpleConsumer&loggingFeatureEnabled=true" />
</bean>
</code>```

The json string I see in the log as the "Payload:" doesn't look any different than the json string I'm sending via template.requestBodyAndHeader(...).

What am I missing or what am I doing wrong here?

Thanks!

答:
Please, try not rewrite your endpoint like this:

myRouteBuilder.setCxfrsEndpoint("direct:start");

Seems to me that overriding your endpoint changes the interface and the CXF now is expecting a XML and not JSON (based on your logs):

```<code>Caused by: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '{' (code 123) in prolog; expected '<'
at [row,col {unknown-source}]: [1,1]
at com.ctc.wstx.sr.StreamScanner.throwUnexpectedChar(StreamScanner.java:647)
at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2054)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1131)
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:164)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:415)
... 74 more
</code>```

You already have the endpoint defined in here:

```<code><bean id="myRouteBuilder" class="com.mycompany.MyRouteBuilder">
      <property name="cxfrsEndpoint"  value="cxfrs:bean:cxfrsEndpoint?bindingStyle=SimpleConsumer&loggingFeatureEnabled=true" />
</bean>
</code>```

My suggestion is to use this code as example and call your endpoint directly via HTTP:

```<code>public void setUp() throws Exception {
    super.setUp();
    httpclient = HttpClientBuilder.create().build();
}

public void tearDown() throws Exception {
    super.tearDown();
    httpclient.close();
}

@Test
public void testGetCustomerOnlyHeaders() throws Exception {
    HttpGet get = new HttpGet("http://serviceurl.com");
    HttpResponse response = httpclient.execute(get);
    assertEquals(200, response.getStatusLine().getStatusCode());
}
</code>```

If you have a chance, take a look into the entire camel-cxf project tests to have an idea how to properly test.

Body:
I have a working cxfrs route. I can hit the rest service using SoapUi with a json object and get a response.

I wanted to write unit tests, and I though to use CamelTestSupport. My routebuilder configure() method looks something like this:

    from(cxfrsEndpoint)
        .recipientList(simple("direct:${header.operationName}"))
        .setHeader(Exchange.CONTENT_LENGTH, simple("-1"));

    from("direct:submitRequest")
        .bean("responseBean", "checkJson")
        .bean("responseBean", "createSuccessResponse");

When I hit the url from SoapUi (http://localhost:8181/cxf/myContext/submitRequest) as a POST with an appropriate json string, I get a "success" json back. Cool.

In my unit test, I created an overriden createRouteBuilder method:

@Override
protected RouteBuilder createRouteBuilder() {

    MyRouteBuilder myRouteBuilder = new MyRouteBuilder();
    myRouteBuilder.setCxfrsEndpoint("direct:start");
    return myRouteBuilder;
}

And then my unit test (I thought) would look something like this:

@Test
public void thisIsATest() throws Exception {

  MyRequest myRequest = new MyRequest();
  request.setSomeProperty("Some property value");

  ObjectMapper objectMapper = new ObjectMapper();
  String goodJsonRequest = objectMapper.writeValueAsString(request);

  String response = (String) template.requestBodyAndHeader(START_POINT, goodJsonRequest, "operationName", "submitRequest");
  assertNotNull(response);
  //Omitted: further assertions for content of the response json
}

Well, when I execute the unit test, I get an unmarshalling exception with this as the cause:

Caused by: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '{' (code 123) in prolog; expected '<'
  at [row,col {unknown-source}]: [1,1]
  at com.ctc.wstx.sr.StreamScanner.throwUnexpectedChar(StreamScanner.java:647)
  at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2054)
  at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1131)
  at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:164)
  at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:415)
... 74 more

It doesn't like my json string. What is the real service receiving?

On the real route, I enabled logging on the endpoint in the blueprint.xml like this:

<bean id="myRouteBuilder" class="com.mycompany.MyRouteBuilder">
  <property name="cxfrsEndpoint"  value="cxfrs:bean:cxfrsEndpoint?bindingStyle=SimpleConsumer&loggingFeatureEnabled=true" />
</bean>

The json string I see in the log as the "Payload:" doesn't look any different than the json string I'm sending via template.requestBodyAndHeader(...).

What am I missing or what am I doing wrong here?

Thanks!

Body:
Please, try not rewrite your endpoint like this:

myRouteBuilder.setCxfrsEndpoint("direct:start");

Seems to me that overriding your endpoint changes the interface and the CXF now is expecting a XML and not JSON (based on your logs):

Caused by: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '{' (code 123) in prolog; expected '<'
at [row,col {unknown-source}]: [1,1]
at com.ctc.wstx.sr.StreamScanner.throwUnexpectedChar(StreamScanner.java:647)
at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2054)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1131)
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:164)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:415)
... 74 more

You already have the endpoint defined in here:

<bean id="myRouteBuilder" class="com.mycompany.MyRouteBuilder">
      <property name="cxfrsEndpoint"  value="cxfrs:bean:cxfrsEndpoint?bindingStyle=SimpleConsumer&amp;loggingFeatureEnabled=true" />
</bean>

My suggestion is to use this code as example and call your endpoint directly via HTTP:

public void setUp() throws Exception {
    super.setUp();
    httpclient = HttpClientBuilder.create().build();
}

public void tearDown() throws Exception {
    super.tearDown();
    httpclient.close();
}

@Test
public void testGetCustomerOnlyHeaders() throws Exception {
    HttpGet get = new HttpGet("http://serviceurl.com");
    HttpResponse response = httpclient.execute(get);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

If you have a chance, take a look into the entire camel-cxf project tests to have an idea how to properly test.