问:
Docker swarm on 'dind' images and networking problems
I am trying to create a local swarm environment based on 'dind' images. Below are the steps for environment recreation:

```<code>docker network create --attachable --subnet 10.0.0.0/16 tools_network

docker run -d --privileged --name swarm-manager-1 --hostname swarm-manager-1 --network tools_network --ip 10.0.0.3 -p 42421:2375 docker:17.03.1-dind

docker --host localhost:42421 swarm init --advertise-addr 10.0.0.3

docker run -d --privileged --name swarm-worker-1 --hostname swarm-worker-1 --network tools_network --ip 10.0.0.4 -p 42423:2375 docker:17.03.1-dind

docker --host localhost:42423 swarm join --token <swarm-token> 10.0.0.3:2377
</code>```

After that I add an nginx-based proxy:

```<code>docker run -d --name swarm-proxy --network tools_network -v $(pwd)/temp-proxy:/etc/nginx:ro -p 80:80 nginx:stable-alpine
</code>```

with the following contents of nginx.conf in the 'temp-proxy' folder:

```<code>events {
    worker_connections  1024;
}

http {
    upstream swarm {
        server 10.0.0.3;
        server 10.0.0.4;

    }

    server {
        listen          80 default_server;
        listen          [::]:80 default_server;

        location / {
            proxy_pass      http://swarm;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}
</code>```

The service I use for testing purposes is launched by:

```<code>docker --host localhost:42421 service create --name test-web --publish 80:80 yeasy/simple-web
</code>```

What I expect at this stage, based on the mesh networking documentation is that curl localhost will return the result from the deployed service. However, I get a 502 Bad Gateway response, with the following log messages from the proxy:

```<code>[error] 7#7: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 10.0.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://10.0.0.4:80/", host: "localhost"
[error] 7#7: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 10.0.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://10.0.0.3:80/", host: "localhost"
10.0.0.1 - -  "GET / HTTP/1.1" 502 173 "-" "curl/7.47.0"
</code>```

Same result (connection refused) for curling from a docker container deployed to the tools_network.

Running netstat -l from inside one of the swarm nodes shows that they don't listen on port 80:

```<code>Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.11:38943        0.0.0.0:*               LISTEN
tcp        0      0 :::2375                 :::*                    LISTEN
tcp        0      0 :::2377                 :::*                    LISTEN
tcp        0      0 :::7946                 :::*                    LISTEN
udp        0      0 127.0.0.11:35094        0.0.0.0:*
udp        0      0 0.0.0.0:4789            0.0.0.0:*
udp        0      0 :::7946                 :::*
</code>```

The questions are:

Is there something wrong with my configuration? What is it?

If not, what steps should I take to get to the problem's root?

答:
After a lot of investigations I found the problem looking at this.
 Docker inside dind images couldn't initialize properly due to absent modules and I actually saw the errors in the container logs (docker logs swarm-manager-1) but didn't pay attention to them.

So the solution for me was launching the swarm nodes like this:

```<code>docker run -d --privileged --name swarm-manager-1 --hostname swarm-manager-1 --network tools_network --ip 10.0.0.3 -p 42421:2375 -v /lib/modules:/lib/modules:ro docker:17.03.1-dind
</code>```

where the /lib/modules mapping is the piece that was absent.

Body:
I am trying to create a local swarm environment based on 'dind' images. Below are the steps for environment recreation:

docker network create --attachable --subnet 10.0.0.0/16 tools_network

docker run -d --privileged --name swarm-manager-1 --hostname swarm-manager-1 --network tools_network --ip 10.0.0.3 -p 42421:2375 docker:17.03.1-dind

docker --host localhost:42421 swarm init --advertise-addr 10.0.0.3

docker run -d --privileged --name swarm-worker-1 --hostname swarm-worker-1 --network tools_network --ip 10.0.0.4 -p 42423:2375 docker:17.03.1-dind

docker --host localhost:42423 swarm join --token <swarm-token> 10.0.0.3:2377

After that I add an nginx-based proxy:

docker run -d --name swarm-proxy --network tools_network -v $(pwd)/temp-proxy:/etc/nginx:ro -p 80:80 nginx:stable-alpine

with the following contents of nginx.conf in the 'temp-proxy' folder:

events {
    worker_connections  1024;
}

http {
    upstream swarm {
        server 10.0.0.3;
        server 10.0.0.4;

    }

    server {
        listen          80 default_server;
        listen          [::]:80 default_server;

        location / {
            proxy_pass      http://swarm;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

The service I use for testing purposes is launched by:

docker --host localhost:42421 service create --name test-web --publish 80:80 yeasy/simple-web

What I expect at this stage, based on the mesh networking documentation is that curl localhost will return the result from the deployed service. However, I get a 502 Bad Gateway response, with the following log messages from the proxy:

[error] 7#7: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 10.0.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://10.0.0.4:80/", host: "localhost"
[error] 7#7: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 10.0.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://10.0.0.3:80/", host: "localhost"
10.0.0.1 - -  "GET / HTTP/1.1" 502 173 "-" "curl/7.47.0"

Same result (connection refused) for curling from a docker container deployed to the tools_network.

Running netstat -l from inside one of the swarm nodes shows that they don't listen on port 80:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.11:38943        0.0.0.0:*               LISTEN
tcp        0      0 :::2375                 :::*                    LISTEN
tcp        0      0 :::2377                 :::*                    LISTEN
tcp        0      0 :::7946                 :::*                    LISTEN
udp        0      0 127.0.0.11:35094        0.0.0.0:*
udp        0      0 0.0.0.0:4789            0.0.0.0:*
udp        0      0 :::7946                 :::*

The questions are:

Is there something wrong with my configuration? What is it?

If not, what steps should I take to get to the problem's root?

Body:
After a lot of investigations I found the problem looking at this.
 Docker inside dind images couldn't initialize properly due to absent modules and I actually saw the errors in the container logs (docker logs swarm-manager-1) but didn't pay attention to them.

So the solution for me was launching the swarm nodes like this:

docker run -d --privileged --name swarm-manager-1 --hostname swarm-manager-1 --network tools_network --ip 10.0.0.3 -p 42421:2375 -v /lib/modules:/lib/modules:ro docker:17.03.1-dind

where the /lib/modules mapping is the piece that was absent.


来源: stackexchange

问:
Get unique count of instance SQL Server
This is something I am not getting for some or other reason.

I have a list of records

```<code>BusinessUnitId     Position      Date          Time
-----------------------------------------------------------
76                 Staff         3/30/2009     11:00:00 AM
76                 Staff         3/30/2009     04:00:00 PM
76                 Management    3/30/2009     05:00:00 PM
78                 Exco          3/30/2009     09:00:00 AM
78                 Staff         3/30/2009     09:30:00 AM
</code>```

If I do a group by

```<code>select
    count(answer.BusinessUnitId)
from
    AnswerSelected answer
group by
    answer.BusinessUnitId
</code>```

I retrieve a value of 3 and 2

What I am trying to achieve is get a count of 2

So in total 2 business units submitted answers, 76 and 78(hope this makes sense)

How can I do this?

Thanks

答:
Use COUNT(DISTINCT ...)

```<code>SELECT
    COUNT(DISTINCT BusinessUnitId)
FROM AnswerSelected
</code>```

You don't need to use GROUP BY in this particular case to get the distinct count of business units across your entire table.

Demo here:

Rextester

ContentLicense: CC BY-SA 3.0

Title: Get unique count of instance SQL Server

Body:
This is something I am not getting for some or other reason.

I have a list of records

BusinessUnitId     Position      Date          Time
-----------------------------------------------------------
76                 Staff         3/30/2009     11:00:00 AM
76                 Staff         3/30/2009     04:00:00 PM
76                 Management    3/30/2009     05:00:00 PM
78                 Exco          3/30/2009     09:00:00 AM
78                 Staff         3/30/2009     09:30:00 AM

If I do a group by

select
    count(answer.BusinessUnitId)
from
    AnswerSelected answer
group by
    answer.BusinessUnitId

I retrieve a value of 3 and 2

What I am trying to achieve is get a count of 2

So in total 2 business units submitted answers, 76 and 78(hope this makes sense)

How can I do this?

Thanks

Body:
Use COUNT(DISTINCT ...)

SELECT
    COUNT(DISTINCT BusinessUnitId)
FROM AnswerSelected

You don't need to use GROUP BY in this particular case to get the distinct count of business units across your entire table.

Demo here:

Rextester


问:
How to properly from VBA connection from Excel sheet to another Excel sheet?
I currently have 2 separate Excel worksheets. One is data entry and another is display.

The display uses VBA to connect to data entry to obtain data. Normally, it functions well enough. However I'm required to have the 2 worksheets in separate windows, meaning both can be displayed at the same time in separate windows, in the same screen.

The issue in this scenario is that when I click Execute in display to begin SQL query, the display window opens another data entry worksheet (read-only) and reads that instead of the one I opened initially. Is this issue due to my connection string or my ADODB.Recordset has issues?

Here is the sub which contains the connection string and ADODB.Recordset.
Edit: Full code is included to provide full context for those who need it.

```<code>Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String, AB As String)
Dim rsData As ADODB.Recordset
Dim szConnect As String
On Error GoTo ErrHandler

If AB = "1st" Then
wbWorkBook = ThisWorkbook.Sheets("Inner Workings").Range("B9").Text
End If

Application.StatusBar = "Retrieving data ....."
'Set up the connection string to excel - thisworkbook
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & wbWorkBook & ";" & _
            "Extended Properties=Excel 8.0;"

Set rsData = New ADODB.Recordset
'Run the query as adCmdText
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

'Check if data is returned
If Not rsData.EOF Then
    'if the recordset contains data put them on the worksheet
    rgStart.CopyFromRecordset rsData
Else

End If
'Close connection
rsData.Close
'Clean up and get out
Set rsData = Nothing
Application.StatusBar = False
Exit Sub

ErrHandler:
'an error occured in the SQL-statement
MsgBox "Your query could not be executed, the SQL-statement is incorrect."
Set rsData = Nothing
Application.StatusBar = False

End Sub

Sub process()
Call clear
Call testsql("1st")  ' populate 1st Summary
Call testsql("2nd")  ' find Date+Time
Call testsql("3rd")  ' arrange record by newest
Call testsql("4th")  ' show final results
End Sub

Sub testsql(AB As String)

Dim rgPlaceOutput As Range    'first cell for the output of the query
Dim stSQLstring As String     'text of the cell containing the SQL statement
Dim rg As String, SQL As String

If AB = "1st" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B2").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("1st Summary").Range("A2")
End If
If AB = "2nd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B3").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("2nd Summary").Range("A2")
End If
If AB = "3rd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B4").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("3rd Summary").Range("A2")
End If
If AB = "4th" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B5").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("Final Summary").Range("A5")
End If

QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName, AB

End Sub

Sub clear()
ActiveWorkbook.Sheets("1st Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("2nd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("3rd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("Final Summary").Range("A5:BR5000").Value = Empty
End Sub
</code>```

Also another thing I noticed. Depending on which file I open first, it can result in both files creating a read-only copy when I click Execute. If I open Display first then Entry form, both in different instances of Excel, it will create read-only copies of both files.

If I open Entry form first, then Display in again, different instances of Excel, only the read-only copy of Display will appear.

The only time a read-only does not appear is when both files are in a single instance of Excel, which is not what I want.

Edit2:

For more info, here is the SQL I used (4 total)

SQL1 - select * from EntryTable

SQL2 - select A.*,[Date + Time] from Summary1 A left join (select [Die No], max (Date + Time) as [Date + Time] from Summary1 group by [Die No]) B on A.[Die No] = B.[Die No]

SQL3 - select * from Summary2 where [Date + Time] = Date + Time

SQL4 - select Project_No, Die_No, Description, Repair_Details, Status from Summary3

Workbook name in cell B9 = V:\Die Maintenance System v2\Die Maintenance Menu.xlsx

Update: My colleague has tested the system on her PC and tested no problems. I've been told its most likely my Excel settings. But for the life of me, I can't figure out what is causing it. What type of setting is used to prevent the read-only file from appearing?

Edit: I can see that this post has gone on too long. I decided to continue this on a new thread right here.

答:
Your SQL FROM clause is referencing a different named range.  Please post your SQL text.  It must be qualified to correct Named Range or sheet name.

```<code>    SELECT Project No, Die No, Description, Repair Details, Status
    FROM DATA1  <- correct this to qualified named range or sheet name
</code>```

like

```<code>   FROM [Entry Form$] 'or

   FROM [Named Range] <- this can be found in Formulas | Name Manager
</code>```

Edit:
I am not sure about your "1st" source workbook's location so let us try to insert the line I commented below

```<code>   wbWorkBook = ThisWorkbook.Sheets("Inner Workings").Range("B9").Text
   wbWorkBook = Workbooks(wbWorkbook).FullName  '<- add this line
</code>```

If it still does not work, please post your SQL AND Workbook name in cell B9.

Edit 2:
What is the result if you change the FROM clause like:

```<code>   select * from [EntryTable$]
</code>```

Edit 3: Do you have password? if so, try to disable it first to isolate the problem in read only.

Body:
I currently have 2 separate Excel worksheets. One is data entry and another is display.

The display uses VBA to connect to data entry to obtain data. Normally, it functions well enough. However I'm required to have the 2 worksheets in separate windows, meaning both can be displayed at the same time in separate windows, in the same screen.

The issue in this scenario is that when I click Execute in display to begin SQL query, the display window opens another data entry worksheet (read-only) and reads that instead of the one I opened initially. Is this issue due to my connection string or my ADODB.Recordset has issues?

Here is the sub which contains the connection string and ADODB.Recordset.
Edit: Full code is included to provide full context for those who need it.

Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String, AB As String)
Dim rsData As ADODB.Recordset
Dim szConnect As String
On Error GoTo ErrHandler

If AB = "1st" Then
wbWorkBook = ThisWorkbook.Sheets("Inner Workings").Range("B9").Text
End If

Application.StatusBar = "Retrieving data ....."
'Set up the connection string to excel - thisworkbook
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & wbWorkBook & ";" & _
            "Extended Properties=Excel 8.0;"

Set rsData = New ADODB.Recordset
'Run the query as adCmdText
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

'Check if data is returned
If Not rsData.EOF Then
    'if the recordset contains data put them on the worksheet
    rgStart.CopyFromRecordset rsData
Else

End If
'Close connection
rsData.Close
'Clean up and get out
Set rsData = Nothing
Application.StatusBar = False
Exit Sub

ErrHandler:
'an error occured in the SQL-statement
MsgBox "Your query could not be executed, the SQL-statement is incorrect."
Set rsData = Nothing
Application.StatusBar = False

End Sub

Sub process()
Call clear
Call testsql("1st")  ' populate 1st Summary
Call testsql("2nd")  ' find Date+Time
Call testsql("3rd")  ' arrange record by newest
Call testsql("4th")  ' show final results
End Sub

Sub testsql(AB As String)

Dim rgPlaceOutput As Range    'first cell for the output of the query
Dim stSQLstring As String     'text of the cell containing the SQL statement
Dim rg As String, SQL As String

If AB = "1st" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B2").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("1st Summary").Range("A2")
End If
If AB = "2nd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B3").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("2nd Summary").Range("A2")
End If
If AB = "3rd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B4").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("3rd Summary").Range("A2")
End If
If AB = "4th" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B5").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("Final Summary").Range("A5")
End If

QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName, AB

End Sub

Sub clear()
ActiveWorkbook.Sheets("1st Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("2nd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("3rd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("Final Summary").Range("A5:BR5000").Value = Empty
End Sub

Also another thing I noticed. Depending on which file I open first, it can result in both files creating a read-only copy when I click Execute. If I open Display first then Entry form, both in different instances of Excel, it will create read-only copies of both files.

If I open Entry form first, then Display in again, different instances of Excel, only the read-only copy of Display will appear.

The only time a read-only does not appear is when both files are in a single instance of Excel, which is not what I want.

Edit2:

For more info, here is the SQL I used (4 total)

SQL1 - select * from EntryTable

SQL2 - select A.*,[Date + Time] from Summary1 A left join (select [Die No], max (Date + Time) as [Date + Time] from Summary1 group by [Die No]) B on A.[Die No] = B.[Die No]

SQL3 - select * from Summary2 where [Date + Time] = Date + Time

SQL4 - select Project_No, Die_No, Description, Repair_Details, Status from Summary3

Workbook name in cell B9 = V:\Die Maintenance System v2\Die Maintenance Menu.xlsx

Update: My colleague has tested the system on her PC and tested no problems. I've been told its most likely my Excel settings. But for the life of me, I can't figure out what is causing it. What type of setting is used to prevent the read-only file from appearing?

Edit: I can see that this post has gone on too long. I decided to continue this on a new thread right here.

Body:
Your SQL FROM clause is referencing a different named range.  Please post your SQL text.  It must be qualified to correct Named Range or sheet name.

    SELECT Project No, Die No, Description, Repair Details, Status
    FROM DATA1  <- correct this to qualified named range or sheet name

like

   FROM [Entry Form$] 'or

   FROM [Named Range] <- this can be found in Formulas | Name Manager

Edit:
I am not sure about your "1st" source workbook's location so let us try to insert the line I commented below

   wbWorkBook = ThisWorkbook.Sheets("Inner Workings").Range("B9").Text
   wbWorkBook = Workbooks(wbWorkbook).FullName  '<- add this line

If it still does not work, please post your SQL AND Workbook name in cell B9.

Edit 2:
What is the result if you change the FROM clause like:

   select * from [EntryTable$]

Edit 3: Do you have password? if so, try to disable it first to isolate the problem in read only.


问:
how to push sub array object into an a array in javascript
hi all i am using javascript i am trying to push object values into one array here i attached my code

```<code>var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }
</code>```

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this

答:
Try with Object.key() and Object.values() function  .And Array#forEach used for iterate the array .Don't hardcore with volume[0] .batter iterate with forEach

var data = [{ BuildingID: "56", FloorId: "65", volume: [{ one: 12, two: 15,   three: 12}] }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {
                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                data[i].volume.forEach(function(a,c){
                Object.keys(data[i].volume[c]).forEach(function(a,b){
                  obj[a] = Object.values(data[i].volume[c])[b]
                })
                })
                MainInfo.push(obj);
            }
            console.log(MainInfo)```

Body:
hi all i am using javascript i am trying to push object values into one array here i attached my code

var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this


问:
Equivalent to GOTO in conditions, Python
Since there is no goto operator in Python, what technique can be used instead?

Condition
If it is true, go to thread 1, if is false, go to thread 2
In thread we do something small and after that we go to thread 2 where all other actions take place.

答:
```<code>def thread_1():
  # Do thread_1 type stuff here.

def thread_2():
  # Do thread_2 type stuff here.

if condition:
    thread_1()

# If condition was false, just run thread_2().
# If it was true then thread_1() will return to this point.
thread_2()
</code>```

<p>edit: I'm assuming that by "thread" you mean a piece of code (otherwise known as a subroutine or a function). If you're talking about threads as in parallel execution then you'll need more detail in the question. </p>

ContentLicense: CC BY-SA 2.5

Body:
def thread_1():
  # Do thread_1 type stuff here.

def thread_2():
  # Do thread_2 type stuff here.

if condition:
    thread_1()

# If condition was false, just run thread_2().
# If it was true then thread_1() will return to this point.
thread_2()

edit: I'm assuming that by "thread" you mean a piece of code (otherwise known as a subroutine or a function). If you're talking about threads as in parallel execution then you'll need more detail in the question.


问:
Multiple queries with Entity Framework in C#
I am using C# and EF to work with a SQL Server database.

I need to do several queries at a time. For now I'm doing all the operations together and in the end I'm calling the DbContext.SaveChanges function to apply all the changes at once.

My problem is that if one of the queries has an error, all the queries are cancelled.

Do I need to call the DbContext.SaveChanges for every query for this?

Thanks

答:
DBcontext works as UnitOfWork. It keeps track of all the changes in current DBContext and when you call SaveChanges it figures out what exactly should be done while writing those to database. In other words, this is similar to Database Transaction.

Do I need to call the DbContext.SaveChanges for every query for this?

It depends. You need to identify your UnitOfWork. In web applications, it is generally "DBConstext per Request". It may not be exactly for you. Identify group of DB actions those should be done in one group OR should fail as a group. Then call SaveChanges accordingly.

Calling SaveChanges for each DB call may not be efficient. You are ignoring other important features of ORM those will not be helpful in this case. Take a time to identify your UnitOfWork.


问:
detecting "we have no imagery" of google maps street view static images
I'm generating street view static images like so:

https://maps.googleapis.com/maps/api/streetview?size=1080x400&location=%s&fov=90&heading=235&pitch=0&key=%s

If you visit that link you see an image that says, "Sorry, we have no imagery for this..."

Is there any way to detect this "sorry" state so that I can fall back to another image?

答:
As of 2016, you can use the new Street View Image Metadata API.

Now you just need the status field to know if a panorama is found.

Example requests:

https://maps.googleapis.com/maps/api/streetview/metadata?size=600x300&location=78.648401,14.194336&fov=90&heading=235&pitch=10&key=YOUR_API_KEY

```<code>{
   "status" : "ZERO_RESULTS"
}
</code>```

https://maps.googleapis.com/maps/api/streetview/metadata?size=600x300&location=eiffel%20tower,%20paris,%20france&heading=-45&pitch=42&fov=110&key=YOUR_API_KEY

```<code>{
   ...
   "status" : "OK"
}
</code>```

Body:
As of 2016, you can use the new Street View Image Metadata API.

Now you just need the status field to know if a panorama is found.

Example requests:

https://maps.googleapis.com/maps/api/streetview/metadata?size=600x300&location=78.648401,14.194336&fov=90&heading=235&pitch=10&key=YOUR_API_KEY

{
   "status" : "ZERO_RESULTS"
}

https://maps.googleapis.com/maps/api/streetview/metadata?size=600x300&location=eiffel%20tower,%20paris,%20france&heading=-45&pitch=42&fov=110&key=YOUR_API_KEY

{
   ...
   "status" : "OK"
}


问:
Splitting a vector of objects in c++
I know my message is not properly formattd, but I'm new so please help me anyway.
I have two classes: Father and Son. In Son I have an int and a string.
In father i have a vector of son objects.
How can I access just the part of the vector composed by integers and/or the part just composed by strings?
Thank you very much!

CLASS SON.H

```<code>#ifndef SON_H
#define SON_H
#include <iostream>
using namespace std;

class Son
{
    public:
        Son() {}
        Son(int first, string second);
        virtual ~Son();
        int getFirst() const;
        string getSecond() const;
    private:
        int _first_parameter;
        string _second_parameter;
};

#endif // SON_H
</code>```

CLASS SON.CPP

```<code>#include "son.h"

Son::Son(int first, string second)
{
    _first_parameter=first;
    _second_parameter=second;
}

Son::~Son()
{
    //dtor
}

int Son::getFirst() const
{
    return _first_parameter;
}

string Son::getSecond() const
{
    return _second_parameter;
}
</code>```

CLASS FATHER.H

```<code>#ifndef FATHER_H
#define FATHER_H
#include <vector>
#include "son.h"

class Father
{
    public:
        Father() {}
        virtual ~Father();
        void filling();
    private:
        vector<Son> _access_vector;
        void _printIntegers(vector<int> v);
        void _printStrings(vector<string> v);
};

#endif // FATHER_H
</code>```

CLASS FATHER.CPP

```<code>#include "father.h"

Father::~Father()
{
    //dtor
}

void Father::filling()
{
    int temp_first_param;
    string temp_second_param;
    cout<<"Insert integer: "<<endl;
    cin>>temp_first_param;
    cout<<"Insert text"<<endl;
    cin>>temp_second_param;
    _access_vector.push_back(Son(temp_first_param, temp_second_param));
    _printIntegers(_access_vector.getFirst());                       /// Here I want to take just the vector of integers
    _printStrings(_access_vector.getSecond());                       /// Here I want to take just the vector of strings
}

void Father::_printIntegers(vector<int> v)
{
    for(unsigned i=0; i<v.size(); ++i)
        cout<<v[i]<<endl;
}

void Father::_printStrings(vector<string> v)
{
    for(unsigned i=0; i<v.size(); ++i)
    {
        cout<<v[i]<<endl;
    }
}
</code>```

COMPILER ERRORS:

||=== Build: Debug in Vector_access_experiment (compiler: GNU GCC Compiler) ===|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp||In member function 'void Father::filling()':|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp|17|error: 'class std::vector' has no member named 'getFirst'|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp|18|error: 'class std::vector' has no member named 'getSecond'|
  ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

答:
You can't call ```_access_vector.getFirst()``` and ```_access_vector.getSecond()```because std:vector has no such function.If you want to call this function,use this

```<code>_access_vector.at(i).getFirst();
_access_vector.at(i).getSecond();
</code>```

which i is position of your object in std::vector.

Title: Splitting a vector of objects in c++

Body:
I know my message is not properly formattd, but I'm new so please help me anyway.
I have two classes: Father and Son. In Son I have an int and a string.
In father i have a vector of son objects.
How can I access just the part of the vector composed by integers and/or the part just composed by strings?
Thank you very much!

CLASS SON.H

#ifndef SON_H
#define SON_H
#include <iostream>
using namespace std;

class Son
{
    public:
        Son() {}
        Son(int first, string second);
        virtual ~Son();
        int getFirst() const;
        string getSecond() const;
    private:
        int _first_parameter;
        string _second_parameter;
};

#endif // SON_H

CLASS SON.CPP

#include "son.h"

Son::Son(int first, string second)
{
    _first_parameter=first;
    _second_parameter=second;
}

Son::~Son()
{
    //dtor
}

int Son::getFirst() const
{
    return _first_parameter;
}

string Son::getSecond() const
{
    return _second_parameter;
}

CLASS FATHER.H

#ifndef FATHER_H
#define FATHER_H
#include <vector>
#include "son.h"

class Father
{
    public:
        Father() {}
        virtual ~Father();
        void filling();
    private:
        vector<Son> _access_vector;
        void _printIntegers(vector<int> v);
        void _printStrings(vector<string> v);
};

#endif // FATHER_H

CLASS FATHER.CPP

#include "father.h"

Father::~Father()
{
    //dtor
}

void Father::filling()
{
    int temp_first_param;
    string temp_second_param;
    cout<<"Insert integer: "<<endl;
    cin>>temp_first_param;
    cout<<"Insert text"<<endl;
    cin>>temp_second_param;
    _access_vector.push_back(Son(temp_first_param, temp_second_param));
    _printIntegers(_access_vector.getFirst());                       /// Here I want to take just the vector of integers
    _printStrings(_access_vector.getSecond());                       /// Here I want to take just the vector of strings
}

void Father::_printIntegers(vector<int> v)
{
    for(unsigned i=0; i<v.size(); ++i)
        cout<<v[i]<<endl;
}

void Father::_printStrings(vector<string> v)
{
    for(unsigned i=0; i<v.size(); ++i)
    {
        cout<<v[i]<<endl;
    }
}

COMPILER ERRORS:

||=== Build: Debug in Vector_access_experiment (compiler: GNU GCC Compiler) ===|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp||In member function 'void Father::filling()':|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp|17|error: 'class std::vector' has no member named 'getFirst'|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp|18|error: 'class std::vector' has no member named 'getSecond'|
  ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Body:
You can't call
_access_vector.getFirst()
 and
_access_vector.getSecond()
because std:vector has no such function.If you want to call this function,use this

_access_vector.at(i).getFirst();
_access_vector.at(i).getSecond();

which i is position of your object in std::vector.


问:
How to set content of a parent selection tag in Tinymce Wordpress editor
I need to select an image in wordpress visual editor to edit its url in a shortcode dialog window. It work fine and the img url is replaced as well:

```<code>var content = editor.selection.getContent();
content = content.replace(original_url, new_url);
editor.selection.setContent(content);
</code>```

But my problem is to replace also the parent selected image href> attribute with the new_url value.

The editor.selection.getContent() function return only the img tag:

```<code><img class="wp-image-1007 size-medium" src="**original_url**" width="373" height="250" />
</code>```

and not:

```<code><a href="**original_url**" target="_blank">
<img class="wp-image-1007 size-medium" src="**original_url**" width="373" height="250" />
</a>
</code>```

With jQuery i could do:

```<code>var imgsel = editor.selection.getNode();
jQuery(imgsel).parent("a").attr("href", new_url);
</code>```

but inside the editor doesn't works.
How can i replace the image link url using editor.selection.setContent() function?
Thanks

答:
Try this code , use selection.getNode();</p>

```<code>var img = editor.selection.getNode();
img.setAttribute('src' , newURL);
var parent  = editor.dom.getParent(img,'a');
parent.setAttribute('href' ,newURL);
</code>```

Body:
I need to select an image in wordpress visual editor to edit its url in a shortcode dialog window. It work fine and the img url is replaced as well:

var content = editor.selection.getContent();
content = content.replace(original_url, new_url);
editor.selection.setContent(content);

But my problem is to replace also the parent selected image  attribute with the new_url value.

The editor.selection.getContent() function return only the img tag:

and not:

With jQuery i could do:

var imgsel = editor.selection.getNode();
jQuery(imgsel).parent("a").attr("href", new_url);

but inside the editor doesn't works.
How can i replace the image link url using editor.selection.setContent() function?
Thanks

Body:
Try this code , use selection.getNode();

var img = editor.selection.getNode();
img.setAttribute('src' , newURL);
var parent  = editor.dom.getParent(img,'a');
parent.setAttribute('href' ,newURL);


问:
Return only matches from substitution in Perl 5.8.8 (was: Perl "p" regex modifier equivalent)
I've got a script (source) to parse svn info to create a suitable string for Bash's $PS1. Unfortunately this doesn't work on one system I'm using which is running Perl 5.8.8 - It outputs all lines instead of only the matches. What would be the Perl 5.8.8 equivalent to the following?

```<code>__svn_ps1()
{
    local result=$(
        svn info 2>/dev/null | \
        perl -pe 's;^URL: .*?/((trunk)|(branches|tags)/([^/]*)).*;\2\4 ;p')
    if [ -n "$result" ]
    then
        printf "${1:- (%s)}" $result
    fi
}
</code>```

The output from Perl 5.10 contains only a space, parenthesis, one of branch name, tag name or trunk, and the end parenthesis. The output from Perl 5.8.8 (without the final p) contains this plus a parenthesized version of each space-separated part of the svn info output.

A possible workaround involves a simple grep '^URL: ' between the svn and perl commands, but I was hoping to avoid that since this will be executed for each Bash prompt.

答:
As of perl 5.10, the /p switch tells perl to put matched content into ${^PREMATCH}, ${^MATCH} and ${^POSTMATCH}.

And the one-liner you've posted never uses those vars, so omit the /p.

UPDATE: Trying to keep up with the initial question...

```<code>perl -ne 's/search/replace/ and print'
</code>```

Will only print lines for which the replacement was made. Note -n versus -p switch. Also, I've tried the -p /p combo on my 5.10 and it happily prints unaltered non-matching lines too. Maybe I missed something...

Body:
I've got a script (source) to parse svn info to create a suitable string for Bash's $PS1. Unfortunately this doesn't work on one system I'm using which is running Perl 5.8.8 - It outputs all lines instead of only the matches. What would be the Perl 5.8.8 equivalent to the following?

__svn_ps1()
{
    local result=$(
        svn info 2>/dev/null | \
        perl -pe 's;^URL: .*?/((trunk)|(branches|tags)/([^/]*)).*;\2\4 ;p')
    if [ -n "$result" ]
    then
        printf "${1:- (%s)}" $result
    fi
}

The output from Perl 5.10 contains only a space, parenthesis, one of branch name, tag name or trunk, and the end parenthesis. The output from Perl 5.8.8 (without the final p) contains this plus a parenthesized version of each space-separated part of the svn info output.

A possible workaround involves a simple grep '^URL: ' between the svn and perl commands, but I was hoping to avoid that since this will be executed for each Bash prompt.

Body:
As of perl 5.10, the /p switch tells perl to put matched content into ${^PREMATCH}, ${^MATCH} and ${^POSTMATCH}.

And the one-liner you've posted never uses those vars, so omit the /p.

UPDATE: Trying to keep up with the initial question...

perl -ne 's/search/replace/ and print'

Will only print lines for which the replacement was made. Note -n versus -p switch. Also, I've tried the -p /p combo on my 5.10 and it happily prints unaltered non-matching lines too. Maybe I missed something...


答:
This should work for you

var data = [
 {
  BuildingID : "56",
  FloorId : "65",
  volume : [
   {
    one : 12,
    two : 15,
    three : 12
   }
  ]
 }
];
var MainInfo = [];
for (i = 0; i < data.length; i++) {
 var obj = {};
 obj.BuildingID = data[i].BuildingID;
 obj.FloorId = data[i].FloorId;
 Object.getOwnPropertyNames(data[i].volume[0]).forEach(function (key) {
   obj[key] = data[i].volume[0][key];
 });
 MainInfo.push(obj);
}
console.log(MainInfo);```

Title: how to push sub array object into an a array in javascript


问:
Ajax call is not working in Django?
This is my ajax call:

```<code><script>
    $(document).ready(function(){
        $("#butt2").click(function(){
            $.ajax({
                url:'{% url 'task:deletetask' %}',
                data:{'id':2 },
                type:"GET",
                success:function(text){
                    $("#task2").hide();
                    alert(text);
            }});
        });
    });

</script>
</code>```

This is my view function:

```<code>class DeleteTaskView(generic.View):
    def get(self,request):
        id = request.GET.get('id',None)
        Task.objects.get(id=id).delete()
        return JsonResponse("Task Removed")
</code>```

This is the url:

```<code>url(r'user/task/delete/$',views.DeleteTaskView.as_view(),name='deletetask'),
</code>```

If I remove the ajax call, and simply add  alert function, then it is properly working, means jquery is working, there is some problem with ajax call only. Help !

Edit: I change the url function to :

```<code>url : "{% url 'task:deletetask' %}",
</code>```

Now the item is getting deleted from database but in success response hide and alert function is not working.

答:
JsonResponse can take - by default - only a dict parameter for data.

So you should have:

```<code>return JsonResponse({'text': 'Task Removed'})
</code>```

Title: Ajax call is not working in Django?

Body:
This is my ajax call:

This is my view function:

class DeleteTaskView(generic.View):
    def get(self,request):
        id = request.GET.get('id',None)
        Task.objects.get(id=id).delete()
        return JsonResponse("Task Removed")

This is the url:

url(r'user/task/delete/$',views.DeleteTaskView.as_view(),name='deletetask'),

If I remove the ajax call, and simply add  alert function, then it is properly working, means jquery is working, there is some problem with ajax call only. Help !

Edit: I change the url function to :

url : "{% url 'task:deletetask' %}",

Now the item is getting deleted from database but in success response hide and alert function is not working.

Body:
JsonResponse can take - by default - only a dict parameter for data.

So you should have:

return JsonResponse({'text': 'Task Removed'})


问:
C++ callback to class function
I'm using the Arduino IDE and the things network arduino library to create a LoRa mote.

I have created a class which should handle all the LoRa related functions. In this class I need to handle a callback if i receive a downlink message.
The ttn library has the onMessage function which I want to setup in my init function and parse another function, which are a class member, called message.
I'm getting the error "invalid use of non-static member function".

```<code>// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>

TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);

LoRa::LoRa(){
}

void LoRa::init(){
  // Set the callback
  ttn.onMessage(this->message);
}

// Other functions

void LoRa::message(const uint8_t *payload, size_t size, port_t port)
{
  // Stuff to do when reciving a downlink
}
</code>```

and the header file

```<code>// File: LoRa.h
#ifndef LoRa_h
#define LoRa_h

#include "Arduino.h"
#include <TheThingsNetwork.h>

// Define serial interface for communication with LoRa module
#define loraSerial Serial1
#define debugSerial Serial

// define the frequency plan - EU or US. (TTN_FP_EU868 or TTN_FP_US915)
#define freqPlan TTN_FP_EU868

class LoRa{
  // const vars

  public:
    LoRa();

    void init();

    // other functions

    void message(const uint8_t *payload, size_t size, port_t port);

  private:
    // Private functions
};

#endif
</code>```

I have tried:

```<code>ttn.onMessage(this->message);
ttn.onMessage(LoRa::message);
ttn.onMessage(message);
</code>```

However none of them worked as I had expected.

答:
I Solved the problem by making the message function a normal function outside the class. Not sure if it is good practice - but it works. </p>

```<code>// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>

TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);

void message(const uint8_t *payload, size_t size, port_t port)
{
  // Stuff to do when reciving a downlink
}

LoRa::LoRa(){
}

void LoRa::init(){
  // Set the callback
  ttn.onMessage(message);
}
</code>```

Title: C++ callback to class function

Body:
I'm using the Arduino IDE and the things network arduino library to create a LoRa mote.

I have created a class which should handle all the LoRa related functions. In this class I need to handle a callback if i receive a downlink message.
The ttn library has the onMessage function which I want to setup in my init function and parse another function, which are a class member, called message.
I'm getting the error "invalid use of non-static member function".

// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>

TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);

LoRa::LoRa(){
}

void LoRa::init(){
  // Set the callback
  ttn.onMessage(this->message);
}

// Other functions

void LoRa::message(const uint8_t *payload, size_t size, port_t port)
{
  // Stuff to do when reciving a downlink
}

and the header file

// File: LoRa.h
#ifndef LoRa_h
#define LoRa_h

#include "Arduino.h"
#include <TheThingsNetwork.h>

// Define serial interface for communication with LoRa module
#define loraSerial Serial1
#define debugSerial Serial

// define the frequency plan - EU or US. (TTN_FP_EU868 or TTN_FP_US915)
#define freqPlan TTN_FP_EU868

class LoRa{
  // const vars

  public:
    LoRa();

    void init();

    // other functions

    void message(const uint8_t *payload, size_t size, port_t port);

  private:
    // Private functions
};

#endif

I have tried:

ttn.onMessage(this->message);
ttn.onMessage(LoRa::message);
ttn.onMessage(message);

However none of them worked as I had expected.

Body:
I Solved the problem by making the message function a normal function outside the class. Not sure if it is good practice - but it works.

// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>

TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);

void message(const uint8_t *payload, size_t size, port_t port)
{
  // Stuff to do when reciving a downlink
}

LoRa::LoRa(){
}

void LoRa::init(){
  // Set the callback
  ttn.onMessage(message);
}


问:
Delegate for UITextField not working...Return button not responding
I've just started with xcode and objective-c and did some very basic apps, but what i'm having problem with is very basic this. the keyboard return button not hiding the keyboard.

I've searched the internet for the solution and all they say is to connect delegate to the file's owner and add the function and it should work, i did that and nothing is working.

I have an ok button and it is working and also clicking on any free space on the screen is working, just the return button....

I am using the simulator, not testing on iphone yet. (xcode 3.2.5 64 bit with the 4.2 simulator).

This is the line of code that should connect the delegate to every textFiled.
1. i've tried already to return both YES and NO, didn't work.
2. i've tried both a specific object name for the textField and this general way, didn't work.

```<code>- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
</code>```

In the: basic view controller connection -> connections -> outlets, i have the: delegate -- File's Owner. and in the file's owner in referencing outlets there is: delegate - Round style text.....

EDIT - i forgot to mention before, i've check and the method isn't being called!!!

```<code>- (BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"Working!!!");
[textField resignFirstResponder];
return YES;
</code>```

}

what should i do to make it happen? that is why people say to connect the delegate, but in my case it is connected and not triggering the function...i know it is kind of dumb question but for a nobie like me the solution is not obvious...

OK, another Edit - with all my code: just can't understand what to do....
This is: basicViewController.h:

```<code>#import <UIKit/UIKit.h>

@interface basicViewController : <#superclass#> <UITextFieldDelegate>

@interface basicViewController : UIViewController <UITextFieldDelegate> {
//every object that we want to interact with (like text field or lable) is call an   outlet!!!!
//here we define the outlets for our program
IBOutlet UITextField *txtName;
IBOutlet UILabel *lblMessage;
 }

//here are the getters and setter for our outlets
@property (nonatomic, retain) IBOutlet UITextField *txtName;
@property (nonatomic, retain) IBOutlet UILabel *lblMessage;

//method decleration for the OK button action
- (IBAction) doSomething;

//method for hiding the keyboard when clicking on empty area in the app
   //we will put an invisible button on all area and clicking on it will make keyboard disapear
   - (IBAction) makeKeyboardGoAway;

   @end
</code>```

This is basicViewController.m:

```<code> #import "basicViewController.h"

 @implementation basicViewController

 //synthesizeing the objects that we made' this will create the getter and setters automaticly
 @synthesize txtName;
 @synthesize lblMessage;

 - (IBAction) doSomething{
// makeing keyboard disapear when pressing ok button (doing that form the text field)
//when pressing the OK button, the keyboard will disapear and when clicking in the text field it will show again
[txtName resignFirstResponder];

NSString *msg = [[NSString alloc] initWithFormat:@"Hello, %@",txtName.text];

//the objective-c way for setting the test in the text field
[lblMessage setText:msg];
//the regular object oriented way
//lblMessage.text = msg;
[msg  release];
 }

 - (IBAction) makeKeyboardGoAway{
[txtName resignFirstResponder];
 }

 //when clicking the return button in the keybaord
 - (BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"Working!!!");
[textField resignFirstResponder];
return YES;
 }

 - (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
 }

 - (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
 }

 - (void)dealloc {
     [super dealloc];
 }

 @end
</code>```

Maybe now i am more clear, sorry i didn't do it before.
Any one has an idea what am i doing wrong? it should be pretty strait forward.....

EDIT - Adding an image of all the elements, i hope that will help to help me :-)

10x a lot for every one that is trying to help....i really like this framework, it is so great after c++ and java, python and many other...and i am working with a book, but it is for ios 3.1, maybe that is the problem.....

答:
Firstly you should check if textFieldShouldReturn: is actually being called by adding an NSLog statement or breakpoint at the beginning of the method.

Once that's out of the way, try an manually declare that your view controller conforms to <UITextFieldDelegate> protocol in your interface file:

@interface YourClass : ... <UITextFieldDelegate>

Also declare a property & outlet for your UITextField, make the appropriate connections in IB and manually declare self as the UITextField delegate with:

self.yourUITextFieldObject.delegate = self;

Once that's done see if your method above is now being called and make sure you return YES.

Body:
I've just started with xcode and objective-c and did some very basic apps, but what i'm having problem with is very basic this. the keyboard return button not hiding the keyboard.

I've searched the internet for the solution and all they say is to connect delegate to the file's owner and add the function and it should work, i did that and nothing is working.

I have an ok button and it is working and also clicking on any free space on the screen is working, just the return button....

I am using the simulator, not testing on iphone yet. (xcode 3.2.5 64 bit with the 4.2 simulator).

This is the line of code that should connect the delegate to every textFiled.
1. i've tried already to return both YES and NO, didn't work.
2. i've tried both a specific object name for the textField and this general way, didn't work.

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}

In the: basic view controller connection -> connections -> outlets, i have the: delegate -- File's Owner. and in the file's owner in referencing outlets there is: delegate - Round style text.....

EDIT - i forgot to mention before, i've check and the method isn't being called!!!

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"Working!!!");
[textField resignFirstResponder];
return YES;

}

what should i do to make it happen? that is why people say to connect the delegate, but in my case it is connected and not triggering the function...i know it is kind of dumb question but for a nobie like me the solution is not obvious...

OK, another Edit - with all my code: just can't understand what to do....
This is: basicViewController.h:

#import <UIKit/UIKit.h>

@interface basicViewController : <#superclass#> <UITextFieldDelegate>

@interface basicViewController : UIViewController <UITextFieldDelegate> {
//every object that we want to interact with (like text field or lable) is call an   outlet!!!!
//here we define the outlets for our program
IBOutlet UITextField *txtName;
IBOutlet UILabel *lblMessage;
 }

//here are the getters and setter for our outlets
@property (nonatomic, retain) IBOutlet UITextField *txtName;
@property (nonatomic, retain) IBOutlet UILabel *lblMessage;

//method decleration for the OK button action
- (IBAction) doSomething;

//method for hiding the keyboard when clicking on empty area in the app
   //we will put an invisible button on all area and clicking on it will make keyboard disapear
   - (IBAction) makeKeyboardGoAway;

   @end

This is basicViewController.m:

 #import "basicViewController.h"

 @implementation basicViewController

 //synthesizeing the objects that we made' this will create the getter and setters automaticly
 @synthesize txtName;
 @synthesize lblMessage;

 - (IBAction) doSomething{
// makeing keyboard disapear when pressing ok button (doing that form the text field)
//when pressing the OK button, the keyboard will disapear and when clicking in the text field it will show again
[txtName resignFirstResponder];

NSString *msg = [[NSString alloc] initWithFormat:@"Hello, %@",txtName.text];

//the objective-c way for setting the test in the text field
[lblMessage setText:msg];
//the regular object oriented way
//lblMessage.text = msg;
[msg  release];
 }

 - (IBAction) makeKeyboardGoAway{
[txtName resignFirstResponder];
 }

 //when clicking the return button in the keybaord
 - (BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"Working!!!");
[textField resignFirstResponder];
return YES;
 }

 - (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
 }

 - (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
 }

 - (void)dealloc {
     [super dealloc];
 }

 @end

Maybe now i am more clear, sorry i didn't do it before.
Any one has an idea what am i doing wrong? it should be pretty strait forward.....

EDIT - Adding an image of all the elements, i hope that will help to help me :-)

10x a lot for every one that is trying to help....i really like this framework, it is so great after c++ and java, python and many other...and i am working with a book, but it is for ios 3.1, maybe that is the problem.....


问:
Why does the content overflow when mu content is set to 100% height
My layout has a header and footer and in between those a content div.

When I set my content height to 100% it overflows instead of expanding the div.

* {
  margin: 0;
  padding: 0;
}

body,
html {
  height: 100%;
}

.header,
.footer {
  height: 100px;
  width: 100%;
  background-color: red;
  color: white;
}

.content {
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <h1>Heading</h1>
</div>
<div class="content">
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
</div>
<div class="footer">
  <h1>Footer
    <h1>
</div></code>```

I already know the solution is to get rid of the 100% height.
But what I want to know is why does this happen. Shouldn't 100% height expand it's height to fit the parent?

Here is the fiddle for my code.

答:
Just remove height:100%.

```<code>.content {
  width: 100%;
  height: 100%;<------Remove This----------
}
</code>```

Full Code :

*{
    margin: 0;
    padding: 0;
}

body, html {
   height: 100%;
}

.header, .footer {
  height: 100px;
  width: 100%;
  background-color: red;
  color: white;
}

.content {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <h1>Heading</h1>
</div>
<div class="content">
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
</div>
<div class="footer">
  <h1>Footer
    <h1>
</div></code>```

Body:
My layout has a header and footer and in between those a content div.

When I set my content height to 100% it overflows instead of expanding the div.

* {
  margin: 0;
  padding: 0;
}

body,
html {
  height: 100%;
}

.header,
.footer {
  height: 100px;
  width: 100%;
  background-color: red;
  color: white;
}

.content {
  width: 100%;
  height: 100%;
}

Heading

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Footer

I already know the solution is to get rid of the 100% height.
But what I want to know is why does this happen. Shouldn't 100% height expand it's height to fit the parent?

Here is the fiddle for my code.

Body:
Just remove height:100%.

.content {
  width: 100%;
  height: 100%;<------Remove This----------
}

Full Code :

*{
    margin: 0;
    padding: 0;
}

body, html {
   height: 100%;
}

.header, .footer {
  height: 100px;
  width: 100%;
  background-color: red;
  color: white;
}

.content {
  width: 100%;
}

<div class="header">
  <h1>Heading</h1>
</div>
<div class="content">
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
</div>
<div class="footer">
  <h1>Footer
    <h1>
</div>


问:
C# WebApi Json Posting
I have below C# code for WEB API When I post below JSON the Account object is always null. Please, anyone can guide on below code.

```<code>public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}

public object Post([FromBody] Account account)
{
    Message msg = new Message();
    msg.status = "Status";
    return Request.CreateResponse(msg);
}
</code>```

JSON

```<code>{
  "Accounts": {
    "id": "13456454",
    "number": "222",
  }
}
</code>```

答: You are sending list of accounts from the client side but api is expecting a single object if you want to sent single object you can send single object from json file else you can change server object as List</p>

Title: C# WebApi Json Posting

Body:
I have below C# code for WEB API When I post below JSON the Account object is always null. Please, anyone can guide on below code.

public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}

public object Post([FromBody] Account account)
{
    Message msg = new Message();
    msg.status = "Status";
    return Request.CreateResponse(msg);
}

JSON

{
  "Accounts": {
    "id": "13456454",
    "number": "222",
  }
}


问:
Android imagebutton: how to remove tinted rectangle around image?
I'm developing and Android app. I have a main menu with lots of imagebuttons, each of which takes the user to a new view on click.

The problem I'm having is that surrounding each icon is a tinted rectangle that changes to a light blue colour when tapped. How do I remove this transparent square in the .xml layout file?

Many thanks in advance,

答:
You could always use the framework's

android:background="@android:color/transparent"

But for what you are trying to archive this is the better solution:

android:background="@null"


答:
You can use a function like this one:

```<code>function copyProperties(sourceObject, destinationObject)
{
    var k;
    for (k in sourceObject)
    {
       if (sourceObject.hasOwnProperty(k))
         destinationObject[k] = sourceObject[k];
    }
}
</code>```

Note that you haven't quite described what should happen if there's more than one object in the volume array.

Body:
hi all i am using javascript i am trying to push object values into one array here i attached my code

var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this

Body:
You can use a function like this one:

function copyProperties(sourceObject, destinationObject)
{
    var k;
    for (k in sourceObject)
    {
       if (sourceObject.hasOwnProperty(k))
         destinationObject[k] = sourceObject[k];
    }
}

Note that you haven't quite described what should happen if there's more than one object in the volume array.


问:
What's the equivalent of jasmine.createSpy().and.callFake(fn) in sinonjs
I'm looking for the equivalent of jasmine.createSpy().and.callFake(fn) in sinonjs.

For example:

```<code>const mySpy = jasmine.createSpy('my spy')
.and
.callFake((options) => Object.assign({}, {name: 'foo'}, options));
</code>```

答:
From what I understand from the Jasmine documentation, this should do something similar:</p>

```<code>const mySpy = sinon.spy((options) => Object.assign({}, {name: 'foo'}, options))
</code>```

Body:
I'm looking for the equivalent of jasmine.createSpy().and.callFake(fn) in sinonjs.

For example:

const mySpy = jasmine.createSpy('my spy')
.and
.callFake((options) => Object.assign({}, {name: 'foo'}, options));

Body:
From what I understand from the Jasmine documentation, this should do something similar:

const mySpy = sinon.spy((options) => Object.assign({}, {name: 'foo'}, options))


问:
How to sort dates of string?
I have an array of date as 2017-07-06,2017-06-07,2017-07-07. I want to sort these dates in ascending order. So 2017-06-07 will come first. But it is not happening at all. I am using below code for this:

```<code>func sortDates(array:NSMutableArray)->[String]  {

        var strArray:[String] = []
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"// yyyy-MM-dd"
        var convertedArray: [Date] = []
        for dat in array {
            let date = dateFormatter.date(from: dat as! String)
            convertedArray.append(date!)
        }
        let arrDates = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
        for value in arrDates {
            let formatter = DateFormatter()
            // initially set the format based on your datepicker date
            formatter.dateFormat = "yyyy-MM-dd"
            let myString = formatter.string(from: value)
            // convert your string to date
            let yourDate = formatter.date(from: myString)
            if yourDate != nil {
                //then again set the date format whhich type of output you need
                formatter.dateFormat = "yyyy-MM-dd"
                // again convert your date to string
                let myStringafd = formatter.string(from: yourDate!)
                strArray.append(myStringafd)
            }
        }
        return strArray
    }
</code>```

Please guide me where I am doing wrong ?

答:
You could create an extension to convert the string to date and then just append all your dates-objects to an array and sort that array.

Extensions:

```<code>extension String {
    var toDate: Date {
        return Date.Formatter.customDate.date(from: self)!
    }
}

extension Date {
    struct Formatter {
        static let customDate: DateFormatter = {
            let formatter = DateFormatter()
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.dateFormat = "yyyy-MM-dd"
            return formatter
        }()
    }
}
</code>```

Usage:

```<code>let d1 = "2017-01-01".toDate
let d2 = "2016-01-01".toDate
let d3 = "2018-01-01".toDate
let d4 = "2013-01-01".toDate

let convertedArray = [d1,d2, d3, d4]
let sorted = convertedArray.sorted() // note that the sort works on a string too.
print(sorted)
</code>```

Title: How to sort dates of string?

Body:
I have an array of date as 2017-07-06,2017-06-07,2017-07-07. I want to sort these dates in ascending order. So 2017-06-07 will come first. But it is not happening at all. I am using below code for this:

func sortDates(array:NSMutableArray)->[String]  {

        var strArray:[String] = []
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"// yyyy-MM-dd"
        var convertedArray: [Date] = []
        for dat in array {
            let date = dateFormatter.date(from: dat as! String)
            convertedArray.append(date!)
        }
        let arrDates = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
        for value in arrDates {
            let formatter = DateFormatter()
            // initially set the format based on your datepicker date
            formatter.dateFormat = "yyyy-MM-dd"
            let myString = formatter.string(from: value)
            // convert your string to date
            let yourDate = formatter.date(from: myString)
            if yourDate != nil {
                //then again set the date format whhich type of output you need
                formatter.dateFormat = "yyyy-MM-dd"
                // again convert your date to string
                let myStringafd = formatter.string(from: yourDate!)
                strArray.append(myStringafd)
            }
        }
        return strArray
    }

Please guide me where I am doing wrong ?

Body:
You could create an extension to convert the string to date and then just append all your dates-objects to an array and sort that array.

Extensions:

extension String {
    var toDate: Date {
        return Date.Formatter.customDate.date(from: self)!
    }
}

extension Date {
    struct Formatter {
        static let customDate: DateFormatter = {
            let formatter = DateFormatter()
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.dateFormat = "yyyy-MM-dd"
            return formatter
        }()
    }
}

Usage:

let d1 = "2017-01-01".toDate
let d2 = "2016-01-01".toDate
let d3 = "2018-01-01".toDate
let d4 = "2013-01-01".toDate

let convertedArray = [d1,d2, d3, d4]
let sorted = convertedArray.sorted() // note that the sort works on a string too.
print(sorted)


问:
React how to pass an state to another component
Hello i split my app and would like to pass the state from my <button />
to <menu />   I'm simply trying to do is toggle a function with an onClick.

So the Button.js file will have 1 buttons when clicked will toggle the states to visible or invisible. The menu  component Menu.js will need know about these state changes so they can toggle the function and will show the menu

Button component

```<code>import React, { PureComponent } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { themr } from 'react-css-themr';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import localStyles from './NavButton.scss';

@themr('NavButton', localStyles)

export default class NavButton extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
    this.toggleMenu = this.toggleMenu.bind(this);
  }

  toggleMenu() {
    this.setState({
      visible: !this.state.visible
    })
    console.log('toggle');
  }

  render() {

    const {theme } = this.props;
    return (
      <div className={theme['nav-button']} onClick={this.toggleMenu}>
      <span></span>
      <span></span>
      </div>
    );
  }
}
</code>```

Menu

```<code>import React, { PureComponent } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { themr } from 'react-css-themr';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import localStyles from './Menu.scss';
import { NavButton } from '../../components';

@themr('Menu', localStyles)

export default class Menu extends React.Component {

  render() {

    return (

      <div className="menu-wrapper">
      <CSSTransitionGroup
        transitionName="menu"
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}>
        {this.state.visible &&
        <Menus alignment="right">
          <MenuItem hash="first-page">First Page</MenuItem>
          <MenuItem hash="second-page">Second Page</MenuItem>
          <MenuItem hash="third-page">Third Page</MenuItem>
        </Menus>}
        </CSSTransitionGroup>
      </div>
    );
  }
}
const Menus = ({alignment, children, theme }) => (
  <div className="menu">
  <div className={alignment}>{children}</div>
  </div>
);
</code>```

答:
Although you have imported Button component to Menu, you are not using it, Also what you should do is keep the state visible in the menu component and communicate to Menu from Button component like

```<code>export default class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
    this.toggleMenu = this.toggleMenu.bind(this);
  }
  toggleMenu() {
    this.setState({
      visible: !this.state.visible
    })
    console.log('toggle');
  }
  render() {

    return (
      <NavButton toggleMenu={this.toggleMenu}/>
      <div className="menu-wrapper">
      <CSSTransitionGroup
        transitionName="menu"
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}>
        {this.state.visible &&
        <Menus alignment="right">
          <MenuItem hash="first-page">First Page</MenuItem>
          <MenuItem hash="second-page">Second Page</MenuItem>
          <MenuItem hash="third-page">Third Page</MenuItem>
        </Menus>}
        </CSSTransitionGroup>
      </div>
    );
  }
}
const Menus = ({alignment, children, theme }) => (
  <div className="menu">
  <div className={alignment}>{children}</div>
  </div>
);
</code>```

Now you NavButton will be like

```<code>export default class NavButton extends React.Component {

  render() {

    const {theme } = this.props;
    return (
      <div className={theme['nav-button']} onClick={this.props.toggleMenu}>
      <span></span>
      <span></span>
      </div>
    );
  }
}
</code>```

Body:
Hello i split my app and would like to pass the state from my <button />
to <menu />   I'm simply trying to do is toggle a function with an onClick.

So the Button.js file will have 1 buttons when clicked will toggle the states to visible or invisible. The menu  component Menu.js will need know about these state changes so they can toggle the function and will show the menu

Button component

import React, { PureComponent } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { themr } from 'react-css-themr';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import localStyles from './NavButton.scss';

@themr('NavButton', localStyles)

export default class NavButton extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
    this.toggleMenu = this.toggleMenu.bind(this);
  }

  toggleMenu() {
    this.setState({
      visible: !this.state.visible
    })
    console.log('toggle');
  }

  render() {

    const {theme } = this.props;
    return (

    );
  }
}

Menu

import React, { PureComponent } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { themr } from 'react-css-themr';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import localStyles from './Menu.scss';
import { NavButton } from '../../components';

@themr('Menu', localStyles)

export default class Menu extends React.Component {

  render() {

    return (

      <CSSTransitionGroup
        transitionName="menu"
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}>
        {this.state.visible &&
        <Menus alignment="right">
          <MenuItem hash="first-page">First Page</MenuItem>
          <MenuItem hash="second-page">Second Page</MenuItem>
          <MenuItem hash="third-page">Third Page</MenuItem>
        </Menus>}
        </CSSTransitionGroup>

    );
  }
}
const Menus = ({alignment, children, theme }) => (

{children}

);

Body:
Although you have imported Button component to Menu, you are not using it, Also what you should do is keep the state visible in the menu component and communicate to Menu from Button component like

export default class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
    this.toggleMenu = this.toggleMenu.bind(this);
  }
  toggleMenu() {
    this.setState({
      visible: !this.state.visible
    })
    console.log('toggle');
  }
  render() {

    return (
      <NavButton toggleMenu={this.toggleMenu}/>
      <div className="menu-wrapper">
      <CSSTransitionGroup
        transitionName="menu"
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}>
        {this.state.visible &&
        <Menus alignment="right">
          <MenuItem hash="first-page">First Page</MenuItem>
          <MenuItem hash="second-page">Second Page</MenuItem>
          <MenuItem hash="third-page">Third Page</MenuItem>
        </Menus>}
        </CSSTransitionGroup>
      </div>
    );
  }
}
const Menus = ({alignment, children, theme }) => (
  <div className="menu">
  <div className={alignment}>{children}</div>
  </div>
);

Now you NavButton will be like

export default class NavButton extends React.Component {

  render() {

    const {theme } = this.props;
    return (
      <div className={theme['nav-button']} onClick={this.props.toggleMenu}>
      <span></span>
      <span></span>
      </div>
    );
  }
}


问:
db.get doesn't work if I call it the first time, typescript
I have a strange problem:
I have a simple function to get the user information from my DB in myData.ts.

```<code>test = <any>{};

  getUserInfoFromPouch(filter: string):any{

    this.db.get(filter).then((result) => {
      this.test = result;
    })
    return this.test;
  }
</code>```

and it works ... kinda.

I call the function in my user-data-page constructor:

```<code>this.userData = this.myData.getUserInfoFromPouch(this.userId);
console.log('------------------t1----------------------------------');
console.log(this.userData);
console.log('------------------t2----------------------------------');
console.log(this.myData.test);
</code>```

but I only get an ampty object back:

```<code>------------------t1----------------------------------  main.js:62736:9
Object {  }  main.js:62737:9
------------------t2----------------------------------  main.js:62738:9
Object {  }
</code>```

If I call the function again via a button, I get the actual output I would expect.
If I don't call the function in the constructor first, I have to use the button twice to get the data.
That is very confusing.
I tried many different function spellings like:

```<code>test = <any>{};

      getUserInfoFromPouch(filter: string):any{

        return this.db.get(filter).then((result) => {
        })
      }
</code>```

or

```<code>test = <any>{};

      getUserInfoFromPouch(filter: string):any{

        this.db.get(filter).then((result) => {
        return result;
      })
      }
</code>```

What am I doing wrong?
Thank you for help.

Btw. I Have only one record in the database. (for test purposes)

Edit:
Okay, I tried the function like this:

```<code>async getUserInfoFromPouch(_id: string){

    try {
      this.test = await this.db.get(_id);
    } catch (err) {
      console.log(err);
    }
    console.log('------------------t3----------------------------------');
    console.log(this.test);

  }
</code>```

and I call the function in the constructor of my user page, like before.
After I called the function, I fill my userdata with the test var from the function:

```<code>    this.myData.getUserInfoFromPouch("userinfo");
    this.userData = this.myData.test;
    console.log('------------------t1----------------------------------');
    console.log(this.userData);
</code>```

but the userData is empty. And I get the console.output of the function AFTER I did:

```<code>this.userData = this.myData.test;
</code>```

I'm doing something pretty wrong ;-(

答:
Okay, it solved the problem with promises.

```<code> this.myData.getDocumentById('userInfo').then(res=>{
      if (res!=undefined){
        this.userData=res;
      }
    }).catch(err=>{
      console.log('userInfo-error:  ', err)
    });
</code>```

Now it works as it should
my getDocumentById function locks like this:

```<code> getDocumentById(id: string):any {
    this.syncTwoWay();
    return this.db.get(id).then((doc) => {
      return doc;
    }).catch((err) => {
      console.log('getDocumentById' + err);
    });
  }
</code>```

Body:
I have a strange problem:
I have a simple function to get the user information from my DB in myData.ts.

test = <any>{};

  getUserInfoFromPouch(filter: string):any{

    this.db.get(filter).then((result) => {
      this.test = result;
    })
    return this.test;
  }

and it works ... kinda.

I call the function in my user-data-page constructor:

this.userData = this.myData.getUserInfoFromPouch(this.userId);
console.log('------------------t1----------------------------------');
console.log(this.userData);
console.log('------------------t2----------------------------------');
console.log(this.myData.test);

but I only get an ampty object back:

------------------t1----------------------------------  main.js:62736:9
Object {  }  main.js:62737:9
------------------t2----------------------------------  main.js:62738:9
Object {  }

If I call the function again via a button, I get the actual output I would expect.
If I don't call the function in the constructor first, I have to use the button twice to get the data.
That is very confusing.
I tried many different function spellings like:

test = <any>{};

      getUserInfoFromPouch(filter: string):any{

        return this.db.get(filter).then((result) => {
        })
      }

or

test = <any>{};

      getUserInfoFromPouch(filter: string):any{

        this.db.get(filter).then((result) => {
        return result;
      })
      }

What am I doing wrong?
Thank you for help.

Btw. I Have only one record in the database. (for test purposes)

Edit:
Okay, I tried the function like this:

async getUserInfoFromPouch(_id: string){

    try {
      this.test = await this.db.get(_id);
    } catch (err) {
      console.log(err);
    }
    console.log('------------------t3----------------------------------');
    console.log(this.test);

  }

and I call the function in the constructor of my user page, like before.
After I called the function, I fill my userdata with the test var from the function:

    this.myData.getUserInfoFromPouch("userinfo");
    this.userData = this.myData.test;
    console.log('------------------t1----------------------------------');
    console.log(this.userData);

but the userData is empty. And I get the console.output of the function AFTER I did:

this.userData = this.myData.test;

I'm doing something pretty wrong ;-(

Body:
Okay, it solved the problem with promises.

 this.myData.getDocumentById('userInfo').then(res=>{
      if (res!=undefined){
        this.userData=res;
      }
    }).catch(err=>{
      console.log('userInfo-error:  ', err)
    });

Now it works as it should
my getDocumentById function locks like this:

 getDocumentById(id: string):any {
    this.syncTwoWay();
    return this.db.get(id).then((doc) => {
      return doc;
    }).catch((err) => {
      console.log('getDocumentById' + err);
    });
  }


问:
Project Layout with regards to Exrin and Databases
What is the preferred solution for Exrin project layout when adding a database?

The sample Tesla app had a separate project for the Services and another separate app for the Repository. With the removal of both of those projects in the latest template, it makes the most sense for it to go within the Logic project, but I'm curious if the author had a different preferred implementation.

答:
The Tesla Sample project is designed for a very large app, and Service and Repository don't need to be separated out into a separate project, they can all be referenced directly in the logic app, as per this diagram.

This is the project setup, I now recommend for most projects.


问:
@Asyn annotation with Spring
I am trying to use @Async annotation provided by spring. Going through some of the blogs I found there are the following constraints for using it:

It must be applied to public methods only

Self-invocation – calling the async method from within the same class – won’t work

I have a method which is getting called from the same class which I want to mark @Async. Is there any way of achieving it from the same class?

答:
In Spring v4.3+ you can use self injection, and call the method on the self injected reference.

So for example:

```<code>@Component
public class SomeClass {
    @Autowired
    private SomeClass selfInjected;

    public void someMethod() {
       selfInjected.someOtherMethod();
    }

    @Async
    public void someOtherMethod(){
      ...;
    }
}
</code>```

Updated as OP is using version before 4.3:

This will work for you.

```<code>@Component
public class SomeClass {

    @Autowired
    private ApplicationContext applicationContext;

    private SomeClass selfInjected;

    @PostConstruct
    private void init() {
        selfInjected = applicationContext.getBean(SomeClass.class);
    }
}
</code>```

Or

The other option is to extract the method to separate class and autowire it. I would personally explore this option before doing the above method.

Title: @Asyn annotation with Spring

Body:
In Spring v4.3+ you can use self injection, and call the method on the self injected reference.

So for example:

@Component
public class SomeClass {
    @Autowired
    private SomeClass selfInjected;

    public void someMethod() {
       selfInjected.someOtherMethod();
    }

    @Async
    public void someOtherMethod(){
      ...;
    }
}

Updated as OP is using version before 4.3:

This will work for you.

@Component
public class SomeClass {

    @Autowired
    private ApplicationContext applicationContext;

    private SomeClass selfInjected;

    @PostConstruct
    private void init() {
        selfInjected = applicationContext.getBean(SomeClass.class);
    }
}

Or

The other option is to extract the method to separate class and autowire it. I would personally explore this option before doing the above method.