问:
How to insert empty row at the table based on condition in case using JRBeanCollectionDataSource?
There is a list and I use this mechanism to pass it to my jasper report:

```<code>JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(list);
</code>```

The Object of that list is as follows:

```<code>public class Test{
  private int id;
  //other properties  + getters & setter
}
</code>```

Now Assume I have 10 elements within my list (id= 1 to 10) and I want to separate them in one table using an empty row, meaning 5 rows top, one empty row, 5 rows down.

How to do that ?

答:
The subreport element can helps with solving this problem - we can show or hide subreport based on condition using printWhenExpression.

In your case we need to show subreport with one empty line.

Example

The subreport for showing empty line is very simple. It does not need datasource for showing data - we can put staticText right at Title band. We don't need also margins.

The jrxml will be:

```<code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Empty Line" pageWidth="572" pageHeight="30" whenNoDataType="AllSectionsNoDetail" columnWidth="572" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0">
    <style name="bordered">
        <box>
            <pen lineWidth="0.25"/>
        </box>
    </style>
    <title>
        <band height="30" splitType="Stretch">
            <staticText>
                <reportElement style="bordered" x="0" y="0" width="572" height="30"/>
            </staticText>
        </band>
    </title>
</jasperReport>
</code>```

I used simple csv datasource for example - file films.csv contains data for report:

```<code>id,name,year,rating
1,The Shawshank Redemption,1994,9.3
2,The Godfather,1972,9.2
3,The Dark Knight,2008,9.0
4,The Godfather: Part II,1974,9.0
5,The Lord of the Rings: The Return of the King,2003,8.9
6,Pulp Fiction,1994,8.9
7,Schindler's List,1993,8.9
8,"The Good, the Bad and the Ugly",1966,8.9
9,12 Angry Men,1957,8.9
10,Avengers: Endgame,2019,8.8
</code>```

The main (master) report is using CSV File Data Adapter for building report.

The jrxml of master report:

```<code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Insert blank row on condition" pageWidth="612" pageHeight="792" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" >
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="films.csv"/>
    <style name="bordered">
        <box>
            <pen lineWidth="0.25"/>
        </box>
    </style>
    <field name="id" class="java.lang.Integer"/>
    <field name="name" class="java.lang.String"/>
    <field name="year" class="java.lang.String"/>
    <field name="rating" class="java.math.BigDecimal"/>
    <title>
        <band height="30" splitType="Stretch">
            <staticText>
                <reportElement x="158" y="0" width="256" height="30"/>
                <text><![CDATA[Films. Showing empty line for Id == 5]]></text>
            </staticText>
        </band>
    </title>
    <columnHeader>
        <band height="30">
            <staticText>
                <reportElement x="0" y="0" width="70" height="30"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <text><![CDATA[Id]]></text>
            </staticText>
            <staticText>
                <reportElement x="70" y="0" width="290" height="30"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <text><![CDATA[Name]]></text>
            </staticText>
            <staticText>
                <reportElement x="360" y="0" width="69" height="30"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <text><![CDATA[Year]]></text>
            </staticText>
            <staticText>
                <reportElement x="429" y="0" width="143" height="30"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <text><![CDATA[Rating]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="60">
            <subreport>
                <reportElement x="0" y="30" width="572" height="30" isRemoveLineWhenBlank="true" >
                    <printWhenExpression><![CDATA[$F{id} == 5]]></printWhenExpression>
                </reportElement>
                <subreportExpression><![CDATA["empty_row.jasper"]]></subreportExpression>
            </subreport>
            <textField>
                <reportElement style="bordered" x="0" y="0" width="70" height="30"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement style="bordered" x="70" y="0" width="290" height="30"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement style="bordered" x="360" y="0" width="69" height="30"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{year}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement style="bordered" x="429" y="0" width="143" height="30"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{rating}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>
</code>```

I used <printWhenExpression><![CDATA[$F{id} == 5]]></printWhenExpression> for hiding subreport with empty line, it means that empty line will show only of row with id == 5. You can use any expression you want.

The output at JSS will be:

Alternative solutions

You can insert element during building collection before passing this collection at JRBeanCollectionDataSource.

You can implement custom DataSource based on JRBeanCollectionDataSource with some logic.

Body:
There is a list and I use this mechanism to pass it to my jasper report:

JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(list);

The Object of that list is as follows:

public class Test{
  private int id;
  //other properties  + getters & setter
}

Now Assume I have 10 elements within my list (id= 1 to 10) and I want to separate them in one table using an empty row, meaning 5 rows top, one empty row, 5 rows down.

How to do that ?

Body:
The subreport element can helps with solving this problem - we can show or hide subreport based on condition using printWhenExpression.

In your case we need to show subreport with one empty line.

Example

The subreport for showing empty line is very simple. It does not need datasource for showing data - we can put staticText right at Title band. We don't need also margins.

The jrxml will be:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Empty Line" pageWidth="572" pageHeight="30" whenNoDataType="AllSectionsNoDetail" columnWidth="572" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0">
    <style name="bordered">
        <box>
            <pen lineWidth="0.25"/>
        </box>
    </style>
    <title>
        <band height="30" splitType="Stretch">
            <staticText>
                <reportElement style="bordered" x="0" y="0" width="572" height="30"/>
            </staticText>
        </band>
    </title>
</jasperReport>

I used simple csv datasource for example - file films.csv contains data for report:

id,name,year,rating
1,The Shawshank Redemption,1994,9.3
2,The Godfather,1972,9.2
3,The Dark Knight,2008,9.0
4,The Godfather: Part II,1974,9.0
5,The Lord of the Rings: The Return of the King,2003,8.9
6,Pulp Fiction,1994,8.9
7,Schindler's List,1993,8.9
8,"The Good, the Bad and the Ugly",1966,8.9
9,12 Angry Men,1957,8.9
10,Avengers: Endgame,2019,8.8

The main (master) report is using CSV File Data Adapter for building report.

The jrxml of master report:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Insert blank row on condition" pageWidth="612" pageHeight="792" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" >
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="films.csv"/>
    <style name="bordered">
        <box>
            <pen lineWidth="0.25"/>
        </box>
    </style>
    <field name="id" class="java.lang.Integer"/>
    <field name="name" class="java.lang.String"/>
    <field name="year" class="java.lang.String"/>
    <field name="rating" class="java.math.BigDecimal"/>
    <title>
        <band height="30" splitType="Stretch">
            <staticText>
                <reportElement x="158" y="0" width="256" height="30"/>
                <text><![CDATA[Films. Showing empty line for Id == 5]]></text>
            </staticText>
        </band>
    </title>
    <columnHeader>
        <band height="30">
            <staticText>
                <reportElement x="0" y="0" width="70" height="30"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <text><![CDATA[Id]]></text>
            </staticText>
            <staticText>
                <reportElement x="70" y="0" width="290" height="30"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <text><![CDATA[Name]]></text>
            </staticText>
            <staticText>
                <reportElement x="360" y="0" width="69" height="30"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <text><![CDATA[Year]]></text>
            </staticText>
            <staticText>
                <reportElement x="429" y="0" width="143" height="30"/>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <text><![CDATA[Rating]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="60">
            <subreport>
                <reportElement x="0" y="30" width="572" height="30" isRemoveLineWhenBlank="true" >
                    <printWhenExpression><![CDATA[$F{id} == 5]]></printWhenExpression>
                </reportElement>
                <subreportExpression><![CDATA["empty_row.jasper"]]></subreportExpression>
            </subreport>
            <textField>
                <reportElement style="bordered" x="0" y="0" width="70" height="30"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement style="bordered" x="70" y="0" width="290" height="30"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement style="bordered" x="360" y="0" width="69" height="30"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{year}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement style="bordered" x="429" y="0" width="143" height="30"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{rating}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

I used <printWhenExpression><![CDATA[$F{id} == 5]]></printWhenExpression> for hiding subreport with empty line, it means that empty line will show only of row with id == 5. You can use any expression you want.

The output at JSS will be:

Alternative solutions

You can insert element during building collection before passing this collection at JRBeanCollectionDataSource.

You can implement custom DataSource based on JRBeanCollectionDataSource with some logic.


来源: stackexchange

问:
Is there a digital ocean sandbox where you can experiment with digital ocean before you pay?
Is there a digital ocean sandbox where you can experiment with digital ocean before you pay?

Can I learn and experiment with digital ocean before I pay for droplet? Is it possible or do I have to get one and experiment with it?

答:
Sadly there is no sandbox or free-tier option with DO.

You have a couple of options thought;
1 - Spin your own VM test image locally using something like VMWare Player
2 - Contact a friend or college who may already use DO and see if they are willing to spin another basic droplet up for you.

To save account sharing DO have a teams feature.

DigitalOcean teams allow you to invite multiple users to access and
manage shared resources (like Droplets, DigitalOcean Load Balancers,
and Spaces) without sharing login credentials or billing information.

Teams are useful for project leaders and business owners who want to
share control of server infrastructure with trusted collaborators,
such as developers and system administrators. They’re available to
anyone with a DigitalOcean account at no additional cost.

It's also worth point out that if you decide to spin your own local image you can actually take that image with you to DO at a later date and turn it into a droplet.

They have some documentation here though it's not great. If you do decide to go this route there are 2 very important things you must do when you make your local VM.

The file system MUST be ext4

The disk MUST be a single vmdk file

IPv6 Will not be available.

ContentLicense: CC BY-SA 4.0


问:
AWS CLI environment create error CREATE_FAILED, reason: resources failed to create
I used to deploy a Java web application to Elastic Beanstalk (EC2) as root user without this problem. Now I'm using a recommended way of deploying as IAM service user and I get the following errors. I suspect it's because of lack of permissions (policies) but I don't know what policies should I assign to the IAM user.

QUESTION: Could you help me in finding the right policies?

commands:

```<code>eb init --profile eb_admin
eb create --single
</code>```

output of the 2nd command:

```<code>Printing Status:
2019-05-26 12:08:58    INFO    createEnvironment is starting.
2019-05-26 12:08:59    INFO    Using elasticbeanstalk-eu-central-1-726173845157 as Amazon S3 storage bucket for environment data.
2019-05-26 12:09:26    INFO    Created security group named: awseb-e-ire9qdzahd-stack-AWSEBSecurityGroup-L5VUAQLDAA9F
2019-05-26 12:09:42    ERROR   Stack named 'awseb-e-ire9qdzahd-stack' aborted operation. Current state: 'CREATE_FAILED'  Reason: The following resource(s) failed to create: [MountTargetSecurityGroup, AWSEBEIP, sslSecurityGroupIngress, FileSystem].
2019-05-26 12:09:42    ERROR   Creating security group failed Reason: The vpc ID 'vpc-7166611a' does not exist (Service: AmazonEC2; Status Code: 400; Error Code: InvalidVpcID.NotFound; Request ID: c1d0ce4d-830d-4b0c-9f84-85d8da4f7243)
2019-05-26 12:09:42    ERROR   Creating EIP: 54.93.84.166 failed. Reason: Resource creation cancelled
2019-05-26 12:09:42    ERROR   Creating security group ingress named: sslSecurityGroupIngress failed Reason: Resource creation cancelled
2019-05-26 12:09:44    INFO    Launched environment: stack-overflow-dev. However, there were issues during launch. See event log for details.
</code>```

Important!

I use a few .ebextensions scripts in order to initialize the environment:

nginx

https-instance-securitygroup

storage-efs-createfilesystem

storage-efs-mountfilesystem

After reviewing the logs, I also noticed that I forgot to create VPC which is required for EFS filesystem. Could it be that 1 failed script (storage-efs-createfilesystem) is the root cause of subsequent failing operations?

答:
Yes, the lack of VPC has caused the other resources to fail to create. Elastic Beanstalk and the storage-efs-createfilesystem extension use CloudFormation underneath.

storage-efs-createfilesystem Cfn template creates MountTargetSecurityGroup SG and that failed due to lack of VPC. The AWSEBEIP, sslSecurityGroupIngress and FileSystem resource creation is then cancelled.

Body:
I used to deploy a Java web application to Elastic Beanstalk (EC2) as root user without this problem. Now I'm using a recommended way of deploying as IAM service user and I get the following errors. I suspect it's because of lack of permissions (policies) but I don't know what policies should I assign to the IAM user.

QUESTION: Could you help me in finding the right policies?

commands:

eb init --profile eb_admin
eb create --single

output of the 2nd command:

Printing Status:
2019-05-26 12:08:58    INFO    createEnvironment is starting.
2019-05-26 12:08:59    INFO    Using elasticbeanstalk-eu-central-1-726173845157 as Amazon S3 storage bucket for environment data.
2019-05-26 12:09:26    INFO    Created security group named: awseb-e-ire9qdzahd-stack-AWSEBSecurityGroup-L5VUAQLDAA9F
2019-05-26 12:09:42    ERROR   Stack named 'awseb-e-ire9qdzahd-stack' aborted operation. Current state: 'CREATE_FAILED'  Reason: The following resource(s) failed to create: [MountTargetSecurityGroup, AWSEBEIP, sslSecurityGroupIngress, FileSystem].
2019-05-26 12:09:42    ERROR   Creating security group failed Reason: The vpc ID 'vpc-7166611a' does not exist (Service: AmazonEC2; Status Code: 400; Error Code: InvalidVpcID.NotFound; Request ID: c1d0ce4d-830d-4b0c-9f84-85d8da4f7243)
2019-05-26 12:09:42    ERROR   Creating EIP: 54.93.84.166 failed. Reason: Resource creation cancelled
2019-05-26 12:09:42    ERROR   Creating security group ingress named: sslSecurityGroupIngress failed Reason: Resource creation cancelled
2019-05-26 12:09:44    INFO    Launched environment: stack-overflow-dev. However, there were issues during launch. See event log for details.

Important!

I use a few .ebextensions scripts in order to initialize the environment:

nginx

https-instance-securitygroup

storage-efs-createfilesystem

storage-efs-mountfilesystem

After reviewing the logs, I also noticed that I forgot to create VPC which is required for EFS filesystem. Could it be that 1 failed script (storage-efs-createfilesystem) is the root cause of subsequent failing operations?


问:
Getting release details during tests run
I'm running automation tests using MsTest from Azure devops.
In the test TestCleanup I wish to know which release (Name+number) triggered the tests.
Is there a way to do that?</p>

答: Refer to the documentation. Various values about a running build or release are set as environment variables, which you can retrieve during your tests. Release.ReleaseName contains the release name.


问:
How to add horizontal bar in table row whose width depends on the value passed
I am implementing vote application in which i need to show horizontal bar in table row whose width is depended on particular value. This horizontal bar will act as a indicator to show percentage of vote.</p>

答:
One solution could be like this.....

Use two UILabels..... with different color..... combined length of this label would be 100px and we will vary individual's length based on the percentage......

Thanks,

ContentLicense: CC BY-SA 3.0


问:
MathJax not always rendering with Vue filtered list
I'm trying to build a filtered list in Vue with equations rendered with MathJax, and it seems to be having some problems, since the equations renders on the first load, but when I search for terms, some equations render and some don't, I can't understand why.
Basically on the first load, if I type a character in my search bar, everything renders correctly, but when I search more, or erase it and do it again, it doesn't, as you can see in these images:

my Vue code is as follows:

```<code>var analisiMatematica = new Vue({

el: '#searcher',
data: {
    searchQuery: '',
    isResult: false,
    results: [],
    //json: 'json/analisimatematica.json',
    error: ''
},

mounted: function() {
    axios.get('./json/analisimatematica.json')
    .then(function(response) {
        this.results = response.data.Domande;
        console.log(this.results);
    }.bind(this))
    .catch(function(error) {
        this.error = error.data;
        console.log(error.data);
    }.bind(this));
},

methods: {
    removeSearchQuery: function() {
      this.searchQuery = '';
      this.isResult = false;
    },
    submitSearch: function() {
      this.isResult = true;

    }
},
computed: {
    filteredObj: function() {
        var list = [];
        this.results.forEach(function(el) {
            if(el.domanda.toLowerCase().indexOf(this.searchQuery.toLowerCase()) > -1) {
                list.push(el);
            }
        }.bind(this))
        return list;
    }
}

});
</code>```

MathJax is loaded in my html file's  like this:

```<code><script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],

    }
  });
</script>
  <script type="text/javascript" async
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-MML-AM_CHTML">
</script>
</code>```

While the vue app section is like this:

```<code><div id="searcher">
            <p v-show="error" v-html="error"></p>
            <form class="searchForm" v-on:submit.prevent="submitSearch">
                <input type="text" name="queryInput" v-model="searchQuery" placeholder="Che domanda cerchi?" @keyup="submitSearch">
                <span v-show="searchQuery" class="removeInput" @click="removeSearchQuery">+</span>
            </form>
            <div class="results" v-show="isResult">
                <ul>
                    <li v-for="result in filteredObj">
                        <p id="domanda">{{ result.domanda }}</p>
                        <p id="risposta">{{ result.risposta }}</p>
                    </li>
                </ul>

            </div>
        </div>
</code>```

答:
All you need is to trigger MathJax to render again when filteredObj is changed. Watch filteredObj:

```<code>watch: {
    filteredObj: function () {
      if ('MathJax' in window) {
        this.$nextTick(function() {
           MathJax.Hub.Queue(["Typeset",MathJax.Hub, document.body])
        });
      }
    }
}
</code>```

var analisiMatematica = new Vue({
    el: '#searcher',
    data: {
        searchQuery: '',
        isResult: false,
        results: [],
        //json: 'json/analisimatematica.json',
        error: ''
    },

    mounted: function() {
            this.results = [{domanda: '$a+b=c$', risposta: '$a+b=c$'}]
    },

    methods: {
        removeSearchQuery: function() {
          this.searchQuery = '';
          this.isResult = false;
        },
        submitSearch: function() {
          this.isResult = true;

        }
    },
    computed: {
        filteredObj: function() {
            var list = [];
            this.results.forEach(function(el) {
                if(el.domanda.toLowerCase().indexOf(this.searchQuery.toLowerCase()) > -1) {
                    list.push(el);
                }
            }.bind(this))
            return list;
        }
    },
     watch: {
        filteredObj: function () {
          if ('MathJax' in window) {
            this.$nextTick(function() {
               MathJax.Hub.Queue(["Typeset",MathJax.Hub, document.body])
            });
          }
        }
    }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],

    }
  });
</script>
  <script type="text/javascript" async
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-MML-AM_CHTML">
</script>

<div id="searcher">
  <p v-show="error" v-html="error"></p>
  <form class="searchForm" v-on:submit.prevent="submitSearch">
      <input type="text" name="queryInput" v-model="searchQuery" placeholder="Che domanda cerchi?" @keyup="submitSearch">
      <span v-show="searchQuery" class="removeInput" @click="removeSearchQuery">+</span>
  </form>
  <div class="results" v-show="isResult">
      <ul>
          <li v-for="result in filteredObj">
              <p id="domanda">{{ result.domanda }}</p>
              <p id="risposta">{{ result.risposta }}</p>
          </li>
      </ul>

  </div>
</div></code>```

Body:
I'm trying to build a filtered list in Vue with equations rendered with MathJax, and it seems to be having some problems, since the equations renders on the first load, but when I search for terms, some equations render and some don't, I can't understand why.
Basically on the first load, if I type a character in my search bar, everything renders correctly, but when I search more, or erase it and do it again, it doesn't, as you can see in these images:

my Vue code is as follows:

var analisiMatematica = new Vue({

el: '#searcher',
data: {
    searchQuery: '',
    isResult: false,
    results: [],
    //json: 'json/analisimatematica.json',
    error: ''
},

mounted: function() {
    axios.get('./json/analisimatematica.json')
    .then(function(response) {
        this.results = response.data.Domande;
        console.log(this.results);
    }.bind(this))
    .catch(function(error) {
        this.error = error.data;
        console.log(error.data);
    }.bind(this));
},

methods: {
    removeSearchQuery: function() {
      this.searchQuery = '';
      this.isResult = false;
    },
    submitSearch: function() {
      this.isResult = true;

    }
},
computed: {
    filteredObj: function() {
        var list = [];
        this.results.forEach(function(el) {
            if(el.domanda.toLowerCase().indexOf(this.searchQuery.toLowerCase()) > -1) {
                list.push(el);
            }
        }.bind(this))
        return list;
    }
}

});

MathJax is loaded in my html file's  like this:

While the vue app section is like this:

            <form class="searchForm" v-on:submit.prevent="submitSearch">
                <input type="text" name="queryInput" v-model="searchQuery" placeholder="Che domanda cerchi?" @keyup="submitSearch">
                +
            </form>

{{ result.domanda }}

{{ result.risposta }}

Body:
All you need is to trigger MathJax to render again when filteredObj is changed. Watch filteredObj:

watch: {
    filteredObj: function () {
      if ('MathJax' in window) {
        this.$nextTick(function() {
           MathJax.Hub.Queue(["Typeset",MathJax.Hub, document.body])
        });
      }
    }
}

var analisiMatematica = new Vue({
    el: '#searcher',
    data: {
        searchQuery: '',
        isResult: false,
        results: [],
        //json: 'json/analisimatematica.json',
        error: ''
    },

    mounted: function() {
            this.results = [{domanda: '$a+b=c$', risposta: '$a+b=c$'}]
    },

    methods: {
        removeSearchQuery: function() {
          this.searchQuery = '';
          this.isResult = false;
        },
        submitSearch: function() {
          this.isResult = true;

        }
    },
    computed: {
        filteredObj: function() {
            var list = [];
            this.results.forEach(function(el) {
                if(el.domanda.toLowerCase().indexOf(this.searchQuery.toLowerCase()) > -1) {
                    list.push(el);
                }
            }.bind(this))
            return list;
        }
    },
     watch: {
        filteredObj: function () {
          if ('MathJax' in window) {
            this.$nextTick(function() {
               MathJax.Hub.Queue(["Typeset",MathJax.Hub, document.body])
            });
          }
        }
    }

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],

    }
  });
</script>
  <script type="text/javascript" async
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-MML-AM_CHTML">
</script>

<div id="searcher">
  <p v-show="error" v-html="error"></p>
  <form class="searchForm" v-on:submit.prevent="submitSearch">
      <input type="text" name="queryInput" v-model="searchQuery" placeholder="Che domanda cerchi?" @keyup="submitSearch">
      <span v-show="searchQuery" class="removeInput" @click="removeSearchQuery">+</span>
  </form>
  <div class="results" v-show="isResult">
      <ul>
          <li v-for="result in filteredObj">
              <p id="domanda">{{ result.domanda }}</p>
              <p id="risposta">{{ result.risposta }}</p>
          </li>
      </ul>

  </div>
</div>


问:
Android - Styling string with html markup
In my Android app, I'm trying to dynamically change the color of part of a text following the instructions here. But, this is not working. The color is always the same. Is there anything I'm doing wrong?

Here's what I have in my strings.xml:

```<code><string name="red_status">Status: <font color="#FF0000">Red</font></string>
<string name="green_status">Status: <font color="#00FF00">Green</font></string>
</code>```

And, here's my TextView:

```<code><TextView
    android:id="@+id/status"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="16dp"
    android:textSize="24sp"
    android:textAlignment="center"
    android:textColor="@color/charcoal_grey"
    android:letterSpacing="-0.01"
    android:lineSpacingExtra="8sp"
    android:gravity="center_horizontal"
    android:text="@{item.status == Status.RED ? @string/red_status : @string/green_status}" />
</code>```

答: As CommonsWare pointed out in the comments, the issue was that the binging expressing uses getString() and therefore wipes out the formatting. I ended up using two separate TextViews side by side, one for the static part and one for the dynamic Red/Green part.

Body:
In my Android app, I'm trying to dynamically change the color of part of a text following the instructions here. But, this is not working. The color is always the same. Is there anything I'm doing wrong?

Here's what I have in my strings.xml:

<string name="red_status">Status: Red</string>
<string name="green_status">Status: Green</string>

And, here's my TextView:

<TextView
    android:id="@+id/status"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="16dp"
    android:textSize="24sp"
    android:textAlignment="center"
    android:textColor="@color/charcoal_grey"
    android:letterSpacing="-0.01"
    android:lineSpacingExtra="8sp"
    android:gravity="center_horizontal"
    android:text="@{item.status == Status.RED ? @string/red_status : @string/green_status}" />


问:
Keyboard disappears when you submit a form
I am making real time chat app and when user types something in an input and submits a form(clicks a send button) a keyboard (virtual keyboard on mobile devices) disappear.

I want to keep the keyboard opened.

<form class="panel" action="">
  <input type="text" class="message" id="message" autocomplete="off" spellcheck="false">

  <button type="submit" class="send" id="send"></button>
</form>
```

答:
You can try redirecting the server response to an iframe that's on the same page as the form. Doing so saves the page from reloading when a response is received (the page in the iframe gets reloaded instead).

Setup Redirect

Assign a  [target] attribute to the form.

Add an iframe to the page and give it a [name].

Now go back to that [target] attribute from step #1 and give it the same value of the [name] attribute from step #2.

You should have something like this:

```<code> <form action='https://example.com/rx.php/post' method='post' target='response'>
  ....
   <iframe src='https://example.com/' name='response'></iframe>
 </form>
</code>```

Most likely you'll probably don't want a gaping iframe eating up precious space (especially on a mobile page) so included in the demo is the means to hide said iframe. There are of course many ways to hide an iframe and still keep it functioning but this particular way I have the most success with.

Setup Concealment

Wrap iframe in a block level element.

Add a class to the block element and assign the class this CSS property/value: visibility: collapse.

Demo Outline

First click the Submit button. The first thing you should notice is that the page didn't reload. The form actually sends to a live test server. It sends a response back to notify you of a successful 200.

Next click the Toggle button. You should see an iframe with a response from the server. The toggle button and JavaScript is just for demonstration purposes and is not required.

// This is for demonstration
const f = document.forms[0]
f.elements.toggle.onclick = toggleIframe;

function toggleIframe(e) {
  e.target.nextElementSibling.classList.toggle('overlay');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.overlay {
  visibility: collapse;
}</code>```

<form id='panel' action="https://www.hashemian.com/tools/form-post-tester.php" method='post' target='response'>
  <input name='message' autocomplete="off" spellcheck="false" type="text" value='TEST'>

  <input type="submit"><input id='toggle' type='button' value='Toggle'>

  <fieldset name='cover' class='overlay'>

  </fieldset>
</form>```

Body:
You can try redirecting the server response to an iframe that's on the same page as the form. Doing so saves the page from reloading when a response is received (the page in the iframe gets reloaded instead).

Setup Redirect

Assign a  [target] attribute to the form.

Add an iframe to the page and give it a [name].

Now go back to that [target] attribute from step #1 and give it the same value of the [name] attribute from step #2.

You should have something like this:

 <form action='https://example.com/rx.php/post' method='post' target='response'>
  ....
   <iframe src='https://example.com/' name='response'></iframe>
 </form>

Most likely you'll probably don't want a gaping iframe eating up precious space (especially on a mobile page) so included in the demo is the means to hide said iframe. There are of course many ways to hide an iframe and still keep it functioning but this particular way I have the most success with.

Setup Concealment

Wrap iframe in a block level element.

Add a class to the block element and assign the class this CSS property/value: visibility: collapse.

Demo Outline

First click the Submit button. The first thing you should notice is that the page didn't reload. The form actually sends to a live test server. It sends a response back to notify you of a successful 200.

Next click the Toggle button. You should see an iframe with a response from the server. The toggle button and JavaScript is just for demonstration purposes and is not required.

// This is for demonstration
const f = document.forms[0]
f.elements.toggle.onclick = toggleIframe;

function toggleIframe(e) {
  e.target.nextElementSibling.classList.toggle('overlay');
}

.overlay {
  visibility: collapse;
}

<form id='panel' action="https://www.hashemian.com/tools/form-post-tester.php" method='post' target='response'>
  <input name='message' autocomplete="off" spellcheck="false" type="text" value='TEST'>
  <!--toggle is for demonstration-->
  <input type="submit"><input id='toggle' type='button' value='Toggle'>

  <fieldset name='cover' class='overlay'>
    <iframe src='https://css-tricks.com' name='response'></iframe>
  </fieldset>
</form>


问:
How do I get rid of [Object: null prototype] in Node.js?
Is there a way to get rid of the [Object: null prototype] in the terminal so it will only display {title: 'book'} ?

I was doing console.log(req.body); in node/express.js

答:
This sounds like you're using {extended: false} within .urlencoded() when you're parsing the body. Try removing it or changing to true.

Go back a few steps and edit which may look something like this

app.use(bodyParser.urlencoded({extended: true}));

or just simply

app.use(bodyParser.urlencoded());

To find out more about the extended option, read the docs or someone here has answered it well -  What does 'extended' mean in express 4.0?


问:
CRTP - Can I make a private method?
I'm implementing a static polymorphism:

```<code>template<typename T>
class Base {
public:
    void method() {
         // do something
         impl();
         // do something else
    }
    void impl() { // intended to be private
        static_cast<T*>(this)->impl();
    }
};

class Derived : public Base<Derived> {
public:
     void impl() { // intended to be private
     }
};
</code>```

This code is a static implementation of a dynamic polymorphic classes where void impl() was virtual and private.

I've achieved polymorphism (static). But I had to make the method void impl() public in order to allow access to it from a Base class. I want method void impl() to be private again. Can it be done?

UPDATE:
I don't want to write

```<code>friend class Base<Derived>;
</code>```

in Derived class, because it allows Base access to all members of Derived.

答:
Adding a line to your Derived class:

class Derived : public Base<Derived> {
public:
private:
     void impl() { // intended to be private
     }
     friend class Base<Derived>;
};
```

<p>which will specify the base class as a friend, allows me to compile the code with <code>impl</code> being private.</p>

<p><strong>EDIT</strong></p>

<p>As suggested in the comment by @Oliv, the implementation of the Attorney-Client idiom would look like:</p>

<pre class="lang-cpp prettyprint-override"><code>
template<typename T>
class Attorney;

template<typename T>
class Base {
public:
    void method() {
        // do something
        impl();
        // do something else
    }
private:
    void impl() { // intended to be private
        Attorney<T>::impl(*static_cast<T*>(this));
    }
};

class Derived : public Base<Derived> {
private:
    void impl() { // intended to be private
    }
    friend class Attorney<Derived>;
};

template<typename T>
class Attorney {
private:
    friend class Base<Derived>;

    static void impl(Derived & c) { // add additional parameters as needed by impl
        c.impl();
    }
};

</code>```

Title: CRTP - Can I make a private method?

Body:
I'm implementing a static polymorphism:

template<typename T>
class Base {
public:
    void method() {
         // do something
         impl();
         // do something else
    }
    void impl() { // intended to be private
        static_cast<T*>(this)->impl();
    }
};

class Derived : public Base<Derived> {
public:
     void impl() { // intended to be private
     }
};

This code is a static implementation of a dynamic polymorphic classes where void impl() was virtual and private.

I've achieved polymorphism (static). But I had to make the method void impl() public in order to allow access to it from a Base class. I want method void impl() to be private again. Can it be done?

UPDATE:
I don't want to write

friend class Base<Derived>;

in Derived class, because it allows Base access to all members of Derived.

Body:
Adding a line to your Derived class:

class Derived : public Base<Derived> {
public:
private:
     void impl() { // intended to be private
     }
     friend class Base<Derived>;
};

which will specify the base class as a friend, allows me to compile the code with impl being private.

EDIT

As suggested in the comment by @Oliv, the implementation of the Attorney-Client idiom would look like:

template<typename T>
class Attorney;

template<typename T>
class Base {
public:
    void method() {
        // do something
        impl();
        // do something else
    }
private:
    void impl() { // intended to be private
        Attorney<T>::impl(*static_cast<T*>(this));
    }
};

class Derived : public Base<Derived> {
private:
    void impl() { // intended to be private
    }
    friend class Attorney<Derived>;
};

template<typename T>
class Attorney {
private:
    friend class Base<Derived>;

    static void impl(Derived & c) { // add additional parameters as needed by impl
        c.impl();
    }
};


问:
Google FCM No "Message" class
I want to sent a message with the fcm of google but I need a class named "Message" but it doesn't exist with my imports. (I implemented com.google.firebase:firebase-messaging:18.0.0)

I tried using the remote message class but it doesn't fit to my problem.

```<code>implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-messaging:18.0.0'
</code>```

I want to use this example code:

// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";

// See documentation on defining a message payload.
Message message = Message.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .setTopic(topic)
    .build();

// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
```

The needed class is this: https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/messaging/Message but it doesn't exist.

答:
Sending messages to users/devices with Firebase Cloud Messaging, requires that your code has access to the FCM Server Key. As its name implies, this key should only be used on a server, as having access to this key allows one to send any messages to all users of your app.

You seem to be writing code in an Android app, while the Message class you're referring to is part of the Firebase Admin SDK. The Admin SDK gives its users full access to your Firebase project (including your FCM server key), and for that reason can only be used in a trusted environment, such as your development machine, a server you control, or Cloud Functions.

So to send messages to a user/device, you will always need a server, or otherwise trusted environment, to send them from. For more on this, see:

How to send Device to device notification by using FCM without using XMPP or any other script.?

my blog post Sending notifications between devices with Firebase Database and Cloud Messaging

How to send device to device messages using Firebase Cloud Messaging?

Title: Google FCM No "Message" class

Body:
I want to sent a message with the fcm of google but I need a class named "Message" but it doesn't exist with my imports. (I implemented com.google.firebase:firebase-messaging:18.0.0)

I tried using the remote message class but it doesn't fit to my problem.

implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-messaging:18.0.0'

I want to use this example code:

// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";

// See documentation on defining a message payload.
Message message = Message.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .setTopic(topic)
    .build();

// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

The needed class is this: https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/messaging/Message but it doesn't exist.


问:
Overriding model save method does not allow assignment of values
I am attempting to override a model's save method and assign a value to the field when the field is saved:

My models.py:

```<code>def NewInviteCode():
    import secrets
    print(secrets.token_urlsafe(16))

class Invitation(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    name = models.CharField(max_length=300, default='', blank=True)
    email = models.EmailField(max_length=100, default='')
    mobile = models.CharField(max_length=15, default='', blank=True)
    last_sent = models.DateTimeField(default=timezone.now)
    num_invitations = models.IntegerField(default=1)
    uniqcode = models.CharField(max_length=300, default='', blank=True)

    def save(self, *args, **kwargs):
        if not self.uniqcode:
            self.uniqcode = NewInviteCode()
            print(f"Saved new unique code: {self.uniqcode}")
        if self.num_invitations:
            self.num_invitations = self.num_invitations + 1
        print(f"Sending invitation to {self.email}..")
        SendInviteActual(self.email)
        print(f"Parameters to be saved are: Code:{self.uniqcode} Name: {self.name} Email: {self.email}")
        super().save(*args, **kwargs)  # Call the "real" save() method.
</code>```

Unfortunately, on my code execution:

```<code>fktewVPm63tV-YqXxWPNxQ
Saved new unique code: None
Sending invitation to joel@domain.com.
Mail sent
Parameters to be saved are: Code:None Name: joel Email: joel@domain.com
2019-05-26 20:04:48,972 django.request ERROR    Internal Server Error: /clinic/sendinvites
</code>```

What's the problem with the following lines of code?

```<code>if not self.uniqcode:
    self.uniqcode = NewInviteCode()
    print(f"Saved new unique code: {self.uniqcode}")
</code>```

答:
Your NewInviteCode does not return anything, it only prints something. If a Python function does not return something explicitly, it returns None. You should return a value, like:

```<code>def NewInviteCode():
    from secrets import token_urlsafe
    <b>return</b> token_urlsafe(16)</code>```

That being said, you can set a callable as default= parameter [Django-doc] for field, like:

```<code>def <b>new_invite_code</b>():
    from secrets import token_urlsafe
    return token_urlsafe(16)

class Invitation(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    name = models.CharField(max_length=300, default='', blank=True)
    email = models.EmailField(max_length=100, default='')
    mobile = models.CharField(max_length=15, default='', blank=True)
    last_sent = models.DateTimeField(default=timezone.now)
    num_invitations = models.IntegerField(default=1)
    uniqcode = models.CharField(max_length=300, <b>default=new_invite_code</b>, blank=True)</code>```

We here thus do not call the function we pass new_invite_code, not the result of new_invite_code, we thus do not write brackets (like <s>new_invite_code()</s>).

this makes your models and safe(..) function simpler.

Note: according to the PEP-8 style guide, you probably should rename NewInviteCode to new_invite_code, like I did in the second code fragment.

Body:
I am attempting to override a model's save method and assign a value to the field when the field is saved:

My models.py:

def NewInviteCode():
    import secrets
    print(secrets.token_urlsafe(16))

class Invitation(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    name = models.CharField(max_length=300, default='', blank=True)
    email = models.EmailField(max_length=100, default='')
    mobile = models.CharField(max_length=15, default='', blank=True)
    last_sent = models.DateTimeField(default=timezone.now)
    num_invitations = models.IntegerField(default=1)
    uniqcode = models.CharField(max_length=300, default='', blank=True)

    def save(self, *args, **kwargs):
        if not self.uniqcode:
            self.uniqcode = NewInviteCode()
            print(f"Saved new unique code: {self.uniqcode}")
        if self.num_invitations:
            self.num_invitations = self.num_invitations + 1
        print(f"Sending invitation to {self.email}..")
        SendInviteActual(self.email)
        print(f"Parameters to be saved are: Code:{self.uniqcode} Name: {self.name} Email: {self.email}")
        super().save(*args, **kwargs)  # Call the "real" save() method.

Unfortunately, on my code execution:

fktewVPm63tV-YqXxWPNxQ
Saved new unique code: None
Sending invitation to joel@domain.com.
Mail sent
Parameters to be saved are: Code:None Name: joel Email: joel@domain.com
2019-05-26 20:04:48,972 django.request ERROR    Internal Server Error: /clinic/sendinvites

What's the problem with the following lines of code?

if not self.uniqcode:
    self.uniqcode = NewInviteCode()
    print(f"Saved new unique code: {self.uniqcode}")

Body:
Your NewInviteCode does not return anything, it only prints something. If a Python function does not return something explicitly, it returns None. You should return a value, like:

def NewInviteCode():
    from secrets import token_urlsafe
    return token_urlsafe(16)

That being said, you can set a callable as default= parameter [Django-doc] for field, like:

def new_invite_code():
    from secrets import token_urlsafe
    return token_urlsafe(16)

class Invitation(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    name = models.CharField(max_length=300, default='', blank=True)
    email = models.EmailField(max_length=100, default='')
    mobile = models.CharField(max_length=15, default='', blank=True)
    last_sent = models.DateTimeField(default=timezone.now)
    num_invitations = models.IntegerField(default=1)
    uniqcode = models.CharField(max_length=300, default=new_invite_code, blank=True)

We here thus do not call the function we pass new_invite_code, not the result of new_invite_code, we thus do not write brackets (like <s>new_invite_code()</s>).

this makes your models and safe(..) function simpler.

Note: according to the PEP-8 style guide, you probably should rename NewInviteCode to new_invite_code, like I did in the second code fragment.


问:
In a one to zero/one relationship, (MySQL, InnoDB) are there any performance improvements by using the foreign key as primary key?
So reading this old blog post (which is quite old to be fair), gave me some thoughts on how to structure some of my table relationships.

If any secondary index look ups contain the primary key and the primary key is what accesses the row data, then for this sort of schema,

```<code>Users : id, name, country, etc.

User_Mailboxes : id, user_id, location, height, etc.
</code>```

Where a user may or may not have a mailbox but at max one, would it be more efficient to get rid of the 'id' as the primary key of the user_mailboxes table and set the foreign key as the primary key?

From my understanding of InnoDB, that way we'd save any secondary index look ups for the corresponding primary key and be able to use the User.id directly to find the related mailbox info.

So something more akin to this,

```<code>Users : id (PRIMARY), name, country, etc.

User_Mailboxes : user_id(FOREIGN, PRIMARY), location, height, etc.
</code>```

Should be slightly more performant in terms of index storage and random lookups? Especially if I'm considering grabbing a bunch of mailboxes at once based on some user criteria?

答:
A FOREIGN KEY slows down inserts because of the check that is performed.  (But it is a minor performance hit.)

Nothing "requires" the existence of any FKs.  (Other than some textbooks.)

A FOREIGN KEY implicitly creates an INDEX (if one does not already exist).

INDEXes can make a big difference in the performance of SELECTs.

This trick can shift 'important' queries to the PRIMARY KEY.  The trick makes fetching by range to the PK take advantage of clustering.

```<code>  -- Instead of
PRIMARY KEY (id),
INDEX (foo)
  -- change to
PRIMARY KEY (foo, id),   -- `id` included to achieve UNIQUEness
INDEX (id)   -- to keep AUTO_INCREMENT happy
</code>```

If you have a 'natural' primary key, use it and jettison the auto_increment.  (In some cases this helps overall; in some cases, it hurts.)

Body:
So reading this old blog post (which is quite old to be fair), gave me some thoughts on how to structure some of my table relationships.

If any secondary index look ups contain the primary key and the primary key is what accesses the row data, then for this sort of schema,

Users : id, name, country, etc.

User_Mailboxes : id, user_id, location, height, etc.

Where a user may or may not have a mailbox but at max one, would it be more efficient to get rid of the 'id' as the primary key of the user_mailboxes table and set the foreign key as the primary key?

From my understanding of InnoDB, that way we'd save any secondary index look ups for the corresponding primary key and be able to use the User.id directly to find the related mailbox info.

So something more akin to this,

Users : id (PRIMARY), name, country, etc.

User_Mailboxes : user_id(FOREIGN, PRIMARY), location, height, etc.

Should be slightly more performant in terms of index storage and random lookups? Especially if I'm considering grabbing a bunch of mailboxes at once based on some user criteria?

Body:
A FOREIGN KEY slows down inserts because of the check that is performed.  (But it is a minor performance hit.)

Nothing "requires" the existence of any FKs.  (Other than some textbooks.)

A FOREIGN KEY implicitly creates an INDEX (if one does not already exist).

INDEXes can make a big difference in the performance of SELECTs.

This trick can shift 'important' queries to the PRIMARY KEY.  The trick makes fetching by range to the PK take advantage of clustering.

  -- Instead of
PRIMARY KEY (id),
INDEX (foo)
  -- change to
PRIMARY KEY (foo, id),   -- `id` included to achieve UNIQUEness
INDEX (id)   -- to keep AUTO_INCREMENT happy

If you have a 'natural' primary key, use it and jettison the auto_increment.  (In some cases this helps overall; in some cases, it hurts.)


问:
PHP - how to read json file header and other objects and insert in mysql
I am trying to read a json file, which has header, body and footer part and subsequently want to insert in mysql db using PHP code.

I tried to read json file, however the file has few header objects and data object. Data object has many records. I want to read header and data seperately. I tried to read data object, however even print statement didn't work. Please help in parsing the header and data object seperately.

php code

```<code>$json = file_get_contents('./f.json');

$json_data = json_decode($json,true);

print_r($json_data);

foreach ($json_data['data'] as $item => $value) {
    print $item['symbol'];
    print ' - ';
    print $item['ltp'];
    print ' - ';
    print '<br>';
}
</code>```

json file

```<code>{

    "noChg":0,
    "adv":10,
    "dec":3,
    "data":[
        {
            "symbol":"TECHM",
            "open":"749.90",
            "high":"749.90",
            "low":"732.05",
            "ltP":"737.00",
            "ptsC":"-6.30",
            "per":"-0.85"
        },
        {
            "symbol":"HAVELLS",
            "open":"752.85",
            "high":"754.90",
            "low":"739.10",
            "ltP":"745.00",
            "ptsC":"-6.50",
            "per":"-0.86"
        },
        {
            "symbol":"NESTLEIND",
            "open":"10,813.00",
            "high":"10,849.90",
            "low":"10,592.30",
            "ltP":"10,682.40",
            "ptsC":"-114.65",
            "per":"-1.06"
        },
        {
            "symbol":"HEXAWARE",
            "open":"356.30",
            "high":"357.45",
            "low":"349.45",
            "ltP":"352.00",
            "ptsC":"-4.15",
            "per":"-1.17"
        },
        {
            "symbol":"ADANIENT",
            "open":"162.35",
            "high":"163.75",
            "low":"151.85",
            "ltP":"159.15",
            "ptsC":"-1.90",
            "per":"-1.18"
        },
        {
            "symbol":"TORNTPHARM",
            "open":"1,554.80",
            "high":"1,566.90",
            "low":"1,511.20",
            "ltP":"1,530.00",
            "ptsC":"-22.20",
            "per":"-1.43"
        },
        {
            "symbol":"BATAINDIA",
            "open":"1,374.90",
            "high":"1,374.90",
            "low":"1,329.00",
            "ltP":"1,345.00",
            "ptsC":"-20.50",
            "per":"-1.50"
        },
        {
            "symbol":"KAJARIACER",
            "open":"616.05",
            "high":"619.00",
            "low":"595.20",
            "ltP":"603.00",
            "ptsC":"-12.80",
            "per":"-2.08"
        },
        {
            "symbol":"RELINFRA",
            "open":"116.40",
            "high":"116.90",
            "low":"111.05",
            "ltP":"111.85",
            "ptsC":"-2.60",
            "per":"-2.27"
        },
        {
            "symbol":"PVR",
            "open":"1,783.80",
            "high":"1,783.80",
            "low":"1,698.85",
            "ltP":"1,716.00",
            "ptsC":"-50.85",
            "per":"-2.88"
        },
        {
            "symbol":"SUNTV",
            "open":"553.00",
            "high":"561.30",
            "low":"512.00",
            "ltP":"531.70",
            "ptsC":"-16.15",
            "per":"-2.95"
        },
        {
            "symbol":"JETAIRWAYS",
            "open":"146.15",
            "high":"152.90",
            "low":"142.35",
            "ltP":"147.70",
            "ptsC":"-7.75",
            "per":"-4.99"
        },
        {
            "symbol":"JUSTDIAL",
            "open":"744.00",
            "high":"744.00",
            "low":"673.35",
            "ltP":"680.60",
            "ptsC":"-66.35",
            "per":"-8.88"
        }
    ],
    "totQty":"14,259.87",
    "totQtyMil":"1,425.99",
    "totValMil":"353.59",
    "time":"May 24, 2019 16:00:00",
    "totVal":"35,358.82" }
</code>```

I expect to parse and extract values from data objects, but i am getting the following error:

PHP Fatal error:  Cannot use object of type stdClass as array in
  /home/fut/public_html/on.php

答:
I cannot reproduce the error your getting, but there are a few issues with the code you currently have.

You are trying to use $item as the contents of the array instead of $value, $tem is the index of the array and not the contents.

Also as keys are case sensitive - you must use 'ltP' and not 'ltp'...

```<code>foreach ($json_data['data'] as $item => $value) {
    print $value['symbol'];
    print ' - ';
    print $value['ltP'];
    print ' - ';
    print '<br>';
}
</code>```

Body:
I am trying to read a json file, which has header, body and footer part and subsequently want to insert in mysql db using PHP code.

I tried to read json file, however the file has few header objects and data object. Data object has many records. I want to read header and data seperately. I tried to read data object, however even print statement didn't work. Please help in parsing the header and data object seperately.

php code

$json = file_get_contents('./f.json');

$json_data = json_decode($json,true);

print_r($json_data);

foreach ($json_data['data'] as $item => $value) {
    print $item['symbol'];
    print ' - ';
    print $item['ltp'];
    print ' - ';
    print '
';
}

json file

{

    "noChg":0,
    "adv":10,
    "dec":3,
    "data":[
        {
            "symbol":"TECHM",
            "open":"749.90",
            "high":"749.90",
            "low":"732.05",
            "ltP":"737.00",
            "ptsC":"-6.30",
            "per":"-0.85"
        },
        {
            "symbol":"HAVELLS",
            "open":"752.85",
            "high":"754.90",
            "low":"739.10",
            "ltP":"745.00",
            "ptsC":"-6.50",
            "per":"-0.86"
        },
        {
            "symbol":"NESTLEIND",
            "open":"10,813.00",
            "high":"10,849.90",
            "low":"10,592.30",
            "ltP":"10,682.40",
            "ptsC":"-114.65",
            "per":"-1.06"
        },
        {
            "symbol":"HEXAWARE",
            "open":"356.30",
            "high":"357.45",
            "low":"349.45",
            "ltP":"352.00",
            "ptsC":"-4.15",
            "per":"-1.17"
        },
        {
            "symbol":"ADANIENT",
            "open":"162.35",
            "high":"163.75",
            "low":"151.85",
            "ltP":"159.15",
            "ptsC":"-1.90",
            "per":"-1.18"
        },
        {
            "symbol":"TORNTPHARM",
            "open":"1,554.80",
            "high":"1,566.90",
            "low":"1,511.20",
            "ltP":"1,530.00",
            "ptsC":"-22.20",
            "per":"-1.43"
        },
        {
            "symbol":"BATAINDIA",
            "open":"1,374.90",
            "high":"1,374.90",
            "low":"1,329.00",
            "ltP":"1,345.00",
            "ptsC":"-20.50",
            "per":"-1.50"
        },
        {
            "symbol":"KAJARIACER",
            "open":"616.05",
            "high":"619.00",
            "low":"595.20",
            "ltP":"603.00",
            "ptsC":"-12.80",
            "per":"-2.08"
        },
        {
            "symbol":"RELINFRA",
            "open":"116.40",
            "high":"116.90",
            "low":"111.05",
            "ltP":"111.85",
            "ptsC":"-2.60",
            "per":"-2.27"
        },
        {
            "symbol":"PVR",
            "open":"1,783.80",
            "high":"1,783.80",
            "low":"1,698.85",
            "ltP":"1,716.00",
            "ptsC":"-50.85",
            "per":"-2.88"
        },
        {
            "symbol":"SUNTV",
            "open":"553.00",
            "high":"561.30",
            "low":"512.00",
            "ltP":"531.70",
            "ptsC":"-16.15",
            "per":"-2.95"
        },
        {
            "symbol":"JETAIRWAYS",
            "open":"146.15",
            "high":"152.90",
            "low":"142.35",
            "ltP":"147.70",
            "ptsC":"-7.75",
            "per":"-4.99"
        },
        {
            "symbol":"JUSTDIAL",
            "open":"744.00",
            "high":"744.00",
            "low":"673.35",
            "ltP":"680.60",
            "ptsC":"-66.35",
            "per":"-8.88"
        }
    ],
    "totQty":"14,259.87",
    "totQtyMil":"1,425.99",
    "totValMil":"353.59",
    "time":"May 24, 2019 16:00:00",
    "totVal":"35,358.82" }

I expect to parse and extract values from data objects, but i am getting the following error:

PHP Fatal error:  Cannot use object of type stdClass as array in
  /home/fut/public_html/on.php

Body:
I cannot reproduce the error your getting, but there are a few issues with the code you currently have.

You are trying to use $item as the contents of the array instead of $value, $tem is the index of the array and not the contents.

Also as keys are case sensitive - you must use 'ltP' and not 'ltp'...

foreach ($json_data['data'] as $item => $value) {
    print $value['symbol'];
    print ' - ';
    print $value['ltP'];
    print ' - ';
    print '<br>';
}


问:
return function returns array values using Closure
I'm trying to use Closure in JS in order to declare a function named **expandArray()** which contain an Array named **myArray**and Returns an anonymous function that directly modifies myArray by increase the values by 1 than the returned function then returns the value of **myArray**. My Problem here one the last part where the returned function return a function not Array value ?!

This is my code

```<code>function expandArray() {
  const myArray = [1, 1, 1];

  return function () {
    myArray.forEach( function (num, index, myArray) {
        myArray[index] = num + 1;
    });
    return myArray;
  };
}

console.log(expandArray());
</code>```

答:
Old post, but I still like to contribute. I came up with this solution, as I think you want add something to the array instead of incrementing the numbers.</p>

```<code>function expandArray() {
    let myArray = [1, 1, 1];

    return function() {
        myArray.push(1)
        return myArray
    }
}

const array = expandArray();
const result = array();
console.log(result)
</code>```

Body:
I'm trying to use Closure in JS in order to declare a function named **expandArray()** which contain an Array named **myArray**and Returns an anonymous function that directly modifies myArray by increase the values by 1 than the returned function then returns the value of **myArray**. My Problem here one the last part where the returned function return a function not Array value ?!

This is my code

function expandArray() {
  const myArray = [1, 1, 1];

  return function () {
    myArray.forEach( function (num, index, myArray) {
        myArray[index] = num + 1;
    });
    return myArray;
  };
}

console.log(expandArray());

Body:
Old post, but I still like to contribute. I came up with this solution, as I think you want add something to the array instead of incrementing the numbers.

function expandArray() {
    let myArray = [1, 1, 1];

    return function() {
        myArray.push(1)
        return myArray
    }
}

const array = expandArray();
const result = array();
console.log(result)


问:
Remove everything after a certain character
Is there a way to remove everything after a certain character or just choose everything up to that character?  I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

Like this

```<code>/Controller/Action?id=11112&value=4444
</code>```

I want the href to be /Controller/Action only, so I want to remove everything after the "?".

I'm using this now:

```<code> $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');
     var url = $(this).attr('href');

     console.log(url);
 }
</code>```

答:
It can easly be done using JavaScript for reference see link
JS String

EDIT
it can easly done as. ;)

```<code>var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);
</code>```

Body:
Is there a way to remove everything after a certain character or just choose everything up to that character?  I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

Like this

/Controller/Action?id=11112&value=4444

I want the href to be /Controller/Action only, so I want to remove everything after the "?".

I'm using this now:

 $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');
     var url = $(this).attr('href');

     console.log(url);
 }

Body:
It can easly be done using JavaScript for reference see link
JS String

EDIT
it can easly done as. ;)

var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);


问:
How to extract elements from each line in a jsonline file?
I have a jsonl file which contains per line both a sentence and the tokens that are found in that sentence. I wish to extract the tokens from each line in the JSON lines file, but my loop only returns the tokens from the last line.

This is the input.

```<code>{"text":"This is the first sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"first","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}
{"text":"This is the second sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"second","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}
</code>```

I have tried running the following code:

with jsonlines.open('path/to/file') as reader:
        for obj in reader:
        data = obj['tokens'] # just extract the tokens
        data = [(i['text'], i['id']) for i in data] # elements from the tokens

data
```

<p>The actual result:</p>

<blockquote>
  <p>[('This', 0),
   ('is', 1),
   ('the', 2),
   ('first', 3),
   ('sentence', 4),
   ('.', 5)]</p>
</blockquote>

<p>What the result is that I want to get to:</p>

<p><img src="https://i.stack.imgur.com/xdmgG.png" alt="enter image description here"></p>

<h1>Additional question</h1>

<p>Some tokens contain a "label" instead of an "id". How could I incorporate that into the code? An example would be:</p>

```{"text":"This is the first sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"first","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}
{"text":"This is coded in python.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"coded","id":2},
{"text":"in","id":3},
{"text":"python","label":"Programming"},
{"text":".","id":5}]}
```

答:
```<code>f=open('data.csv','w')
print('Sentence','Word','ID',file=f)
with jsonlines.open('path/to/file') as reader:
        for sentence_no,obj in enumerate(reader):
            data = obj['tokens']
            for i in data:
                print(sentence_no+1,i['text'], i['id']+1,file=f)
</code>```

Body:
I have a jsonl file which contains per line both a sentence and the tokens that are found in that sentence. I wish to extract the tokens from each line in the JSON lines file, but my loop only returns the tokens from the last line.

This is the input.

{"text":"This is the first sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"first","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}
{"text":"This is the second sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"second","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}

I have tried running the following code:

with jsonlines.open('path/to/file') as reader:
        for obj in reader:
        data = obj['tokens'] # just extract the tokens
        data = [(i['text'], i['id']) for i in data] # elements from the tokens

data

The actual result:

[('This', 0),
   ('is', 1),
   ('the', 2),
   ('first', 3),
   ('sentence', 4),
   ('.', 5)]

What the result is that I want to get to:

Additional question

Some tokens contain a "label" instead of an "id". How could I incorporate that into the code? An example would be:

{"text":"This is the first sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"first","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}
{"text":"This is coded in python.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"coded","id":2},
{"text":"in","id":3},
{"text":"python","label":"Programming"},
{"text":".","id":5}]}


答:
Some issues/changes in the code

You are reassign the variable data in the loop everytime, hence you only see the result for the last json line, instead you want to extend the list everytime

You want to use enumerate on the reader iterator to get the first item of the tuple

The code then changes to

```<code>import jsonlines

data = []
#Iterate over the json files
with jsonlines.open('file.txt') as reader:
    #Iterate over the each line on the reader via enumerate
    for idx, obj in enumerate(reader):

        #Append the data to the result
        data.extend([(idx+1, i['text'], i['id']+1) for i in obj['tokens']])  # elements from the tokens

print(data)
</code>```

Or more compact by making a double for-loop in the list comprehension itself

```<code>import jsonlines

#Open the file, iterate over the tokens and make the tuples
result = [(idx+1, i['text'], i['id']+1) for idx, obj in enumerate(jsonlines.open('file.txt')) for i in obj['tokens']]

print(result)
</code>```

The output will be

```<code>[
(1, 'This', 1),
(1, 'is', 2),
(1, 'the', 3),
(1, 'first', 4),
(1, 'sentence', 5),
(1, '.', 6),
(2, 'This', 1),
(2, 'is', 2),
(2, 'the', 3),
(2, 'second', 4),
(2, 'sentence', 5),
(2, '.', 6)
]
</code>```

Title: How to extract elements from each line in a jsonline file?

Body:
Some issues/changes in the code

You are reassign the variable data in the loop everytime, hence you only see the result for the last json line, instead you want to extend the list everytime

You want to use enumerate on the reader iterator to get the first item of the tuple

The code then changes to

import jsonlines

data = []
#Iterate over the json files
with jsonlines.open('file.txt') as reader:
    #Iterate over the each line on the reader via enumerate
    for idx, obj in enumerate(reader):

        #Append the data to the result
        data.extend([(idx+1, i['text'], i['id']+1) for i in obj['tokens']])  # elements from the tokens

print(data)

Or more compact by making a double for-loop in the list comprehension itself

import jsonlines

#Open the file, iterate over the tokens and make the tuples
result = [(idx+1, i['text'], i['id']+1) for idx, obj in enumerate(jsonlines.open('file.txt')) for i in obj['tokens']]

print(result)

The output will be

[
(1, 'This', 1),
(1, 'is', 2),
(1, 'the', 3),
(1, 'first', 4),
(1, 'sentence', 5),
(1, '.', 6),
(2, 'This', 1),
(2, 'is', 2),
(2, 'the', 3),
(2, 'second', 4),
(2, 'sentence', 5),
(2, '.', 6)
]


问:
How to choose right source for x86 Assembly Language
I want to dive computer world, that is why i want to learn x86 Assembly. I found some books for source. But i don't know if they will help me. How should i start and where should i. These are books that i found. There are pdf pages for these books, but i don't know it is forbidden to share or not.

Programming from the Ground Up.

64 Bit Intel Assembly Language Programming for Linux.

X86 Assembly Language and C Fundamentals.

Assembly Language Step-By-Step - Programming with Linux, 3rd edition.

Guide to Assembly Language Programming in Linux.

答:
You should learn about computer architecture in general, then the choice of x86 sources becomes less important.   Understanding the ways, abilities and limitations of an architecture is critical to this sort of programming.

If you are new to programming, before diving into computer architecture, you should learn a hassle-free computer language.   Processing seems to be quite good.   Most production languages (Java, c++, ...) are a bad choice because they require too much decoration for the task at hand.   Processing is free for just about any device, has a free online book, and a printed one available.

Good luck; it is a lot of fun.   I have been programming for a living for over 30 years, and still enjoy it.


问:
CodeIgniter3 HMVC Routing with .htaccess not working
I am new to CI3 and I got really frustated spending more than one week in making the CodeIgniter3 HMVC WireDesignz  Routing working with .htaccess and still it is not working properly.

Because there are multiple sources that can cause the error, I write you the link of my GitHub Repository https://github.com/ibudisteanu/PHP-TESTS

The behavior is super easy: I can access the following address with no errors

http://localhost/

http://localhost/index.php/login

http://localhost/index.php/awesome

I get returns for the following links in my routing:

http://localhost/login

http://localhost/awesome

The error I get is Not Found The requested URL /login was not found on this server.

答:
I am using the below code in .htaccess in My HMVC CI3...its working fine on the live Server & on the localhost-</p>

```<code><IfModule mod_rewrite.c>
RewriteEngine On
Options -Indexes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
</code>```

Body:
I am using the below code in .htaccess in My HMVC CI3...its working fine on the live Server & on the localhost-

<IfModule mod_rewrite.c>
RewriteEngine On
Options -Indexes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>


问:
Need to display the max price and company that has it
So, i just started working with python and i need to display the maximum price and the company that has it. I got the data from an CSV file that has multiple columns that describes some cars. I'm only interested in two of them: price and company.

I need to display the maximum price and the company that has it. Some advice?
This is what i tried and I don't know how to get the company too, not only the maximum price.

import pandas as pd
df = pd.read_csv("Automobile_data.csv")
for x in df['price']:
    if x == df['price'].max():
       print(x)
```

答:
Use Series.max, create index by DataFrame.set_index and get company name by Series.idxmax:

```<code>df = pd.DataFrame({
        'company':list('abcdef'),
         'price':[7,8,9,4,2,3],

})

print (df)
  company  price
0       a      7
1       b      8
2       c      9
3       d      4
4       e      2
5       f      3

print(df['price'].max())
9
print(df.set_index('company')['price'].idxmax())
c
</code>```

Another idea is use DataFrame.agg:

```<code>s = df.set_index('company')['price'].agg(['max','idxmax'])
print (s['max'])
9
print (s['idxmax'])
c
</code>```

If possible duplicated maximum values and need all companies of max price use boolean indexing with DataFrame.loc - get Series:

```<code>df = pd.DataFrame({
        'company':list('abcdef'),
         'price':[7,8,9,4,2,9],

})

print (df)
  company  price
0       a      7
1       b      8
2       c      9
3       d      4
4       e      2
5       f      9

print(df['price'].max())
9

#only first value
print(df.set_index('company')['price'].idxmax())
c

#all maximum values
s = df.loc[df['price'] == df['price'].max(), 'company']
print (s)
2    c
5    f
Name: company, dtype: object
</code>```

If need one row DataFrame:

```<code>out = df.loc[df['price'] == df['price'].max(), ['company','price']]
print (out)
  company  price
2       c      9

out = df.loc[df['price'] == df['price'].max(), ['company','price']]
print (out)
  company  price
2       c      9
5       f      9
</code>```

Body:
Use Series.max, create index by DataFrame.set_index and get company name by Series.idxmax:

df = pd.DataFrame({
        'company':list('abcdef'),
         'price':[7,8,9,4,2,3],

})

print (df)
  company  price
0       a      7
1       b      8
2       c      9
3       d      4
4       e      2
5       f      3

print(df['price'].max())
9
print(df.set_index('company')['price'].idxmax())
c

Another idea is use DataFrame.agg:

s = df.set_index('company')['price'].agg(['max','idxmax'])
print (s['max'])
9
print (s['idxmax'])
c

If possible duplicated maximum values and need all companies of max price use boolean indexing with DataFrame.loc - get Series:

df = pd.DataFrame({
        'company':list('abcdef'),
         'price':[7,8,9,4,2,9],

})

print (df)
  company  price
0       a      7
1       b      8
2       c      9
3       d      4
4       e      2
5       f      9

print(df['price'].max())
9

#only first value
print(df.set_index('company')['price'].idxmax())
c

#all maximum values
s = df.loc[df['price'] == df['price'].max(), 'company']
print (s)
2    c
5    f
Name: company, dtype: object

If need one row DataFrame:

out = df.loc[df['price'] == df['price'].max(), ['company','price']]
print (out)
  company  price
2       c      9

out = df.loc[df['price'] == df['price'].max(), ['company','price']]
print (out)
  company  price
2       c      9
5       f      9


问:
Move carousel caption outside carousel
I'm trying to move the caption outside the coursel towards the left side but the problem it's not working.  Whenever it moves outside its parent container it stops showing. Can somebody please help me out. Here is a JS bin link --> JSBin

It would be great if anyone could help me out. Thanks

```<code>OS: Mac

Browser: Chrome 74.0

Bootstrap version: 4.1.1
</code>```

答:
The element with the class carousel-inner has the following declaration set by Bootstrap: overflow: hidden. It prevents any of its children elements placed outside its padding-box to be visible.

To prevent that behaviour, you need to override that declaration with: overflow: visible. Then, to prevent the slides from being shown when moving, you need to wrap the carousel inside another element, add some padding at the bottom of that element to allow the caption to be visible (60px for instance), and set its overflow property to hidden.

So you need to add the following code to your CSS:

.carousel-container {
  padding: 0 0 60px 0;
  overflow: hidden;
}

.carousel-inner {
  overflow: visible;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="carousel-container">
  <div class="carousel">
    <!-- The code of the carousel -->
  </div>
</div></code>```

Title: Move carousel caption outside carousel

Body:
I'm trying to move the caption outside the coursel towards the left side but the problem it's not working.  Whenever it moves outside its parent container it stops showing. Can somebody please help me out. Here is a JS bin link --> JSBin

It would be great if anyone could help me out. Thanks

OS: Mac

Browser: Chrome 74.0

Bootstrap version: 4.1.1

Body:
The element with the class carousel-inner has the following declaration set by Bootstrap: overflow: hidden. It prevents any of its children elements placed outside its padding-box to be visible.

To prevent that behaviour, you need to override that declaration with: overflow: visible. Then, to prevent the slides from being shown when moving, you need to wrap the carousel inside another element, add some padding at the bottom of that element to allow the caption to be visible (60px for instance), and set its overflow property to hidden.

So you need to add the following code to your CSS:

.carousel-container {
  padding: 0 0 60px 0;
  overflow: hidden;
}

.carousel-inner {
  overflow: visible;
}

<div class="carousel-container">
  <div class="carousel">
    <!-- The code of the carousel -->
  </div>
</div>


问:
Get the full, raw HTTP request message that would be sent from an HttpPost
I'm trying to build a raw HTTP POST request. I don't want to actually connect to the server and send the message, however.

I've been poking around the Apache HTTP libraries, hoping that I could just create an HttpPost object, set the entity, and then grab the message that it would have created. So far, I can dump the entity, but not the entire request as it'd appear on the server-side.

Any ideas? Aside from just re-creating the wheel, of course.

Solution

I refactored ShyJ's response into a pair of static classes, however the original response works just fine. Here are the two classes:

```<code>public static final class LoopbackPostMethod extends PostMethod {
    private static final String STATUS_LINE = "HTTP/1.1 200 OK";

    @Override
    protected void readResponse(HttpState state, HttpConnection conn) throws IOException, HttpException {
        statusLine = new StatusLine (STATUS_LINE);
    }
}

public static final class LoopbackHttpConnection extends HttpConnection {
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 80;

    private final OutputStream fOutputStream;

    public LoopbackHttpConnection(OutputStream outputStream) {
        super(HOST, PORT);
        fOutputStream = outputStream;
    }

    @Override
    public void flushRequestOutputStream() throws IOException { /* do nothing */ }

    @Override
    public OutputStream getRequestOutputStream() throws IOException, IllegalStateException {
        return fOutputStream;
    }

    @Override
    public void write(byte[] data) throws IOException, IllegalStateException {
        fOutputStream.write(data);
    }
}
</code>```

Here's the factory method that I'm using for my own implementation, as an example:

```<code>private ByteBuffer createHttpRequest(ByteBuffer data) throws HttpException, IOException {
    LoopbackPostMethod postMethod = new LoopbackPostMethod();
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    postMethod.setRequestEntity(new ByteArrayRequestEntity(data.array()));
    postMethod.execute(new HttpState(), new LoopbackHttpConnection(outputStream));
    byte[] bytes = outputStream.toByteArray();
    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    buffer.put(bytes);
    return buffer;
}
</code>```

答:
With HttpClient 4.x

```<code>    private static String toRawHttp(HttpUriRequest request) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        HttpTransportMetricsImpl outTransportMetrics = new HttpTransportMetricsImpl();
        SessionOutputBufferImpl buffer = new SessionOutputBufferImpl(outTransportMetrics, 1);
        HttpMessageWriter<HttpRequest> defaultHttpRequestWriter = DefaultHttpRequestWriterFactory.INSTANCE.create(buffer);
        DefaultHttpRequestWriterFactory writerFactory = new DefaultHttpRequestWriterFactory(null) {
            @Override
            public HttpMessageWriter<HttpRequest> create(SessionOutputBuffer buffer) {
                return defaultHttpRequestWriter;
            }
        };
        buffer.bind(baos);

        ConnectionConfig config = ConnectionConfig.DEFAULT;
        DefaultBHttpClientConnection connection = new DefaultBHttpClientConnection(config.getBufferSize(),
                                                                                config.getFragmentSizeHint(),
                                                                                ConnSupport.createDecoder(config),
                                                                                ConnSupport.createEncoder(config),
                                                                                config.getMessageConstraints(),
                                                                                null,
                                                                                null,
                                                                                writerFactory,
                                                                                null) {
            @Override
            protected void ensureOpen() {
                //using writerFactory buffer instead of socket
            }

            @Override
            protected OutputStream createOutputStream(long len, SessionOutputBuffer outbuffer) {
                if (len == ContentLengthStrategy.CHUNKED) {
                    return new ChunkedOutputStream(2048, buffer);
                } else if (len == ContentLengthStrategy.IDENTITY) {
                    return new IdentityOutputStream(buffer);
                } else {
                    return new ContentLengthOutputStream(buffer, len);
                }
            }
        };

        CloseableHttpClient client = HttpClients.custom()
                                                .setRequestExecutor(new HttpRequestExecutor() {

                                                    @Override
                                                    protected HttpResponse doSendRequest(HttpRequest request, HttpClientConnection conn, HttpContext context) throws IOException, HttpException {
                                                        // inject fake connection
                                                        return super.doSendRequest(request, connection, context);
                                                    }

                                                    @Override
                                                    protected HttpResponse doReceiveResponse(HttpRequest request, HttpClientConnection conn, HttpContext context) {
                                                        return new BasicHttpResponse(request.getProtocolVersion(), 200, "OK");
                                                    }
                                                })
                                                .build();
        client.execute(request);
        return new String(baos.toByteArray());
    }
</code>```

Using:

```<code> RequestBuilder builder = RequestBuilder.post(requestModel.getUrl()).addHeader("X-Hello","Word");
 System.out.println(toRawHttp(builder.build()));

</code>```

Will print:

```<code>POST /ff HTTP/1.1
X-Hello: Word
Host: localhost:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.8 (Java/1.8.0_161)
Accept-Encoding: gzip,deflate

</code>```

Body:
I'm trying to build a raw HTTP POST request. I don't want to actually connect to the server and send the message, however.

I've been poking around the Apache HTTP libraries, hoping that I could just create an HttpPost object, set the entity, and then grab the message that it would have created. So far, I can dump the entity, but not the entire request as it'd appear on the server-side.

Any ideas? Aside from just re-creating the wheel, of course.

Solution

I refactored ShyJ's response into a pair of static classes, however the original response works just fine. Here are the two classes:

public static final class LoopbackPostMethod extends PostMethod {
    private static final String STATUS_LINE = "HTTP/1.1 200 OK";

    @Override
    protected void readResponse(HttpState state, HttpConnection conn) throws IOException, HttpException {
        statusLine = new StatusLine (STATUS_LINE);
    }
}

public static final class LoopbackHttpConnection extends HttpConnection {
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 80;

    private final OutputStream fOutputStream;

    public LoopbackHttpConnection(OutputStream outputStream) {
        super(HOST, PORT);
        fOutputStream = outputStream;
    }

    @Override
    public void flushRequestOutputStream() throws IOException { /* do nothing */ }

    @Override
    public OutputStream getRequestOutputStream() throws IOException, IllegalStateException {
        return fOutputStream;
    }

    @Override
    public void write(byte[] data) throws IOException, IllegalStateException {
        fOutputStream.write(data);
    }
}

Here's the factory method that I'm using for my own implementation, as an example:

private ByteBuffer createHttpRequest(ByteBuffer data) throws HttpException, IOException {
    LoopbackPostMethod postMethod = new LoopbackPostMethod();
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    postMethod.setRequestEntity(new ByteArrayRequestEntity(data.array()));
    postMethod.execute(new HttpState(), new LoopbackHttpConnection(outputStream));
    byte[] bytes = outputStream.toByteArray();
    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    buffer.put(bytes);
    return buffer;
}

Body:
With HttpClient 4.x

    private static String toRawHttp(HttpUriRequest request) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        HttpTransportMetricsImpl outTransportMetrics = new HttpTransportMetricsImpl();
        SessionOutputBufferImpl buffer = new SessionOutputBufferImpl(outTransportMetrics, 1);
        HttpMessageWriter<HttpRequest> defaultHttpRequestWriter = DefaultHttpRequestWriterFactory.INSTANCE.create(buffer);
        DefaultHttpRequestWriterFactory writerFactory = new DefaultHttpRequestWriterFactory(null) {
            @Override
            public HttpMessageWriter<HttpRequest> create(SessionOutputBuffer buffer) {
                return defaultHttpRequestWriter;
            }
        };
        buffer.bind(baos);

        ConnectionConfig config = ConnectionConfig.DEFAULT;
        DefaultBHttpClientConnection connection = new DefaultBHttpClientConnection(config.getBufferSize(),
                                                                                config.getFragmentSizeHint(),
                                                                                ConnSupport.createDecoder(config),
                                                                                ConnSupport.createEncoder(config),
                                                                                config.getMessageConstraints(),
                                                                                null,
                                                                                null,
                                                                                writerFactory,
                                                                                null) {
            @Override
            protected void ensureOpen() {
                //using writerFactory buffer instead of socket
            }

            @Override
            protected OutputStream createOutputStream(long len, SessionOutputBuffer outbuffer) {
                if (len == ContentLengthStrategy.CHUNKED) {
                    return new ChunkedOutputStream(2048, buffer);
                } else if (len == ContentLengthStrategy.IDENTITY) {
                    return new IdentityOutputStream(buffer);
                } else {
                    return new ContentLengthOutputStream(buffer, len);
                }
            }
        };

        CloseableHttpClient client = HttpClients.custom()
                                                .setRequestExecutor(new HttpRequestExecutor() {

                                                    @Override
                                                    protected HttpResponse doSendRequest(HttpRequest request, HttpClientConnection conn, HttpContext context) throws IOException, HttpException {
                                                        // inject fake connection
                                                        return super.doSendRequest(request, connection, context);
                                                    }

                                                    @Override
                                                    protected HttpResponse doReceiveResponse(HttpRequest request, HttpClientConnection conn, HttpContext context) {
                                                        return new BasicHttpResponse(request.getProtocolVersion(), 200, "OK");
                                                    }
                                                })
                                                .build();
        client.execute(request);
        return new String(baos.toByteArray());
    }

Using:

 RequestBuilder builder = RequestBuilder.post(requestModel.getUrl()).addHeader("X-Hello","Word");
 System.out.println(toRawHttp(builder.build()));

Will print:

POST /ff HTTP/1.1
X-Hello: Word
Host: localhost:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.8 (Java/1.8.0_161)
Accept-Encoding: gzip,deflate