问:
How to swap value in SQL Server?
I want to swap the value between the row but I don't have an idea how to make it as I create a script to do it but the answer still not correct. I get the data raw in from the pdf then convert it into excel 'xls'.

Please see the sample below.

```<code>DECLARE @MyTable TABLE(Id INT, RoomNo INT, Class VARCHAR(10), Price VARCHAR(255))

INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 1,    21,     'A',        '43,028,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 2,    NULL,   NULL,       '43,896,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 3,    20,     'A',        '42,681,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 4,    NULL,   NULL,       '43,549,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 5,    19,     'A',        '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 6,    NULL,   NULL,       '43,202,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 7,    18,     'A',        '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 8,    NULL,   NULL,       '42,855,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 9,    17,     'A',        '41,467,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 10,   NULL,   NULL,       '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 11,   16,     'A',        '41,120,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 12,   NULL,   NULL,       '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 13,   NULL,   'A',        '39,211,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 14,   9,      NULL,       '40,079,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 15,   NULL,   NULL,       '38,691,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 16,   6,      NULL,       '39,385,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 17,   NULL,   'A',        '44,756,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 18,   5,      NULL,       '45,591,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 19,   21,     'B',        '26,598,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 20,   20,     'B',        '26,393,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 21,   NULL,   NULL,       '26,905,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 22,   19,     'B',        '26,189,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 23,   NULL,   NULL,       '26,700,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 24,   18,     'B',        '25,984,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 25,   NULL,   NULL,       '26,496,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 26,   17,     'B',        '25,677,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 27,   NULL,   'B',        '24,041,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 28,   6,      NULL,       '24,552,000'
</code>```

what i tried

```<code>SELECT
        *,
        ISNULL(RoomNo, (SELECT TOP 1 RoomNo FROM @MyTable WHERE Id < MyTable.Id AND RoomNo IS NOT NULL ORDER BY ID DESC)),
        ISNULL(Class, (SELECT TOP 1 Class FROM @MyTable WHERE Id < MyTable.Id AND Class IS NOT NULL ORDER BY ID DESC)),
        Price
    FROM @MyTable as MyTable
</code>```

Result is wrong:

```<code>Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  21          A           43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  20          A           42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  19          A           42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  18          A           41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  17          A           41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  16          A           41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  16          A           39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  9           A           38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  6           A           44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  20          B           26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  19          B           26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  18          B           25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  17          B           24,041,000
28  6       NULL    24,552,000  6           B           24,552,000
</code>```

I want to achieve:

```<code>Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  NULL        NULL        43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  NULL        NULL        42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  NULL        NULL        42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  NULL        NULL        41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  NULL        NULL        41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  NULL        NULL        41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  NULL        NULL        39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  NULL        NULL        38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  NULL        NULL        44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  NULL        NULL        26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  NULL        NULL        26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  NULL        NULL        25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  NULL        NULL        24,041,000
28  6       NULL    24,552,000  6           B           24,552,000
</code>```

答:
Not an exact answer but following should give you a clear idea and you can play on top of that to see what else suits your detailed requirements.</p>

```<code>SELECT
    Id,
    NULLIF(RoomNo,LAG(RoomNo) OVER (ORDER BY ID)) RoomNo,
    NULLIF(Class,LAG(Class) OVER (ORDER BY ID)) Class,
    Price,
    LAG(RoomNo) OVER (ORDER BY ID) AS NewRoomNo,
    LAG(Class) OVER (ORDER BY ID)  AS NewClass,
    Price As Price2
FROM @MyTable as MyTable
</code>```

Title: How to swap value in SQL Server?

Body:
I want to swap the value between the row but I don't have an idea how to make it as I create a script to do it but the answer still not correct. I get the data raw in from the pdf then convert it into excel 'xls'.

Please see the sample below.

DECLARE @MyTable TABLE(Id INT, RoomNo INT, Class VARCHAR(10), Price VARCHAR(255))

INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 1,    21,     'A',        '43,028,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 2,    NULL,   NULL,       '43,896,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 3,    20,     'A',        '42,681,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 4,    NULL,   NULL,       '43,549,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 5,    19,     'A',        '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 6,    NULL,   NULL,       '43,202,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 7,    18,     'A',        '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 8,    NULL,   NULL,       '42,855,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 9,    17,     'A',        '41,467,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 10,   NULL,   NULL,       '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 11,   16,     'A',        '41,120,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 12,   NULL,   NULL,       '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 13,   NULL,   'A',        '39,211,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 14,   9,      NULL,       '40,079,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 15,   NULL,   NULL,       '38,691,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 16,   6,      NULL,       '39,385,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 17,   NULL,   'A',        '44,756,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 18,   5,      NULL,       '45,591,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 19,   21,     'B',        '26,598,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 20,   20,     'B',        '26,393,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 21,   NULL,   NULL,       '26,905,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 22,   19,     'B',        '26,189,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 23,   NULL,   NULL,       '26,700,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 24,   18,     'B',        '25,984,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 25,   NULL,   NULL,       '26,496,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 26,   17,     'B',        '25,677,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 27,   NULL,   'B',        '24,041,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 28,   6,      NULL,       '24,552,000'

what i tried

SELECT
        *,
        ISNULL(RoomNo, (SELECT TOP 1 RoomNo FROM @MyTable WHERE Id < MyTable.Id AND RoomNo IS NOT NULL ORDER BY ID DESC)),
        ISNULL(Class, (SELECT TOP 1 Class FROM @MyTable WHERE Id < MyTable.Id AND Class IS NOT NULL ORDER BY ID DESC)),
        Price
    FROM @MyTable as MyTable

Result is wrong:

Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  21          A           43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  20          A           42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  19          A           42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  18          A           41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  17          A           41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  16          A           41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  16          A           39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  9           A           38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  6           A           44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  20          B           26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  19          B           26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  18          B           25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  17          B           24,041,000
28  6       NULL    24,552,000  6           B           24,552,000

I want to achieve:

Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  NULL        NULL        43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  NULL        NULL        42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  NULL        NULL        42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  NULL        NULL        41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  NULL        NULL        41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  NULL        NULL        41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  NULL        NULL        39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  NULL        NULL        38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  NULL        NULL        44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  NULL        NULL        26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  NULL        NULL        26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  NULL        NULL        25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  NULL        NULL        24,041,000
28  6       NULL    24,552,000  6           B           24,552,000

Body:
Not an exact answer but following should give you a clear idea and you can play on top of that to see what else suits your detailed requirements.

SELECT
    Id,
    NULLIF(RoomNo,LAG(RoomNo) OVER (ORDER BY ID)) RoomNo,
    NULLIF(Class,LAG(Class) OVER (ORDER BY ID)) Class,
    Price,
    LAG(RoomNo) OVER (ORDER BY ID) AS NewRoomNo,
    LAG(Class) OVER (ORDER BY ID)  AS NewClass,
    Price As Price2
FROM @MyTable as MyTable


来源: stackexchange

问:
is there a function in dlg class as getdocument()?
I want to get a doc* in dlg class, and i know in view class we can get doc* like

```<code>doc* pdc=getdocument();
</code>```

But how can i do it in dlg class?

答: MFC's CDialog class does not have built-in CDocument's.  You can implement a CFormView that is derived from CView (which are part of the Document/View architecture of MFC), but CFormView is not a dialog.  However, CFormView's can hold controls like a dialog - you can actually assign a dialog template to a CFormView.</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to get a doc* in dlg class, and i know in view class we can get doc* like

doc* pdc=getdocument();

But how can i do it in dlg class?

ContentLicense: CC BY-SA 2.5


问:
CAN'T Build Apache spark with MAVEN
I have downloaded Apache spark and trying to build it with MAVEN as suggested here. http://spark.apache.org/docs/1.0.0/building-with-maven.html

But I am not able to resolve the error after running the command -
  build/mvn -DskipTests clean package run , the error is- build/mvn: No such file or directory .
I checked by running mvn -v and also JAVA_HOME is set to the JDK.(screen shot attached ) .
Please  help to resolve the problem.command promt output

答:
```<code>mvn -DskipTests clean package run
</code>```

You don't need to use build/mvn. I am assuming you have mvn installed somewhere within the system.

Title: CAN'T Build Apache spark with MAVEN

Body:
mvn -DskipTests clean package run

You don't need to use build/mvn. I am assuming you have mvn installed somewhere within the system.


问:
NodeJS, React on Heroku, Socket.io gives error
Help pls! I am making a website with Node/Express and React on Heroku.
Server.js serves an expresshandlebar template on client side, rendering App.js

So far everything was working, until I tried to implement Socket.IO. Socket.IO works perfectly on localhost but gives an error on Heroku:

VM63:35 WebSocket connection to 'ws://mysite:8080/socket.io-client/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

Here is the relevant portion of the code:

Server.js

```<code>var express = require('express'),
var port = process.env.PORT || 8080;
var httpServer = require('http').createServer(app);
httpServer.listen(port)
io.on('connection', function (socket) {
console.log('Connection started');});
</code>```

App.js

```<code>var io = require('socket.io-client');
var new_socket = io.connect();
</code>```

I have read many sites, and tried many alternatives, such as:
1) setting on both client and server socket.io 'path' and 'transports'

```<code>path: '/socket.io-client'
transports: ['websocket']
</code>```

2) Trying WebSockets as recommended by Heroku. This throws another error 'error 503'

答:
```<code>this.io = socket.connect(yourpath, {
  transports: ['websocket'],
  upgrade: false,
});
</code>```

First, you need to connect to exactly socket server. Could you try above code, I'm using that for my project

Body:
Help pls! I am making a website with Node/Express and React on Heroku.
Server.js serves an expresshandlebar template on client side, rendering App.js

So far everything was working, until I tried to implement Socket.IO. Socket.IO works perfectly on localhost but gives an error on Heroku:

VM63:35 WebSocket connection to 'ws://mysite:8080/socket.io-client/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

Here is the relevant portion of the code:

Server.js

var express = require('express'),
var port = process.env.PORT || 8080;
var httpServer = require('http').createServer(app);
httpServer.listen(port)
io.on('connection', function (socket) {
console.log('Connection started');});

App.js

var io = require('socket.io-client');
var new_socket = io.connect();

I have read many sites, and tried many alternatives, such as:
1) setting on both client and server socket.io 'path' and 'transports'

path: '/socket.io-client'
transports: ['websocket']

2) Trying WebSockets as recommended by Heroku. This throws another error 'error 503'

Body:
this.io = socket.connect(yourpath, {
  transports: ['websocket'],
  upgrade: false,
});

First, you need to connect to exactly socket server. Could you try above code, I'm using that for my project


问:
Android - Spinner doesn't get any selected value
I have a problem with my spinner. My spinner doesn't get any value when selected. I don't know what to do because I had applied so many answered and nothing affect on my code.

Here is my code. I am using retrofit2.

```<code>private List<String> listKotaNegara= new GetData().getListKota();

    spinnerJenisKamar = (Spinner) findViewById(R.id.spinnerHotelJenisKamar);
            dataAdapterJenisKamar = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listJenisKamar);
            dataAdapterJenisKamar.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerJenisKamar.setAdapter(dataAdapterJenisKamar);

            spinnerJenisKamar.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String item = parent.getSelectedItem().toString();
                    Toast.makeText(parent.getContext(), "Selected: "+item, Toast.LENGTH_LONG).show();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
</code>```

This is how I GetData from server.

```<code>public List<String> getListKota(){
    apiservice.getListKota("liskota").enqueue(new Callback<ListKotaResponse>() {

        @Override
        public void onResponse(Call<ListKotaResponse> call, Response<ListKotaResponse> response) {
            System.out.println("syalala : "+response.body()+", Response code; "+response.code()+", Response msg: "+response.message());
            final ListKotaResponse responses = response.body();
            List<ListNegara> listNegaras = responses.getListNegara();
            if(responses.getResult().equalsIgnoreCase("OK"))
            {
                System.out.println("masuk if");

                for(ListNegara n: listNegaras)
                {
                    for(ListKotum k: n.getListKota()) {
                        listKotaNegara.add(k.getKota()+", "+n.getNegara());
                    }
                }
            }
        }

        @Override
        public void onFailure(Call<ListKotaResponse> call, Throwable t) {
            Log.i("fail ",t.getMessage());
        }
    });
    return listKotaNegara;
}
</code>```

Thank you very much :")

答:
I have found my solution. I must write the ArrayAdapter code inside the onResponse in Callback Retrofit 2.

Thank you for your support. :)

Body:
I have a problem with my spinner. My spinner doesn't get any value when selected. I don't know what to do because I had applied so many answered and nothing affect on my code.

Here is my code. I am using retrofit2.

private List<String> listKotaNegara= new GetData().getListKota();

    spinnerJenisKamar = (Spinner) findViewById(R.id.spinnerHotelJenisKamar);
            dataAdapterJenisKamar = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listJenisKamar);
            dataAdapterJenisKamar.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerJenisKamar.setAdapter(dataAdapterJenisKamar);

            spinnerJenisKamar.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String item = parent.getSelectedItem().toString();
                    Toast.makeText(parent.getContext(), "Selected: "+item, Toast.LENGTH_LONG).show();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

This is how I GetData from server.

public List<String> getListKota(){
    apiservice.getListKota("liskota").enqueue(new Callback<ListKotaResponse>() {

        @Override
        public void onResponse(Call<ListKotaResponse> call, Response<ListKotaResponse> response) {
            System.out.println("syalala : "+response.body()+", Response code; "+response.code()+", Response msg: "+response.message());
            final ListKotaResponse responses = response.body();
            List<ListNegara> listNegaras = responses.getListNegara();
            if(responses.getResult().equalsIgnoreCase("OK"))
            {
                System.out.println("masuk if");

                for(ListNegara n: listNegaras)
                {
                    for(ListKotum k: n.getListKota()) {
                        listKotaNegara.add(k.getKota()+", "+n.getNegara());
                    }
                }
            }
        }

        @Override
        public void onFailure(Call<ListKotaResponse> call, Throwable t) {
            Log.i("fail ",t.getMessage());
        }
    });
    return listKotaNegara;
}

Thank you very much :")


问:
Handle big bytes when receiving from serial port in c#
I am new in the serial port. Currently, my project is to extract data from the machine. I'm getting data via an event onDataReceive and the machine is sending bytes.

My problem is that the first wave of bytes seemed to be converted correctly to string but in the second batch of bytes, I got garbage data.

Screen Shot of the output(this is the output given by the multi-currency reader machine:

The garbage data is I think the Serial Nos.

Here is my code in onDataReceive method:

```<code>private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        while (serialPort.BytesToRead > 0)
        {
            // Initialize a buffer to hold the received data
            byte[] buffer = new byte[serialPort.ReadBufferSize];
            //// There is no accurate method for checking how many bytes are read
            //// unless you check the return from the Read method
            int bytesRead = serialPort.Read(buffer, 0, buffer.Length);
            String asd = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, bytesRead);

            //// For the example assume the data we are received is ASCII data.
            tString += Encoding.ASCII.GetString(buffer, 0, bytesRead);
            temp += System.Text.Encoding.Unicode.GetString(buffer, 0, bytesRead);
            temp2 += System.Text.Encoding.UTF32.GetString(buffer, 0, bytesRead);
            System.IO.File.WriteAllText(@"C:\OutputTextFiles\WriteLines.txt", tString);
            System.IO.File.WriteAllText(@"C:\OutputTextFiles\WriteLines2.txt", temp);
            System.IO.File.WriteAllText(@"C:\OutputTextFiles\WriteLines3.txt", temp2);
        }
    }
</code>```

I'm trying to put the output with a txt file.

I hope someone could help me in my problem. Any tips and suggestions in data handling especially bytes?

答:
Without knowing the size of serialPort.ReadBufferSize I can only suspect that your buffer is breaking the encoding bytes of your string. A character can be made of one or more bytes.

The trick is to read all of the bytes before decoding the string.

Try this example program:

```<code>var encoding = System.Text.Encoding.Unicode;
var message = "I am new in serial port. Currently my project is to extract data from machine.";
using (var ms = new MemoryStream(encoding.GetBytes(message)))
{
    var bytes = new List<byte>();
    var buffer = new byte[23];
    var bytesRead = ms.Read(buffer, 0, buffer.Length);
    while (bytesRead > 0)
    {
        Console.WriteLine(encoding.GetString(buffer, 0, bytesRead));
        bytes.AddRange(buffer.Take(bytesRead));
        bytesRead = ms.Read(buffer, 0, buffer.Length);
    }
    Console.WriteLine(encoding.GetString(bytes.ToArray(), 0, bytes.Count));
}
</code>```

It will output the following:

```
I am new in�
猀攀爀椀愀氀 瀀漀爀琀�
. Currently�
洀礀 瀀爀漀樀攀挀琀 �
is to extra�
琀 搀愀琀愀 昀爀漀洀�
 machine.
I am new in serial port. Currently my project is to extract data from machine.
```

The final line is correct because it uses all of the bytes to decode. The previous lines have errors because I've used a buffer size of 23 which breaks the string encoding.

Body:
I am new in the serial port. Currently, my project is to extract data from the machine. I'm getting data via an event onDataReceive and the machine is sending bytes.

My problem is that the first wave of bytes seemed to be converted correctly to string but in the second batch of bytes, I got garbage data.

Screen Shot of the output(this is the output given by the multi-currency reader machine:

The garbage data is I think the Serial Nos.

Here is my code in onDataReceive method:

private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        while (serialPort.BytesToRead > 0)
        {
            // Initialize a buffer to hold the received data
            byte[] buffer = new byte[serialPort.ReadBufferSize];
            //// There is no accurate method for checking how many bytes are read
            //// unless you check the return from the Read method
            int bytesRead = serialPort.Read(buffer, 0, buffer.Length);
            String asd = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, bytesRead);

            //// For the example assume the data we are received is ASCII data.
            tString += Encoding.ASCII.GetString(buffer, 0, bytesRead);
            temp += System.Text.Encoding.Unicode.GetString(buffer, 0, bytesRead);
            temp2 += System.Text.Encoding.UTF32.GetString(buffer, 0, bytesRead);
            System.IO.File.WriteAllText(@"C:\OutputTextFiles\WriteLines.txt", tString);
            System.IO.File.WriteAllText(@"C:\OutputTextFiles\WriteLines2.txt", temp);
            System.IO.File.WriteAllText(@"C:\OutputTextFiles\WriteLines3.txt", temp2);
        }
    }

I'm trying to put the output with a txt file.

I hope someone could help me in my problem. Any tips and suggestions in data handling especially bytes?

Body:
Without knowing the size of serialPort.ReadBufferSize I can only suspect that your buffer is breaking the encoding bytes of your string. A character can be made of one or more bytes.

The trick is to read all of the bytes before decoding the string.

Try this example program:

var encoding = System.Text.Encoding.Unicode;
var message = "I am new in serial port. Currently my project is to extract data from machine.";
using (var ms = new MemoryStream(encoding.GetBytes(message)))
{
    var bytes = new List<byte>();
    var buffer = new byte[23];
    var bytesRead = ms.Read(buffer, 0, buffer.Length);
    while (bytesRead > 0)
    {
        Console.WriteLine(encoding.GetString(buffer, 0, bytesRead));
        bytes.AddRange(buffer.Take(bytesRead));
        bytesRead = ms.Read(buffer, 0, buffer.Length);
    }
    Console.WriteLine(encoding.GetString(bytes.ToArray(), 0, bytes.Count));
}

It will output the following:

I am new in�
猀攀爀椀愀氀 瀀漀爀琀�
. Currently�
洀礀 瀀爀漀樀攀挀琀 �
is to extra�
琀 搀愀琀愀 昀爀漀洀�
 machine.
I am new in serial port. Currently my project is to extract data from machine.

The final line is correct because it uses all of the bytes to decode. The previous lines have errors because I've used a buffer size of 23 which breaks the string encoding.


问:
Converting JSON Data in VB.NET
I am trying to convert This Data to a structure.

I have the structure as so:

```<code>Public Structure cChartData
    Public cUDate As String
    Public cOpen As Double
    Public cClose As Double
    Public cHigh As Double
    Public cLow As Double
End Structure
</code>```

and the class as so:

```<code>Friend Class ChartData
Public Property uDate() As String
    Get
        Return m_date
    End Get
    Set
        m_date = Value
    End Set
End Property
Private m_date As String
Public Property high() As String
    Get
        Return m_high
    End Get
    Set
        m_high = Value
    End Set
End Property
Private m_high As String
Public Property low() As String
    Get
        Return m_low
    End Get
    Set
        m_low = Value
    End Set
End Property
Private m_low As String
Public Property open() As String
    Get
        Return m_open
    End Get
    Set
        m_open = Value
    End Set
End Property
Private m_open As String
Public Property close() As String
    Get
        Return m_close
    End Get
    Set
        m_close = Value
    End Set
End Property
Private m_close As String
Public Property volume() As String
    Get
        Return m_volume
    End Get
    Set
        m_volume = Value
    End Set
End Property
Private m_volume As String
Public Property quoteVolume() As String
    Get
        Return m_quoteVolume
    End Get
    Set
        m_quoteVolume = Value
    End Set
End Property
Private m_quoteVolume As String
Public Property weightedAverage() As String
    Get
        Return m_weightedAverage
    End Get
    Set
        m_weightedAverage = Value
    End Set
End Property
Private m_weightedAverage As String
End Class
</code>```

I am trying to retrieve all variables from each line. I get all of them except the date. I am using the following code (where chartInfo = JSON Data):

```<code>Dim cdata = JsonConvert.DeserializeObject(Of List(Of ChartData))(chartInfo)
        Dim cResData(cdata.Count - 1) As cChartData
        For i = 0 To cdata.Count - 1
            cResData(i).cUDate = cdata(i).uDate
            cResData(i).cOpen = Convert.ToDouble(cdata(i).open)
            cResData(i).cClose = Convert.ToDouble(cdata(i).close)
            cResData(i).cHigh = Convert.ToDouble(cdata(i).high)
            cResData(i).cLow = Convert.ToDouble(cdata(i).low)
        Next
        Return cResData
</code>```

The date returns a "blank" value, or nothing, when displayed, but all other values return properly. It is the first value so I wonder if it has something to do with it...

Any help is greatly appreciated.

答:
The reason why you get "empty" value for uDate property is that porperty names should match for successful deserialization.

You can change property name to satisfy  this rule. But if you want keep property names in class as it is - you can use JsonPropertyAttribute for json names.

Public Class ChartData

    <JsonProperty("date")>
    Public Property uDate As String

    <JsonProperty("high")>
    Public Property high As String

End Class
```

With attributes you can use different naming conventions for different code environments. For example "PascalCase" in .NET and "camelCase" in JSON

Title: Converting JSON Data in VB.NET

Body:
I am trying to convert This Data to a structure.

I have the structure as so:

Public Structure cChartData
    Public cUDate As String
    Public cOpen As Double
    Public cClose As Double
    Public cHigh As Double
    Public cLow As Double
End Structure

and the class as so:

Friend Class ChartData
Public Property uDate() As String
    Get
        Return m_date
    End Get
    Set
        m_date = Value
    End Set
End Property
Private m_date As String
Public Property high() As String
    Get
        Return m_high
    End Get
    Set
        m_high = Value
    End Set
End Property
Private m_high As String
Public Property low() As String
    Get
        Return m_low
    End Get
    Set
        m_low = Value
    End Set
End Property
Private m_low As String
Public Property open() As String
    Get
        Return m_open
    End Get
    Set
        m_open = Value
    End Set
End Property
Private m_open As String
Public Property close() As String
    Get
        Return m_close
    End Get
    Set
        m_close = Value
    End Set
End Property
Private m_close As String
Public Property volume() As String
    Get
        Return m_volume
    End Get
    Set
        m_volume = Value
    End Set
End Property
Private m_volume As String
Public Property quoteVolume() As String
    Get
        Return m_quoteVolume
    End Get
    Set
        m_quoteVolume = Value
    End Set
End Property
Private m_quoteVolume As String
Public Property weightedAverage() As String
    Get
        Return m_weightedAverage
    End Get
    Set
        m_weightedAverage = Value
    End Set
End Property
Private m_weightedAverage As String
End Class

I am trying to retrieve all variables from each line. I get all of them except the date. I am using the following code (where chartInfo = JSON Data):

Dim cdata = JsonConvert.DeserializeObject(Of List(Of ChartData))(chartInfo)
        Dim cResData(cdata.Count - 1) As cChartData
        For i = 0 To cdata.Count - 1
            cResData(i).cUDate = cdata(i).uDate
            cResData(i).cOpen = Convert.ToDouble(cdata(i).open)
            cResData(i).cClose = Convert.ToDouble(cdata(i).close)
            cResData(i).cHigh = Convert.ToDouble(cdata(i).high)
            cResData(i).cLow = Convert.ToDouble(cdata(i).low)
        Next
        Return cResData

The date returns a "blank" value, or nothing, when displayed, but all other values return properly. It is the first value so I wonder if it has something to do with it...

Any help is greatly appreciated.

Body:
The reason why you get "empty" value for uDate property is that porperty names should match for successful deserialization.

You can change property name to satisfy  this rule. But if you want keep property names in class as it is - you can use JsonPropertyAttribute for json names.

Public Class ChartData

    <JsonProperty("date")>
    Public Property uDate As String

    <JsonProperty("high")>
    Public Property high As String

End Class

With attributes you can use different naming conventions for different code environments. For example "PascalCase" in .NET and "camelCase" in JSON


问:
Python split not recognizing hyphen
I imported a table with the years that each coach served as the football coach. Some of the years listed look like this: "1903–1910, 1917, 1919"

I am aiming for [1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1917, 1919]

In my original DataFrame this list is an object.

I have tried:

x = "1903–1910, 1917, 1919"

x[0].split('-')

re.split(r'\s|-', x[0])

x[0].replace('-', ' ').split(' ')

I keep getting:

['1903–1910']

What am I doing wrong? Why isn't python finding the hyphen?

答:
This works but not optimal

```<code># -*- coding: utf-8 -*-
x = "1903–1910, 1917, 1919"
endash = '–'
years = x.split(', ')
new_list = []
for year in years:
    if endash in year:
        start, finish = year.split(endash)
        new_list.extend(range(int(start), int(finish)+1))
    else:
        new_list.append(int(year))
print new_list
</code>```

Output: [1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1917, 1919]

Title: Python split not recognizing hyphen

Body:
This works but not optimal

# -*- coding: utf-8 -*-
x = "1903–1910, 1917, 1919"
endash = '–'
years = x.split(', ')
new_list = []
for year in years:
    if endash in year:
        start, finish = year.split(endash)
        new_list.extend(range(int(start), int(finish)+1))
    else:
        new_list.append(int(year))
print new_list

Output: [1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1917, 1919]


问:
XSLT 2 chain replaces?
I need to do a series of replacements in a XSLT 2 stylesheet.  For example I need to replace all occurrences of “aaa” with “bbb”, and all “ccc” with “ddd”.  In terms of normal replace calls, I should have

```<code><xsl:value-of select="replace(replace(text(), 'aaa', 'bbb'), 'ccc', 'ddd')"/>
</code>```

However, the situation is that I have hundreds of such replacement pairs, and for that I need a super long select attribute.  I guess I can generate the select string with, for example, a Python script, but it'll be ugly.  Is there a XSLT thing maybe like

```<code><xsl:replace from="aaa" to="bbb"/>
<xsl:replace from="ccc" to="ddd"/>
…
</code>```

so that the XSLT is more readable and maintainable (and machine-manipulatable)?

答:
you have to create a function that can replace each term

XSLT 2.0

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:funct="http://something"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:template match="text()">
        <xsl:value-of select="funct:textreplace($replaces/replaces/rep, .)"/>
    </xsl:template>

    <xsl:param name="replaces">
        <replaces>
            <rep from="aaa" to="bbb"/>
            <rep from="ccc" to="ddd"/>
        </replaces>
    </xsl:param>

    <xsl:function name="funct:textreplace" as="xs:string">
        <xsl:param name="reps" as="element(rep)*"/>
        <xsl:param name="text" as="xs:string"/>
        <xsl:choose>
            <xsl:when test="not($reps)">
                <xsl:value-of select="$text"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="funct:textreplace($reps[position() gt 1], replace($text, $reps[1]/@from, $reps[1]/@to))"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:function>

</xsl:stylesheet>
</code>```

Title: XSLT 2 chain replaces?

Body:
I need to do a series of replacements in a XSLT 2 stylesheet.  For example I need to replace all occurrences of “aaa” with “bbb”, and all “ccc” with “ddd”.  In terms of normal replace calls, I should have

<xsl:value-of select="replace(replace(text(), 'aaa', 'bbb'), 'ccc', 'ddd')"/>

However, the situation is that I have hundreds of such replacement pairs, and for that I need a super long select attribute.  I guess I can generate the select string with, for example, a Python script, but it'll be ugly.  Is there a XSLT thing maybe like

<xsl:replace from="aaa" to="bbb"/>
<xsl:replace from="ccc" to="ddd"/>
…

so that the XSLT is more readable and maintainable (and machine-manipulatable)?

Body:
you have to create a function that can replace each term

XSLT 2.0

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:funct="http://something"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:template match="text()">
        <xsl:value-of select="funct:textreplace($replaces/replaces/rep, .)"/>
    </xsl:template>

    <xsl:param name="replaces">
        <replaces>
            <rep from="aaa" to="bbb"/>
            <rep from="ccc" to="ddd"/>
        </replaces>
    </xsl:param>

    <xsl:function name="funct:textreplace" as="xs:string">
        <xsl:param name="reps" as="element(rep)*"/>
        <xsl:param name="text" as="xs:string"/>
        <xsl:choose>
            <xsl:when test="not($reps)">
                <xsl:value-of select="$text"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="funct:textreplace($reps[position() gt 1], replace($text, $reps[1]/@from, $reps[1]/@to))"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:function>

</xsl:stylesheet>


问:
Unexpected Identifer when logging an array
I am sending over an array from node/express to my frontend.

like so:

```<code>res.render({product: req.product_data });
</code>```

Now on the front end, I am purely testing to see if it is there and i do this:

```<code><script>

 console.log(<%= product %>);

</script>
</code>```

From here In the browser's console it say's Uncaught SyntaxError: Unexpected identifier

Looks like so in the sources:

```<code>    console.log([object Object]);
</code>```

I've tried to JSON.stringify it,

```<code><script>

console.log(<%= JSON.stringify(product) %>);

</script>
</code>```

Output:

```<code>console.log([{"product_id":11089187470}]);
</code>```

and when i do that I get this error:

```<code>Uncaught SyntaxError: Unexpected token &
</code>```

How should I go about this?

答:
The res.render function is used server side by express to render template files (like jade/pug).

The JSON object containing variables you pass into the render function (typically as the 2nd argument, since the first argument specifies the template file you want to render) is for you to use in your server side templates only, it will not be available once the file is rendered and sent over to the client.

Body:
I am sending over an array from node/express to my frontend.

like so:

res.render({product: req.product_data });

Now on the front end, I am purely testing to see if it is there and i do this:

From here In the browser's console it say's Uncaught SyntaxError: Unexpected identifier

Looks like so in the sources:

    console.log([object Object]);

I've tried to JSON.stringify it,

Output:

console.log([{"product_id":11089187470}]);

and when i do that I get this error:

Uncaught SyntaxError: Unexpected token &

How should I go about this?


问:
How to loop through array and ignore selected value
```<code>String response = "[\n" +
        "  {\n" +
        "    \"id\": 1,\n" +
        "    \"name\": \"What is your your father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 2,\n" +
        "    \"name\": \"What is your mother's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 3,\n" +
        "    \"name\": \"What is your brother's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 4,\n" +
        "    \"name\": \"What is your father's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 5,\n" +
        "    \"name\": \"What is your sister's father name\"\n" +
        "  }\n" +
        "]";
</code>```

I have this set of questions and I wanted to loop through it to show in Dialog list. There are going to be 2 AlertDialog and if user select the value from one of the AlertDialog. The questions wont show in the other AlerDialog. For the loops, this is my code:

```<code>public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.q1:
                try {
                    JSONArray jsonArray = new JSONArray(response);
                    if (selected2>-1)
                        q1 = new String[jsonArray.length()-1];
                    else
                        q1 = new String[jsonArray.length()];
                    int index = 0;

                    for (int x = 0; x<jsonArray.length(); x++){
                        idQuestion[index] = jsonArray.getJSONObject(x).getInt("id");
                        if (selected2==x)
                            continue;
                        q1[index]= jsonArray.getJSONObject(x).getString("name");
                        index++;
                    }

                    AlertDialog alertDialog =new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.select_security_question)
                            .setItems(q1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    question1.setText(q1[which]);
                                    if(selected == -1) {
                                        selected = which;
                                    } else {
                                        selected = which+1;
                                    }
                                }
                            }).create();
                    alertDialog.show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;

            case R.id.q2:
                try {
                    JSONArray ja = new JSONArray(response);
                    if (selected>-1)
                        q2 = new String[ja.length()-1];
                    else
                        q2 = new String[ja.length()];
                    int index = 0;
                    for (int x = 0; x<ja.length(); x++){
                        if (selected==x)
                            continue;
                        q2[index] = ja.getJSONObject(x).getString("name");
                        index++;
                    }
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.select_security_question)
                            .setItems(q2, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    question2.setText(q2[which]);
                                    selected2 = which;
                                    if(selected2 == -1) {
                                        selected2 = which;
                                    } else {
                                        selected2 = which+1;
                                    }
                                }
                            }).create();
                    alertDialog.show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
</code>```

But I found that this logic is wrong.Questions are form server, that's why its is JSON format. If possible I want to use the id of the questions., since I'll have to return the value of id, not the question.

答:
It's not the complete solution but I am giving some idea on how to achieve it.

at first convert your all questions to ArrayList for that you can do manually or you can use gson as well.

```<code>public Question
{
  int id;
  String name;
}
</code>```

First create a list of all questions

i.e. ArrayList<Question> all

then create another list for ArrayList<Question> filteredList

and store selected id in variables selected_1, selected_2;

as you select items you put assign it to selected_1 or selected_2
and filter items and put in filteredList

```<code>for (Question q : all)
{
 if (id in selected_1 or selected_2) //based on your alertdialog
    ignore;
else
  filteredList.add(q);
}
</code>```

Use this everytime you select something

and to show the list in AlertDialog use this filteredList.

Body:
String response = "[\n" +
        "  {\n" +
        "    \"id\": 1,\n" +
        "    \"name\": \"What is your your father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 2,\n" +
        "    \"name\": \"What is your mother's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 3,\n" +
        "    \"name\": \"What is your brother's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 4,\n" +
        "    \"name\": \"What is your father's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 5,\n" +
        "    \"name\": \"What is your sister's father name\"\n" +
        "  }\n" +
        "]";

I have this set of questions and I wanted to loop through it to show in Dialog list. There are going to be 2 AlertDialog and if user select the value from one of the AlertDialog. The questions wont show in the other AlerDialog. For the loops, this is my code:

public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.q1:
                try {
                    JSONArray jsonArray = new JSONArray(response);
                    if (selected2>-1)
                        q1 = new String[jsonArray.length()-1];
                    else
                        q1 = new String[jsonArray.length()];
                    int index = 0;

                    for (int x = 0; x<jsonArray.length(); x++){
                        idQuestion[index] = jsonArray.getJSONObject(x).getInt("id");
                        if (selected2==x)
                            continue;
                        q1[index]= jsonArray.getJSONObject(x).getString("name");
                        index++;
                    }

                    AlertDialog alertDialog =new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.select_security_question)
                            .setItems(q1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    question1.setText(q1[which]);
                                    if(selected == -1) {
                                        selected = which;
                                    } else {
                                        selected = which+1;
                                    }
                                }
                            }).create();
                    alertDialog.show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;

            case R.id.q2:
                try {
                    JSONArray ja = new JSONArray(response);
                    if (selected>-1)
                        q2 = new String[ja.length()-1];
                    else
                        q2 = new String[ja.length()];
                    int index = 0;
                    for (int x = 0; x<ja.length(); x++){
                        if (selected==x)
                            continue;
                        q2[index] = ja.getJSONObject(x).getString("name");
                        index++;
                    }
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.select_security_question)
                            .setItems(q2, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    question2.setText(q2[which]);
                                    selected2 = which;
                                    if(selected2 == -1) {
                                        selected2 = which;
                                    } else {
                                        selected2 = which+1;
                                    }
                                }
                            }).create();
                    alertDialog.show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }

But I found that this logic is wrong.Questions are form server, that's why its is JSON format. If possible I want to use the id of the questions., since I'll have to return the value of id, not the question.

Body:
It's not the complete solution but I am giving some idea on how to achieve it.

at first convert your all questions to ArrayList for that you can do manually or you can use gson as well.

public Question
{
  int id;
  String name;
}

First create a list of all questions

i.e. ArrayList<Question> all

then create another list for ArrayList<Question> filteredList

and store selected id in variables selected_1, selected_2;

as you select items you put assign it to selected_1 or selected_2
and filter items and put in filteredList

for (Question q : all)
{
 if (id in selected_1 or selected_2) //based on your alertdialog
    ignore;
else
  filteredList.add(q);
}

Use this everytime you select something

and to show the list in AlertDialog use this filteredList.


问:
Getting error while encoding str in UTF8 format

This is working code.

```<code>line = 'line'
another_line = 'new ' + line
another_line.encode('utf-8')
</code>```

output

```<code>b'new line'
</code>```

Now I'm trying to figure out why I'm getting the error for below code in python3 vs I'm getting concatenated string in python2 ?.

```<code>line = 'line'
'new '+line.encode('utf-8')
</code>```

TypeError: Can't convert 'bytes' object to str implicitly

答:
As the error states, Python3 will not automatically convert a byte type to a string (the + operator sees a string first so wants a string on the right as well) implicitly (automatically) so you need to tell it explicitly to do so.

```<code>line = 'line'
print('new '+str(line.encode('utf-8')))
</code>```

note that this gives slightly different output.

If you want the exact same output then this works:

```<code>line = 'line'
print('new '.encode('utf-8')+line.encode('utf-8'))
</code>```

From the docs

"The + (addition) operator yields the sum of its arguments. The arguments must either both be numbers or both be sequences of the same type. In the former case, the numbers are converted to a common type and then added together. In the latter case, the sequences are concatenated." and "Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side."

Body:
This is working code.

line = 'line'
another_line = 'new ' + line
another_line.encode('utf-8')

output

b'new line'

Now I'm trying to figure out why I'm getting the error for below code in python3 vs I'm getting concatenated string in python2 ?.

line = 'line'
'new '+line.encode('utf-8')

TypeError: Can't convert 'bytes' object to str implicitly

Body:
As the error states, Python3 will not automatically convert a byte type to a string (the + operator sees a string first so wants a string on the right as well) implicitly (automatically) so you need to tell it explicitly to do so.

line = 'line'
print('new '+str(line.encode('utf-8')))

note that this gives slightly different output.

If you want the exact same output then this works:

line = 'line'
print('new '.encode('utf-8')+line.encode('utf-8'))

From the docs

"The + (addition) operator yields the sum of its arguments. The arguments must either both be numbers or both be sequences of the same type. In the former case, the numbers are converted to a common type and then added together. In the latter case, the sequences are concatenated." and "Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side."


问:
scrapy xpath how to use?
guys,
I have a question, scrapy, selector, XPath
I would like to choose the link in the "a" tag in the last "li" tag in HTML, and how to write the query for XPath
I did that, but I believe there are simpler ways to do that, such as using XPath queries, not using list fragmentation, but I don't know how to write</p>

```<code>from scrapy import Selector

sel = Selector(text=html)
print sel.xpath('(//ul/li)').xpath('a/@href').extract()[-1]

'''
html
'''

</ul>
<li>
    <a href="/info/page/" rel="follow">
       <span class="page-numbers">
       35
       </span>
    </a>
</li>
<li>
    <a href="/info/page/" rel="follow">
        <span class="next">
        next page.
        </span>
   </a>
</li>
</ul>
</code>```

答:
I am assuming you want specifically the link to the "next" page. If this is the case, you can locate an a element checking the child span to the "next" class:

```<code>//a[span/@class = "next"]/@href
</code>```

Title: scrapy xpath how to use?

Body:
guys,
I have a question, scrapy, selector, XPath
I would like to choose the link in the "a" tag in the last "li" tag in HTML, and how to write the query for XPath
I did that, but I believe there are simpler ways to do that, such as using XPath queries, not using list fragmentation, but I don't know how to write

from scrapy import Selector

sel = Selector(text=html)
print sel.xpath('(//ul/li)').xpath('a/@href').extract()[-1]

'''
html
'''

       35

        next page.

Body:
I am assuming you want specifically the link to the "next" page. If this is the case, you can locate an a element checking the child span to the "next" class:

//a[span/@class = "next"]/@href


问:
Spring boot JPA: remove column on entity change
I am try to create table in MySQL database from java class using spring-boot-starter-data-jpa. It work pretty well except when I change/remove column name in java class. Here an example:

I have a class call "Staff" with 2 fields: id, name

```<code>@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;

@Column(name = "name", length = 15)
private String name;

public Staff() {
}
// some setter and getter here
</code>```

When I run my project, a "Staff" table generated exactly as I want with 2 columns: id, name. The problem is if I split "name" into "firstname" and "lastname" like this:

```<code>@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;

@Column(name = "firstname", length = 15)
private String firstname;

@Column(name = "lastname", length = 15)
private String lastname;

public Staff() {
}
//some getter and setter here
</code>```

The "Staff" table now contain 4 columns (id, name, firstname, lastname) instead of 3. Then I need to remove the "name" column myself. Is there anyway to get rid of it automatically?

答:
Looks like you use :

```<code> spring.jpa.properties.hibernate.ddl-auto=update
</code>```

78.1 Initialize a database using JPA

spring.jpa.generate-ddl (boolean) switches the feature on and off and
is vendor independent. spring.jpa.hibernate.ddl-auto (enum) is a
Hibernate feature that controls the behavior in a more fine-grained
way. See below for more detail.

You can set spring.jpa.hibernate.ddl-auto explicitly and the standard
Hibernate property values are none, validate, update, create,
create-drop.

as you can see there is nothing new (different from hibernate)

ddl-auto=update - generate changes but it doen't drop not mapped columns .
For example you can have a table with 10 columns and mapping only for 3 of them , in this case auto mode might drop them but for hibernate / jpa full mapping table-entity in not mandatory. Here is jira ticket Alter and drop columns with hbm2ddl.auto=update created Nov 2011 and now status is 'not fixed'.

If you update db often (your domain model is changed) , you can use ddl/dml tools like liquibase , flywaydb. You describe db changes in xml file , and execute tool , all changes will be apply automatically (with auto control what already modifyed before and what should be modifed now).

Just recommendation :
Better use ddl tools if you don't want to guess why something is droped in production. hibernate.ddl-auto maily used for development , not for production. In production you can use none or validate - as they are safe.

Body:
I am try to create table in MySQL database from java class using spring-boot-starter-data-jpa. It work pretty well except when I change/remove column name in java class. Here an example:

I have a class call "Staff" with 2 fields: id, name

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;

@Column(name = "name", length = 15)
private String name;

public Staff() {
}
// some setter and getter here

When I run my project, a "Staff" table generated exactly as I want with 2 columns: id, name. The problem is if I split "name" into "firstname" and "lastname" like this:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;

@Column(name = "firstname", length = 15)
private String firstname;

@Column(name = "lastname", length = 15)
private String lastname;

public Staff() {
}
//some getter and setter here

The "Staff" table now contain 4 columns (id, name, firstname, lastname) instead of 3. Then I need to remove the "name" column myself. Is there anyway to get rid of it automatically?

Body:
Looks like you use :

 spring.jpa.properties.hibernate.ddl-auto=update

78.1 Initialize a database using JPA

spring.jpa.generate-ddl (boolean) switches the feature on and off and
is vendor independent. spring.jpa.hibernate.ddl-auto (enum) is a
Hibernate feature that controls the behavior in a more fine-grained
way. See below for more detail.

You can set spring.jpa.hibernate.ddl-auto explicitly and the standard
Hibernate property values are none, validate, update, create,
create-drop.

as you can see there is nothing new (different from hibernate)

ddl-auto=update - generate changes but it doen't drop not mapped columns .
For example you can have a table with 10 columns and mapping only for 3 of them , in this case auto mode might drop them but for hibernate / jpa full mapping table-entity in not mandatory. Here is jira ticket Alter and drop columns with hbm2ddl.auto=update created Nov 2011 and now status is 'not fixed'.

If you update db often (your domain model is changed) , you can use ddl/dml tools like liquibase , flywaydb. You describe db changes in xml file , and execute tool , all changes will be apply automatically (with auto control what already modifyed before and what should be modifed now).

Just recommendation :
Better use ddl tools if you don't want to guess why something is droped in production. hibernate.ddl-auto maily used for development , not for production. In production you can use none or validate - as they are safe.

ContentLicense: CC BY-SA 4.0


问:
Remove newline/carriage return characters in Netsuite String
I need to remove some empty lines from one string in Netsuite.

For various reasons, it's okay for the string to remain as-is within Netsuite, but I need to format it correctly for the Advanced PDF/HTML Templates.

At the moment on the transaction forms AND the PDF/HTML templates, {description} can (but doesn't always) show up as;

```<code>Item General description

additional item notes

additional decoration

customization notes
</code>```

What I need to do is trim this output (either in SQL on the forms, or in freemarker for the templates), so that {description} would then show;

```<code>Item General description
additional item notes
additional decoration
customization notes
</code>```

答:
Try this:</p>

```<code>${description?replace("<br /><br />", "<br />")}
</code>```

Body:
I need to remove some empty lines from one string in Netsuite.

For various reasons, it's okay for the string to remain as-is within Netsuite, but I need to format it correctly for the Advanced PDF/HTML Templates.

At the moment on the transaction forms AND the PDF/HTML templates, {description} can (but doesn't always) show up as;

Item General description

additional item notes

additional decoration

customization notes

What I need to do is trim this output (either in SQL on the forms, or in freemarker for the templates), so that {description} would then show;

Item General description
additional item notes
additional decoration
customization notes

Body:
Try this:

${description?replace("<br /><br />", "<br />")}


问:
Storing a sqllite database in a location that visual studio and dotnet can see it
So I have a solution with two projects (webapi, console app) in it.  I created a shared directory between them to put a sqlite database.

So I use

```<code>     Path.GetFullPath(@"../shared/" + Configuration["DBName"]);
</code>```

and get this path when i run it in visual studio 2017

```<code>     \shared\sqlite.db
</code>```

However when I try to run the console command

```<code>     dotnet ef database update
</code>```

it thinks it's located here

```<code>     \projecta\bin\Debug\shared\
</code>```

How can I get the Visual Studio debug and dotnet ef commands to use the same path?

答:
When you call Path.GetFullPath, it uses the value of Directory.GetCurrentDirectory, which may vary based on who called your code (VS, dotnet, etc)

A better way to do this is give your SQLite file path a consistent location that won't vary based on the caller:

```<code>var dbPath = Path.Combine(System.AppContext.BaseDirectory, "..", "shared", Configuration["DBName"]);
</code>```

Body:
So I have a solution with two projects (webapi, console app) in it.  I created a shared directory between them to put a sqlite database.

So I use

     Path.GetFullPath(@"../shared/" + Configuration["DBName"]);

and get this path when i run it in visual studio 2017

     \shared\sqlite.db

However when I try to run the console command

     dotnet ef database update

it thinks it's located here

     \projecta\bin\Debug\shared\

How can I get the Visual Studio debug and dotnet ef commands to use the same path?

Body:
When you call Path.GetFullPath, it uses the value of Directory.GetCurrentDirectory, which may vary based on who called your code (VS, dotnet, etc)

A better way to do this is give your SQLite file path a consistent location that won't vary based on the caller:

var dbPath = Path.Combine(System.AppContext.BaseDirectory, "..", "shared", Configuration["DBName"]);


问:
Bug? UILabel live updating by UITextFieldDelegate is off by one character
Here is a sample app to demonstrate the issue that I ran into:

```<code>import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var aTextField: UITextField!
    @IBOutlet weak var aTextLbl: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        aTextField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        aTextLbl.text = aTextField.text
        return true
    }
}
</code>```

Here is a demo:

Link to Animated Gif

My question is, how to make it such that the label is exactly synced with what I type in the textfield? Thanks!

答:
You can do this using UITextFieldDelegate function as well.

You need to manually append string with textField.text value like below:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let currentText = txtFldPassword.text
    let newText = (currentText! as NSString).replacingCharacters(in: range, with: string)
    print(newText)

    return true
}
</code>```

Body:
Here is a sample app to demonstrate the issue that I ran into:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var aTextField: UITextField!
    @IBOutlet weak var aTextLbl: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        aTextField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        aTextLbl.text = aTextField.text
        return true
    }
}

Here is a demo:

Link to Animated Gif

My question is, how to make it such that the label is exactly synced with what I type in the textfield? Thanks!

Body:
You can do this using UITextFieldDelegate function as well.

You need to manually append string with textField.text value like below:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let currentText = txtFldPassword.text
    let newText = (currentText! as NSString).replacingCharacters(in: range, with: string)
    print(newText)

    return true
}


问:
Object_Detection_Demo: Google protobuf text_format.Merge: a bytes-like object is required, not 'str'
Reference: object_detection_tutorial.ipynb

NOTE : I have successfully installed everything according to installation instructions Installation and researched regarding this on github but had no luck.

Label maps map indices to category names, so that when our convolution network predicts 5, we know that this corresponds to airplane.

```<code>label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
</code>```

This raises a error as

```<code>TypeError: a bytes-like object is required, not 'str'
</code>```

After drilling down in this function label_map_util.load_labelmap, below is the used function (load_labelmap)

```<code>from google.protobuf import text_format
from object_detection.protos import string_int_label_map_pb2

with tf.gfile.GFile(PATH_TO_LABELS, 'rb') as fid:
    label_map_string = fid.read()
    label_map = string_int_label_map_pb2.StringIntLabelMap()
    print(type(label_map_string))
    print(type(label_map))
    try:
      text_format.Merge(label_map_string, label_map)
    except text_format.ParseError:
      label_map.ParseFromString(label_map_string)
</code>```

I tried to see the error which is same. But label_map_string is already a Bytes object as you can see in the output. Tried 'r' mode also while reading.

OUTPUT

```<code><class 'bytes'>
<class 'object_detection.protos.string_int_label_map_pb2.StringIntLabelMap'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-3fce64fd5c00> in <module>()
      5     print(type(label_map))
      6     try:
----> 7       text_format.Merge(label_map_string, label_map)
      8     except text_format.ParseError:
      9       label_map.ParseFromString(label_map_string)

C:\Users\GUS9KOR\AppData\Local\Continuum\Anaconda3\envs\dlnd\lib\site-packages\protobuf-3.3.0-py3.5.egg\google\protobuf\text_format.py in Merge(text, message, allow_unknown_extension, allow_field_number, descriptor_pool)
    475   """
    476   return MergeLines(
--> 477       text.split('\n'),
    478       message,
    479       allow_unknown_extension,

TypeError: a bytes-like object is required, not 'str'
</code>```

Thanks in advance.

答: Could you provide more information about your environment? I've gotten this work on my Windows 10 machine using Anaconda 3. Specifically, whta version of tensorflow are you using, and which version of protoc did you compile the protos with?</p>

Body:
Reference: object_detection_tutorial.ipynb

NOTE : I have successfully installed everything according to installation instructions Installation and researched regarding this on github but had no luck.

Label maps map indices to category names, so that when our convolution network predicts 5, we know that this corresponds to airplane.

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)

This raises a error as

TypeError: a bytes-like object is required, not 'str'

After drilling down in this function label_map_util.load_labelmap, below is the used function (load_labelmap)

from google.protobuf import text_format
from object_detection.protos import string_int_label_map_pb2

with tf.gfile.GFile(PATH_TO_LABELS, 'rb') as fid:
    label_map_string = fid.read()
    label_map = string_int_label_map_pb2.StringIntLabelMap()
    print(type(label_map_string))
    print(type(label_map))
    try:
      text_format.Merge(label_map_string, label_map)
    except text_format.ParseError:
      label_map.ParseFromString(label_map_string)

I tried to see the error which is same. But label_map_string is already a Bytes object as you can see in the output. Tried 'r' mode also while reading.

OUTPUT

<class 'bytes'>
<class 'object_detection.protos.string_int_label_map_pb2.StringIntLabelMap'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-3fce64fd5c00> in <module>()
      5     print(type(label_map))
      6     try:
----> 7       text_format.Merge(label_map_string, label_map)
      8     except text_format.ParseError:
      9       label_map.ParseFromString(label_map_string)

C:\Users\GUS9KOR\AppData\Local\Continuum\Anaconda3\envs\dlnd\lib\site-packages\protobuf-3.3.0-py3.5.egg\google\protobuf\text_format.py in Merge(text, message, allow_unknown_extension, allow_field_number, descriptor_pool)
    475   """
    476   return MergeLines(
--> 477       text.split('\n'),
    478       message,
    479       allow_unknown_extension,

TypeError: a bytes-like object is required, not 'str'

Thanks in advance.


问:
Custom design SeekBar in android
I have done the seekbar but I need to do the customization like the below image.

I used the code like this

```<code><SeekBar
                        android:id="@+id/seekbarPoints"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="-16dp"
                        android:layout_marginTop="@dimen/small"
                        android:max="0"
                        android:progress="0"
                        android:progressDrawable="@drawable/shape_seekbar_points_style"
                        android:thumb="@null" />

if (TextUtils.isDigitsOnly(maxPoints)) {
            int maxP = Integer.parseInt(maxPoints);
            mBinding.seekbarPoints.setMax(maxP);
            if (!TextUtils.isEmpty(points)) {
                int p = (int) Double.parseDouble(points);
                mBinding.seekbarPoints.setProgress(p);
            }
        }
mBinding.seekbarPoints.setProgressDrawable(ContextCompat.getDrawable(getContext(), R.drawable.shape_seekbar_points_style));
</code>```

In this image there should be a current points showing textView like the image below

Please suggest some solution for this
Thanks in advance.

答:
you can use following library to achieve your goal
take a look below libray

Library 1

Library 2

Library 3

Library 4

Title: Custom design SeekBar in android

Body:
I have done the seekbar but I need to do the customization like the below image.

I used the code like this

<SeekBar
                        android:id="@+id/seekbarPoints"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="-16dp"
                        android:layout_marginTop="@dimen/small"
                        android:max="0"
                        android:progress="0"
                        android:progressDrawable="@drawable/shape_seekbar_points_style"
                        android:thumb="@null" />

if (TextUtils.isDigitsOnly(maxPoints)) {
            int maxP = Integer.parseInt(maxPoints);
            mBinding.seekbarPoints.setMax(maxP);
            if (!TextUtils.isEmpty(points)) {
                int p = (int) Double.parseDouble(points);
                mBinding.seekbarPoints.setProgress(p);
            }
        }
mBinding.seekbarPoints.setProgressDrawable(ContextCompat.getDrawable(getContext(), R.drawable.shape_seekbar_points_style));

In this image there should be a current points showing textView like the image below

Please suggest some solution for this
Thanks in advance.


问:
How to set sequence data with existing random data?
I have a table entity named it as uniqueId where the entry generate randomly.Such as

```<code>$customer->uniqueId = $request->Input(['uniqueId']) ?: mt_rand(1000, 9999);
</code>```

means if there is existing uniqueId it will store the existing one otherwise it will be set to the random number. Now instead of setting the random number i want to set it as sequentially . means  from 1, 2, 3 like that.. as i can't delete the existing uniqueId which has already created how do I create new entry sequentially with the existing one?

答:
If you simply set column to auto increment you will achieve this automatically you dont even need to call it.

In laravel you can achieve this in your migrations by

$table->increments('uniqueId');

OR

You can achieve this by

lets assume you have a customer Model

```<code> // find the last entry in you table

$oldCustomer = Customer::orderBy('uniqueId','DESC')->first();

$customer->uniqueId = ++($olderCustomer->uniqueId);
</code>```

I hope this helps

**EDIT **

```<code>  $customers = Customer::all();

  $index = 1;
  @foreach($customers as $customer)
  {
      $customer->uniqueID = $index++;
      $customer->update();
  }
</code>```

Body:
I have a table entity named it as uniqueId where the entry generate randomly.Such as

$customer->uniqueId = $request->Input(['uniqueId']) ?: mt_rand(1000, 9999);

means if there is existing uniqueId it will store the existing one otherwise it will be set to the random number. Now instead of setting the random number i want to set it as sequentially . means  from 1, 2, 3 like that.. as i can't delete the existing uniqueId which has already created how do I create new entry sequentially with the existing one?

Body:
If you simply set column to auto increment you will achieve this automatically you dont even need to call it.

In laravel you can achieve this in your migrations by

$table->increments('uniqueId');

OR

You can achieve this by

lets assume you have a customer Model

 // find the last entry in you table

$oldCustomer = Customer::orderBy('uniqueId','DESC')->first();

$customer->uniqueId = ++($olderCustomer->uniqueId);

I hope this helps

**EDIT **

  $customers = Customer::all();

  $index = 1;
  @foreach($customers as $customer)
  {
      $customer->uniqueID = $index++;
      $customer->update();
  }


问:
aligning text to top of webpage in html code using css
I have this css code:

```<code>.post {
    margin-top: 0.5em;
    margin-left: 2em;
    margin-right: 2em;
    text-align: center;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}
</code>```

and have this in html:

```<code><div class="post">
 <h1>Title of Sample Work 2</h1>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.</p>
</div>
</code>```

And this is what I see:

Why there is so much margin at the top and the text title is so down?
You can see an example of the actual page on the web here:
http://www.nanogomo.com/sample1.html

It is interesting that if I add more content to it, it pushes the text up.

答:
use margin top and give value according to the need.</p>

```<code>.post h1{
    text-align: center;
    margin-top: -7px;
}
</code>```

Body:
I have this css code:

.post {
    margin-top: 0.5em;
    margin-left: 2em;
    margin-right: 2em;
    text-align: center;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}

and have this in html:

Title of Sample Work 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.

And this is what I see:

Why there is so much margin at the top and the text title is so down?
You can see an example of the actual page on the web here:
http://www.nanogomo.com/sample1.html

It is interesting that if I add more content to it, it pushes the text up.

Body:
use margin top and give value according to the need.

.post h1{
    text-align: center;
    margin-top: -7px;
}


问:
Android Studio "R.array" Error:(36, 44) error: cannot find symbol variable array
Error highlights the text "array" red. How do I fix it?</p>

```<code>public class Signup extends Activity {

    AutoCompleteTextView y;
    String[] z;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);

        y = (AutoCompleteTextView) findViewById(R.id.cntry);
        z = getResources().getStringArray(R.array.country);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, z);
</code>```

答:
You use a TypedArray in arrays.xml file within your res/values folder that looks like this,</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="country">
        <item>@drawable/pakistan</item>
        <item>@drawable/india</item>
        <item>@drawable/USA</item>
    </string-array>
</resources>
</code>```

Body:
Error highlights the text "array" red. How do I fix it?

public class Signup extends Activity {

    AutoCompleteTextView y;
    String[] z;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);

        y = (AutoCompleteTextView) findViewById(R.id.cntry);
        z = getResources().getStringArray(R.array.country);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, z);

Body:
You use a TypedArray in arrays.xml file within your res/values folder that looks like this,

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="country">
        <item>@drawable/pakistan</item>
        <item>@drawable/india</item>
        <item>@drawable/USA</item>
    </string-array>
</resources>


问:
Conflicting Constraints Error Message in Debugger
I'm working through an online tutorial. I have followed everything step by step and am getting a message in the debugger when running the simulator saying I have conflicting constraints. I don't believe there is conflicting constraints, so I figured I would reach out for an informed second opinion.

Here is a screenshot of the view controller with the conflicting constraints.

View Controller from Xcode Project

Here are the screenshots of the error message in the debugger: It looks like it has an issue with the width constraint on the stop button, but I can't tell from the error message how to fix it.

Part of Error Message

Any help is greatly appreciated!

答:
It looks like you set stop button width = 64 but actual you not set width for parent view so it automatic set equal to 0 or 343.
Did you get any red constraints when click on stop button?</p>


问:
Destructive string assignment
In this code,

```<code>def string_assignment_original_name(name)
  save_name = name
  name.upcase!
  name
end
</code>```

if name = "Bob", the output will be "BOB". Meanwhile in this code,

```<code>def string_assignment_save_name(name)
  save_name = name
  name.upcase!
  save_name
end
</code>```

if name = "Bob", the output is also "BOB".

Why is this the case?

答:
Ruby variables are basically "object references" which is a sort of pointer internally. Both name and save_name refer to the same object both before and after your in-place modification.

Look at the result of name.object_id and save_name.object_id to see how this plays out, as that method is a window into what's going on internally:

```<code>name = "bob"
name.object_id
# => ...2980

save_name = name
save_name.object_id
# => ...2980

name.upcase!
name.object_id
# => ...2980
</code>```

Now if you duplicate the object via a method like .dup or .clone, or if you create a whole new string through some other process, then it's a new object:

```<code>name = name.downcase
name.object_id
# => ...8480
</code>```

Now you've got two objects in play:

```<code>name.object_id
# => ...8480
save_name.object_id
# => ...2980
</code>```

These object_id values are for all intents random but are unique per object instance. If two objects have the same object_id value they are the same object.†

† Technically objects can override their object_id method to return something else but this is rare.

Title: Destructive string assignment

Body:
In this code,

def string_assignment_original_name(name)
  save_name = name
  name.upcase!
  name
end

if name = "Bob", the output will be "BOB". Meanwhile in this code,

def string_assignment_save_name(name)
  save_name = name
  name.upcase!
  save_name
end

if name = "Bob", the output is also "BOB".

Why is this the case?

Body:
Ruby variables are basically "object references" which is a sort of pointer internally. Both name and save_name refer to the same object both before and after your in-place modification.

Look at the result of name.object_id and save_name.object_id to see how this plays out, as that method is a window into what's going on internally:

name = "bob"
name.object_id
# => ...2980

save_name = name
save_name.object_id
# => ...2980

name.upcase!
name.object_id
# => ...2980

Now if you duplicate the object via a method like .dup or .clone, or if you create a whole new string through some other process, then it's a new object:

name = name.downcase
name.object_id
# => ...8480

Now you've got two objects in play:

name.object_id
# => ...8480
save_name.object_id
# => ...2980

These object_id values are for all intents random but are unique per object instance. If two objects have the same object_id value they are the same object.†

† Technically objects can override their object_id method to return something else but this is rare.


问:
sort with operator overriding does not get I want
I am trying to sort a person vector by person.name and age. Therefore, I tried to override the operator< in the Person definition, and to use functor with std::sort().

However, I did not get what I want. My expectation is that Persons are first ordered by their name, and then by their age. But I get the same result with both solutions:

```<code>che is less than xu
(wu, 30)
(che, 34)
(xu, 21)
</code>```

What I expect order is:

```<code>(che, 34)
(wu, 30)
(xu, 21)
</code>```

Could anyone help point the mistake I made? Thanks

The source code is:

```<code>class Person{
 public:
  string _name;
  int _age;

 public:
  Person(string name, int age):_name(name),_age(age){
  }
    bool operator<(const Person* b) const {
   cout<<"Expect "<<_name <<b->_name <<"   "<< (_name < b->_name)<<endl;
  if(_name != b->_name) {
      return _name < b->_name;
   }
    else return _age<b->_age;
   }

   bool operator<(const Person& b) const {
     if(_name!=b._name) {
       cout<<_name <<" is less than "<<b._name<<endl;
       return _name<b._name;
     }  else return _age<b._age;
   }
  friend ostream& operator<<(ostream& out, const Person& b) {
    out << "(" << b._name << ", " << b._age << ")"<<endl;
    return out;
}

};

bool PersonCompare(const Person* a, const Person* b ){
     cout<<"Expect "<<a->_name <<b->_name <<"   "<< (a->_name < b->_name)<<endl;
    if(a->_name != b->_name) {
      return a->_name < b->_name;
    }
    else return a->_age<b->_age;
}

class PersonPrint{
 public:
  PersonPrint(){
  }

  void operator()(const Person& person){
    cout<<person;
  }
 void operator()(const Person* person){
    cout<<*person;
  }
};

void testSort(){
  vector<Person*> personsList;
  personsList.push_back(new Person("xu", 12));
  personsList.push_back(new Person("che", 23));
  personsList.push_back(new Person("sxy", 34));
  /*std::sort(personsList.begin(), personsList.end(), [](Person* a, Person* b ){
      if(a->_name!=b->_name) return a->_name<b->_name;
      else return a->_age<b->_age;
      }); *///This works
 /* std::sort(personsList.begin(), personsList.end(), PersonCompare ) *///This works..
  std::sort(personsList.begin(), personsList.end()); //This does not work

  for_each(personsList.begin(), personsList.end(), PersonPrint());
}
</code>```

==============
It is the logic error inside of lambda/operator. After changing if(a._name<b._name) to if(a._name!=b._name), the error is fixed.

/////////////////////////////////////

I updated the code.
Add bool operator<(const Person* b) const{} for class Person, and then try to sort a vector of Person*. But the result is not sorted as I expected, and the newly added operator<(const Person*) is not called. Any suggestion here? Thanks

答:
Your comparison function is treading the territories of undefined behavior. No surprise you are not seeing what you expect.
From std::sort's documentation

comp  -   comparison function object (i.e. an object that satisfies the
  requirements of Compare) which returns true if the first argument is
  less than (i.e. is ordered before) the second.

Requirements of Compare:

The return value of the function call operation applied to an object
  of type Compare, when contextually converted to bool, yields true if
  the first argument of the call appears before the second in the strict
  weak ordering relation induced by this Compare type, and false
  otherwise.

Your comparison function doesn't meet the criteria of strict week ordering.

You can simply do:

```<code>std::sort(persons.begin(), persons.end(),
[](const Person& a, const Person& b) { return std::tie(a.name, a.age) < std::tie(b.name, b.age); })
</code>```

I have written an article on this: https://isocpp.org/blog/2016/05/strict-weak-ordering-and-stl which you may want to refer.

Edit(Based on OP's edit):

This doesn't works because you have provided member functions for Person class whereas the type on which you want to call is Person*. Both are different types.
You will have to move the PrintPerson function's definition outside the class and make it declare as a friend method in Person class. Unfortunately you cannot do the same with the bool operator<(Person *a, Person *b) because operator overloading doesn't works with pointer types. Your only alternative is to pass a comparer.

Body:
I am trying to sort a person vector by person.name and age. Therefore, I tried to override the operator< in the Person definition, and to use functor with std::sort().

However, I did not get what I want. My expectation is that Persons are first ordered by their name, and then by their age. But I get the same result with both solutions:

che is less than xu
(wu, 30)
(che, 34)
(xu, 21)

What I expect order is:

(che, 34)
(wu, 30)
(xu, 21)

Could anyone help point the mistake I made? Thanks

The source code is:

class Person{
 public:
  string _name;
  int _age;

 public:
  Person(string name, int age):_name(name),_age(age){
  }
    bool operator<(const Person* b) const {
   cout<<"Expect "<<_name <_name <<"   "<< (_name _name)<<endl;
  if(_name != b->_name) {
      return _name _name;
   }
    else return _age_age;
   }

   bool operator<(const Person& b) const {
     if(_name!=b._name) {
       cout<<_name <<" is less than "<<b._name<<endl;
       return _name<b._name;
     }  else return _age<b._age;
   }
  friend ostream& operator<<(ostream& out, const Person& b) {
    out << "(" << b._name << ", " << b._age << ")"<<endl;
    return out;
}

};

bool PersonCompare(const Person* a, const Person* b ){
     cout<<"Expect "<_name <_name <<"   "<< (a->_name _name)<<endl;
    if(a->_name != b->_name) {
      return a->_name _name;
    }
    else return a->_age_age;
}

class PersonPrint{
 public:
  PersonPrint(){
  }

  void operator()(const Person& person){
    cout<<person;
  }
 void operator()(const Person* person){
    cout<<*person;
  }
};

void testSort(){
  vector<Person*> personsList;
  personsList.push_back(new Person("xu", 12));
  personsList.push_back(new Person("che", 23));
  personsList.push_back(new Person("sxy", 34));
  /*std::sort(personsList.begin(), personsList.end(), [](Person* a, Person* b ){
      if(a->_name!=b->_name) return a->_name_name;
      else return a->_age_age;
      }); *///This works
 /* std::sort(personsList.begin(), personsList.end(), PersonCompare ) *///This works..
  std::sort(personsList.begin(), personsList.end()); //This does not work

  for_each(personsList.begin(), personsList.end(), PersonPrint());
}

==============
It is the logic error inside of lambda/operator. After changing if(a._name<b._name) to if(a._name!=b._name), the error is fixed.

/////////////////////////////////////

I updated the code.
Add bool operator<(const Person* b) const{} for class Person, and then try to sort a vector of Person*. But the result is not sorted as I expected, and the newly added operator<(const Person*) is not called. Any suggestion here? Thanks

Body:
Your comparison function is treading the territories of undefined behavior. No surprise you are not seeing what you expect.
From std::sort's documentation

comp  -   comparison function object (i.e. an object that satisfies the
  requirements of Compare) which returns true if the first argument is
  less than (i.e. is ordered before) the second.

Requirements of Compare:

The return value of the function call operation applied to an object
  of type Compare, when contextually converted to bool, yields true if
  the first argument of the call appears before the second in the strict
  weak ordering relation induced by this Compare type, and false
  otherwise.

Your comparison function doesn't meet the criteria of strict week ordering.

You can simply do:

std::sort(persons.begin(), persons.end(),
[](const Person& a, const Person& b) { return std::tie(a.name, a.age) < std::tie(b.name, b.age); })

I have written an article on this: https://isocpp.org/blog/2016/05/strict-weak-ordering-and-stl which you may want to refer.

Edit(Based on OP's edit):

This doesn't works because you have provided member functions for Person class whereas the type on which you want to call is Person*. Both are different types.
You will have to move the PrintPerson function's definition outside the class and make it declare as a friend method in Person class. Unfortunately you cannot do the same with the bool operator<(Person *a, Person *b) because operator overloading doesn't works with pointer types. Your only alternative is to pass a comparer.


问:
Spacing between checkboxes and values
JSFiddle

How would I go about editing the HTML/CSS  to create spacing between each checkbox/value pairing? Right now each checkbox and each value are spaced evenly. I'd like value1 to be close to checkbox1, but checkbox2 to have some distance from the value1.

Code here:

```<code>.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 20px 0;
}

<div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four
  </span>
</div>
</code>```

答:
Use CSS in this way margin: top left bottom right;

```<code>.checkboxes input{
  margin: 0 5px 0 20px;
}
</code>```

.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 5px 0 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four
  </span>
</div></code>```

Title: Spacing between checkboxes and values

Body:
JSFiddle

How would I go about editing the HTML/CSS  to create spacing between each checkbox/value pairing? Right now each checkbox and each value are spaced evenly. I'd like value1 to be close to checkbox1, but checkbox2 to have some distance from the value1.

Code here:

.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 20px 0;
}

    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four

Body:
Use CSS in this way margin: top left bottom right;

.checkboxes input{
  margin: 0 5px 0 20px;
}

.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 5px 0 20px;
}

<div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four
  </span>
</div>