问:
My web2py application cannot find a file on pythonanywhere
My web2py application cannot find a file on pythonanywhere.

Controller:

```<code>def RA_download():
    import os
    path = os.path.join(request.folder,"uploads","ra.txt")
    return dict(path=path)
</code>```

View

```<code><a href="{{=path}}" download>Download ra.txt</a>

{{=BEAUTIFY(response._vars)}}
</code>```

The file exists

But when I click on the link. it says "no file"

Here is the link to the application

http://speakertgorobots.pythonanywhere.com/MCEdit/default/RA_download

答:
web2py does not serve files by specifying the operating system filepath as the URL. Rather, you must either put the file in the application's /static folder (and generate a URL relative to that folder) or serve the file via a controller.

If you place the file in the root of the /static folder, the link would look like this:

```<code><a href="{{=URL('static', 'ra.txt')}}" download>Download ra.txt</a>
</code>```

If you want to leave the file in the /uploads folder (or some other location), you need to create a controller to serve it. For example:

```<code>import os
def serve_ra_file():
    return response.stream(os.path.join(request.folder, 'ra.txt'), attachment=True)
</code>```

and the link would be:

```<code><a href="{{=URL('default', 'serve_ra_file')}}" download>Download ra.txt</a>
</code>```

Body:
My web2py application cannot find a file on pythonanywhere.

Controller:

def RA_download():
    import os
    path = os.path.join(request.folder,"uploads","ra.txt")
    return dict(path=path)

View

Download ra.txt

{{=BEAUTIFY(response._vars)}}

The file exists

But when I click on the link. it says "no file"

Here is the link to the application

http://speakertgorobots.pythonanywhere.com/MCEdit/default/RA_download

Body:
web2py does not serve files by specifying the operating system filepath as the URL. Rather, you must either put the file in the application's /static folder (and generate a URL relative to that folder) or serve the file via a controller.

If you place the file in the root of the /static folder, the link would look like this:

<a href="{{=URL('static', 'ra.txt')}}" download>Download ra.txt</a>

If you want to leave the file in the /uploads folder (or some other location), you need to create a controller to serve it. For example:

import os
def serve_ra_file():
    return response.stream(os.path.join(request.folder, 'ra.txt'), attachment=True)

and the link would be:

<a href="{{=URL('default', 'serve_ra_file')}}" download>Download ra.txt</a>


来源: stackexchange

问:
Layerslider 6 Callback Events
I checked the documentation on callbacks here: https://layerslider.kreaturamedia.com/documentation/ but  it says that I should use the events on the sitebuilder. (Which I cannot access since I have the jQuery version of the plugin).
I only want an example on how should I use callbacks on the jQuery version.

I've been trying stuff like this with no sucess:

```<code>$('#layerslider').layerSlider({
autoStart: true,
firstSlide: 1,
skin: 'borderlesslight',
showCircleTimer: false,
slideChangeDidStart: function(element) {
    console.log('function called');
}
</code>```

});

Any help would be appreciated.

答:
They are relying on jQuery's event handling functions, so they are fully compatible. You should use the .on() function for bind events.</p>

```

    // Binding event
    $('#slider').on('slideChangeDidStart', function(event, slider) {
        // Your code ...
    });

    // Initializing the slider
    $('#slider').layerSlider({
        // Your settings ...
    });

```

ContentLicense: CC BY-SA 3.0

Title: Layerslider 6 Callback Events

Body:
I checked the documentation on callbacks here: https://layerslider.kreaturamedia.com/documentation/ but  it says that I should use the events on the sitebuilder. (Which I cannot access since I have the jQuery version of the plugin).
I only want an example on how should I use callbacks on the jQuery version.

I've been trying stuff like this with no sucess:

$('#layerslider').layerSlider({
autoStart: true,
firstSlide: 1,
skin: 'borderlesslight',
showCircleTimer: false,
slideChangeDidStart: function(element) {
    console.log('function called');
}

});

Any help would be appreciated.

Body:
They are relying on jQuery's event handling functions, so they are fully compatible. You should use the .on() function for bind events.

    // Binding event
    $('#slider').on('slideChangeDidStart', function(event, slider) {
        // Your code ...
    });

    // Initializing the slider
    $('#slider').layerSlider({
        // Your settings ...
    });


问:
SQLite: Selecting all rows with IDs from one table that match IDs in a different table
I have two tables. Both have an ID column.

I want to select all rows in Table A that have an ID that matches an ID in Table b.

Is there a straightforward way to do this?

答:
This can be done with a subquery:</p>

```<code>SELECT *
FROM TableA
WHERE ID IN (SELECT ID
             FROM TableB);
</code>```

Body:
This can be done with a subquery:

SELECT *
FROM TableA
WHERE ID IN (SELECT ID
             FROM TableB);


问:
stop button activity if function returns false
I have a onclick button and a function to check if email is valid.
If it is not valid it will return false.

What I want is a way to stop the button action if it is false.

Is there a way, like die(); in php to stop button action if boolean is false?

```<code>register.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                Boolean valid_email = isValidEmail(email);

//how can I stop the onclick if boolean is false?

                Response.Listener<String> responseListener = new Response.Listener<String>(){

                    @Override
                    public void onResponse(String response){
                        try {
...
</code>```

答:
```<code>If (validemail){
     //Add your response call here .I.e make server call here
}else{
  //Do nothing will be fine
   }
</code>```

Body:
I have a onclick button and a function to check if email is valid.
If it is not valid it will return false.

What I want is a way to stop the button action if it is false.

Is there a way, like die(); in php to stop button action if boolean is false?

register.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                Boolean valid_email = isValidEmail(email);

//how can I stop the onclick if boolean is false?

                Response.Listener<String> responseListener = new Response.Listener<String>(){

                    @Override
                    public void onResponse(String response){
                        try {
...


问:
Count registers by day including zero
I have a table in a SQL Server database containing a register of each time a user downloads an image from my app so my table TBL_Downloads has the following structure:

```<code>UserID|  ImageID  | DownloadDate              |
------+-----------+---------------------------+
  292 |    782    |  02-01-2016 14:20:22.737  |
  292 |    783    |  02-01-2016 14:20:22.737  |
  292 |    784    |  02-02-2016 14:20:22.737  |
  292 |    785    |  02-04-2016 14:20:22.737  |
  292 |    786    |  02-05-2016 14:20:22.737  |
  292 |    787    |  02-06-2016 14:20:22.737  |
</code>```

In table there are shown only registers for 1 specific user even when there are several just to simplify the example.

What I would like to have is a result table containing the number of downloads made BY DAY in the last 30 days for a specific user including a zero for the days in which there was no download. I currently have the following query:

```<code>SELECT COUNT(*) AS Downloads
FROM TBL_Downloads
WHERE DownloadDate BETWEEN DATEADD(day, -30, GETDATE()) AND GETDATE()
  AND IdUser = 292
GROUP BY CAST(DownloadDate AS DATE)
</code>```

This returns a table with the sum, but only for days for which there is at least one entry of a download.

Do you have any idea how can I solve this?

答:
You can use a Calendar or dates table for this sort of thing.

For only 152kb in memory, you can have 30 years of dates in a table with this:

```<code>/* dates table */
declare @fromdate date = '20000101';
declare @years    int  = 30;
/* 30 years, 19 used data pages ~152kb in memory, ~264kb on disk */
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
select top (datediff(day, @fromdate,dateadd(year,@years,@fromdate)))
    [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
into dbo.Dates
from n as deka cross join n as hecto cross join n as kilo
               cross join n as tenK cross join n as hundredK
order by [Date];
create unique clustered index ix_dbo_Dates_date
  on dbo.Dates([Date]);
</code>```

Without taking the actual step of creating a table, you can use it inside a common table expression with just this:

```<code>declare @fromdate date = dateadd(day  , datediff(day  , 0, getdate() )-30 , 0);
declare @thrudate date = dateadd(day  , datediff(day  , 0, getdate() ), 0);
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1)
      [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
  from n as deka cross join n as hecto cross join n as kilo
                cross join n as tenK cross join n as hundredK
   order by [Date]
)
select [Date]
from dates;
</code>```

Use either like so:

```<code>select
    d.Date
  , count(t.DownloadDate) as DownloadCount
from dates d
  left join TBL_Downloads t
    on d.date = convert(date,t.DownloadDate)
   and t.userid = 292
where d.date >= dateadd(day  , datediff(day  , 0, getdate() )-30 , 0)
  and d.date <= dateadd(day  , datediff(day  , 0, getdate() ), 0)
group by d.date
</code>```

rextester demo: http://rextester.com/ISK37732 (dates changed to be within last 30 days)

returns:

```<code>+------------+---------------+
|    Date    | DownloadCount |
+------------+---------------+
| 2017-02-27 |             0 |
| 2017-02-28 |             0 |
| 2017-03-01 |             2 |
| 2017-03-02 |             1 |
| 2017-03-03 |             0 |
| 2017-03-04 |             1 |
| 2017-03-05 |             1 |
| 2017-03-06 |             1 |
| 2017-03-07 |             0 |
| 2017-03-08 |             0 |
| 2017-03-09 |             0 |
| 2017-03-10 |             0 |
| 2017-03-11 |             0 |
| 2017-03-12 |             0 |
| 2017-03-13 |             0 |
| 2017-03-14 |             0 |
| 2017-03-15 |             0 |
| 2017-03-16 |             0 |
| 2017-03-17 |             0 |
| 2017-03-18 |             0 |
| 2017-03-19 |             0 |
| 2017-03-20 |             0 |
| 2017-03-21 |             0 |
| 2017-03-22 |             0 |
| 2017-03-23 |             0 |
| 2017-03-24 |             0 |
| 2017-03-25 |             0 |
| 2017-03-26 |             0 |
| 2017-03-27 |             0 |
| 2017-03-28 |             0 |
| 2017-03-29 |             0 |
+------------+---------------+
</code>```

Number and Calendar table reference:

Generate a set or sequence without loops - 1 - Aaron Bertrand

Generate a set or sequence without loops - 2 - Aaron Bertrand

Generate a set or sequence without loops - 3 - Aaron Bertrand

The "Numbers" or "Tally" Table: What it is and how it replaces a loop - Jeff Moden

Creating a Date Table/Dimension in sql Server 2008 - David Stein

Calendar Tables - Why You Need One - David Stein

Creating a date dimension or calendar table in sql Server - Aaron Bertrand

tsql Function to Determine Holidays in sql Server - Aaron Bertrand

F_table_date - Michael Valentine Jones

Title: Count registers by day including zero

Body:
I have a table in a SQL Server database containing a register of each time a user downloads an image from my app so my table TBL_Downloads has the following structure:

UserID|  ImageID  | DownloadDate              |
------+-----------+---------------------------+
  292 |    782    |  02-01-2016 14:20:22.737  |
  292 |    783    |  02-01-2016 14:20:22.737  |
  292 |    784    |  02-02-2016 14:20:22.737  |
  292 |    785    |  02-04-2016 14:20:22.737  |
  292 |    786    |  02-05-2016 14:20:22.737  |
  292 |    787    |  02-06-2016 14:20:22.737  |

In table there are shown only registers for 1 specific user even when there are several just to simplify the example.

What I would like to have is a result table containing the number of downloads made BY DAY in the last 30 days for a specific user including a zero for the days in which there was no download. I currently have the following query:

SELECT COUNT(*) AS Downloads
FROM TBL_Downloads
WHERE DownloadDate BETWEEN DATEADD(day, -30, GETDATE()) AND GETDATE()
  AND IdUser = 292
GROUP BY CAST(DownloadDate AS DATE)

This returns a table with the sum, but only for days for which there is at least one entry of a download.

Do you have any idea how can I solve this?

Body:
You can use a Calendar or dates table for this sort of thing.

For only 152kb in memory, you can have 30 years of dates in a table with this:

/* dates table */
declare @fromdate date = '20000101';
declare @years    int  = 30;
/* 30 years, 19 used data pages ~152kb in memory, ~264kb on disk */
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
select top (datediff(day, @fromdate,dateadd(year,@years,@fromdate)))
    [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
into dbo.Dates
from n as deka cross join n as hecto cross join n as kilo
               cross join n as tenK cross join n as hundredK
order by [Date];
create unique clustered index ix_dbo_Dates_date
  on dbo.Dates([Date]);

Without taking the actual step of creating a table, you can use it inside a common table expression with just this:

declare @fromdate date = dateadd(day  , datediff(day  , 0, getdate() )-30 , 0);
declare @thrudate date = dateadd(day  , datediff(day  , 0, getdate() ), 0);
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1)
      [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
  from n as deka cross join n as hecto cross join n as kilo
                cross join n as tenK cross join n as hundredK
   order by [Date]
)
select [Date]
from dates;

Use either like so:

select
    d.Date
  , count(t.DownloadDate) as DownloadCount
from dates d
  left join TBL_Downloads t
    on d.date = convert(date,t.DownloadDate)
   and t.userid = 292
where d.date >= dateadd(day  , datediff(day  , 0, getdate() )-30 , 0)
  and d.date <= dateadd(day  , datediff(day  , 0, getdate() ), 0)
group by d.date

rextester demo: http://rextester.com/ISK37732 (dates changed to be within last 30 days)

returns:

+------------+---------------+
|    Date    | DownloadCount |
+------------+---------------+
| 2017-02-27 |             0 |
| 2017-02-28 |             0 |
| 2017-03-01 |             2 |
| 2017-03-02 |             1 |
| 2017-03-03 |             0 |
| 2017-03-04 |             1 |
| 2017-03-05 |             1 |
| 2017-03-06 |             1 |
| 2017-03-07 |             0 |
| 2017-03-08 |             0 |
| 2017-03-09 |             0 |
| 2017-03-10 |             0 |
| 2017-03-11 |             0 |
| 2017-03-12 |             0 |
| 2017-03-13 |             0 |
| 2017-03-14 |             0 |
| 2017-03-15 |             0 |
| 2017-03-16 |             0 |
| 2017-03-17 |             0 |
| 2017-03-18 |             0 |
| 2017-03-19 |             0 |
| 2017-03-20 |             0 |
| 2017-03-21 |             0 |
| 2017-03-22 |             0 |
| 2017-03-23 |             0 |
| 2017-03-24 |             0 |
| 2017-03-25 |             0 |
| 2017-03-26 |             0 |
| 2017-03-27 |             0 |
| 2017-03-28 |             0 |
| 2017-03-29 |             0 |
+------------+---------------+

Number and Calendar table reference:

Generate a set or sequence without loops - 1 - Aaron Bertrand

Generate a set or sequence without loops - 2 - Aaron Bertrand

Generate a set or sequence without loops - 3 - Aaron Bertrand

The "Numbers" or "Tally" Table: What it is and how it replaces a loop - Jeff Moden

Creating a Date Table/Dimension in sql Server 2008 - David Stein

Calendar Tables - Why You Need One - David Stein

Creating a date dimension or calendar table in sql Server - Aaron Bertrand

tsql Function to Determine Holidays in sql Server - Aaron Bertrand

F_table_date - Michael Valentine Jones


问:
Is this query returning a reference to a cursor?
I have a doubt about how a function returns a reference to a cursor in PostgreSQL. I have the following query :

```<code>CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
BEGIN
    OPEN $1 FOR SELECT col FROM test;
    RETURN $1;
END;
' LANGUAGE plpgsql;

BEGIN;
SELECT reffunc('funccursor');
FETCH ALL IN funccursor;
COMMIT;
</code>```

Does this function return a reference to a cursor ? If not, how can I modify it to return a reference to a cursor ?

答:
A refcursor variable contains the name of a cursor, a data structure that holds the active query.

See the documentation.

So yes, it is a reference to a cursor.

Body:
I have a doubt about how a function returns a reference to a cursor in PostgreSQL. I have the following query :

CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
BEGIN
    OPEN $1 FOR SELECT col FROM test;
    RETURN $1;
END;
' LANGUAGE plpgsql;

BEGIN;
SELECT reffunc('funccursor');
FETCH ALL IN funccursor;
COMMIT;

Does this function return a reference to a cursor ? If not, how can I modify it to return a reference to a cursor ?


问:
Dynamically creating table in Javascript
I'm asking you for help with DOM table in JS. When I click buttons table will be creating automagically with example texts. I want to write a few functions for create table tag, thead, border and align center, caption, data (rows and cells with text), tfoot, deleting row, adding row.

I don't know how to do it.

答:
Here's an example to get you started, you'll have to add the rest of the features yourself.

// get the first button by it's ID, and listen to the click event
// add an empty table to the container div
document.getElementById("btnTable").addEventListener("click", function(){
 var basicTable = '

';
  document.getElementById('container').innerHTML = basicTable;
});

// add contents to the table, ADD instead of REPLACE by using the += operator
document.getElementById("btnTableContentsAdd").addEventListener("click", function(){
 var tableContents = '
Hello world!
';
  document.getElementById('table').innerHTML += tableContents;
});

// remove last table row
document.getElementById("btnTableContentsRemove").addEventListener("click", function(){
  var lastRow = document.getElementById('table').lastElementChild;
  document.getElementById('table').removeChild(lastRow);
});

// set the border to 1px solid blue
document.getElementById("btnTableBlueBorder").addEventListener("click", function(){
 document.getElementById('table').style.border = "1px solid blue";
});

// set the border to 1px solid red
document.getElementById("btnTableRedBorder").addEventListener("click", function(){
 document.getElementById('table').style.border = "1px solid red";
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="btnTable">add empty table (invisible)</button>
<button id="btnTableContentsAdd">add table contents</button>
<button id="btnTableContentsRemove">remove table contents</button>
<button id="btnTableBlueBorder">add blue table border</button>
<button id="btnTableRedBorder">add red table border</button>
<div id="container"></div></code>```

Body:
Here's an example to get you started, you'll have to add the rest of the features yourself.

// get the first button by it's ID, and listen to the click event
// add an empty table to the container div
document.getElementById("btnTable").addEventListener("click", function(){
 var basicTable = '<table id="table"></table>';
  document.getElementById('container').innerHTML = basicTable;
});

// add contents to the table, ADD instead of REPLACE by using the += operator
document.getElementById("btnTableContentsAdd").addEventListener("click", function(){
 var tableContents = '<tr><td>Hello world!</td></tr>';
  document.getElementById('table').innerHTML += tableContents;
});

// remove last table row
document.getElementById("btnTableContentsRemove").addEventListener("click", function(){
  var lastRow = document.getElementById('table').lastElementChild;
  document.getElementById('table').removeChild(lastRow);
});

// set the border to 1px solid blue
document.getElementById("btnTableBlueBorder").addEventListener("click", function(){
 document.getElementById('table').style.border = "1px solid blue";
});

// set the border to 1px solid red
document.getElementById("btnTableRedBorder").addEventListener("click", function(){
 document.getElementById('table').style.border = "1px solid red";
});

<button id="btnTable">add empty table (invisible)</button>
<button id="btnTableContentsAdd">add table contents</button>
<button id="btnTableContentsRemove">remove table contents</button>
<button id="btnTableBlueBorder">add blue table border</button>
<button id="btnTableRedBorder">add red table border</button>
<div id="container"></div>


问:
Powerpoint VBA dont close Excel
My VBA code in Powerpoint wont "kill" my excel application.
it still runs if i have a look in task manager.

I would like to close it the right way rather than kill.

Anyone that could help me? I already searched and tried to get it working but with no luck.

```<code>Public Sub OnSlideShowPageChange(ByVal Wn As SlideShowWindow)
If Wn.View.CurrentShowPosition = 2 Then

    Dim xlApp As Object
    Dim xlWorkBook As Object

    Set xlApp = CreateObject("Excel.Application")
    xlApp.Visible = False
    Set xlWorkBook = xlApp.Workbooks.Open("D:\ELE_powerpoint\book1.xlsx", True, False)

    With xlWorkBook.ActiveSheet
    txt1 = xlWorkBook.sheets(1).Range("A2")
    txt2 = xlWorkBook.sheets(1).Range("A3")
    txt3 = xlWorkBook.sheets(1).Range("A4")
    End With

    ActivePresentation.Slides(2).Shapes("a2").TextFrame.TextRange = txt1
    ActivePresentation.Slides(2).Shapes("a3").TextFrame.TextRange = txt2
    ActivePresentation.Slides(2).Shapes("a4").TextFrame.TextRange = txt3

    Set xlApp = Nothing
    Set xlWorkBook = Nothing

End If
End Sub
</code>```

答: Try xlApp.Quit before Set xlApp = Nothing

Title: Powerpoint VBA dont close Excel

Body:
My VBA code in Powerpoint wont "kill" my excel application.
it still runs if i have a look in task manager.

I would like to close it the right way rather than kill.

Anyone that could help me? I already searched and tried to get it working but with no luck.

Public Sub OnSlideShowPageChange(ByVal Wn As SlideShowWindow)
If Wn.View.CurrentShowPosition = 2 Then

    Dim xlApp As Object
    Dim xlWorkBook As Object

    Set xlApp = CreateObject("Excel.Application")
    xlApp.Visible = False
    Set xlWorkBook = xlApp.Workbooks.Open("D:\ELE_powerpoint\book1.xlsx", True, False)

    With xlWorkBook.ActiveSheet
    txt1 = xlWorkBook.sheets(1).Range("A2")
    txt2 = xlWorkBook.sheets(1).Range("A3")
    txt3 = xlWorkBook.sheets(1).Range("A4")
    End With

    ActivePresentation.Slides(2).Shapes("a2").TextFrame.TextRange = txt1
    ActivePresentation.Slides(2).Shapes("a3").TextFrame.TextRange = txt2
    ActivePresentation.Slides(2).Shapes("a4").TextFrame.TextRange = txt3

    Set xlApp = Nothing
    Set xlWorkBook = Nothing

End If
End Sub


问:
First time user used Facebook App
How can I tell if its the user's first time that he/she is using my facebook application. I want to do some initialisations for the user but only for the first time. </p>

答:
```<code>FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    // the user is logged in and has authenticated your
    // app, and response.authResponse supplies
    // the user's ID, a valid access token, a signed
    // request, and the time the access token
    // and signed request each expire
    var uid = response.authResponse.userID;
    var accessToken = response.authResponse.accessToken;
  } else if (response.status === 'not_authorized') {
    // the user is logged in to Facebook,
    // but has not authenticated your app
  } else {
    // the user isn't logged in to Facebook.
  }
 });
</code>```

https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus

Title: First time user used Facebook App

Body:
FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    // the user is logged in and has authenticated your
    // app, and response.authResponse supplies
    // the user's ID, a valid access token, a signed
    // request, and the time the access token
    // and signed request each expire
    var uid = response.authResponse.userID;
    var accessToken = response.authResponse.accessToken;
  } else if (response.status === 'not_authorized') {
    // the user is logged in to Facebook,
    // but has not authenticated your app
  } else {
    // the user isn't logged in to Facebook.
  }
 });

https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus


问:
Validate phone number using angular js
Want to set phone-number to 10 digits, How can I do this using Angular js.

This is what I have tried:

<form class="form-horizontal" role="form" method="post" name="registration" novalidate>

    Phone :

      <input type="number"
             class="form-control"
             ng-minlength="10"
             ng-maxlength="10"
             id="inputPhone"
             name="phone"
             placeholder="Phone"
             ng-model="user.phone"
             ng-required="true">

                     Valid phone number is required

                      phone number should be 10 digits

</form>
```

But I am not getting the validation error.

答:
use ng-intl-tel-input to validate mobile numbers for all countries. you can set default country also.
on npm: https://www.npmjs.com/package/ng-intl-tel-input

more details: https://techpituwa.wordpress.com/2017/03/29/angular-js-phone-number-validation-with-ng-intl-tel-input/

Title: Validate phone number using angular js

Body:
Want to set phone-number to 10 digits, How can I do this using Angular js.

This is what I have tried:

<form class="form-horizontal" role="form" method="post" name="registration" novalidate>

    Phone :

      <input type="number"
             class="form-control"
             ng-minlength="10"
             ng-maxlength="10"
             id="inputPhone"
             name="phone"
             placeholder="Phone"
             ng-model="user.phone"
             ng-required="true">

                     Valid phone number is required

                      phone number should be 10 digits

</form>

But I am not getting the validation error.


问:
iphone sdk beyond bounds NSException
I am having an "Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index 24 beyond bounds [0 .. 23]'"
I'm not sure how to put my .m on here without it being really long. Please let me know how i can assist to get this problem solved.
Thanks in advance!

code:

```<code>#import "RootViewController.h"
#import "FSDAppDelegate.h"
#import "DetailViewController.h"
@implementation RootViewController

#pragma mark -
#pragma mark Synthesizers

@synthesize mainTableView;
@synthesize contentsList;
@synthesize descArray;
@synthesize bannerImages;
@synthesize childController;
@synthesize searchResults;
@synthesize savedSearchTerm;

#pragma mark -
#pragma mark View methods

- (void)viewDidLoad
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Descriptions" ofType:@"plist"];

    NSArray *desc = [[NSArray alloc] initWithContentsOfFile:filePath];
    self.descArray = desc;
    [desc release];

    UIImage *texas = [UIImage imageNamed:@"1andtexas.jpg"];
    UIImage *cali = [UIImage imageNamed:@"2andcalifornia.jpg"];
    UIImage *ny = [UIImage imageNamed:@"3andnewyork.jpg"];
    UIImage *tmark = [UIImage imageNamed:@"1Tmark.jpg"];
    UIImage *walkie = [UIImage imageNamed:@"Walkietalkie.jpg"];
    UIImage *onekh = [UIImage imageNamed:@"Tracingpaper.jpg"];
    UIImage *onetwonine = [UIImage imageNamed:@"diffusion.jpg"];
    UIImage *greycard = [UIImage imageNamed:@"Greycard.jpg"];
    UIImage *oneeighty = [UIImage imageNamed:@"Oneeighty.jpg"];
    UIImage *two = [UIImage imageNamed:@"Two.jpg"];
    UIImage *twofourteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofifteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twosixteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twotwenty = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twotwentynine = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofifty = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyone = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftytwo = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftythree = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyfour = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyfive = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftysix = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyseven = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyeight = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *thirtytwohk = [UIImage imageNamed:@"3200k.jpg"];

    NSArray *banners = [[NSArray alloc] initWithObjects:
                        texas,
                        cali,
                        ny,
                        tmark,
                        walkie,
                        onekh,
                        onetwonine,
                        greycard,
                        oneeighty,
                        two,
                        twofourteen,
                        twofifteen,
                        twosixteen,
                        twotwenty,
                        twotwentynine,
                        twofifty,
                        twofiftyone,
                        twofiftytwo,
                        twofiftythree,
                        twofiftyfour,
                        twofiftyfive,
                        twofiftysix,
                        twofiftyseven,
                        twofiftyeight,
                        thirtytwohk,
                        nil];

    self.bannerImages = banners;

    [banners release];

    [super viewDidLoad];

    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
                             @"#1 or NUMBER ONE",
                             @"#2 or NUMBER TWO",
                             @"#3 or NUMBER THREE",
                             @"1 or ONE",
                             @"10-100,10-1,10-200,10-2,10-4 and 20",
                             @"1000H PAPER",
                             @"129 or HEAVY FROST",
                             @"18% GRAY or GREY CARD",
                             @"180 DEGREE RULE",
                             @"2 or TWO",
                             @"214 or FULL TOUGH SPUN",
                             @"215 or HALF TOUGH SPUN",
                             @"216 or FULL WHITE DIFFUSION",
                             @"220 or WHITE FROST",
                             @"229 or QUARTER TOUGH SPUN",
                             @"250 or HALF WHITE DIFFUSION",
                             @"251 or QUARTER WHITE DIFFUSION",
                             @"252 or EIGHTH WHITE DIFFUSION",
                             @"253 or FULL HAMPSHIRE",
                             @"254 or NEW HAMPSHIRE",
                             @"255 or HOLLYWOOD FROST",
                             @"256 or HALF HAMPSHIRE FROST",
                             @"257 or QUARTER HAMPSHIRE FROST",
                             @"258 or EIGHTH HAMPSHIRE FROST",
                             @"3200K or TUNGSTEN",
                             nil];
    [self setContentsList:array];
    [array release], array = nil;

    if ([self savedSearchTerm])
    {
        [[[self searchDisplayController] searchBar] setText:[self savedSearchTerm]];
    }

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [super viewWillAppear:animated];

    [[self mainTableView] reloadData];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

#pragma mark -
#pragma mark Table view datasource methods

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
    for(char c = 'A'; c <= 'Z'; c++) [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
    return toBeReturned;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSInteger rows;

    if (tableView == [[self searchDisplayController] searchResultsTableView])
        rows = [[self searchResults] count];
    else
        rows = [[self contentsList] count];

    return [contentsList count];
    return rows;

    NSLog(@"rows is: %d", rows);
    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

-(UITableViewCell *) tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSInteger row = [indexPath row];
    NSString *contentForThisRow = nil;

    if (tableView == [[self searchDisplayController] searchResultsTableView])
        contentForThisRow = [[self searchResults] objectAtIndex:row];
    else
        contentForThisRow = [[self contentsList] objectAtIndex:row];

    static NSString *CellIdentifier = @"CellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    [[cell textLabel] setText:contentForThisRow];

    cell.textLabel.text = [contentsList objectAtIndex:indexPath.row];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);

    return cell;
}

#pragma mark -
#pragma mark Table view delegate methods

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    return @"Film Set Decipher";
}

-(void) tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    FSDAppDelegate *delegate = (FSDAppDelegate *)[[UIApplication sharedApplication] delegate];
    DetailViewController *detailVC = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailVC.banner = [bannerImages objectAtIndex:indexPath.row];
    detailVC.description = [descArray objectAtIndex:indexPath.row];
    detailVC.title = [contentsList objectAtIndex:indexPath.row];
    self.childController = detailVC;
    [delegate.navigationController pushViewController:childController animated:YES];

    [detailVC release];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self handleSearchForTerm:searchString];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
    return YES;
}

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self setSavedSearchTerm:nil];

    [[self mainTableView] reloadData];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}
#pragma mark -
#pragma mark Memory Management

- (void)didReceiveMemoryWarning {
    NSLog(@"Memory warning!");
    [super didReceiveMemoryWarning];
}
- (void)dealloc
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [mainTableView release]; mainTableView = nil;
    [contentsList release]; contentsList = nil;
    [descArray release]; descArray = nil;
    [bannerImages release]; bannerImages = nil;
    [childController release]; childController = nil;
    [searchResults release], searchResults = nil;
    [savedSearchTerm release], savedSearchTerm = nil;

    [super dealloc];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

- (void)viewDidUnload {
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    self.mainTableView = nil;
    self.contentsList = nil;
    self.descArray = nil;
    self.bannerImages = nil;
    self.childController = nil;

    [super viewDidUnload];

    [self setSavedSearchTerm:[[[self searchDisplayController] searchBar] text]];

    [self setSearchResults:nil];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);

}

- (void)handleSearchForTerm:(NSString *)searchTerm
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self setSavedSearchTerm:searchTerm];

    if ([self searchResults] == nil)
    {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [self setSearchResults:array];
        [array release], array = nil;
    }

    [[self searchResults] removeAllObjects];

    if ([[self savedSearchTerm] length] != 0)
    {
        for (NSString *currentString in [self contentsList])
        {
            if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
            {
                [[self searchResults] addObject:currentString];
            }
        }
    }

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

@end
</code>```

Turns out the problem was that the images weren't all copied into the Target>Copy Bundle Resources folder, and thats what was making it crash!?!? Thanks a million!

答:
The error says that the array has 24 elements, yet you are trying to access the 25th element. So you need to post the code that is trying to access the 25th element. Or figure out why it's trying to find the 25th element in a 24 element array.

EDIT:

You should set a breakpoint in the first line or so of tableView:didSelectRowAtIndexPath:

then at the gdb> prompt type:

```<code>po descArray
</code>```

OR just:

```<code>p(int) [descArray count]
</code>```

OR look in the variables pane to see how many items are actually in descArray at that point. Repeat if necessary for the other two arrays.

EDIT AGAIN:

You have another issue (possibly unrelated) in our tableView:numberOfRowsInSection:

You return the contentList count all the time. The lines after that return including the NSLogs will never be reached. As soon as you hit that first return in C, you will return from that method immediately. I don't think that's your immediate problem, but it is another problem that will happen when you start to get search working.

Title: iphone sdk beyond bounds NSException

Body:
I am having an "Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index 24 beyond bounds [0 .. 23]'"
I'm not sure how to put my .m on here without it being really long. Please let me know how i can assist to get this problem solved.
Thanks in advance!

code:

#import "RootViewController.h"
#import "FSDAppDelegate.h"
#import "DetailViewController.h"
@implementation RootViewController

#pragma mark -
#pragma mark Synthesizers

@synthesize mainTableView;
@synthesize contentsList;
@synthesize descArray;
@synthesize bannerImages;
@synthesize childController;
@synthesize searchResults;
@synthesize savedSearchTerm;

#pragma mark -
#pragma mark View methods

- (void)viewDidLoad
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Descriptions" ofType:@"plist"];

    NSArray *desc = [[NSArray alloc] initWithContentsOfFile:filePath];
    self.descArray = desc;
    [desc release];

    UIImage *texas = [UIImage imageNamed:@"1andtexas.jpg"];
    UIImage *cali = [UIImage imageNamed:@"2andcalifornia.jpg"];
    UIImage *ny = [UIImage imageNamed:@"3andnewyork.jpg"];
    UIImage *tmark = [UIImage imageNamed:@"1Tmark.jpg"];
    UIImage *walkie = [UIImage imageNamed:@"Walkietalkie.jpg"];
    UIImage *onekh = [UIImage imageNamed:@"Tracingpaper.jpg"];
    UIImage *onetwonine = [UIImage imageNamed:@"diffusion.jpg"];
    UIImage *greycard = [UIImage imageNamed:@"Greycard.jpg"];
    UIImage *oneeighty = [UIImage imageNamed:@"Oneeighty.jpg"];
    UIImage *two = [UIImage imageNamed:@"Two.jpg"];
    UIImage *twofourteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofifteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twosixteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twotwenty = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twotwentynine = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofifty = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyone = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftytwo = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftythree = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyfour = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyfive = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftysix = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyseven = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyeight = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *thirtytwohk = [UIImage imageNamed:@"3200k.jpg"];

    NSArray *banners = [[NSArray alloc] initWithObjects:
                        texas,
                        cali,
                        ny,
                        tmark,
                        walkie,
                        onekh,
                        onetwonine,
                        greycard,
                        oneeighty,
                        two,
                        twofourteen,
                        twofifteen,
                        twosixteen,
                        twotwenty,
                        twotwentynine,
                        twofifty,
                        twofiftyone,
                        twofiftytwo,
                        twofiftythree,
                        twofiftyfour,
                        twofiftyfive,
                        twofiftysix,
                        twofiftyseven,
                        twofiftyeight,
                        thirtytwohk,
                        nil];

    self.bannerImages = banners;

    [banners release];

    [super viewDidLoad];

    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
                             @"#1 or NUMBER ONE",
                             @"#2 or NUMBER TWO",
                             @"#3 or NUMBER THREE",
                             @"1 or ONE",
                             @"10-100,10-1,10-200,10-2,10-4 and 20",
                             @"1000H PAPER",
                             @"129 or HEAVY FROST",
                             @"18% GRAY or GREY CARD",
                             @"180 DEGREE RULE",
                             @"2 or TWO",
                             @"214 or FULL TOUGH SPUN",
                             @"215 or HALF TOUGH SPUN",
                             @"216 or FULL WHITE DIFFUSION",
                             @"220 or WHITE FROST",
                             @"229 or QUARTER TOUGH SPUN",
                             @"250 or HALF WHITE DIFFUSION",
                             @"251 or QUARTER WHITE DIFFUSION",
                             @"252 or EIGHTH WHITE DIFFUSION",
                             @"253 or FULL HAMPSHIRE",
                             @"254 or NEW HAMPSHIRE",
                             @"255 or HOLLYWOOD FROST",
                             @"256 or HALF HAMPSHIRE FROST",
                             @"257 or QUARTER HAMPSHIRE FROST",
                             @"258 or EIGHTH HAMPSHIRE FROST",
                             @"3200K or TUNGSTEN",
                             nil];
    [self setContentsList:array];
    [array release], array = nil;

    if ([self savedSearchTerm])
    {
        [[[self searchDisplayController] searchBar] setText:[self savedSearchTerm]];
    }

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [super viewWillAppear:animated];

    [[self mainTableView] reloadData];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

#pragma mark -
#pragma mark Table view datasource methods

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
    for(char c = 'A'; c <= 'Z'; c++) [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
    return toBeReturned;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSInteger rows;

    if (tableView == [[self searchDisplayController] searchResultsTableView])
        rows = [[self searchResults] count];
    else
        rows = [[self contentsList] count];

    return [contentsList count];
    return rows;

    NSLog(@"rows is: %d", rows);
    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

-(UITableViewCell *) tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSInteger row = [indexPath row];
    NSString *contentForThisRow = nil;

    if (tableView == [[self searchDisplayController] searchResultsTableView])
        contentForThisRow = [[self searchResults] objectAtIndex:row];
    else
        contentForThisRow = [[self contentsList] objectAtIndex:row];

    static NSString *CellIdentifier = @"CellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    [[cell textLabel] setText:contentForThisRow];

    cell.textLabel.text = [contentsList objectAtIndex:indexPath.row];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);

    return cell;
}

#pragma mark -
#pragma mark Table view delegate methods

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    return @"Film Set Decipher";
}

-(void) tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    FSDAppDelegate *delegate = (FSDAppDelegate *)[[UIApplication sharedApplication] delegate];
    DetailViewController *detailVC = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailVC.banner = [bannerImages objectAtIndex:indexPath.row];
    detailVC.description = [descArray objectAtIndex:indexPath.row];
    detailVC.title = [contentsList objectAtIndex:indexPath.row];
    self.childController = detailVC;
    [delegate.navigationController pushViewController:childController animated:YES];

    [detailVC release];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self handleSearchForTerm:searchString];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
    return YES;
}

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self setSavedSearchTerm:nil];

    [[self mainTableView] reloadData];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}
#pragma mark -
#pragma mark Memory Management

- (void)didReceiveMemoryWarning {
    NSLog(@"Memory warning!");
    [super didReceiveMemoryWarning];
}
- (void)dealloc
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [mainTableView release]; mainTableView = nil;
    [contentsList release]; contentsList = nil;
    [descArray release]; descArray = nil;
    [bannerImages release]; bannerImages = nil;
    [childController release]; childController = nil;
    [searchResults release], searchResults = nil;
    [savedSearchTerm release], savedSearchTerm = nil;

    [super dealloc];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

- (void)viewDidUnload {
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    self.mainTableView = nil;
    self.contentsList = nil;
    self.descArray = nil;
    self.bannerImages = nil;
    self.childController = nil;

    [super viewDidUnload];

    [self setSavedSearchTerm:[[[self searchDisplayController] searchBar] text]];

    [self setSearchResults:nil];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);

}

- (void)handleSearchForTerm:(NSString *)searchTerm
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self setSavedSearchTerm:searchTerm];

    if ([self searchResults] == nil)
    {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [self setSearchResults:array];
        [array release], array = nil;
    }

    [[self searchResults] removeAllObjects];

    if ([[self savedSearchTerm] length] != 0)
    {
        for (NSString *currentString in [self contentsList])
        {
            if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
            {
                [[self searchResults] addObject:currentString];
            }
        }
    }

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

@end

Turns out the problem was that the images weren't all copied into the Target>Copy Bundle Resources folder, and thats what was making it crash!?!? Thanks a million!

Body:
The error says that the array has 24 elements, yet you are trying to access the 25th element. So you need to post the code that is trying to access the 25th element. Or figure out why it's trying to find the 25th element in a 24 element array.

EDIT:

You should set a breakpoint in the first line or so of tableView:didSelectRowAtIndexPath:

then at the gdb> prompt type:

po descArray

OR just:

p(int) [descArray count]

OR look in the variables pane to see how many items are actually in descArray at that point. Repeat if necessary for the other two arrays.

EDIT AGAIN:

You have another issue (possibly unrelated) in our tableView:numberOfRowsInSection:

You return the contentList count all the time. The lines after that return including the NSLogs will never be reached. As soon as you hit that first return in C, you will return from that method immediately. I don't think that's your immediate problem, but it is another problem that will happen when you start to get search working.

ContentLicense: CC BY-SA 2.5


问:
Convert data strings into Date format using ISODate function during the insertion mongo query to java code
```<code>  db.collection.find().forEach(function(element){
      element.BOOKING_CREATED_DATE = ISODate(element.BOOKING_CREATED_DATE);
      db.collection.save(element);
    })
</code>```

Please help to convert this query to DBobject type to run in spring boot

答:
Finally found the answer</p>

```<code>MongoClient mongo = new MongoClient();
DB db = mongo.getDB("datarepo");

DBCollection collection = db.getCollection("rawdata");

db.eval("db.rawdata.find( { BOOKING_CREATED_DATE : { $type : 2 } } ).forEach(function(element){" +
                "element.BOOKING_CREATED_DATE = ISODate(element.BOOKING_CREATED_DATE);" +
                "db.rawdata.save(element);})")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
  db.collection.find().forEach(function(element){
      element.BOOKING_CREATED_DATE = ISODate(element.BOOKING_CREATED_DATE);
      db.collection.save(element);
    })

Please help to convert this query to DBobject type to run in spring boot

Body:
Finally found the answer

MongoClient mongo = new MongoClient();
DB db = mongo.getDB("datarepo");

DBCollection collection = db.getCollection("rawdata");

db.eval("db.rawdata.find( { BOOKING_CREATED_DATE : { $type : 2 } } ).forEach(function(element){" +
                "element.BOOKING_CREATED_DATE = ISODate(element.BOOKING_CREATED_DATE);" +
                "db.rawdata.save(element);})")


问:
Shrinking the JPanel in Swing
I am trying to make a login page but unfortunately my formPanel's border is so out of bounds. Here in the pic you can see the titled border is way out. I need it to be more around my panel with login form:

I see that when creating this formPanel it is that big and the border just surround it. I tried with setPrefferedSize but its not working. How can I fix it?

Here is my code:

```<code>public class LoginPanel extends JPanel {
private JLabel title;

public LoginPanel() {
    this.setBackground(new Color(0, 128, 43));
    this.setBorder(new EmptyBorder(10, 10, 10, 10));
    this.setLayout(new BorderLayout());

    //adding the title
    title = new JLabel("<html><h1><strong><i>Krisko Beatz Quiz</i></strong></h1><hr></html>");
    title.setForeground(Color.BLACK);
    JPanel titlePanel = new JPanel();
    titlePanel.setBackground(new Color(0, 128, 43));
    titlePanel.add(title);
    this.add(titlePanel, BorderLayout.PAGE_START);

    //creating the login form
    JPanel formPanel = new JPanel(new GridBagLayout());
    formPanel.setBackground(new Color(0, 128, 43));

    //gbc
    GridBagConstraints gbc = new GridBagConstraints();

    //gbc for username
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.insets = new Insets(5, 0, 0, 0);

    JLabel username = new JLabel("Username: ");
    username.setForeground(Color.BLACK);
    formPanel.add(username, gbc);

    //gbc for textfield
    gbc.gridx = 1;
    gbc.gridy = 0;

    JTextField usernameField = new JTextField(10);
    formPanel.add(usernameField, gbc);

    //gbc for pass
    gbc.gridx = 0;
    gbc.gridy = 1;

    JLabel password = new JLabel("Password: ");
    password.setForeground(Color.BLACK);
    formPanel.add(password, gbc);

    //gbc for pass field
    gbc.gridx = 1;
    gbc.gridy = 1;

    JPasswordField passField = new JPasswordField(10);
    formPanel.add(passField, gbc);

    //gbc for button
    gbc.gridx = 1;
    gbc.gridy = 2;
    gbc.gridwidth = 2;
    gbc.anchor = GridBagConstraints.PAGE_END;

    JButton loginButton = new JButton("Login");
    formPanel.add(loginButton, gbc);

    //add border to the form panel
    TitledBorder title = BorderFactory.createTitledBorder("Login");
    formPanel.setBorder(title);

    this.add(formPanel, BorderLayout.CENTER);
}
}
</code>```

答:
I took your LoginPanel class as is, and wrote a Main class around it to start the GUI.

```<code>public class Main {
  public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new LoginPanel());
        frame.pack();
        frame.setVisible(true);
    });
  }
}
</code>```

Especially note, I did no explicit setting of the size, only a pack() call which resizes everything to its preferred size according to your layout.

The resulting layout looks perfectly fine to me.

So the conclusion is: Your LoginPanel is fine, but probably there is something wrong in your other code which you didn't post here.

Title: Shrinking the JPanel in Swing

Body:
I am trying to make a login page but unfortunately my formPanel's border is so out of bounds. Here in the pic you can see the titled border is way out. I need it to be more around my panel with login form:

I see that when creating this formPanel it is that big and the border just surround it. I tried with setPrefferedSize but its not working. How can I fix it?

Here is my code:

public class LoginPanel extends JPanel {
private JLabel title;

public LoginPanel() {
    this.setBackground(new Color(0, 128, 43));
    this.setBorder(new EmptyBorder(10, 10, 10, 10));
    this.setLayout(new BorderLayout());

    //adding the title
    title = new JLabel("
Krisko Beatz Quiz

");
    title.setForeground(Color.BLACK);
    JPanel titlePanel = new JPanel();
    titlePanel.setBackground(new Color(0, 128, 43));
    titlePanel.add(title);
    this.add(titlePanel, BorderLayout.PAGE_START);

    //creating the login form
    JPanel formPanel = new JPanel(new GridBagLayout());
    formPanel.setBackground(new Color(0, 128, 43));

    //gbc
    GridBagConstraints gbc = new GridBagConstraints();

    //gbc for username
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.insets = new Insets(5, 0, 0, 0);

    JLabel username = new JLabel("Username: ");
    username.setForeground(Color.BLACK);
    formPanel.add(username, gbc);

    //gbc for textfield
    gbc.gridx = 1;
    gbc.gridy = 0;

    JTextField usernameField = new JTextField(10);
    formPanel.add(usernameField, gbc);

    //gbc for pass
    gbc.gridx = 0;
    gbc.gridy = 1;

    JLabel password = new JLabel("Password: ");
    password.setForeground(Color.BLACK);
    formPanel.add(password, gbc);

    //gbc for pass field
    gbc.gridx = 1;
    gbc.gridy = 1;

    JPasswordField passField = new JPasswordField(10);
    formPanel.add(passField, gbc);

    //gbc for button
    gbc.gridx = 1;
    gbc.gridy = 2;
    gbc.gridwidth = 2;
    gbc.anchor = GridBagConstraints.PAGE_END;

    JButton loginButton = new JButton("Login");
    formPanel.add(loginButton, gbc);

    //add border to the form panel
    TitledBorder title = BorderFactory.createTitledBorder("Login");
    formPanel.setBorder(title);

    this.add(formPanel, BorderLayout.CENTER);
}
}

Body:
I took your LoginPanel class as is, and wrote a Main class around it to start the GUI.

public class Main {
  public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new LoginPanel());
        frame.pack();
        frame.setVisible(true);
    });
  }
}

Especially note, I did no explicit setting of the size, only a pack() call which resizes everything to its preferred size according to your layout.

The resulting layout looks perfectly fine to me.

So the conclusion is: Your LoginPanel is fine, but probably there is something wrong in your other code which you didn't post here.


问:
How to set AND expand variables in a heredoc section
I have a heredoc that needs to call existing variables from the main script, and set its own variables to use later. Something like this:

```<code>count=0

ssh $other_host <<ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH
</code>```

That doesn't work because 'output' doesn't get set to anything.

I tried using the solution from this question:

```<code>count=0

ssh $other_host << \ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH
</code>```

It didn't work either. $output got set to "string2" because $count wasn't expanded.

How can I use a heredoc that expands variables from the parent script, and sets its own variables?

答:
You can escape the variables as @anubhava said, or, if you get too much variables for the escaping, you can do it in two steps:

```<code># prepare the part which should not be expanded
# note the quoted 'EOF'
read -r -d '' commands <<'EOF'
if [[ "$count" == "0" ]]; then
    echo "$count - $HOME"
else
    echo "$count - $PATH"
fi
EOF

localcount=1
#use the unquoted ENDSSH
ssh me@nox.local <<ENDSSH
count=$localcount # count=1
#here will be inserted the above prepared commands
$commands
ENDSSH
</code>```

will print something like:

```<code>1 - /usr/bin:/bin:/usr/sbin:/sbin
</code>```

Body:
I have a heredoc that needs to call existing variables from the main script, and set its own variables to use later. Something like this:

count=0

ssh $other_host <<ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH

That doesn't work because 'output' doesn't get set to anything.

I tried using the solution from this question:

count=0

ssh $other_host << \ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH

It didn't work either. $output got set to "string2" because $count wasn't expanded.

How can I use a heredoc that expands variables from the parent script, and sets its own variables?

Body:
You can escape the variables as @anubhava said, or, if you get too much variables for the escaping, you can do it in two steps:

# prepare the part which should not be expanded
# note the quoted 'EOF'
read -r -d '' commands <<'EOF'
if [[ "$count" == "0" ]]; then
    echo "$count - $HOME"
else
    echo "$count - $PATH"
fi
EOF

localcount=1
#use the unquoted ENDSSH
ssh me@nox.local <<ENDSSH
count=$localcount # count=1
#here will be inserted the above prepared commands
$commands
ENDSSH

will print something like:

1 - /usr/bin:/bin:/usr/sbin:/sbin


问:
Regex to insert and replace characters in a string C#
I have a string which looks like this :-
"$.ConfigSettings.DatabaseSettings.DatabaseConnections.SqlConnectionString.0.Id"
and I want the result to look like this :-
"$.ConfigSettings.DatabaseSettings.DatabaseConnections.SqlConnectionString[0].Id"

Basically wherever there is a single digit preceded and succeeded by a period I need to change it to [digit] followed by period ie [digit]. .I have seen tons of examples where people are only replacing the regex string.

How will I do this using Regex.Replace in C#

答:
```<code>Regex.Replace(input, @"\.(\d)(?=\.)", "[$1]")

\.            - capture a "."
  (\d)        - then a single digit in a capturing group ($1 in the replacement)
      (?=     - start a positive lookahead
         \.   - that matches a "."
           )  - end the lookahead
</code>```

So, it means : (match a dot followed by a digit in a capturing group) only if it is followed by a dot

So we matched ".0" and captured "0". We replace the entire match with "[$1]", where $1 refers to the first captured group.

See "Grouping Constructs in Regular Expressions" : https://msdn.microsoft.com/en-us/library/bs2twtah(v=vs.110).aspx for information about the different grouping constructs that I use in this solution.

Body:
Regex.Replace(input, @"\.(\d)(?=\.)", "[$1]")

\.            - capture a "."
  (\d)        - then a single digit in a capturing group ($1 in the replacement)
      (?=     - start a positive lookahead
         \.   - that matches a "."
           )  - end the lookahead

So, it means : (match a dot followed by a digit in a capturing group) only if it is followed by a dot

So we matched ".0" and captured "0". We replace the entire match with "[$1]", where $1 refers to the first captured group.

See "Grouping Constructs in Regular Expressions" : https://msdn.microsoft.com/en-us/library/bs2twtah(v=vs.110).aspx for information about the different grouping constructs that I use in this solution.


问:
Import text file with uneven column number and complicated delimiter
Say I have text file like below:

```<code>apple  pear  banana,  peach orange grape

dog  cat  white horse

salmon

tiger  lion  eagle hawk  monkey
</code>```

Looking for output like:

```<code>"apple", "pear", "banana", "peach orange grape"

"dog", "cat", "white horse"

"salmon"

"tiger", "lion", "eagle hawk", "monkey"
</code>```

Two problems,

each row I only want separate them by double space '   '

column number of each row could be random, from 1 to 100

How can I load them into a pandas dataframe?

In fact I am wondering if it is possible to complete this without reading line by line, because I initial solution is:

read each line, use REX

re.split(r'\s{2,}', line)

to split by double space

after split by double space, insert each row into DF

however, coz the column number is random, I can't simply generate a DF by that.
Adding names=[] in pd.read_csv() will handle uneven columns, but this requires pre define column names and number.

Any suggestion?

Thank you!

答:
read_table() is your friend here...

```<code>df = pd.read_table('./test.txt', sep="  ", header=None)
df.to_csv('outfile.csv')
</code>```

any missing columns will be filled with NaN.

The text file test.txt above is the following:

```<code>test  2  1
t
t2  1
t3
t4  3  4
</code>```

and df looks like this:

```<code>      0    1    2
0  test  2.0  1.0
1     t  NaN  NaN
2    t2  1.0  NaN
3    t3  NaN  NaN
4    t4  3.0  4.0
</code>```

To get the quoting in the output you may need to use the quoting option from csv:

```<code>import csv
import pandas as pd

df = pd.read_table('./test.txt', sep="  ", header=None)
df.to_csv(quoting=csv.QUOTE_NONNUMERIC)
</code>```

Body:
Say I have text file like below:

apple  pear  banana,  peach orange grape

dog  cat  white horse

salmon

tiger  lion  eagle hawk  monkey

Looking for output like:

"apple", "pear", "banana", "peach orange grape"

"dog", "cat", "white horse"

"salmon"

"tiger", "lion", "eagle hawk", "monkey"

Two problems,

each row I only want separate them by double space '   '

column number of each row could be random, from 1 to 100

How can I load them into a pandas dataframe?

In fact I am wondering if it is possible to complete this without reading line by line, because I initial solution is:

read each line, use REX

re.split(r'\s{2,}', line)

to split by double space

after split by double space, insert each row into DF

however, coz the column number is random, I can't simply generate a DF by that.
Adding names=[] in pd.read_csv() will handle uneven columns, but this requires pre define column names and number.

Any suggestion?

Thank you!

Body:
read_table() is your friend here...

df = pd.read_table('./test.txt', sep="  ", header=None)
df.to_csv('outfile.csv')

any missing columns will be filled with NaN.

The text file test.txt above is the following:

test  2  1
t
t2  1
t3
t4  3  4

and df looks like this:

      0    1    2
0  test  2.0  1.0
1     t  NaN  NaN
2    t2  1.0  NaN
3    t3  NaN  NaN
4    t4  3.0  4.0

To get the quoting in the output you may need to use the quoting option from csv:

import csv
import pandas as pd

df = pd.read_table('./test.txt', sep="  ", header=None)
df.to_csv(quoting=csv.QUOTE_NONNUMERIC)


问:
using a time series of parameters to solve ODE in R
I am trying to solve a simple ODE in R using deSolve: dQ/dt = f(Q)*(P - E).The whole thing is a time series of Q. The trick is that P and E are fixed time series of data themselves, so the diff eq is effectively in Q alone.

It's relatively straightforward to solve this iteratively with a fixed time step, but I am trying to find a way to use an adaptive time step in R. Because P and E are discrete, successive timesteps may have the same value of P and E, which is fine. I have been playing around with deSolve, but have not been able to work this out. Ideally I would like to use standard 4th order Runge-Kutta.

Any ideas? Do it in MATLAB?

Edited for reproduceable example. I would like to be able to do this calc with a variable time step Runge-Kutta 4 method. I could program a fixed time step rk4 pretty easily, not so much adaptive.

```<code>working <- structure(list(datetime = structure(c(1185915600, 1185919200,
1185922800, 1185926400, 1185930000, 1185933600, 1185937200, 1185940800,
1185944400, 1185948000, 1185951600), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), p = c(0, 0, 0, 1.1, 0.5, 0.7, 0, 0, 1.3, 0,
0), e = c(0.15, 0.14, 0.13, 0.21, 0.15, 0.1, 0.049, 0, 0, 0,
0), qsim = c(-1.44604436552566, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA)), .Names = c("datetime", "p", "e", "qsim"), row.names = c(NA, 11L),
class = "data.frame")

# this is the derivative function dQ/dt = f(Q,p,e) where p and e are time series
dqdt <- function(qsim, pcp, pet) {
  dq <- (qsim ^ 2) * ((pcp - pet) / qsim)
  return(dq)
}

# loops through and calculates the Q at each time step using the Euler method
for (i in 1:(nrow(working) - 1)) {
  dq <- dqdt(working$qsim[i], pcp = working$p[i], pet = working$e[i])
  working$qsim[i + 1] <- working$qsim[i] + dq
}
</code>```

答:
Ben's solution can be improved by saving your vectors working$p and working$e in the "parameter" list that will be passed to the ODE.
Instead of parameters <- NULL, do parameters2 <- list(vec1 = your_time_series, vec2 = your_other_time_series). Then:

```<code>gradfun <- function(t,y,parms) {
   pcp <- vec1[pmax(1,ceiling(t))]
   pet <- vec2[pmax(1,ceiling(t))]
   list(y^2*((pcp-pet)/y),NULL)
}
</code>```

That way you don't have to relay in the external (global) variables, which can be a huge pain

Body:
I am trying to solve a simple ODE in R using deSolve: dQ/dt = f(Q)*(P - E).The whole thing is a time series of Q. The trick is that P and E are fixed time series of data themselves, so the diff eq is effectively in Q alone.

It's relatively straightforward to solve this iteratively with a fixed time step, but I am trying to find a way to use an adaptive time step in R. Because P and E are discrete, successive timesteps may have the same value of P and E, which is fine. I have been playing around with deSolve, but have not been able to work this out. Ideally I would like to use standard 4th order Runge-Kutta.

Any ideas? Do it in MATLAB?

Edited for reproduceable example. I would like to be able to do this calc with a variable time step Runge-Kutta 4 method. I could program a fixed time step rk4 pretty easily, not so much adaptive.

working <- structure(list(datetime = structure(c(1185915600, 1185919200,
1185922800, 1185926400, 1185930000, 1185933600, 1185937200, 1185940800,
1185944400, 1185948000, 1185951600), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), p = c(0, 0, 0, 1.1, 0.5, 0.7, 0, 0, 1.3, 0,
0), e = c(0.15, 0.14, 0.13, 0.21, 0.15, 0.1, 0.049, 0, 0, 0,
0), qsim = c(-1.44604436552566, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA)), .Names = c("datetime", "p", "e", "qsim"), row.names = c(NA, 11L),
class = "data.frame")

# this is the derivative function dQ/dt = f(Q,p,e) where p and e are time series
dqdt <- function(qsim, pcp, pet) {
  dq <- (qsim ^ 2) * ((pcp - pet) / qsim)
  return(dq)
}

# loops through and calculates the Q at each time step using the Euler method
for (i in 1:(nrow(working) - 1)) {
  dq <- dqdt(working$qsim[i], pcp = working$p[i], pet = working$e[i])
  working$qsim[i + 1] <- working$qsim[i] + dq
}

Body:
Ben's solution can be improved by saving your vectors working$p and working$e in the "parameter" list that will be passed to the ODE.
Instead of parameters <- NULL, do parameters2 <- list(vec1 = your_time_series, vec2 = your_other_time_series). Then:

gradfun <- function(t,y,parms) {
   pcp <- vec1[pmax(1,ceiling(t))]
   pet <- vec2[pmax(1,ceiling(t))]
   list(y^2*((pcp-pet)/y),NULL)
}

That way you don't have to relay in the external (global) variables, which can be a huge pain


问:
Android: chronometer as a persistent stopwatch. How to set starting time? What is Chronometer "Base"?
I do have one service running in the background. Whenever it starts I store in memory the starting time in milliseconds:

```<code>startingTime = new Date().getTime();
</code>```

I want to display a chronometer that starts counting when the service starts and never stops until the user presses a button. I want to allow the user to leave the activity rendering the chronometer, do some stuff and then return. But the idea is that when the user returns I dont want the chronometer to go to 0:00 again. Insted I want it to show the exact time that has passed ever since the service has started.

I can calculate elapsedTime every time the user return to the chronometer activity:

```<code>elapsedTime =  new Date().getTime() - startingTime;
</code>```

The thing is that i dont know how to tell the chronometer to start counting from that time!

Setting it as the chronometer base does not work. Can someon explain what exactly "base" means or how to accomplish this?

thanks a lot!
BYE

答:
How to set starting time? What is Chronometer “Base”?

Use SystemClock.elapsedRealtime() for this purpose:

```<code>   myChronometer.setBase(SystemClock.elapsedRealtime());
</code>```

Body:
I do have one service running in the background. Whenever it starts I store in memory the starting time in milliseconds:

startingTime = new Date().getTime();

I want to display a chronometer that starts counting when the service starts and never stops until the user presses a button. I want to allow the user to leave the activity rendering the chronometer, do some stuff and then return. But the idea is that when the user returns I dont want the chronometer to go to 0:00 again. Insted I want it to show the exact time that has passed ever since the service has started.

I can calculate elapsedTime every time the user return to the chronometer activity:

elapsedTime =  new Date().getTime() - startingTime;

The thing is that i dont know how to tell the chronometer to start counting from that time!

Setting it as the chronometer base does not work. Can someon explain what exactly "base" means or how to accomplish this?

thanks a lot!
BYE

Body:
How to set starting time? What is Chronometer “Base”?

Use SystemClock.elapsedRealtime() for this purpose:

   myChronometer.setBase(SystemClock.elapsedRealtime());


问:
Count keywords from a string
I'm trying to count the keywords in a string from a webpage:

```<code>#get the URL
u <- "http://www.dlink.com/it/it"
doc <- getURL(u)

#get the text from the body
html <- htmlTreeParse(doc, useInternal = TRUE)
txt <- xpathApply(html, "//body//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)]", xmlValue)
txt<-toString(txt)
txt

#clean
str_replace_all(txt, "[\r\n\t,]" , "")

search <- c("Wi-Fi","Router","Switch","ADSL")
search
stri_detect_fixed(txt, search)

sum(stri_detect_fixed(text, search))
</code>```

Unfortunately counts only if the word is in or not, instead, I want to count how many keywords are present (e.g if Wi-Fi is present two times would be +2), any idea using the stringi library?

答:
Use stri_count_fixed

```<code>library(stringi)

stri_count_fixed(txt, search)
[1] 3 2 5 1

sum(stri_count_fixed(txt, search))
[1] 11
</code>```

Title: Count keywords from a string

Body:
I'm trying to count the keywords in a string from a webpage:

#get the URL
u <- "http://www.dlink.com/it/it"
doc <- getURL(u)

#get the text from the body
html <- htmlTreeParse(doc, useInternal = TRUE)
txt <- xpathApply(html, "//body//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)]", xmlValue)
txt<-toString(txt)
txt

#clean
str_replace_all(txt, "[\r\n\t,]" , "")

search <- c("Wi-Fi","Router","Switch","ADSL")
search
stri_detect_fixed(txt, search)

sum(stri_detect_fixed(text, search))

Unfortunately counts only if the word is in or not, instead, I want to count how many keywords are present (e.g if Wi-Fi is present two times would be +2), any idea using the stringi library?

Body:
Use stri_count_fixed

library(stringi)

stri_count_fixed(txt, search)
[1] 3 2 5 1

sum(stri_count_fixed(txt, search))
[1] 11


问:
Check if list view contain item
i have a listview with 3 columns (id , name, author), i use this method to add row:

```<code>     public void addToLv(Book book)
    {

        //TODO: Verifier si l'item existe avant d'ajouter
        ListViewItem lvi1 = new ListViewItem(book.id.ToString());
        lvi1.Text = book.id.ToString();
        lvi1.SubItems.Add(book.name);
        lvi1.SubItems.Add(carte.author);

        listView1.Items.Add(lvi1);

    }
</code>```

Now i wan't to check if book exists before i insert the new one to avoid duplicate element, i try this code but it'S not working
i have use this line but it's not working:

```<code>  (listView1.Items.ContainsKey(book.id))
         {
      listView1.Items.Add(lvi1);
         }
</code>```

Can you help me please? thank you

答:
From MSDN:

The key comparison is not case-sensitive. The Name property corresponds to the key for a ListViewItem in the ListView.ListViewItemCollection.

So, you have to set the Name in order to use ContainsKey

```<code>lvi1.Name = book.id.ToString();
</code>```

And then the rest like you did:

```<code>if (!listView1.Items.ContainsKey(book.id.ToString()))
{
     listView1.Items.Add(lvi1);
}
</code>```

Title: Check if list view contain item

Body:
i have a listview with 3 columns (id , name, author), i use this method to add row:

     public void addToLv(Book book)
    {

        //TODO: Verifier si l'item existe avant d'ajouter
        ListViewItem lvi1 = new ListViewItem(book.id.ToString());
        lvi1.Text = book.id.ToString();
        lvi1.SubItems.Add(book.name);
        lvi1.SubItems.Add(carte.author);

        listView1.Items.Add(lvi1);

    }

Now i wan't to check if book exists before i insert the new one to avoid duplicate element, i try this code but it'S not working
i have use this line but it's not working:

  (listView1.Items.ContainsKey(book.id))
         {
      listView1.Items.Add(lvi1);
         }

Can you help me please? thank you

Body:
From MSDN:

The key comparison is not case-sensitive. The Name property corresponds to the key for a ListViewItem in the ListView.ListViewItemCollection.

So, you have to set the Name in order to use ContainsKey

lvi1.Name = book.id.ToString();

And then the rest like you did:

if (!listView1.Items.ContainsKey(book.id.ToString()))
{
     listView1.Items.Add(lvi1);
}


问:
Using reflection to create instance when using xmlbeans
I've got a xsd file with over 100 types defined in it. I generated java code with xmlbeans binding, and then I can use

```<code>MyType.Factory.newInstance();
</code>```

to get the class instance. But since there are too many types I've decide to use reflection to get create instances for each type.

I can now get the class(interface) of MyType using

```<code>Class clz = Class.forName("com.foo.MyType");
</code>```

But have no idea of how to get the Factory class defined in the MyType interface and then get the new instance.

Any comment or hint is appreciated. Thanks in advance.

答:
So, you have an inner class Factory declared inside your interface MyType? If I have that right, and if Factory is the only member class declared by `MyType', and if I understand what you're looking for, then the following should work.

```<code>clz.getDeclaredClasses( )[0].newInstance( );
</code>```

Edit: Tested my answer out, and it works. I wasn't aware of the technique Pangea mentioned, but that works, too, and it's better than my answer. The code would look like this.

```<code>Class.forName("MyType$Factory").newInstance( );
</code>```

Body:
I've got a xsd file with over 100 types defined in it. I generated java code with xmlbeans binding, and then I can use

MyType.Factory.newInstance();

to get the class instance. But since there are too many types I've decide to use reflection to get create instances for each type.

I can now get the class(interface) of MyType using

Class clz = Class.forName("com.foo.MyType");

But have no idea of how to get the Factory class defined in the MyType interface and then get the new instance.

Any comment or hint is appreciated. Thanks in advance.

Body:
So, you have an inner class Factory declared inside your interface MyType? If I have that right, and if Factory is the only member class declared by `MyType', and if I understand what you're looking for, then the following should work.

clz.getDeclaredClasses( )[0].newInstance( );

Edit: Tested my answer out, and it works. I wasn't aware of the technique Pangea mentioned, but that works, too, and it's better than my answer. The code would look like this.

Class.forName("MyType$Factory").newInstance( );


问:
Can I build a localhost resided on an IOS(ipad ,iphone) or Android tablets with Node.js(JXcore) ?
Background: we have an existing web application written in JAVA with tomcat, JVM environment etc.

And now, the client want to have the partial application running on their tablet devices in an offline environment which breaks the rule of Client-Server (no internet access !)

In order to do less coding/development, our team decided to use nodejs and to write a light weight platform independent server side code, (localhost +browser access, it seems awkward, but it is impossible to rewrite the whole application in Swift and SDK etc).

Can this be achieved though JXcore or other frameworks?
(it is just a CRUD type application)

Or what other solution you can think of in this situation. (no internet connection environment)

答:
No. You can't create a native iOS app using Node.js

And also there isn't any bridging between Swift and Node.js

Though there is something called NodObjC which exposes the Objective-C runtime to Node.js in a high-level.


问:
How to print the elements in odd positions in a list using an iterative function in Lisp?
I have to make a recursive function in lisp which takes a list and makes another list with only the elements on odd position in the given list.

If I have (1 2 3 4 5) I have to output (1 3 5)

I have a code here:

```<code>(defun pozpar(lst) (do(
(l lst (cddr l))
(x '() (cons x (car l))))
((null l) x)))
</code>```

This outputs:

```<code>(5 3 1)
</code>```

I know cons adds the elements at the beginning and I tried with append or list but nothing worked.

答:
The easiest way is to reverse the result:

```<code>(defun pozpar (lst)
  (do ((l lst (cddr l))
       (x '() (cons (car l) x)))
      ((null l)
       (nreverse x))))

(pozpar '(1 2 3 4 5))
==> (1 3 5)
</code>```

Notes

This returns, not outputs the value you want.

Prepending values and reverting the result is a common Lisp coding pattern.

Since append is linear in the length of its argument, using it in a loop produces quadratic code.

I formatted the code in the standard Lisp way. If you use this style, lispers will have an easier time reading your code, and, consequently, more willing to help you.

Body:
I have to make a recursive function in lisp which takes a list and makes another list with only the elements on odd position in the given list.

If I have (1 2 3 4 5) I have to output (1 3 5)

I have a code here:

(defun pozpar(lst) (do(
(l lst (cddr l))
(x '() (cons x (car l))))
((null l) x)))

This outputs:

(5 3 1)

I know cons adds the elements at the beginning and I tried with append or list but nothing worked.

Body:
The easiest way is to reverse the result:

(defun pozpar (lst)
  (do ((l lst (cddr l))
       (x '() (cons (car l) x)))
      ((null l)
       (nreverse x))))

(pozpar '(1 2 3 4 5))
==> (1 3 5)

Notes

This returns, not outputs the value you want.

Prepending values and reverting the result is a common Lisp coding pattern.

Since append is linear in the length of its argument, using it in a loop produces quadratic code.

I formatted the code in the standard Lisp way. If you use this style, lispers will have an easier time reading your code, and, consequently, more willing to help you.


问:
pandas: calculate percentiles within subgroups?
I've got a Pandas dataframe that looks like this:

```<code> school_id  uni_id  points
 123        44      180
 123        45      160
 123        45      160
 123        48      110
 124        44      180
 124        45      160
 124        47      130
 123        48      120
</code>```

Generated as follows, to help kind answerers:

```<code>df = pd.DataFrame({
    'school_id': [123, 123, 123, 123, 124, 124, 124, 124],
    'school_id': [44, 45, 45, 48, 44, 45, 47, 48],
    'points': [180, 160, 160, 110, 180, 160, 130, 120]
})
</code>```

I'd like to add a percentile column, which represents the percentile of the points value for each school. So this dataset would look like this:

```<code> school_id  uni_id  points  percentile
 123        44      180     100
 123        45      160     50
 123        45      160     50
 123        48      110     0
 124        44      180     100
 124        45      160     66
 124        47      130     33
 123        48      120     0
</code>```

What's the best way to do this? I assume that I need to group by school_id, then do df.quantile() within each subgroup somehow, then ungroup?

UPDATE: Maybe I need to start with something like this... df.groupby('school_id')['points'].rank(ascending=False) and then divide the rank by the length of each group to normalise it between 0 and 100?

答:
You are looking to do several things here.

you want your rankings to be dense

you want to have the lowest be zero and the highest be 100.  I call this inclusive ranking

I create a separate function to apply with.

```<code>def dense_inclusive_pct(x):
    # I subtract one to handle the inclusive bit
    r = x.rank(method='dense') - 1
    return r / r.max() * 100

df.assign(pct=df.groupby('school_id').points.apply(dense_inclusive_pct).astype(int))

   points  school_id  uni_id  pct
0     180        123      44  100
1     160        123      45   50
2     160        123      45   50
3     110        123      48    0
4     180        124      44  100
5     160        124      45   66
6     130        124      47   33
7     120        124      48    0
</code>```

Body:
I've got a Pandas dataframe that looks like this:

 school_id  uni_id  points
 123        44      180
 123        45      160
 123        45      160
 123        48      110
 124        44      180
 124        45      160
 124        47      130
 123        48      120

Generated as follows, to help kind answerers:

df = pd.DataFrame({
    'school_id': [123, 123, 123, 123, 124, 124, 124, 124],
    'school_id': [44, 45, 45, 48, 44, 45, 47, 48],
    'points': [180, 160, 160, 110, 180, 160, 130, 120]
})

I'd like to add a percentile column, which represents the percentile of the points value for each school. So this dataset would look like this:

 school_id  uni_id  points  percentile
 123        44      180     100
 123        45      160     50
 123        45      160     50
 123        48      110     0
 124        44      180     100
 124        45      160     66
 124        47      130     33
 123        48      120     0

What's the best way to do this? I assume that I need to group by school_id, then do df.quantile() within each subgroup somehow, then ungroup?

UPDATE: Maybe I need to start with something like this... df.groupby('school_id')['points'].rank(ascending=False) and then divide the rank by the length of each group to normalise it between 0 and 100?

Body:
You are looking to do several things here.

you want your rankings to be dense

you want to have the lowest be zero and the highest be 100.  I call this inclusive ranking

I create a separate function to apply with.

def dense_inclusive_pct(x):
    # I subtract one to handle the inclusive bit
    r = x.rank(method='dense') - 1
    return r / r.max() * 100

df.assign(pct=df.groupby('school_id').points.apply(dense_inclusive_pct).astype(int))

   points  school_id  uni_id  pct
0     180        123      44  100
1     160        123      45   50
2     160        123      45   50
3     110        123      48    0
4     180        124      44  100
5     160        124      45   66
6     130        124      47   33
7     120        124      48    0


问:
How can I solve the Diverging implicit expansion for type
I want to make my case class Event[K, V] be ordered by key K always. But I need to be able to compare Events of different values V. How can I solve this diverging implicit expansion?

```<code>import scala.math.Ordering

object Event {
  case class Event[K, V](key: K, value: V)
    (implicit o: Ordering[K]) extends Ordered[Event[K, _]] {
      override def compare(that: Event[K, _]): Int = o.compare(key, that.key)
    }
}

object Main extends App {
  // mimicking a librarys function
  def lala[O](e: O)(implicit ordering: Ordering[O]) = ???

  val b = Event.Event("a", 12) <= Event.Event("a", 11.99)
  lala(Event.Event("a", 12))
}
</code>```

The call to lala does not compile because of this diverging implicit expansion:

```<code>diverging implicit expansion for type
scala.math.Ordering[Event.Event[String,Int]] starting with method $conforms
in object Predef lala(Event.Event("a", 12))
</code>```

答:
If your library method expects an Ordering instance for your type, you should provide that indead of extended Ordered, which is totally underalted from a compiler point of view. Try the following instead:

```<code>case class Event[K, V](key: K, value: V)

object Event {
  implicit def eventOrdering[K, V](implicit o: Ordering[K]) =
    new Ordering[Event[K, V]] {
      // ...
    }
}
</code>```

Body:
I want to make my case class Event[K, V] be ordered by key K always. But I need to be able to compare Events of different values V. How can I solve this diverging implicit expansion?

import scala.math.Ordering

object Event {
  case class Event[K, V](key: K, value: V)
    (implicit o: Ordering[K]) extends Ordered[Event[K, _]] {
      override def compare(that: Event[K, _]): Int = o.compare(key, that.key)
    }
}

object Main extends App {
  // mimicking a librarys function
  def lala[O](e: O)(implicit ordering: Ordering[O]) = ???

  val b = Event.Event("a", 12) <= Event.Event("a", 11.99)
  lala(Event.Event("a", 12))
}

The call to lala does not compile because of this diverging implicit expansion:

diverging implicit expansion for type
scala.math.Ordering[Event.Event[String,Int]] starting with method $conforms
in object Predef lala(Event.Event("a", 12))

Body:
If your library method expects an Ordering instance for your type, you should provide that indead of extended Ordered, which is totally underalted from a compiler point of view. Try the following instead:

case class Event[K, V](key: K, value: V)

object Event {
  implicit def eventOrdering[K, V](implicit o: Ordering[K]) =
    new Ordering[Event[K, V]] {
      // ...
    }
}


问:
cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle Mac
I have cx_Oracle installed and I can successfully import it. But when I try to establish an Oracle connection, I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle

My operating system is MacOSX, and my ORACLE_HOME is pointing to instantclient_11_2.

答:
Have you tried fixing how you were connecting?  It sounds like you set it up correctly.

Please try the following (fill in your own information):

```<code>ip_addr = 'ip address'
port = 1521
sid = 'sid'
dsn_tns = cx_Oracle.makedsn(ip_addr, port, sid)
db = cx_Oracle.connect('username', 'password', dsn_tns)
</code>```

If that doesn't work, please make sure your LD_LIBRARY_PATH is set correctly.

Body:
Have you tried fixing how you were connecting?  It sounds like you set it up correctly.

Please try the following (fill in your own information):

ip_addr = 'ip address'
port = 1521
sid = 'sid'
dsn_tns = cx_Oracle.makedsn(ip_addr, port, sid)
db = cx_Oracle.connect('username', 'password', dsn_tns)

If that doesn't work, please make sure your LD_LIBRARY_PATH is set correctly.


问:
dynamically change method name inside array in ruby
I have a user object which i access like this.. user.email, user.first_name

Now I want to loop through each and return a message based on the current key in loop somewhat like this.

```<code>[user.first_name, user.email, user.last_name].each do |key|
      puts "#{key} is required"
 end
</code>```

The above works but loops through values instead of fields. so will do this below but how to prepend user to keys and get values inside array?

```<code>[first_name, email, last_name].each do |key|
 #inside here I want to prepend the user to the keys so that I can access like user.key

 puts "#{user.key} is required"
end
</code>```

If this was a string we can concatenate but how to deal with this here as its a method call?

答:
```<code>[first_name, email, last_name].each do |key|
 puts user.send(key)
end
</code>```

Body:
I have a user object which i access like this.. user.email, user.first_name

Now I want to loop through each and return a message based on the current key in loop somewhat like this.

[user.first_name, user.email, user.last_name].each do |key|
      puts "#{key} is required"
 end

The above works but loops through values instead of fields. so will do this below but how to prepend user to keys and get values inside array?

[first_name, email, last_name].each do |key|
 #inside here I want to prepend the user to the keys so that I can access like user.key

 puts "#{user.key} is required"
end

If this was a string we can concatenate but how to deal with this here as its a method call?


答:
You can simply do:</p>

```<code>user.send(key)
</code>```

Title: dynamically change method name inside array in ruby

Body:
You can simply do:

user.send(key)


问:
Python Pandas Iterate over rows and count how many times a unique pair of columns has shown
I'm trying to add a column to count the how many times a date at a station (No) has shown.

For example, Date 6/12/2013 show only 1 record at No1, so it is counted as 1. There are 3 records on 5/11/2013 at No 3. The first occurrence should count as 1, the second occurrence are counted as 2 and so on, and the third occurrence are counted as 3.

Input:

```<code>    No   Date        Value
0   1    6/12/2013   35
1   1    6/13/2013   45
2   1    6/14/2013   23
3   1    6/14/2013   40
4   2    6/12/2013   15
5   2    6/13/2013   20
6   2    6/14/2013   24
7   2    7/23/2013   33
8   3    5/11/2013   10
9   3    5/11/2013   11
10  3    5/11/2013   34
11  3    5/18/2013   24
.
.
.
</code>```

The result should look like this:

```<code>    No   Date        Value    count
0   1    6/12/2013   35       1
1   1    6/13/2013   45       1
2   1    6/14/2013   23       1
3   1    6/14/2013   40       2
4   2    6/12/2013   15       1
5   2    6/13/2013   20       1
6   2    6/14/2013   24       1
7   2    7/23/2013   33       1
8   3    5/11/2013   10       1
9   3    5/11/2013   11       2
10  3    5/11/2013   34       3
11  3    5/18/2013   24       1
.
.
.
</code>```

My own solution is

```<code>result = []
for n in df['No'].unique():
    df1 = df[df['No'] == n]
    for date in df1['Date'].unique():
        df2 = df1[df1['Date'] == date]
        df2['count'] = np.arange(len(df2)) + 1
        result.append(df2)
</code>```

and merge the result together. But it runs pretty slow. Any better solution?

Body:
I'm trying to add a column to count the how many times a date at a station (No) has shown.

For example, Date 6/12/2013 show only 1 record at No1, so it is counted as 1. There are 3 records on 5/11/2013 at No 3. The first occurrence should count as 1, the second occurrence are counted as 2 and so on, and the third occurrence are counted as 3.

Input:

    No   Date        Value
0   1    6/12/2013   35
1   1    6/13/2013   45
2   1    6/14/2013   23
3   1    6/14/2013   40
4   2    6/12/2013   15
5   2    6/13/2013   20
6   2    6/14/2013   24
7   2    7/23/2013   33
8   3    5/11/2013   10
9   3    5/11/2013   11
10  3    5/11/2013   34
11  3    5/18/2013   24
.
.
.

The result should look like this:

    No   Date        Value    count
0   1    6/12/2013   35       1
1   1    6/13/2013   45       1
2   1    6/14/2013   23       1
3   1    6/14/2013   40       2
4   2    6/12/2013   15       1
5   2    6/13/2013   20       1
6   2    6/14/2013   24       1
7   2    7/23/2013   33       1
8   3    5/11/2013   10       1
9   3    5/11/2013   11       2
10  3    5/11/2013   34       3
11  3    5/18/2013   24       1
.
.
.

My own solution is

result = []
for n in df['No'].unique():
    df1 = df[df['No'] == n]
    for date in df1['Date'].unique():
        df2 = df1[df1['Date'] == date]
        df2['count'] = np.arange(len(df2)) + 1
        result.append(df2)

and merge the result together. But it runs pretty slow. Any better solution?

Body:
Perform a groupby and use cumcount:

df['count'] = df.groupby(['No', 'Date']).cumcount() + 1

Adding 1 in necessary since cumcount starts at 0.

The resulting output:

    No       Date  Value  count
0    1  6/12/2013     35      1
1    1  6/13/2013     45      1
2    1  6/14/2013     23      1
3    1  6/14/2013     40      2
4    2  6/12/2013     15      1
5    2  6/13/2013     20      1
6    2  6/14/2013     24      1
7    2  7/23/2013     33      1
8    3  5/11/2013     10      1
9    3  5/11/2013     11      2
10   3  5/11/2013     34      3
11   3  5/18/2013     24      1