问:
Why does subreport only get one row from a JsonDataSource when using subDataSource()?
I have a clean Jasper report that calls a subreport with no filter.
In that subreport I show all the Json data (10 rows), and if I see the preview it works: Subreport preview.

The problem is when I call the subreport from the main (and clean) report. It only has in the detail the professionalName and the subreport. It should show the professionalName and all the subReport (all 10 rows each time), but it's not the case. It only shows the current row, and I'm sure it's because the main report is not giving all the datasource to the subreport, only that row. Here is the capture: Main report preview.

The Data Source Expression is:

```<code><dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource()]]></dataSourceExpression>
</code>```

and the Json file is this one:

```<code>[   {
        "appointmentId": 153,
        "startDate": 1503061200000,
        "patientId": 417,
        "patientIdentification": {
            "id": 1,
            "name": "85471254B"
        },
        "episodeId": 500358,
        "chn": "500058",
        "patientName": "Aida Mascaró",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "NEUROLOGIA",
        "benefitId": 45,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 30,
            "name": "Neurologia"
        },
        "professionalName": "a",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 26,
            "name": "Privados"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {
            "id": 3,
            "name": "Accidente de trabajo"
        },
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503057809579
    },
    {
        "appointmentId": 150,
        "startDate": 1503039600000,
        "patientId": 405,
        "patientIdentification": {
            "id": 1,
            "name": "40295204D"
        },
        "episodeId": 500349,
        "chn": "500046",
        "patientName": "Cristina Mayo Saez",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "ENDOCRINOLOGIA",
        "benefitId": 28,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 26,
            "name": "Nutrición"
        },
        "professionalName": "b",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 26,
            "name": "Privados"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {},
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503037036812
    }, {
        "appointmentId": 151,
        "startDate": 1503039600000,
        "patientId": 416,
        "patientIdentification": {
            "id": 1,
            "name": "18466341D"
        },
        "episodeId": 500350,
        "chn": "500057",
        "patientName": "Gloria Sena Arrayán",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "NEUROLOGIA",
        "benefitId": 45,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 30,
            "name": "Neurologia"
        },
        "professionalName": "b",
        "insurance": {
            "id": 1396,
            "name": "AGRUPACION MUTUAL ASEGURADORA (AMA)"
        },
        "collective": {
            "id": 30,
            "name": "Trafico"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {},
        "appoState": {
            "id": 4,
            "name": "Atendido"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503038643436
    },  {
        "appointmentId": 154,
        "startDate": 1503298800000,
        "patientId": 389,
        "patientIdentification": {
            "id": 1,
            "name": "23234567J"
        },
        "episodeId": 500359,
        "chn": "500030",
        "patientName": "maria perez perez",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "ENDOCRINOLOGIA",
        "benefitId": 28,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 26,
            "name": "Nutrición"
        },
        "professionalName": "a",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 26,
            "name": "Privados"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {
            "id": 2,
            "name": "Accidente causal"
        },
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503297627789
    }, {
        "appointmentId": 148,
        "startDate": 1503300600000,
        "patientId": 415,
        "episodeId": 500346,
        "chn": "500056",
        "patientName": "Pastora Meseguer Carrión",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "NEUROLOGIA",
        "benefitId": 45,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 30,
            "name": "Neurologia"
        },
        "professionalName": "a",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 25,
            "name": "Privados todos"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 7,
            "name": "No requerida"
        },
        "reason": {},
        "appoState": {
            "id": 4,
            "name": "Atendido"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1502885871664
    },  {
        "appointmentId": 152,
        "startDate": 1503302400000,
        "patientId": 416,
        "patientIdentification": {
            "id": 1,
            "name": "18466341D"
        },
        "episodeId": 500351,
        "chn": "500057",
        "patientName": "Gloria Sena Arrayán",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "NEUROLOGIA",
        "benefitId": 46,
        "benefitName": "REVISION",
        "schedule": {
            "id": 30,
            "name": "Neurologia"
        },
        "professionalName": "a",
        "insurance": {
            "id": 1396,
            "name": "AGRUPACION MUTUAL ASEGURADORA (AMA)"
        },
        "collective": {
            "id": 30,
            "name": "Trafico"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {},
        "appoState": {
            "id": 4,
            "name": "Atendido"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503038674027
    },{
        "appointmentId": 156,
        "startDate": 1503302400000,
        "patientId": 389,
        "patientIdentification": {
            "id": 1,
            "name": "23234567J"
        },
        "episodeId": 500361,
        "chn": "500030",
        "patientName": "maria perez perez",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "PEDIATRIA",
        "benefitId": 3,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 29,
            "name": "Dra. De la Vega"
        },
        "professionalName": "a",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 26,
            "name": "Privados"
        },
        "typeId": 1,
        "observations": "obs",
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {
            "id": 2,
            "name": "Accidente causal"
        },
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503300374408
    },{
        "appointmentId": 142,
        "startDate": 1503298800000,
        "patientId": 412,
        "episodeId": 500337,
        "chn": "500053",
        "patientName": "Mariano López Pastor",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "NEUROLOGIA",
        "benefitId": 45,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 30,
            "name": "Neurologia"
        },
        "professionalName": "b",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 25,
            "name": "Privados todos"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 7,
            "name": "No requerida"
        },
        "reason": {},
        "appoState": {
            "id": 4,
            "name": "Atendido"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1502877885393
    },  {
        "appointmentId": 158,
        "startDate": 1503303300000,
        "patientId": 408,
        "patientIdentification": {
            "id": 2,
            "name": "123123"
        },
        "episodeId": 500363,
        "chn": "500049",
        "patientName": "ANA CARO MARTINEZ",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "PEDIATRIA",
        "benefitId": 3,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 29,
            "name": "Dra. De la Vega"
        },
        "professionalName": "b",
        "insurance": {
            "id": 1749,
            "name": "ADMIRAL INSURANCE"
        },
        "collective": {
            "id": 13,
            "name": "Trafico"
        },
        "typeId": 1,
        "observations": "dewdfe",
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {
            "id": 2,
            "name": "Accidente causal"
        },
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503301904789
    }, {
        "appointmentId": 159,
        "startDate": 1503304200000,
        "patientId": 48,
        "patientIdentification": {
            "id": 5,
            "name": "1425871"
        },
        "episodeId": 500364,
        "chn": "186",
        "patientName": "cayetana jimenez brotons",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "PEDIATRIA",
        "benefitId": 4,
        "benefitName": "REVISION",
        "schedule": {
            "id": 29,
            "name": "Dra. De la Vega"
        },
        "professionalName": "b",
        "insurance": {
            "id": 1390,
            "name": "MAPFRE ESPAÑA, CIA. DE SEGUROS Y REASEGUROS S.A."
        },
        "collective": {
            "id": 4,
            "name": "MAPFRE SALUD"
        },
        "typeId": 1,
        "observations": "dfd",
        "guarantorStatus": {
            "id": 7,
            "name": "No requerida"
        },
        "reason": {
            "id": 2,
            "name": "Accidente causal"
        },
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503301999486
    }
]
</code>```

What can I do to pass the whole DataSet for each row I show? Thank you

答:
The subDataSource method uses the current node when creating a new JsonDataSource instance. A future version of JasperReports will address this issue, but until then, you need to:

Remove the Data Source Expression from your subreport. The subreport itself is going to use a JSON data adapter.

Export your JSON data adapter to file. See step #2 from here in case you haven't done it before in Jaspersoft Studio.

In your subreport, set the report's Default Data Adapter property to point to your saved adapter from previous step. See step #4 from here.

Recompile your subreport if you're note building the project automatically.

Body:
I have a clean Jasper report that calls a subreport with no filter.
In that subreport I show all the Json data (10 rows), and if I see the preview it works: Subreport preview.

The problem is when I call the subreport from the main (and clean) report. It only has in the detail the professionalName and the subreport. It should show the professionalName and all the subReport (all 10 rows each time), but it's not the case. It only shows the current row, and I'm sure it's because the main report is not giving all the datasource to the subreport, only that row. Here is the capture: Main report preview.

The Data Source Expression is:

<dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource()]]></dataSourceExpression>

and the Json file is this one:

[   {
        "appointmentId": 153,
        "startDate": 1503061200000,
        "patientId": 417,
        "patientIdentification": {
            "id": 1,
            "name": "85471254B"
        },
        "episodeId": 500358,
        "chn": "500058",
        "patientName": "Aida Mascaró",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "NEUROLOGIA",
        "benefitId": 45,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 30,
            "name": "Neurologia"
        },
        "professionalName": "a",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 26,
            "name": "Privados"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {
            "id": 3,
            "name": "Accidente de trabajo"
        },
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503057809579
    },
    {
        "appointmentId": 150,
        "startDate": 1503039600000,
        "patientId": 405,
        "patientIdentification": {
            "id": 1,
            "name": "40295204D"
        },
        "episodeId": 500349,
        "chn": "500046",
        "patientName": "Cristina Mayo Saez",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "ENDOCRINOLOGIA",
        "benefitId": 28,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 26,
            "name": "Nutrición"
        },
        "professionalName": "b",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 26,
            "name": "Privados"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {},
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503037036812
    }, {
        "appointmentId": 151,
        "startDate": 1503039600000,
        "patientId": 416,
        "patientIdentification": {
            "id": 1,
            "name": "18466341D"
        },
        "episodeId": 500350,
        "chn": "500057",
        "patientName": "Gloria Sena Arrayán",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "NEUROLOGIA",
        "benefitId": 45,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 30,
            "name": "Neurologia"
        },
        "professionalName": "b",
        "insurance": {
            "id": 1396,
            "name": "AGRUPACION MUTUAL ASEGURADORA (AMA)"
        },
        "collective": {
            "id": 30,
            "name": "Trafico"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {},
        "appoState": {
            "id": 4,
            "name": "Atendido"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503038643436
    },  {
        "appointmentId": 154,
        "startDate": 1503298800000,
        "patientId": 389,
        "patientIdentification": {
            "id": 1,
            "name": "23234567J"
        },
        "episodeId": 500359,
        "chn": "500030",
        "patientName": "maria perez perez",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "ENDOCRINOLOGIA",
        "benefitId": 28,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 26,
            "name": "Nutrición"
        },
        "professionalName": "a",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 26,
            "name": "Privados"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {
            "id": 2,
            "name": "Accidente causal"
        },
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503297627789
    }, {
        "appointmentId": 148,
        "startDate": 1503300600000,
        "patientId": 415,
        "episodeId": 500346,
        "chn": "500056",
        "patientName": "Pastora Meseguer Carrión",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "NEUROLOGIA",
        "benefitId": 45,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 30,
            "name": "Neurologia"
        },
        "professionalName": "a",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 25,
            "name": "Privados todos"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 7,
            "name": "No requerida"
        },
        "reason": {},
        "appoState": {
            "id": 4,
            "name": "Atendido"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1502885871664
    },  {
        "appointmentId": 152,
        "startDate": 1503302400000,
        "patientId": 416,
        "patientIdentification": {
            "id": 1,
            "name": "18466341D"
        },
        "episodeId": 500351,
        "chn": "500057",
        "patientName": "Gloria Sena Arrayán",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "NEUROLOGIA",
        "benefitId": 46,
        "benefitName": "REVISION",
        "schedule": {
            "id": 30,
            "name": "Neurologia"
        },
        "professionalName": "a",
        "insurance": {
            "id": 1396,
            "name": "AGRUPACION MUTUAL ASEGURADORA (AMA)"
        },
        "collective": {
            "id": 30,
            "name": "Trafico"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {},
        "appoState": {
            "id": 4,
            "name": "Atendido"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503038674027
    },{
        "appointmentId": 156,
        "startDate": 1503302400000,
        "patientId": 389,
        "patientIdentification": {
            "id": 1,
            "name": "23234567J"
        },
        "episodeId": 500361,
        "chn": "500030",
        "patientName": "maria perez perez",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "PEDIATRIA",
        "benefitId": 3,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 29,
            "name": "Dra. De la Vega"
        },
        "professionalName": "a",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 26,
            "name": "Privados"
        },
        "typeId": 1,
        "observations": "obs",
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {
            "id": 2,
            "name": "Accidente causal"
        },
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503300374408
    },{
        "appointmentId": 142,
        "startDate": 1503298800000,
        "patientId": 412,
        "episodeId": 500337,
        "chn": "500053",
        "patientName": "Mariano López Pastor",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "NEUROLOGIA",
        "benefitId": 45,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 30,
            "name": "Neurologia"
        },
        "professionalName": "b",
        "insurance": {
            "id": 1387,
            "name": "PRIVADOS"
        },
        "collective": {
            "id": 25,
            "name": "Privados todos"
        },
        "typeId": 1,
        "guarantorStatus": {
            "id": 7,
            "name": "No requerida"
        },
        "reason": {},
        "appoState": {
            "id": 4,
            "name": "Atendido"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1502877885393
    },  {
        "appointmentId": 158,
        "startDate": 1503303300000,
        "patientId": 408,
        "patientIdentification": {
            "id": 2,
            "name": "123123"
        },
        "episodeId": 500363,
        "chn": "500049",
        "patientName": "ANA CARO MARTINEZ",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "PEDIATRIA",
        "benefitId": 3,
        "benefitName": "CONSULTA",
        "schedule": {
            "id": 29,
            "name": "Dra. De la Vega"
        },
        "professionalName": "b",
        "insurance": {
            "id": 1749,
            "name": "ADMIRAL INSURANCE"
        },
        "collective": {
            "id": 13,
            "name": "Trafico"
        },
        "typeId": 1,
        "observations": "dewdfe",
        "guarantorStatus": {
            "id": 1,
            "name": "Solicitada"
        },
        "reason": {
            "id": 2,
            "name": "Accidente causal"
        },
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503301904789
    }, {
        "appointmentId": 159,
        "startDate": 1503304200000,
        "patientId": 48,
        "patientIdentification": {
            "id": 5,
            "name": "1425871"
        },
        "episodeId": 500364,
        "chn": "186",
        "patientName": "cayetana jimenez brotons",
        "centerName": "HOSPITAL CLINICA BENIDORM",
        "serviceName": "PEDIATRIA",
        "benefitId": 4,
        "benefitName": "REVISION",
        "schedule": {
            "id": 29,
            "name": "Dra. De la Vega"
        },
        "professionalName": "b",
        "insurance": {
            "id": 1390,
            "name": "MAPFRE ESPAÑA, CIA. DE SEGUROS Y REASEGUROS S.A."
        },
        "collective": {
            "id": 4,
            "name": "MAPFRE SALUD"
        },
        "typeId": 1,
        "observations": "dfd",
        "guarantorStatus": {
            "id": 7,
            "name": "No requerida"
        },
        "reason": {
            "id": 2,
            "name": "Accidente causal"
        },
        "appoState": {
            "id": 3,
            "name": "Atendiendo"
        },
        "appoType": {
            "id": 1,
            "name": "Simple"
        },
        "professionalCreationName": "Marisol Fernández Lleras",
        "creationDate": 1503301999486
    }
]

What can I do to pass the whole DataSet for each row I show? Thank you


来源: stackexchange

问:
disable ordering by default for django_tables2 Tables
I use django_tables2 to render my tables. For one table, I only want to see the most recent 5 entries. Therefore, I need to order my queryset before passing it to the table object:

```<code>qset = myObject.objects.order_by('-start_time').all()[:5]
table = MyTableClass(qset, template='path/to/template.html')
</code>```

This yields the following error message:

```<code>AssertionError: Cannot reorder a query once a slice has been taken.
</code>```

I could set orderable=False for every django_tables.Column, but since MyTableClass inherits from another table class, I would like to avoid this.

Thanks in advance

答:
You could use __in to select the most recent entries:

```<code>most_recent = list(myObject.objects.order_by('-start_time').all()[:5].values_list('pk', flat=True))  # list is required if databases does not support LIMIT in subqueries
qset = myObject.objects.filter(id__in=most_recent).order_by('-start_time')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use django_tables2 to render my tables. For one table, I only want to see the most recent 5 entries. Therefore, I need to order my queryset before passing it to the table object:

qset = myObject.objects.order_by('-start_time').all()[:5]
table = MyTableClass(qset, template='path/to/template.html')

This yields the following error message:

AssertionError: Cannot reorder a query once a slice has been taken.

I could set orderable=False for every django_tables.Column, but since MyTableClass inherits from another table class, I would like to avoid this.

Thanks in advance

Body:
You could use __in to select the most recent entries:

most_recent = list(myObject.objects.order_by('-start_time').all()[:5].values_list('pk', flat=True))  # list is required if databases does not support LIMIT in subqueries
qset = myObject.objects.filter(id__in=most_recent).order_by('-start_time')


问:
Python comparing two lists and filtering items
I would like to do some word filtering (extracting only items in 'keyword' list that exist in 'whitelist').

Here is my code so far:

```<code>whitelist = ['Cat', 'Dog', 'Cow']
keyword = ['Cat, Cow, Horse', 'Bird, Whale, Dog', 'Pig, Chicken', 'Tiger, Cat']
keyword_filter = []

for word in whitelist:
    for i in range(len(keyword)):
        if word in keyword[i]:
            keyword_filter.append(word)
        else: pass
</code>```

I want to remove every word except for 'Cat', 'Dog', and 'Cow' (which are in the
'whitelist') so that the result ('keyword_filter' list) will look like this:

```<code>['Cat, Cow', 'Dog', '', 'Cat']
</code>```

However, I got the result something like this:

```<code>['Cat', 'Cat', 'Dog', 'Cow']
</code>```

I would sincerely appreciate if you can give some advice.

答:
Since you want to preserve the order of your keyword list, you'll want to have that as the outermost loop.

for phrase in keyword:

Now you need to split up the phrase into its actual words and determine if those words are in the whitelist. Then you need to put the words back together. You can do this in one line.

```<code>   filtered = ", ".join(word in phrase.split(", ") if word in whitelist)
</code>```

Breakdown: phrase.split(", ") gives you a list of strings that were separated by ", " in the original string -- i.e. the words you care about. word in ... if word in whitelist is a list comprehension. It will return a list of each word in ..., in this case phrase.split, that meets the condition word in whitelist. Finally, ", ".join(...) gives you a string made up of every element in the list ... connected by ", ".

Lastly, you need to put the newly filtered string into your list of filtered strings.

```<code>   keyword_filter.append(filtered)
</code>```

As a sidenote, I agree with others that you should use a set for your collection of whitelisted words. It has much faster lookup time. However, for a miniscule list of words like this example you won't notice a performance difference.

ContentLicense: CC BY-SA 4.0

Body:
I would like to do some word filtering (extracting only items in 'keyword' list that exist in 'whitelist').

Here is my code so far:

whitelist = ['Cat', 'Dog', 'Cow']
keyword = ['Cat, Cow, Horse', 'Bird, Whale, Dog', 'Pig, Chicken', 'Tiger, Cat']
keyword_filter = []

for word in whitelist:
    for i in range(len(keyword)):
        if word in keyword[i]:
            keyword_filter.append(word)
        else: pass

I want to remove every word except for 'Cat', 'Dog', and 'Cow' (which are in the
'whitelist') so that the result ('keyword_filter' list) will look like this:

['Cat, Cow', 'Dog', '', 'Cat']

However, I got the result something like this:

['Cat', 'Cat', 'Dog', 'Cow']

I would sincerely appreciate if you can give some advice.

Body:
Since you want to preserve the order of your keyword list, you'll want to have that as the outermost loop.

for phrase in keyword:

Now you need to split up the phrase into its actual words and determine if those words are in the whitelist. Then you need to put the words back together. You can do this in one line.

   filtered = ", ".join(word in phrase.split(", ") if word in whitelist)

Breakdown: phrase.split(", ") gives you a list of strings that were separated by ", " in the original string -- i.e. the words you care about. word in ... if word in whitelist is a list comprehension. It will return a list of each word in ..., in this case phrase.split, that meets the condition word in whitelist. Finally, ", ".join(...) gives you a string made up of every element in the list ... connected by ", ".

Lastly, you need to put the newly filtered string into your list of filtered strings.

   keyword_filter.append(filtered)

As a sidenote, I agree with others that you should use a set for your collection of whitelisted words. It has much faster lookup time. However, for a miniscule list of words like this example you won't notice a performance difference.


问:
Prevent Firefox from opening Privacy Notice when running web-ext?
When developing web extensions, I test them with (for example) web-ext run --bc -u https://stackoverflow.com/.  With Firefox 56.0 (and web-ext 2.2.2), this:

opens a window "Browser Console",

opens another window and starts to load https://stackoverflow.com/ there, and

opens another tab in that window to display the Firefox Privacy Notice.

The last part is not only annoying in itself, but also distracting as (AFAICT) it fills the browser console with warnings related to that page's scripts.

How can I prevent Firefox from opening the Firefox Privacy Notice when called from web-ext, perhaps by setting some preference with --pref?

答:
According to https://github.com/mozilla/web-ext/issues/1114 you can use this:</p>

```<code>web-ext run --pref='datareporting.policy.firstRunURL='
</code>```

Body:
According to https://github.com/mozilla/web-ext/issues/1114 you can use this:

web-ext run --pref='datareporting.policy.firstRunURL='


问:
Display data in Dropdown using model with List<selectListItem>
I'm new to MVC and would like to bind data in DropDownList using Model. But I'm not sure how to get into that.
Below is my code

--Model

```<code>public string Name { get; set; }
    public string Qualification { get; set; }
    public string CountryID { get; set; }
    public string StateID { get; set; }
    public string CityID { get; set; }
    public List<SelectList> CountryList { get; set; }
    //public List<SelectListItem> Country { get; set; }
    public List<SelectList> StateList { get; set; }
    public List<SelectList> CityList { get; set; }
</code>```

--View

```<code><tr>
        <td>@Html.LabelFor(s => s.Name)</td>
        <td>@Html.TextBoxFor(s => s.Name, new { @class = "form-control" })</td>
    </tr>
    <tr>
        <td>@Html.LabelFor(s => s.Qualification)</td>
        <td>@Html.TextBoxFor(s => s.Qualification, new { @class = "form-control" })</td>
    </tr>
    <tr>
        <td>@Html.LabelFor(s => s.Country)</td>
        <td>@Html.DropDownList("Country", new SelectList(Model.CountryList), "Select Country", new { @Class = "form-control" })</td>
    </tr>
</code>```

--Controller

```<code> public ActionResult DisplayView(EmployeeDetails.Models.DisplayModel dm)
    {
        EmployeeDetails.Models.DisplayModel obj = new EmployeeDetails.Models.DisplayModel();
        List<SelectListItem> CountryList = obj.CountryDetails(dm);
        //var CountryList = obj.CountryDetails(dm);

        obj.CountryList = new SelectList(CountryList, "Value", "Text");

        return View();
    }
</code>```

In model, I have a method(CountryDetails) to return COuntrylist as List from Database.

I'm getting error in the below line to assign values to the list in model.

```<code> obj.CountryList = new SelectList(CountryList, "Value", "Text");
</code>```

Please help me out to display the value correctly in Dropdown.

答:
I have just replicated you issue and made some changes to make it run.

In Model i have made change from list<SelectList> to List<SelectListItem>
after that i have PopulateCountry dropdownlist hardcoded data in controller which you can change it by replacing it with database.

After populating dropdownlist next using jquery ajax i have populated states and city dropdownlist.

Model

```<code>public class DisplayModel
{
    [Display(Name = "Choose Country")]
    public string Country { get; set; }
    public string Name { get; set; }
    public string Qualification { get; set; }
    public string CountryID { get; set; }
    public string StateID { get; set; }
    public string CityID { get; set; }
    public List<SelectListItem> CountryList { get; set; }
    public List<SelectListItem> StateList { get; set; }
    public List<SelectListItem> CityList { get; set; }
}
</code>```

Controller Code

```<code> public class DemoController : Controller
{
    // GET: Demo
    public ActionResult Index()
    {
        DisplayModel obj = new DisplayModel();
        obj.CountryList = PopulateCountry();
        return View(obj);
    }

    private static List<SelectListItem> PopulateCountry()
    {
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        li.Add(new SelectListItem { Text = "India", Value = "1" });
        li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
        return li;
    }

    public JsonResult GetStates(string id)
    {
        List<SelectListItem> states = new List<SelectListItem>();
        switch (id)
        {
            case "1":
                states.Add(new SelectListItem { Text = "Select", Value = "0" });
                states.Add(new SelectListItem { Text = "ANDAMAN & NIKOBAR ISLANDS", Value = "1" });
                states.Add(new SelectListItem { Text = "MAHARASHTRA", Value = "2" });
                break;
        }
        return Json(new SelectList(states, "Value", "Text"));
    }

    public JsonResult GetCity(string id)
    {
        List<SelectListItem> City = new List<SelectListItem>();
        switch (id)
        {
            case "2":
                City.Add(new SelectListItem { Text = "Select", Value = "0" });
                City.Add(new SelectListItem { Text = "MUMBAI", Value = "1" });
                City.Add(new SelectListItem { Text = "PUNE", Value = "2" });
                City.Add(new SelectListItem { Text = "KOLHAPUR", Value = "3" });
                City.Add(new SelectListItem { Text = "RATNAGIRI", Value = "4" });
                City.Add(new SelectListItem { Text = "NAGPUR", Value = "5" });
                City.Add(new SelectListItem { Text = "JALGAON", Value = "6" });
                break;
        }
        return Json(new SelectList(City, "Value", "Text"));
    }
}
</code>```

View

```<code>@model WebApplication1.Models.DisplayModel
@{
    ViewBag.Title = "Index";
}
<table>
    <tr>
        <td>@Html.LabelFor(s => s.Country)</td>
        <td>@Html.DropDownList("Country", Model.CountryList, "Select Country", new { @Class = "form-control" })</td>
    </tr>

    <tr>
        <td>State</td>
        <td>@Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { style = "width:250px", @class = "form-control" }) </td>
    </tr>

    <tr>
        <td>City</td>
        <td>@Html.DropDownList("city", new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", @class = "form-control" })   </td>
    </tr>
</table>
</code>```

```

Body:
I'm new to MVC and would like to bind data in DropDownList using Model. But I'm not sure how to get into that.
Below is my code

--Model

public string Name { get; set; }
    public string Qualification { get; set; }
    public string CountryID { get; set; }
    public string StateID { get; set; }
    public string CityID { get; set; }
    public List<SelectList> CountryList { get; set; }
    //public List<SelectListItem> Country { get; set; }
    public List<SelectList> StateList { get; set; }
    public List<SelectList> CityList { get; set; }

--View

        @Html.LabelFor(s => s.Name)
        @Html.TextBoxFor(s => s.Name, new { @class = "form-control" })

        @Html.LabelFor(s => s.Qualification)
        @Html.TextBoxFor(s => s.Qualification, new { @class = "form-control" })

        @Html.LabelFor(s => s.Country)
        @Html.DropDownList("Country", new SelectList(Model.CountryList), "Select Country", new { @Class = "form-control" })

--Controller

 public ActionResult DisplayView(EmployeeDetails.Models.DisplayModel dm)
    {
        EmployeeDetails.Models.DisplayModel obj = new EmployeeDetails.Models.DisplayModel();
        List<SelectListItem> CountryList = obj.CountryDetails(dm);
        //var CountryList = obj.CountryDetails(dm);

        obj.CountryList = new SelectList(CountryList, "Value", "Text");

        return View();
    }

In model, I have a method(CountryDetails) to return COuntrylist as List from Database.

I'm getting error in the below line to assign values to the list in model.

 obj.CountryList = new SelectList(CountryList, "Value", "Text");

Please help me out to display the value correctly in Dropdown.

Body:
I have just replicated you issue and made some changes to make it run.

In Model i have made change from list<SelectList> to List<SelectListItem>
after that i have PopulateCountry dropdownlist hardcoded data in controller which you can change it by replacing it with database.

After populating dropdownlist next using jquery ajax i have populated states and city dropdownlist.

Model

public class DisplayModel
{
    [Display(Name = "Choose Country")]
    public string Country { get; set; }
    public string Name { get; set; }
    public string Qualification { get; set; }
    public string CountryID { get; set; }
    public string StateID { get; set; }
    public string CityID { get; set; }
    public List<SelectListItem> CountryList { get; set; }
    public List<SelectListItem> StateList { get; set; }
    public List<SelectListItem> CityList { get; set; }
}

Controller Code

 public class DemoController : Controller
{
    // GET: Demo
    public ActionResult Index()
    {
        DisplayModel obj = new DisplayModel();
        obj.CountryList = PopulateCountry();
        return View(obj);
    }

    private static List<SelectListItem> PopulateCountry()
    {
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        li.Add(new SelectListItem { Text = "India", Value = "1" });
        li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
        return li;
    }

    public JsonResult GetStates(string id)
    {
        List<SelectListItem> states = new List<SelectListItem>();
        switch (id)
        {
            case "1":
                states.Add(new SelectListItem { Text = "Select", Value = "0" });
                states.Add(new SelectListItem { Text = "ANDAMAN & NIKOBAR ISLANDS", Value = "1" });
                states.Add(new SelectListItem { Text = "MAHARASHTRA", Value = "2" });
                break;
        }
        return Json(new SelectList(states, "Value", "Text"));
    }

    public JsonResult GetCity(string id)
    {
        List<SelectListItem> City = new List<SelectListItem>();
        switch (id)
        {
            case "2":
                City.Add(new SelectListItem { Text = "Select", Value = "0" });
                City.Add(new SelectListItem { Text = "MUMBAI", Value = "1" });
                City.Add(new SelectListItem { Text = "PUNE", Value = "2" });
                City.Add(new SelectListItem { Text = "KOLHAPUR", Value = "3" });
                City.Add(new SelectListItem { Text = "RATNAGIRI", Value = "4" });
                City.Add(new SelectListItem { Text = "NAGPUR", Value = "5" });
                City.Add(new SelectListItem { Text = "JALGAON", Value = "6" });
                break;
        }
        return Json(new SelectList(City, "Value", "Text"));
    }
}

View

@model WebApplication1.Models.DisplayModel
@{
    ViewBag.Title = "Index";
}
<table>
    <tr>
        <td>@Html.LabelFor(s => s.Country)</td>
        <td>@Html.DropDownList("Country", Model.CountryList, "Select Country", new { @Class = "form-control" })</td>
    </tr>

    <tr>
        <td>State</td>
        <td>@Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { style = "width:250px", @class = "form-control" }) </td>
    </tr>

    <tr>
        <td>City</td>
        <td>@Html.DropDownList("city", new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", @class = "form-control" })   </td>
    </tr>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">

    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#Country").change(function () {
            $("#State").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetStates")', // we are calling json method

                dataType: 'json',

                data: { id: $("#Country").val() },
                // here we are get value of selected country and passing same valueas inputto json method GetStates.

                success: function (states) {
                    // states contains the JSON formatted list
                    // of states passed from the controller

                    $.each(states, function (i, state) {
                        $("#State").append('<option value="' + state.Value + '">' + state.Text + '</option>');
                        // here we are adding option for States

                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });
</script>

<script type="text/javascript">

    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#State").change(function () {
            $("#city").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetCity")',
                dataType: 'json',
                data: { id: $("#State").val() },
                success: function (citys) {
                    // states contains the JSON formatted list
                    // of states passed from the controller
                    $.each(citys, function (i, city) {
                        $("#city").append('<option value="' + city.Value + '">' + city.Text + '</option>');
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });
</script>


问:
Forwarded email detection
Is there any way to detect (using RFC 2822 headers) that an email is a forwarded email?</p>

答:
Reading the spec, CTRL+F for "forward" gives the following header fields:

```<code>resent-date     =       "Resent-Date:" date-time CRLF
resent-from     =       "Resent-From:" mailbox-list CRLF
resent-sender   =       "Resent-Sender:" mailbox CRLF
resent-to       =       "Resent-To:" address-list CRLF
resent-cc       =       "Resent-Cc:" address-list CRLF
resent-bcc      =       "Resent-Bcc:" (address-list / [CFWS]) CRLF
resent-msg-id   =       "Resent-Message-ID:" msg-id CRLF
</code>```

I'm not sure whether the major mail software uses these though.

EDIT

Read the spec a little too quickly, there is also this note:

Note: Reintroducing a message into the transport system and using
     resent fields is a different operation from "forwarding".
     "Forwarding" has two meanings: One sense of forwarding is that a mail
     reading program can be told by a user to forward a copy of a message
     to another person, making the forwarded message the body of the new
     message.  A forwarded message in this sense does not appear to have
     come from the original sender, but is an entirely new message from
     the forwarder of the message.  On the other hand, forwarding is also
     used to mean when a mail transport program gets a message and
     forwards it on to a different destination for final delivery.  Resent
     header fields are not intended for use with either type of
     forwarding.

There are no other notices of "forwarding", so there are no header fields that you can use to detect the forward, except for the subject = "Fwd: <msg>" convention.

Title: Forwarded email detection

Body:
Reading the spec, CTRL+F for "forward" gives the following header fields:

resent-date     =       "Resent-Date:" date-time CRLF
resent-from     =       "Resent-From:" mailbox-list CRLF
resent-sender   =       "Resent-Sender:" mailbox CRLF
resent-to       =       "Resent-To:" address-list CRLF
resent-cc       =       "Resent-Cc:" address-list CRLF
resent-bcc      =       "Resent-Bcc:" (address-list / [CFWS]) CRLF
resent-msg-id   =       "Resent-Message-ID:" msg-id CRLF

I'm not sure whether the major mail software uses these though.

EDIT

Read the spec a little too quickly, there is also this note:

Note: Reintroducing a message into the transport system and using
     resent fields is a different operation from "forwarding".
     "Forwarding" has two meanings: One sense of forwarding is that a mail
     reading program can be told by a user to forward a copy of a message
     to another person, making the forwarded message the body of the new
     message.  A forwarded message in this sense does not appear to have
     come from the original sender, but is an entirely new message from
     the forwarder of the message.  On the other hand, forwarding is also
     used to mean when a mail transport program gets a message and
     forwards it on to a different destination for final delivery.  Resent
     header fields are not intended for use with either type of
     forwarding.

There are no other notices of "forwarding", so there are no header fields that you can use to detect the forward, except for the subject = "Fwd: <msg>" convention.

ContentLicense: CC BY-SA 2.5


问:
Frame-by-frame MJPEG streaming with C#/ASP.NET MVC
I have been trying to setup a MJPEG stream in ASP.NET. I want to retrieve a MJEPG stream from a URL, and send every frame that I get to every connected client. Examples that I have been able to find only read from a set file, instead of a continues stream from URL, and send the entire file through MultiStreamContent. Since I retrieve frame-by-frame, I cannot do this.
I would like to know if it is possible to do what I want with ASP.NET MVC. I'm currently using AForge video to retrieve the MJPEG stream from a link.
My code for the controller class:

```<code>using System.Net.Http;
using System.Web.Http;
using AForge.Video;

namespace VideoPrototypeMVC.Controllers
{
    public class CameraController : ApiController
    {
        int framecounter = 0;
        MJPEGStream stream = new MJPEGStream();

        [HttpGet]
        public void GetVideoContent()
        {
            stream.Source = @"http://127.0.0.1:5002/stream";
            stream.NewFrame += new NewFrameEventHandler(showFrame);
            stream.Start();
            MultipartContent content = new MultipartContent();
            while (stream.IsRunning)
            {
            //Continues streaming should be here?
            }
        }

        //Can be used to display of a frame is available
        private void showFrame(object sender, NewFrameEventArgs eventArgs)
        {
            framecounter++;
            System.Diagnostics.Debug.WriteLine("New frame event: " + framecounter);

        }

        //Should be called at the end of the stream
        private void stopStream(object sender, ReasonToFinishPlaying reason)
        {
            System.Diagnostics.Debug.WriteLine("Stop stream");
            stream.Stop();
            framecounter = 0;
        }
    }
}
</code>```

This code is not final, but I just need to get the continues streaming down. I have found examples that use Socket servers, but I would like to stick to MVC since it allows me to set up the rest of the server easier.

答:
To make sure other people will manage with this as well. I managed to combine what @Evk (Thank you once again) said, together with information I found here: creating my own MJPEG stream.

DO NOTE: The code below is just prototype/proof-of-concept! When I run this my processor shoots to 100% because of the endless while loop in StartStream. Will work on making this more event based but I thought the code below was more easely explained.

```<code>using System;
using System.IO;
using System.Net;
using System.Web;
using System.Net.Http;
using System.Web.Http;
using AForge.Video;
using System.Drawing;
using System.Text;
using System.Drawing.Imaging;
using System.Threading;

namespace VideoPrototypeMVC.Controllers
{
    public class CameraController : ApiController
    {
        private MJPEGStream mjpegStream = new MJPEGStream();
        private bool frameAvailable = false;
        private Bitmap frame = null;
        private string BOUNDARY = "frame";

        /// <summary>
        /// Initializer for the MJPEGstream
        /// </summary>
        CameraController()
        {
            mjpegStream.Source = @"{{INSERT STREAM URL}}";
            mjpegStream.NewFrame += new NewFrameEventHandler(showFrameEvent);
        }

        [HttpGet]
        public HttpResponseMessage GetVideoContent()
        {
            mjpegStream.Start();
            var response = Request.CreateResponse();
            response.Content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>)StartStream);
            response.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/x-mixed-replace; boundary=" + BOUNDARY);
            return response;
        }

        /// <summary>
        /// Craete an appropriate header.
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private byte[] CreateHeader(int length)
        {
            string header =
                "--" + BOUNDARY + "\r\n" +
                "Content-Type:image/jpeg\r\n" +
                "Content-Length:" + length + "\r\n\r\n";

            return Encoding.ASCII.GetBytes(header);
        }

        public byte[] CreateFooter()
        {
            return Encoding.ASCII.GetBytes("\r\n");
        }

        /// <summary>
        /// Write the given frame to the stream
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <param name="frame">Bitmap format frame</param>
        private void WriteFrame(Stream stream, Bitmap frame)
        {
            // prepare image data
            byte[] imageData = null;

            // this is to make sure memory stream is disposed after using
            using (MemoryStream ms = new MemoryStream())
            {
                frame.Save(ms, ImageFormat.Jpeg);
                imageData = ms.ToArray();
            }

            // prepare header
            byte[] header = CreateHeader(imageData.Length);
            // prepare footer
            byte[] footer = CreateFooter();

            // Start writing data
            stream.Write(header, 0, header.Length);
            stream.Write(imageData, 0, imageData.Length);
            stream.Write(footer, 0, footer.Length);
        }

        /// <summary>
        /// While the MJPEGStream is running and clients are connected,
        /// continue sending frames.
        /// </summary>
        /// <param name="stream">Stream to write to.</param>
        /// <param name="httpContent">The content information</param>
        /// <param name="transportContext"></param>
        private void StartStream(Stream stream, HttpContent httpContent, TransportContext transportContext)
        {
            while (mjpegStream.IsRunning && HttpContext.Current.Response.IsClientConnected)
            {
                if (frameAvailable)
                {
                    try
                    {
                        WriteFrame(stream, frame);
                        frameAvailable = false;
                    } catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e);
                    }
                }else
                {
                    Thread.Sleep(30);
                }
            }
            stopStream();
        }

        /// <summary>
        /// This event is thrown when a new frame is detected by the MJPEGStream
        /// </summary>
        /// <param name="sender">Object that is sending the event</param>
        /// <param name="eventArgs">Data from the event, including the frame</param>
        private void showFrameEvent(object sender, NewFrameEventArgs eventArgs)
        {
            frame = new Bitmap(eventArgs.Frame);
            frameAvailable = true;
        }

        /// <summary>
        /// Stop the stream.
        /// </summary>
        private void stopStream()
        {
            System.Diagnostics.Debug.WriteLine("Stop stream");
            mjpegStream.Stop();
        }
    }
}
</code>```

Body:
I have been trying to setup a MJPEG stream in ASP.NET. I want to retrieve a MJEPG stream from a URL, and send every frame that I get to every connected client. Examples that I have been able to find only read from a set file, instead of a continues stream from URL, and send the entire file through MultiStreamContent. Since I retrieve frame-by-frame, I cannot do this.
I would like to know if it is possible to do what I want with ASP.NET MVC. I'm currently using AForge video to retrieve the MJPEG stream from a link.
My code for the controller class:

using System.Net.Http;
using System.Web.Http;
using AForge.Video;

namespace VideoPrototypeMVC.Controllers
{
    public class CameraController : ApiController
    {
        int framecounter = 0;
        MJPEGStream stream = new MJPEGStream();

        [HttpGet]
        public void GetVideoContent()
        {
            stream.Source = @"http://127.0.0.1:5002/stream";
            stream.NewFrame += new NewFrameEventHandler(showFrame);
            stream.Start();
            MultipartContent content = new MultipartContent();
            while (stream.IsRunning)
            {
            //Continues streaming should be here?
            }
        }

        //Can be used to display of a frame is available
        private void showFrame(object sender, NewFrameEventArgs eventArgs)
        {
            framecounter++;
            System.Diagnostics.Debug.WriteLine("New frame event: " + framecounter);

        }

        //Should be called at the end of the stream
        private void stopStream(object sender, ReasonToFinishPlaying reason)
        {
            System.Diagnostics.Debug.WriteLine("Stop stream");
            stream.Stop();
            framecounter = 0;
        }
    }
}

This code is not final, but I just need to get the continues streaming down. I have found examples that use Socket servers, but I would like to stick to MVC since it allows me to set up the rest of the server easier.

Body:
To make sure other people will manage with this as well. I managed to combine what @Evk (Thank you once again) said, together with information I found here: creating my own MJPEG stream.

DO NOTE: The code below is just prototype/proof-of-concept! When I run this my processor shoots to 100% because of the endless while loop in StartStream. Will work on making this more event based but I thought the code below was more easely explained.

using System;
using System.IO;
using System.Net;
using System.Web;
using System.Net.Http;
using System.Web.Http;
using AForge.Video;
using System.Drawing;
using System.Text;
using System.Drawing.Imaging;
using System.Threading;

namespace VideoPrototypeMVC.Controllers
{
    public class CameraController : ApiController
    {
        private MJPEGStream mjpegStream = new MJPEGStream();
        private bool frameAvailable = false;
        private Bitmap frame = null;
        private string BOUNDARY = "frame";

        /// <summary>
        /// Initializer for the MJPEGstream
        /// </summary>
        CameraController()
        {
            mjpegStream.Source = @"{{INSERT STREAM URL}}";
            mjpegStream.NewFrame += new NewFrameEventHandler(showFrameEvent);
        }

        [HttpGet]
        public HttpResponseMessage GetVideoContent()
        {
            mjpegStream.Start();
            var response = Request.CreateResponse();
            response.Content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>)StartStream);
            response.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/x-mixed-replace; boundary=" + BOUNDARY);
            return response;
        }

        /// <summary>
        /// Craete an appropriate header.
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private byte[] CreateHeader(int length)
        {
            string header =
                "--" + BOUNDARY + "\r\n" +
                "Content-Type:image/jpeg\r\n" +
                "Content-Length:" + length + "\r\n\r\n";

            return Encoding.ASCII.GetBytes(header);
        }

        public byte[] CreateFooter()
        {
            return Encoding.ASCII.GetBytes("\r\n");
        }

        /// <summary>
        /// Write the given frame to the stream
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <param name="frame">Bitmap format frame</param>
        private void WriteFrame(Stream stream, Bitmap frame)
        {
            // prepare image data
            byte[] imageData = null;

            // this is to make sure memory stream is disposed after using
            using (MemoryStream ms = new MemoryStream())
            {
                frame.Save(ms, ImageFormat.Jpeg);
                imageData = ms.ToArray();
            }

            // prepare header
            byte[] header = CreateHeader(imageData.Length);
            // prepare footer
            byte[] footer = CreateFooter();

            // Start writing data
            stream.Write(header, 0, header.Length);
            stream.Write(imageData, 0, imageData.Length);
            stream.Write(footer, 0, footer.Length);
        }

        /// <summary>
        /// While the MJPEGStream is running and clients are connected,
        /// continue sending frames.
        /// </summary>
        /// <param name="stream">Stream to write to.</param>
        /// <param name="httpContent">The content information</param>
        /// <param name="transportContext"></param>
        private void StartStream(Stream stream, HttpContent httpContent, TransportContext transportContext)
        {
            while (mjpegStream.IsRunning && HttpContext.Current.Response.IsClientConnected)
            {
                if (frameAvailable)
                {
                    try
                    {
                        WriteFrame(stream, frame);
                        frameAvailable = false;
                    } catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e);
                    }
                }else
                {
                    Thread.Sleep(30);
                }
            }
            stopStream();
        }

        /// <summary>
        /// This event is thrown when a new frame is detected by the MJPEGStream
        /// </summary>
        /// <param name="sender">Object that is sending the event</param>
        /// <param name="eventArgs">Data from the event, including the frame</param>
        private void showFrameEvent(object sender, NewFrameEventArgs eventArgs)
        {
            frame = new Bitmap(eventArgs.Frame);
            frameAvailable = true;
        }

        /// <summary>
        /// Stop the stream.
        /// </summary>
        private void stopStream()
        {
            System.Diagnostics.Debug.WriteLine("Stop stream");
            mjpegStream.Stop();
        }
    }
}


问:
Is it possible to make subpackage appear as the actual package
I came around this question and got quite disappointed by how the tensorflow developers try to make the tensorflow directory appear as the actual package, whereas the actual package root is actually tensorflow/python. By using a __init__.py file of the form

```<code>from tensorflow.python import *
del python
</code>```

they try to achieve this goal. This results in some inconsistent behaviour (at least so it seems to me) when working with the package, e.g.

```<code>import tensorflow.python                # seems to work
tensorflow.python                       # AttributeError: no attribute 'python'
from tensorflow.python import Session   # works as expected
tensorflow.python.Session               # AttributeError: no attribute 'python'
from tensorflow import python           # works as expected

tensorflow.nn                           # works as expected
import tensorflow.nn                    # ImportError: no module 'tensorflow.nn'
tensorflow.nn.tanh                      # works as expected
from tensorflow.nn import tanh          # ImportError: no module 'tensorflow.nn'
</code>```

Now, I was wondering whether/how it could be possible to avoid most/all of these issues to get a more consistent behaviour. The first set of inconsistencies could be easily resolved by not deleting the python attribute. However, given that the goal would be to make the complete package appear as if it is a sub-package, this might not be entirely satisfactory.

To keep things simple, let's consider the following package structure

```<code>package/
    __init__.py
    api/
        __init__.py
        code.py
</code>```

where package/api/code.py looks something like

```<code>def a():
    return 'alpha'
def b():
    return 'bravo'
</code>```

and package/api/__init__.py would be

```<code>import package.api.code
</code>```

would it be possible to create package/__init__.py so that the following works

```<code>import package.api                      # ImportError: no module 'package.api'
package.api                             # AttributeError: no attribute 'api'
from package.api import code            # ImportError: no module 'package.api'
package.api.code                        # AttributeError: no attribute 'api'
from package import api                 # ImportError: cannot import 'api'

package.code                            # works as expected
import package.code                     # works as above
package.code.a                          # works as expected
from package import a                   # correctly imports function a
</code>```

I believe that the last four lines of code should give the expected result by adding to sys.modules, but I do not seem to be able to find a way to make import package.api fail.

Would anyone have an idea on how this could be done? Feel free to point me to use-cases that I am overlooking or should consider to achieve the above-mentioned goal.

答:
I managed to write something that almost works (in package/__init__.py):

```<code>import sys

from package.api import *

for key in sys.modules:
    parts = key.split('.')
    if len(parts) > 1 and parts.pop(0) == __name__:
        subkey = parts.pop(0)
        if subkey == 'api' and len(parts) == 0:
            sys.modules['.'.join([__name__, subkey])] = None
        elif subkey == 'api':
            m = sys.modules.pop(key)
            sys.modules['.'.join([__name__] + parts)] = m
del api
del sys
</code>```

The import errors suggest that it is still quite a hack, but apart from that most all of the examples work as specified iff the package has already been loaded once (i.e. if import package or alike has been invoked before running the statements from my question). If the first statement is import package.api, there is thus no ImportError as I would like.

In an attempt to find a solution for this problem, I stumbled upon this answer, which practically leads to the same behaviour with much more elegant code:

```<code>import sys

from package import api

# clean up this module
self = sys.modules.pop(__name__)
del self

# this module becomes hidden module
sys.modules[__name__] = api
sys.modules[api.__name__] = None

del api
del sys
</code>```

However, this still suffers from the problem that if the first import is something like import package.api, no ImportError is thrown.

Body:
I came around this question and got quite disappointed by how the tensorflow developers try to make the tensorflow directory appear as the actual package, whereas the actual package root is actually tensorflow/python. By using a __init__.py file of the form

from tensorflow.python import *
del python

they try to achieve this goal. This results in some inconsistent behaviour (at least so it seems to me) when working with the package, e.g.

import tensorflow.python                # seems to work
tensorflow.python                       # AttributeError: no attribute 'python'
from tensorflow.python import Session   # works as expected
tensorflow.python.Session               # AttributeError: no attribute 'python'
from tensorflow import python           # works as expected

tensorflow.nn                           # works as expected
import tensorflow.nn                    # ImportError: no module 'tensorflow.nn'
tensorflow.nn.tanh                      # works as expected
from tensorflow.nn import tanh          # ImportError: no module 'tensorflow.nn'

Now, I was wondering whether/how it could be possible to avoid most/all of these issues to get a more consistent behaviour. The first set of inconsistencies could be easily resolved by not deleting the python attribute. However, given that the goal would be to make the complete package appear as if it is a sub-package, this might not be entirely satisfactory.

To keep things simple, let's consider the following package structure

package/
    __init__.py
    api/
        __init__.py
        code.py

where package/api/code.py looks something like

def a():
    return 'alpha'
def b():
    return 'bravo'

and package/api/__init__.py would be

import package.api.code

would it be possible to create package/__init__.py so that the following works

import package.api                      # ImportError: no module 'package.api'
package.api                             # AttributeError: no attribute 'api'
from package.api import code            # ImportError: no module 'package.api'
package.api.code                        # AttributeError: no attribute 'api'
from package import api                 # ImportError: cannot import 'api'

package.code                            # works as expected
import package.code                     # works as above
package.code.a                          # works as expected
from package import a                   # correctly imports function a

I believe that the last four lines of code should give the expected result by adding to sys.modules, but I do not seem to be able to find a way to make import package.api fail.

Would anyone have an idea on how this could be done? Feel free to point me to use-cases that I am overlooking or should consider to achieve the above-mentioned goal.

Body:
I managed to write something that almost works (in package/__init__.py):

import sys

from package.api import *

for key in sys.modules:
    parts = key.split('.')
    if len(parts) > 1 and parts.pop(0) == __name__:
        subkey = parts.pop(0)
        if subkey == 'api' and len(parts) == 0:
            sys.modules['.'.join([__name__, subkey])] = None
        elif subkey == 'api':
            m = sys.modules.pop(key)
            sys.modules['.'.join([__name__] + parts)] = m
del api
del sys

The import errors suggest that it is still quite a hack, but apart from that most all of the examples work as specified iff the package has already been loaded once (i.e. if import package or alike has been invoked before running the statements from my question). If the first statement is import package.api, there is thus no ImportError as I would like.

In an attempt to find a solution for this problem, I stumbled upon this answer, which practically leads to the same behaviour with much more elegant code:

import sys

from package import api

# clean up this module
self = sys.modules.pop(__name__)
del self

# this module becomes hidden module
sys.modules[__name__] = api
sys.modules[api.__name__] = None

del api
del sys

However, this still suffers from the problem that if the first import is something like import package.api, no ImportError is thrown.


问:
Python list: Copy single list to 2D list
how can i copy a single dimensional list to a two dimensional list?</p>

```<code>import copy
dataList=[1,2,3,4,5]
multiList=([[],[],[],[],[]])

multiList = copy.deepcopy(dataList)
print(multiList[0][0])
</code>```

答: If what you want is to put your dataList into multiList[0][0] then no need to use deepcopy. Just do this: multiList[0][0] = dataList

Body:
how can i copy a single dimensional list to a two dimensional list?

import copy
dataList=[1,2,3,4,5]
multiList=([[],[],[],[],[]])

multiList = copy.deepcopy(dataList)
print(multiList[0][0])


问:
Value returned by service not update in controller's variable in angularjs
```<code>function getList() {

        SubCategoryService.getAllList().then(function (response) {
            $scope.subCategoryList = response.data;
            $scope.subCategoryDetailsList = [];

            var subCategoryDetails = [];

            for(var i=0; i < $scope.subCategoryList.length; i++) {

                var subCategoryListData = $scope.subCategoryList[i];

                var subcategory = {
                    'id' : subCategoryListData.id,
                    'category' : '',
                    'name' : subCategoryListData.name,
                    'created_on' : subCategoryListData.created_on,
                    'modified_on' :  subCategoryListData.modified_on,
                    'is_deleted' : subCategoryListData.is_deleted,
                    'is_active' : subCategoryListData.is_active,
                    'image_name' : subCategoryListData.image_name,
                    'image_path' : subCategoryListData.image_path
                }

                CategoryService.getCategoryById(subCategoryListData.category_id).then(function(response1) {
                    console.log(response1.data);
                    subcategory.category = response1.data;

                }, function(error) {
                    swal("Error", error.data, "error");
                })

                subCategoryDetails.push(subcategory);
            }

            console.log(JSON.stringify(subCategoryDetails));

        }, function (error) {
            swal("Error", "Something went wrong", "error");
        });
    }
</code>```

CategoryService:

```<code>  this.getCategoryById = function(id) {
            return $http({
                url: globalUrl.baseurl + 'category/getCategoryById/' + id,
                method: 'GET'
            })
        }
</code>```

in the above code i am tring to fetch data from CategoryService service and it successfully return the data within the CategoryService.getCategoryById function. Now i am trying to assign returned value by service to subcategory.category which is present in controller. but my problem is it is not updateing the value in subcategory.category.

答:
my guess is:

you are pushing the new variabile inside the array BEFORE the API call is executed (because of the js callback), can you try something like:

```<code>CategoryService.getCategoryById(subCategoryListData.category_id)
.then(function(response1) {
    console.log(response1.data);
    subcategory.category = response1.data;

    // PUSHING AFTER API RETURNS THE VALUE
    subCategoryDetails.push(subcategory);

}, function(error) {
    swal("Error", error.data, "error");
})

// subCategoryDetails.push(subcategory);
</code>```

Body:
function getList() {

        SubCategoryService.getAllList().then(function (response) {
            $scope.subCategoryList = response.data;
            $scope.subCategoryDetailsList = [];

            var subCategoryDetails = [];

            for(var i=0; i < $scope.subCategoryList.length; i++) {

                var subCategoryListData = $scope.subCategoryList[i];

                var subcategory = {
                    'id' : subCategoryListData.id,
                    'category' : '',
                    'name' : subCategoryListData.name,
                    'created_on' : subCategoryListData.created_on,
                    'modified_on' :  subCategoryListData.modified_on,
                    'is_deleted' : subCategoryListData.is_deleted,
                    'is_active' : subCategoryListData.is_active,
                    'image_name' : subCategoryListData.image_name,
                    'image_path' : subCategoryListData.image_path
                }

                CategoryService.getCategoryById(subCategoryListData.category_id).then(function(response1) {
                    console.log(response1.data);
                    subcategory.category = response1.data;

                }, function(error) {
                    swal("Error", error.data, "error");
                })

                subCategoryDetails.push(subcategory);
            }

            console.log(JSON.stringify(subCategoryDetails));

        }, function (error) {
            swal("Error", "Something went wrong", "error");
        });
    }

CategoryService:

  this.getCategoryById = function(id) {
            return $http({
                url: globalUrl.baseurl + 'category/getCategoryById/' + id,
                method: 'GET'
            })
        }

in the above code i am tring to fetch data from CategoryService service and it successfully return the data within the CategoryService.getCategoryById function. Now i am trying to assign returned value by service to subcategory.category which is present in controller. but my problem is it is not updateing the value in subcategory.category.

Body:
my guess is:

you are pushing the new variabile inside the array BEFORE the API call is executed (because of the js callback), can you try something like:

CategoryService.getCategoryById(subCategoryListData.category_id)
.then(function(response1) {
    console.log(response1.data);
    subcategory.category = response1.data;

    // PUSHING AFTER API RETURNS THE VALUE
    subCategoryDetails.push(subcategory);

}, function(error) {
    swal("Error", error.data, "error");
})

// subCategoryDetails.push(subcategory);


问:
how to add protobuf file for topic in gcloud pubsub?
In google cloud's pubsub, I can see that on creating a new topic, I have to create a new message. Can I store a protobuf file there instead of having to write the whole structure of message in key-value pairs? For the protobuf code that shall be written, I mean this. If the protobuf isnt meant to be put on the gcloud pubsub, how can I use it with grpc client?</p>

答:
If you want to send a ProtoBuf message via the Publish API, you should do so by serializing it to a ByteString and then setting it as the message's data field. For example, if you are using the Java client library and you have a Publisher and obj of some ProtoBuf type, then you could do the following:

```<code>PubsubMessage message = PubsubMessage.newBuilder()
    .setData(obj.toByteString())
    .build();
ApiFuture<String> response = publisher.publish(message);
...
</code>```

On the subscribe side, you would decode the message in your MessageReceiver:

```<code>public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
  ProtoBufMessage obj;
  try {
    obj = ProtoBufMessage.parseFrom(message.getData());
  } catch (Exception e) {
    // Handle improperly encoded message
  }
  ...
}
</code>```

Body:
If you want to send a ProtoBuf message via the Publish API, you should do so by serializing it to a ByteString and then setting it as the message's data field. For example, if you are using the Java client library and you have a Publisher and obj of some ProtoBuf type, then you could do the following:

PubsubMessage message = PubsubMessage.newBuilder()
    .setData(obj.toByteString())
    .build();
ApiFuture<String> response = publisher.publish(message);
...

On the subscribe side, you would decode the message in your MessageReceiver:

public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
  ProtoBufMessage obj;
  try {
    obj = ProtoBufMessage.parseFrom(message.getData());
  } catch (Exception e) {
    // Handle improperly encoded message
  }
  ...
}


问:
How in asp.net core HtmlHelper extension with IDisposable pattern to catch inner content
I am quite novice in ASP.NET Core.
I am trying to migrate our old project to ASP.NET core.
We use a lot of script blocks inside of partials that are centrally rendered in predefined place of layout. We use HtmlHelper with disposable pattern as described here. The problem is that due of the new architecture in ASP.NET core it is not possible to use

```<code>webPageBase.OutputStack.Pop()
</code>```

to catch content. I found similar solution with TagHelpers
but I still will prefer to stay with HtmlHelper extension to have collecting scripts logic and rendering in single place. Otherwise I will need to write 2 tag helpers, coordinate them and replace all 50-100 occurrences of HtmlHelper extension to tag helper.

答:
HTML helpers are still a thing in ASP.NET Core. Just because tag helpers are the new and generally more flexible solution to render custom HTML, that does not mean that HTML helpers are gone or that they have no use left. The built-in tag helpers are actually based on the HTML helpers and will use the same internal backend to generate the output. So it’s just a different interface for the same thing.

That being said, due to how ASP.NET Core renders views, capturing the content inside a using block is a bit more difficult compared to how it works in tag helpers (where it’s a very general feature).

I’ve been sitting on this for a while now and came up with the following. This works by temporarily replacing the view writer to a StringWriter for as long as the block is open. Note that this might be a super terrible idea. But it works…

public static class ScriptHtmlHelper
{
    private const string ScriptsKey = "__ScriptHtmlHelper_Scripts";

    public static ScriptBlock BeginScripts(this IHtmlHelper helper)
    {
        return new ScriptBlock(helper.ViewContext);
    }

    public static IHtmlContent PageScripts(this IHtmlHelper helper)
    {
        if (helper.ViewContext.HttpContext.Items.TryGetValue(ScriptsKey, out var scriptsData) && scriptsData is List<object> scripts)
            return new HtmlContentBuilder(scripts);
        return HtmlString.Empty;
    }

    public class ScriptBlock : IDisposable
    {
        private ViewContext _viewContext;
        private TextWriter _originalWriter;
        private StringWriter _scriptWriter;
        private bool _disposed;

        public ScriptBlock(ViewContext viewContext)
        {
            _viewContext = viewContext;
            _originalWriter = viewContext.Writer;

            // replace writer
            viewContext.Writer = _scriptWriter = new StringWriter();
        }

        public void Dispose()
        {
            if (_disposed)
                return;

            try
            {
                List<object> scripts = null;
                if (_viewContext.HttpContext.Items.TryGetValue(ScriptsKey, out var scriptsData))
                    scripts = scriptsData as List<object>;
                if (scripts == null)
                    _viewContext.HttpContext.Items[ScriptsKey] = scripts = new List<object>();

                scripts.Add(new HtmlString(_scriptWriter.ToString()));
            }
            finally
            {
                // restore the original writer
                _viewContext.Writer = _originalWriter;
                _disposed = true;
            }
        }
    }
}
```

<p>Usage will be like this:</p>

<pre class="lang-csharp prettyprint-override"><code>@using (Html.BeginScripts()) {
    <script>console.log('foo');</script>
    <script>console.log('bar');</script>
}

@using (Html.BeginScripts()) {
    <script>console.log('baz');</script>
}
</code>```

And then to render everything:

@Html.PageScripts()
```

Body:
I am quite novice in ASP.NET Core.
I am trying to migrate our old project to ASP.NET core.
We use a lot of script blocks inside of partials that are centrally rendered in predefined place of layout. We use HtmlHelper with disposable pattern as described here. The problem is that due of the new architecture in ASP.NET core it is not possible to use

webPageBase.OutputStack.Pop()

to catch content. I found similar solution with TagHelpers
but I still will prefer to stay with HtmlHelper extension to have collecting scripts logic and rendering in single place. Otherwise I will need to write 2 tag helpers, coordinate them and replace all 50-100 occurrences of HtmlHelper extension to tag helper.

Body:
HTML helpers are still a thing in ASP.NET Core. Just because tag helpers are the new and generally more flexible solution to render custom HTML, that does not mean that HTML helpers are gone or that they have no use left. The built-in tag helpers are actually based on the HTML helpers and will use the same internal backend to generate the output. So it’s just a different interface for the same thing.

That being said, due to how ASP.NET Core renders views, capturing the content inside a using block is a bit more difficult compared to how it works in tag helpers (where it’s a very general feature).

I’ve been sitting on this for a while now and came up with the following. This works by temporarily replacing the view writer to a StringWriter for as long as the block is open. Note that this might be a super terrible idea. But it works…

public static class ScriptHtmlHelper
{
    private const string ScriptsKey = "__ScriptHtmlHelper_Scripts";

    public static ScriptBlock BeginScripts(this IHtmlHelper helper)
    {
        return new ScriptBlock(helper.ViewContext);
    }

    public static IHtmlContent PageScripts(this IHtmlHelper helper)
    {
        if (helper.ViewContext.HttpContext.Items.TryGetValue(ScriptsKey, out var scriptsData) && scriptsData is List<object> scripts)
            return new HtmlContentBuilder(scripts);
        return HtmlString.Empty;
    }

    public class ScriptBlock : IDisposable
    {
        private ViewContext _viewContext;
        private TextWriter _originalWriter;
        private StringWriter _scriptWriter;
        private bool _disposed;

        public ScriptBlock(ViewContext viewContext)
        {
            _viewContext = viewContext;
            _originalWriter = viewContext.Writer;

            // replace writer
            viewContext.Writer = _scriptWriter = new StringWriter();
        }

        public void Dispose()
        {
            if (_disposed)
                return;

            try
            {
                List<object> scripts = null;
                if (_viewContext.HttpContext.Items.TryGetValue(ScriptsKey, out var scriptsData))
                    scripts = scriptsData as List<object>;
                if (scripts == null)
                    _viewContext.HttpContext.Items[ScriptsKey] = scripts = new List<object>();

                scripts.Add(new HtmlString(_scriptWriter.ToString()));
            }
            finally
            {
                // restore the original writer
                _viewContext.Writer = _originalWriter;
                _disposed = true;
            }
        }
    }
}

Usage will be like this:

@using (Html.BeginScripts()) {
    <script>console.log('foo');</script>
    <script>console.log('bar');</script>
}

@using (Html.BeginScripts()) {
    <script>console.log('baz');</script>
}

And then to render everything:

@Html.PageScripts()


问:
How to display a form inside another form like Visual Studio
How does Visual Studio and other similar programs display a form in their IDE?

Is it possible to achieve the same or a similar effect using C# or VB.NET?

Please see the picture below to get what I mean.

答:
Are you speaking about UI creating tools?
Refer to http://www.icsharpcode.net/opensource/sd/ - SharpDevelop for deep dive. It's open sourse, so you'll be able to find out more details.</p>