问:
Hover effect not working from the second time in Safari
I'm facing a weird problem with safari

I'm now developing a website that loads its contents with Ajax I'm applying this by using Hashchange methodology and when hashchange

I'm getting the url and then load the content for the page

```<code>    jQuery(window).bind('hashchange', function () {
    url = window.location.hash.substring(1);
    if (!url) {
        return;
    }

        var tsTimeStamp= new Date().getTime();

        jQuery.get(url, { action: "get", time: tsTimeStamp,"ajaxed": "true"} , function (data, status, xmlHttp) {

            var container = jQuery("#hidden");
            container.html(xmlHttp.responseText);
            var content = jQuery(".inner", container).html();}
</code>```

and then after loading the content I'm applying some jquery stuff like

```<code>                var ids = " ";
                var ids_2 = " ";
                for (var i = 0; i <= jQuery(".cats").length; i++) {
                    ids += "#c" + i + ",";
                    ids_2 += "#l" + i + ",";
                }

                ids = ids.substr(0, (ids.length) - 1);
                ids_2 = ids_2.substr(0, (ids_2.length) - 1);
                jQuery(ids).hover(function () {
                    href = jQuery(this).attr("href");
                    id = jQuery('a[href="' + href + '"]').attr("id");
                    jQuery("img").not(jQuery("img."+id)).addClass("op");

                }, function () {
                    time = setTimeout(remove, 200);

                });

                jQuery(ids_2).hover(function () {

                    clearTimeout(time);
                    jQuery("img.op").removeClass("op");
                    href = jQuery(this).attr("href");
                    id = jQuery('a[href="' + href + '"]').attr("id");
                    jQuery("img").not(jQuery("img." + id)).addClass("op");

                }, function () {

                    jQuery("img.op").delay(200).removeClass("op");

                });
                function remove() {
                    jQuery("img.op").removeClass("op");
                }
</code>```

The above code is applying hover over effect on map areas for images

(this code is applicable to 4 pages).

All the above code is working fine with all the browser except Safari

The problem is when the first page that contains the maps loaded the code is working fine but when you load another page contains the same areas it will stop working until the whole page being refreshed.

seems like it caches the handler for the first time and then does not apply it to the new selectors

Keep in mind that when Alert ids & ids_2 it gives the correct values but when using alert inside the .hover it does not fire in the second time.

I know its complicated but really I'm stuck with this issue.

答:
Well, it would be better to have small code snippets, but from what I can see you're having problem on binding jQuery handlers on newly created elements. To solve this problem you have to use the jQuery .live().

From jQuery documentation:

This method is a variation on the
  basic .bind() method for attaching
  event handlers to elements. When
  .bind() is called, the elements that
  the jQuery object refers to get the
  handler attached; elements that get
  introduced later do not, so they would
  require another .bind() call.

The .live() method provides an
  alternative to this behavior. To bind
  a click handler to the target element
  using this method:

```<code>$('.hoverme').live('hover', function(){
    // Live handler called.
});
</code>```

And then later add a new element:

```<code>$('body').append('<div class="hoverme">Another target</div>');
</code>```

Then clicks on the new element will
  also trigger the handler.

Body:
I'm facing a weird problem with safari

I'm now developing a website that loads its contents with Ajax I'm applying this by using Hashchange methodology and when hashchange

I'm getting the url and then load the content for the page

    jQuery(window).bind('hashchange', function () {
    url = window.location.hash.substring(1);
    if (!url) {
        return;
    }

        var tsTimeStamp= new Date().getTime();

        jQuery.get(url, { action: "get", time: tsTimeStamp,"ajaxed": "true"} , function (data, status, xmlHttp) {

            var container = jQuery("#hidden");
            container.html(xmlHttp.responseText);
            var content = jQuery(".inner", container).html();}

and then after loading the content I'm applying some jquery stuff like

                var ids = " ";
                var ids_2 = " ";
                for (var i = 0; i <= jQuery(".cats").length; i++) {
                    ids += "#c" + i + ",";
                    ids_2 += "#l" + i + ",";
                }

                ids = ids.substr(0, (ids.length) - 1);
                ids_2 = ids_2.substr(0, (ids_2.length) - 1);
                jQuery(ids).hover(function () {
                    href = jQuery(this).attr("href");
                    id = jQuery('a[href="' + href + '"]').attr("id");
                    jQuery("img").not(jQuery("img."+id)).addClass("op");

                }, function () {
                    time = setTimeout(remove, 200);

                });

                jQuery(ids_2).hover(function () {

                    clearTimeout(time);
                    jQuery("img.op").removeClass("op");
                    href = jQuery(this).attr("href");
                    id = jQuery('a[href="' + href + '"]').attr("id");
                    jQuery("img").not(jQuery("img." + id)).addClass("op");

                }, function () {

                    jQuery("img.op").delay(200).removeClass("op");

                });
                function remove() {
                    jQuery("img.op").removeClass("op");
                }

The above code is applying hover over effect on map areas for images

(this code is applicable to 4 pages).

All the above code is working fine with all the browser except Safari

The problem is when the first page that contains the maps loaded the code is working fine but when you load another page contains the same areas it will stop working until the whole page being refreshed.

seems like it caches the handler for the first time and then does not apply it to the new selectors

Keep in mind that when Alert ids & ids_2 it gives the correct values but when using alert inside the .hover it does not fire in the second time.

I know its complicated but really I'm stuck with this issue.

Body:
Well, it would be better to have small code snippets, but from what I can see you're having problem on binding jQuery handlers on newly created elements. To solve this problem you have to use the jQuery .live().

From jQuery documentation:

This method is a variation on the
  basic .bind() method for attaching
  event handlers to elements. When
  .bind() is called, the elements that
  the jQuery object refers to get the
  handler attached; elements that get
  introduced later do not, so they would
  require another .bind() call.

The .live() method provides an
  alternative to this behavior. To bind
  a click handler to the target element
  using this method:

$('.hoverme').live('hover', function(){
    // Live handler called.
});

And then later add a new element:

$('body').append('<div class="hoverme">Another target</div>');

Then clicks on the new element will
  also trigger the handler.


来源: stackexchange

问:
Does Gatsby need to rebuild my entire site every time a docpage is updated?
I am creating a Documentation site to hold DocPages for each of my products. Gatsby is building all of my sites as static pages. I have multiple tech writers who are constantly updating and creating new pages. How does Gatsby handle this? Do I have to rebuild my entire site with Gatsby each time something is updated? </p>

答:
I know it is an old question, but I struggled with this today and it seems noone out there gave a decent post or answer about it, Gatsby v2 still rebuilds everything when you restart gatsby develop. This is a no-go if your build takes 20min on first run. My solution is below.

You could use the cache API  to save a hash or updatedAt info of your data, and only call createPage action if the cache doesn't match (the data was updated)

This is how I do it in my project:

```<code>exports.createPages = async ({ actions: { createPage }, graphql, cache }) => {
  const results = await graphql(`
    query GetAllCars {
      myNamespaceFromGraphqlSource {
        allCars {
          id
          updatedAt
        }
      }
    }
  `);

  const createDetailsPage = async (car) => {
    const carCache = await cache.get(car.id);
    if(carCache != car.updatedAt) {
      createPage({
        path: `/car_details/${car.id}/`,
        component: require.resolve("./src/templates/details.js"),
        context: {
          id: car.id,
        },
      });
      await cache.set(car.id, car.updatedAt);
    }
  }

  for(let i=0; i < results.data.myNamespaceFromGraphqlSource.allCars.length; i++ ) {
    const car = results.data.myNamespaceFromGraphqlSource.allCars[i];
    await createDetailsPage(car)
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know it is an old question, but I struggled with this today and it seems noone out there gave a decent post or answer about it, Gatsby v2 still rebuilds everything when you restart gatsby develop. This is a no-go if your build takes 20min on first run. My solution is below.

You could use the cache API  to save a hash or updatedAt info of your data, and only call createPage action if the cache doesn't match (the data was updated)

This is how I do it in my project:

exports.createPages = async ({ actions: { createPage }, graphql, cache }) => {
  const results = await graphql(`
    query GetAllCars {
      myNamespaceFromGraphqlSource {
        allCars {
          id
          updatedAt
        }
      }
    }
  `);

  const createDetailsPage = async (car) => {
    const carCache = await cache.get(car.id);
    if(carCache != car.updatedAt) {
      createPage({
        path: `/car_details/${car.id}/`,
        component: require.resolve("./src/templates/details.js"),
        context: {
          id: car.id,
        },
      });
      await cache.set(car.id, car.updatedAt);
    }
  }

  for(let i=0; i < results.data.myNamespaceFromGraphqlSource.allCars.length; i++ ) {
    const car = results.data.myNamespaceFromGraphqlSource.allCars[i];
    await createDetailsPage(car)
  }

ContentLicense: CC BY-SA 4.0


问:
Determine availability for resources on n date periods
Given the following tables:

resources

```<code>| id | name |
| 1  | John |
| 2  | Anna |
</code>```

bookings

```<code>| id | start               | end                | resource_id |
| 1  | 2020-05-29 08:00:00 |2020-05-29 12:00:00 | 1           |
</code>```

I want to find all resource available for n date periods. I can build a dynamic query using subquery as following:

SELECT name, (
    SELECT COUNT(id) FROM bookings WHERE
        resources.id = bookings.resource_id
        AND '2020-05-29 08:00:00' < `end`
        AND '2020-05-29 09:00:00' > `start`
) AS 'dp1',
(SELECT COUNT(id) FROM bookings WHERE
        resources.id = bookings.resource_id
        AND '2020-05-29 09:00:00' < `end`
        AND '2020-05-29 10:00:00' > `start`
) AS 'dp2'
FROM resources
```

<p>which gives me the following result:</p>

```| name | dp1 | dp2 |
| John | 1   | 1   |
| Anna | 0   | 0   |
```

This does not scale very well. If I want to determine availability for a whole week, from 08-17 that would be 70 subqueries with the current solution.

How can I determine availability for resources for a larger n given date periods more elegantly and efficiently?

答:
I would suggest putting periods in rows rather than in columns. This gives you an opportunity for a pure SQL solution - while you otherwise would need dynamic SQL.

If you are running MySQL 8.0, you can use a recursive query to enumerate the periods, cross join it with the resources table to get all the combinations, and then bring the table with a left join.

Here is a query that would give you the result that you want over a given week. You can adapt the boudaries in the cte as needed.

```<code>with period as (
    select '2020-05-22 08:00:00' ts1
    union all
    select case when hour(ts1) = 16
        then date_format(ts, '%Y-%m-%d 09:00:00') + interval 1 day
        else ts + interval 1 hour
    end
    from cte
    where ts < '2020-05-29 17:00:00'
)
select
    p.ts period,
    r.name,
    count(b.id) is_reserved
from periods p
cross join resources r
left join bookings b
    on  b.start <= p.ts + interval 1 hour
    and b.end   >= p.ts
    and b.resource_id = r.id
group by p.ts, r.name
</code>```

If you are going to run this query frequently, you should consider materializing the results of the cte in a table (that's the concept of a calendar table), that you can then use in your queries.

Body:
Given the following tables:

resources

| id | name |
| 1  | John |
| 2  | Anna |

bookings

| id | start               | end                | resource_id |
| 1  | 2020-05-29 08:00:00 |2020-05-29 12:00:00 | 1           |

I want to find all resource available for n date periods. I can build a dynamic query using subquery as following:

SELECT name, (
    SELECT COUNT(id) FROM bookings WHERE
        resources.id = bookings.resource_id
        AND '2020-05-29 08:00:00' < `end`
        AND '2020-05-29 09:00:00' > `start`
) AS 'dp1',
(SELECT COUNT(id) FROM bookings WHERE
        resources.id = bookings.resource_id
        AND '2020-05-29 09:00:00' < `end`
        AND '2020-05-29 10:00:00' > `start`
) AS 'dp2'
FROM resources

which gives me the following result:

| name | dp1 | dp2 |
| John | 1   | 1   |
| Anna | 0   | 0   |

This does not scale very well. If I want to determine availability for a whole week, from 08-17 that would be 70 subqueries with the current solution.

How can I determine availability for resources for a larger n given date periods more elegantly and efficiently?

Body:
I would suggest putting periods in rows rather than in columns. This gives you an opportunity for a pure SQL solution - while you otherwise would need dynamic SQL.

If you are running MySQL 8.0, you can use a recursive query to enumerate the periods, cross join it with the resources table to get all the combinations, and then bring the table with a left join.

Here is a query that would give you the result that you want over a given week. You can adapt the boudaries in the cte as needed.

with period as (
    select '2020-05-22 08:00:00' ts1
    union all
    select case when hour(ts1) = 16
        then date_format(ts, '%Y-%m-%d 09:00:00') + interval 1 day
        else ts + interval 1 hour
    end
    from cte
    where ts < '2020-05-29 17:00:00'
)
select
    p.ts period,
    r.name,
    count(b.id) is_reserved
from periods p
cross join resources r
left join bookings b
    on  b.start <= p.ts + interval 1 hour
    and b.end   >= p.ts
    and b.resource_id = r.id
group by p.ts, r.name

If you are going to run this query frequently, you should consider materializing the results of the cte in a table (that's the concept of a calendar table), that you can then use in your queries.


问:
Python Dictionary How to create combinations of list items?
I have a dictionary which has value as a list.

```<code>thisdict = {  'G1' : [10,20],
              'G2' : [12,13]

}
</code>```

I want to create new dictionary with  all possible 4 combinations.

C1 :[10,12]

C2 :[10,13]

C3 :[20,12]

C4 :[20,13]

How do I create that ?

答:
Is this acceptable?

```<code>from itertools import product

d = {}
offset = 1
for e in product(thisdict['G1'], thisdict['G2']):
    d[f'C{offset}'] = list(e)
    offset += 1
print(d)

</code>```

Output:

```<code>{'C1': [10, 12], 'C2': [10, 13], 'C3': [20, 12], 'C4': [20, 13]}
</code>```

Body:
I have a dictionary which has value as a list.

thisdict = {  'G1' : [10,20],
              'G2' : [12,13]

}

I want to create new dictionary with  all possible 4 combinations.

C1 :[10,12]

C2 :[10,13]

C3 :[20,12]

C4 :[20,13]

How do I create that ?

Body:
Is this acceptable?

from itertools import product

d = {}
offset = 1
for e in product(thisdict['G1'], thisdict['G2']):
    d[f'C{offset}'] = list(e)
    offset += 1
print(d)

Output:

{'C1': [10, 12], 'C2': [10, 13], 'C3': [20, 12], 'C4': [20, 13]}


问:
How to add permalink to widget in Wordpress?
I'm trying to add Outbrain widget to my Wordpress blog and the code is:

```<code><div class="OUTBRAIN" data-src="DROP_PERMALINK_HERE" data-widget-id="XX_1" data-ob-template=“NameGoesHere”></div>
<script type="text/javascript" async="async" src="http://widgets.outbrain.com/outbrain.js"></script>
</code>```

The problem is if I add this into the single.php, I can easily do it using <?php the_permalink(); ?> in place of DROP_PERMALINK_HERE. But I want to add the widget as a Wordpress widget and the text widget in Wordpress allows only HTML and PHP won't run there. So what do I do?

Get the URL of the page through Javascript? Or is there a better way?

Kindly guide.

答:
This is absolutely very easy to do.

All you need is a Header and Footer plugin. With this, you can add the Outbrain code (Widget) to your blog easily.
- Just paste the code in the post-tab of the header and footer.

Body:
I'm trying to add Outbrain widget to my Wordpress blog and the code is:

The problem is if I add this into the single.php, I can easily do it using <?php the_permalink(); ?> in place of DROP_PERMALINK_HERE. But I want to add the widget as a Wordpress widget and the text widget in Wordpress allows only HTML and PHP won't run there. So what do I do?

Get the URL of the page through Javascript? Or is there a better way?

Kindly guide.


问:
Incorporating prop validation
How do I make so that my code return warning in the console if the Prop-value is not string?
The player-name-prop is supposed to be equal to string at all times.

If this: <greet :player-name="5"></greet> contains a number, I want to return a warning from my code below:

```<code>Vue.component('greet', {
  props: {
    'player-name': {
      type: String,
      required: true

    }

  },
  data() {
    return {

    }
  },
  props: ['player-name'],
  template: '<div>Welcome, {{playerName}}!</div>'
})

new Vue({
  el: '#app'
})
</code>```

答:
Vue itself warns you that prop validation failed. Check the devtools console out.

You should get a warning like this:

Title: Incorporating prop validation

Body:
How do I make so that my code return warning in the console if the Prop-value is not string?
The player-name-prop is supposed to be equal to string at all times.

If this: <greet :player-name="5"></greet> contains a number, I want to return a warning from my code below:

Vue.component('greet', {
  props: {
    'player-name': {
      type: String,
      required: true

    }

  },
  data() {
    return {

    }
  },
  props: ['player-name'],
  template: '
Welcome, {{playerName}}!
'
})

new Vue({
  el: '#app'
})


问:
creating a java program to extract svn logs and store them in xml
I'd like to make a GUI that will take in a file directory and start date, and then find the svn logs associated with that directory and time frame.  Once I have the information, I can then parse it and store it in an xml.  The trouble is just getting the logs and reading the information off of them.

I've got svn client and can use the command line to retrieve information, but I want my java program to do this for me.

Does anyone know of a way to accomplish this? Please let me know if you have any questions that I can help you with.

答:
There is SVNKit which is a Java SVN Library

http://svnkit.com/

Also, note that SVN log already has the --xml flag which will generate it in xml form.

http://svnbook.red-bean.com/en/1.0/re15.html


问:
Firebase push notification on new chat message
I have created an app where I have chat in it.

I would like that the users will receive a notification that they got a new message whenever they are outside of the app.

In order to do so, I'm using Firebase service.

Now, whenever a message is sent, I call this method:
I have created the following MyFirebaseMessagingService class to test when it is called:

```<code>private class MyTask extends AsyncTask<MyTaskParams, Void, Void> {
    @Override
    protected Void doInBackground(MyTaskParams... params) {
        String userDeviceIdKey = params[0].url;
        String title = params[0].title;
        String body = params[0].body;

        String authKey = "XXXXX";   // You FCM AUTH key
        String FMCurl = "https://fcm.googleapis.com/fcm/send";
        URL url;
        try {
            url = new URL(FMCurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization","key="+authKey);
            conn.setRequestProperty("Content-Type","application/json");

            JSONObject json = new JSONObject();
            json.put("to",userDeviceIdKey);
            json.put("priority","high");
            JSONObject info = new JSONObject();
            info.put("title", title);   // Notification title
            info.put("body", body); // Notification body
            info.put("var1", chatID);
            info.put("var2",receiverID);
            info.put("var3",itemID);
            json.put("data", info);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();
            Log.w("", "getInstanceId failed" + json);

            conn.getInputStream();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
}
</code>```

and In my Service I created:

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d("TESTING_MESSAGE", "" + remoteMessage);

    }

}
</code>```

However, It seems like I never get this Log when I send a message and it doesnt look like onMessageReceived is ever called.

Is there any reason?

My next goal is to make notification inside onMessageReceived but I want to make sure first that I get there.

My manifest is:

```<code><service
    android:name=".service.MyFirebaseMessagingService"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
</service>
</code>```

答:
The onMessageReceived() method will never be called if the app is killed.
Firebase onMessageReceived not called when app in background

Body:
I have created an app where I have chat in it.

I would like that the users will receive a notification that they got a new message whenever they are outside of the app.

In order to do so, I'm using Firebase service.

Now, whenever a message is sent, I call this method:
I have created the following MyFirebaseMessagingService class to test when it is called:

private class MyTask extends AsyncTask<MyTaskParams, Void, Void> {
    @Override
    protected Void doInBackground(MyTaskParams... params) {
        String userDeviceIdKey = params[0].url;
        String title = params[0].title;
        String body = params[0].body;

        String authKey = "XXXXX";   // You FCM AUTH key
        String FMCurl = "https://fcm.googleapis.com/fcm/send";
        URL url;
        try {
            url = new URL(FMCurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization","key="+authKey);
            conn.setRequestProperty("Content-Type","application/json");

            JSONObject json = new JSONObject();
            json.put("to",userDeviceIdKey);
            json.put("priority","high");
            JSONObject info = new JSONObject();
            info.put("title", title);   // Notification title
            info.put("body", body); // Notification body
            info.put("var1", chatID);
            info.put("var2",receiverID);
            info.put("var3",itemID);
            json.put("data", info);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();
            Log.w("", "getInstanceId failed" + json);

            conn.getInputStream();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
}

and In my Service I created:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d("TESTING_MESSAGE", "" + remoteMessage);

    }

}

However, It seems like I never get this Log when I send a message and it doesnt look like onMessageReceived is ever called.

Is there any reason?

My next goal is to make notification inside onMessageReceived but I want to make sure first that I get there.

My manifest is:

<service
    android:name=".service.MyFirebaseMessagingService"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
</service>


问:
Plot individual data points in each group after pandas groupby
I'd like to group a dataframe using several criteria and then visualize individual data points in each group using a scattered plot.

```<code>import pandas as pd
import seaborn as sns

df_tips = sns.load_dataset('tips')
df_tips.groupby(['sex', 'day', 'smoker'])['tip']    # How could I scatter plot individual tip in each group?
</code>```

Ideally, I'd like to have something looks like this:

答:
I would do:

```<code>df_tips = sns.load_dataset('tips')
groups = df_tips.groupby(['sex', 'day', 'smoker'])['tip']

fig,ax = plt.subplots()
for  i,(k,v) in enumerate(groups):
    ax.scatter([i]*len(v), v)

ax.set_xticks(np.arange(len(groups)))
ax.set_xticklabels([k for k,v in groups],rotation=90);
</code>```

Output:

Body:
I'd like to group a dataframe using several criteria and then visualize individual data points in each group using a scattered plot.

import pandas as pd
import seaborn as sns

df_tips = sns.load_dataset('tips')
df_tips.groupby(['sex', 'day', 'smoker'])['tip']    # How could I scatter plot individual tip in each group?

Ideally, I'd like to have something looks like this:

Body:
I would do:

df_tips = sns.load_dataset('tips')
groups = df_tips.groupby(['sex', 'day', 'smoker'])['tip']

fig,ax = plt.subplots()
for  i,(k,v) in enumerate(groups):
    ax.scatter([i]*len(v), v)

ax.set_xticks(np.arange(len(groups)))
ax.set_xticklabels([k for k,v in groups],rotation=90);

Output:


问:
How do I pass a textfile into a 2D array in c++?
I am required to pass a textfile that contains comma separated integers into a 2D array in c++.
eg if the textfile looks like:

```<code>2,3,56,4
3,5,7,1
0,23,9,87
2,4,5,2
</code>```

I need to put this into a 2D array so that I may later perform calculations (which I do know how to do).
I have the following code, but I am struggling very much. Any help would be appreciated. Thank you.

```<code>#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
int main()
{

    const int row =4;
    const int col =4;
    int array[row][col];
    int r =0;
    int c =0;

    ifstream inputfile("numbers.txt");
    if (!inputfile.is_open())
    {
        cout<<"error"<<endl;
    }
    string line,num;
    int number;
    while(get line(inputfile,line))
    {
        string stream ss(line);
        getline(ss,num,',');
        number = stoi(num);

        for (int r=0; r<row;r++)
        {
            for (int c=0; c<col; c++)
            {
                array[row][col] =number;
            }
        }

        inputfile.close();
        return 0;
    }
</code>```

答:
Here is a simple example:

```<code>static const int MAX_ROWS = 4;
static const int MAX_COLUMNS] = 4;
int matrix[MAX_ROWS][MAX_COLUMNS];
//...
for (int row = 0; row < MAX_ROWS; ++ row)
{
    std::string row_text;
    std::getline(inputfile, row_text);
    std::istringstream row_stream(row_text);
    for (int column = 0; column < MAX_COLUMNS; ++column)
    {
       int number;
       char delimiter;
       row_stream >> number >> delimiter;
       matrix[row][column] = number;
    }
}
</code>```

The above assumes that the text file contains the exact quantity of numbers.

Since the separators differ at the end of a line, each line is read as a string, then use std::istringstream to treat the stream as a file.

Body:
I am required to pass a textfile that contains comma separated integers into a 2D array in c++.
eg if the textfile looks like:

2,3,56,4
3,5,7,1
0,23,9,87
2,4,5,2

I need to put this into a 2D array so that I may later perform calculations (which I do know how to do).
I have the following code, but I am struggling very much. Any help would be appreciated. Thank you.

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
int main()
{

    const int row =4;
    const int col =4;
    int array[row][col];
    int r =0;
    int c =0;

    ifstream inputfile("numbers.txt");
    if (!inputfile.is_open())
    {
        cout<<"error"<<endl;
    }
    string line,num;
    int number;
    while(get line(inputfile,line))
    {
        string stream ss(line);
        getline(ss,num,',');
        number = stoi(num);

        for (int r=0; r<row;r++)
        {
            for (int c=0; c<col; c++)
            {
                array[row][col] =number;
            }
        }

        inputfile.close();
        return 0;
    }

Body:
Here is a simple example:

static const int MAX_ROWS = 4;
static const int MAX_COLUMNS] = 4;
int matrix[MAX_ROWS][MAX_COLUMNS];
//...
for (int row = 0; row < MAX_ROWS; ++ row)
{
    std::string row_text;
    std::getline(inputfile, row_text);
    std::istringstream row_stream(row_text);
    for (int column = 0; column < MAX_COLUMNS; ++column)
    {
       int number;
       char delimiter;
       row_stream >> number >> delimiter;
       matrix[row][column] = number;
    }
}

The above assumes that the text file contains the exact quantity of numbers.

Since the separators differ at the end of a line, each line is read as a string, then use std::istringstream to treat the stream as a file.


问:
Is there a way change an array to a string, split the values at a comma, and join each value via a new line?
I am writing a recursive function that prints an org chart. When logging, this function displays the hierarchy of the chart by adding spaces to the beginning of "subKeys".

Problem:
I am having trouble logging the array as a string and splitting the array and joining it with "\n".

Question:
Is there a way to implement .toString().split(",").join("\n") to results?

I've tried return results.toString().split(",").join("\n") under // Base case and have been receiving a TypeError, TypeError: subKeys.map is not a function.

```<code>const displayOrgChart = (orgChart) => {

  let results = [];

  // General case
  for (let member in orgChart) {
    if (typeof orgChart[member] === "object") {
      let subKeys = displayOrgChart(orgChart[member]);
      results = results.concat(subKeys.map(subKey => {
        return "  " + subKey;
      }))
    } else {
      results.push(orgChart[member]);
    }
  }

  // Base case
  return results
};

console.log(displayOrgChart(orgChart));
</code>```

Array:

EDITED (5/28 2:52 pm): From object to array.

```<code>const orgChart = [
  {
    0: {
      name: "Zuckerberg",
      children: {
        0: {
          name: "Schroepfer",
          children: {
            0: {
              name: "Bosworth",
              children: {
                0: {
                  name: "Steve",
                },
                1: {
                  name: "Kyle",
                },
                2: {
                  name: "Andra",
                },
              },
            },
            1: {
              name: "Zhao",
              children: {
                0: {
                  name: "Richie",
                },
                1: {
                  name: "Sofia",
                },
                2: {
                  name: "Jen",
                },
              },
            },
          },
        },
        1: {
          name: "Schrage",
          children: {
            0: {
              name: "VanDyck",
              children: {
                0: {
                  name: "Sabrina",
                },
                1: {
                  name: "Michelle",
                },
                2: {
                  name: "Josh",
                },
              },
            },
            1: {
              name: "Swain",
              children: {
                0: {
                  name: "Blanch",
                },
                1: {
                  name: "Tom",
                },
                2: {
                  name: "Joe",
                },
              },
            },
          },
        },
        2: {
          name: "Sandberg",
          children: {
            0: {
              name: "Goler",
              children: {
                0: {
                  name: "Eddie",
                },
                1: {
                  name: "Julie",
                },
                2: {
                  name: "Annie",
                },
              },
            },
            1: {
              name: "Hernandez",
              children: {
                0: {
                  name: "Rowi",
                },
                1: {
                  name: "Inga",
                },
                2: {
                  name: "Morgan",
                },
              },
            },
            2: {
              name: "Moissinac",
              children: {
                0: {
                  name: "Amy",
                },
                1: {
                  name: "Chuck",
                },
                2: {
                  name: "Vinni",
                },
              },
            },
            3: {
              name: "Kelley",
              children: {
                0: {
                  name: "Eric",
                },
                1: {
                  name: "Ana",
                },
                2: {
                  name: "Wes",
                },
              },
            },
          },
        },
      },
    },
  },
];
</code>```

Current console log:

```<code>[
  '    Zuckerberg',
  '        Schroepfer',
  '            Bosworth',
  '                Steve',
  '                Kyle',
  '                Andra',
  '            Zhao',
  '                Richie',
  '                Sofia',
  '                Jen',
  '        Schrage',
  '            VanDyck',
  '                Sabrina',
  '                Michelle',
  '                Josh',
  '            Swain',
  '                Blanch',
  '                Tom',
  '                Joe',
  '        Sandberg',
  '            Goler',
  '                Eddie',
  '                Julie',
  '                Annie',
  '            Hernandez',
  '                Rowi',
  '                Inga',
  '                Morgan',
  '            Moissinac',
  '                Amy',
  '                Chuck',
  '                Vinni',
  '            Kelley',
  '                Eric',
  '                Ana',
  '                Wes'
]
</code>```

答:
To answer this:

Is there a way change an array to a string, split the values at a comma, and join each value via a new line?

Yes, there is. The process is:

convert results array to string with Array.prototype.toString()

replace the commas with newlines using String.prototype.replace()

const results = [
  '  Zuckerberg',          '      Schroepfer',
  '          Bosworth',    '              Steve',
  '              Kyle',    '              Andra',
  '          Zhao',        '              Richie',
  '              Sofia',   '              Jen',
  '      Schrage',         '          VanDyck',
  '              Sabrina', '              Michelle',
  '              Josh',    '          Swain',
  '              Blanch',  '              Tom',
  '              Joe',     '      Sandberg',
  '          Goler',       '              Eddie',
  '              Julie',   '              Annie',
  '          Hernandez',   '              Rowi',
  '              Inga',    '              Morgan',
  '          Moissinac',   '              Amy',
  '              Chuck',   '              Vinni',
  '          Kelley',      '              Eric',
  '              Ana',     '              Wes'
];
let tostr = results.toString();
let lines = tostr.replace(/,/g, '\n');
document.getElementById('results').innerHTML = lines;```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Result:
<pre id="results">``````

Body:
I am writing a recursive function that prints an org chart. When logging, this function displays the hierarchy of the chart by adding spaces to the beginning of "subKeys".

Problem:
I am having trouble logging the array as a string and splitting the array and joining it with "\n".

Question:
Is there a way to implement .toString().split(",").join("\n") to results?

I've tried return results.toString().split(",").join("\n") under // Base case and have been receiving a TypeError, TypeError: subKeys.map is not a function.

const displayOrgChart = (orgChart) => {

  let results = [];

  // General case
  for (let member in orgChart) {
    if (typeof orgChart[member] === "object") {
      let subKeys = displayOrgChart(orgChart[member]);
      results = results.concat(subKeys.map(subKey => {
        return "  " + subKey;
      }))
    } else {
      results.push(orgChart[member]);
    }
  }

  // Base case
  return results
};

console.log(displayOrgChart(orgChart));

Array:

EDITED (5/28 2:52 pm): From object to array.

const orgChart = [
  {
    0: {
      name: "Zuckerberg",
      children: {
        0: {
          name: "Schroepfer",
          children: {
            0: {
              name: "Bosworth",
              children: {
                0: {
                  name: "Steve",
                },
                1: {
                  name: "Kyle",
                },
                2: {
                  name: "Andra",
                },
              },
            },
            1: {
              name: "Zhao",
              children: {
                0: {
                  name: "Richie",
                },
                1: {
                  name: "Sofia",
                },
                2: {
                  name: "Jen",
                },
              },
            },
          },
        },
        1: {
          name: "Schrage",
          children: {
            0: {
              name: "VanDyck",
              children: {
                0: {
                  name: "Sabrina",
                },
                1: {
                  name: "Michelle",
                },
                2: {
                  name: "Josh",
                },
              },
            },
            1: {
              name: "Swain",
              children: {
                0: {
                  name: "Blanch",
                },
                1: {
                  name: "Tom",
                },
                2: {
                  name: "Joe",
                },
              },
            },
          },
        },
        2: {
          name: "Sandberg",
          children: {
            0: {
              name: "Goler",
              children: {
                0: {
                  name: "Eddie",
                },
                1: {
                  name: "Julie",
                },
                2: {
                  name: "Annie",
                },
              },
            },
            1: {
              name: "Hernandez",
              children: {
                0: {
                  name: "Rowi",
                },
                1: {
                  name: "Inga",
                },
                2: {
                  name: "Morgan",
                },
              },
            },
            2: {
              name: "Moissinac",
              children: {
                0: {
                  name: "Amy",
                },
                1: {
                  name: "Chuck",
                },
                2: {
                  name: "Vinni",
                },
              },
            },
            3: {
              name: "Kelley",
              children: {
                0: {
                  name: "Eric",
                },
                1: {
                  name: "Ana",
                },
                2: {
                  name: "Wes",
                },
              },
            },
          },
        },
      },
    },
  },
];

Current console log:

[
  '    Zuckerberg',
  '        Schroepfer',
  '            Bosworth',
  '                Steve',
  '                Kyle',
  '                Andra',
  '            Zhao',
  '                Richie',
  '                Sofia',
  '                Jen',
  '        Schrage',
  '            VanDyck',
  '                Sabrina',
  '                Michelle',
  '                Josh',
  '            Swain',
  '                Blanch',
  '                Tom',
  '                Joe',
  '        Sandberg',
  '            Goler',
  '                Eddie',
  '                Julie',
  '                Annie',
  '            Hernandez',
  '                Rowi',
  '                Inga',
  '                Morgan',
  '            Moissinac',
  '                Amy',
  '                Chuck',
  '                Vinni',
  '            Kelley',
  '                Eric',
  '                Ana',
  '                Wes'
]

Body:
To answer this:

Is there a way change an array to a string, split the values at a comma, and join each value via a new line?

Yes, there is. The process is:

convert results array to string with Array.prototype.toString()

replace the commas with newlines using String.prototype.replace()

const results = [
  '  Zuckerberg',          '      Schroepfer',
  '          Bosworth',    '              Steve',
  '              Kyle',    '              Andra',
  '          Zhao',        '              Richie',
  '              Sofia',   '              Jen',
  '      Schrage',         '          VanDyck',
  '              Sabrina', '              Michelle',
  '              Josh',    '          Swain',
  '              Blanch',  '              Tom',
  '              Joe',     '      Sandberg',
  '          Goler',       '              Eddie',
  '              Julie',   '              Annie',
  '          Hernandez',   '              Rowi',
  '              Inga',    '              Morgan',
  '          Moissinac',   '              Amy',
  '              Chuck',   '              Vinni',
  '          Kelley',      '              Eric',
  '              Ana',     '              Wes'
];
let tostr = results.toString();
let lines = tostr.replace(/,/g, '\n');
document.getElementById('results').innerHTML = lines;

Result:
<pre id="results"></pre>


答:
One possible approach would be to create a temporary table, where you will place the periods you are interested in called periods_table:

```<code>| period_id | period_start        | period_end         |
|        1  | 2020-05-29 08:00:00 |2020-05-29 09:00:00 |
|        2  | 2020-05-29 09:00:00 |2020-05-29 10:00:00 |
|        3  | 2020-05-29 10:00:00 |2020-05-29 11:00:00 |
|        4  | 2020-05-29 11:00:00 |2020-05-29 12:00:00 |
    ... etc
</code>```

And then you would match the periods against your values from bookings and resources:

```<code>SELECT name, period_start, period_end, count(period_id) FROM (
SELECT bookings.start, bookings.end JOIN resources ON
   resources.id = bookings.resource_id
) AS `subquery` JOIN periods_table WHERE
        period_end > `start`
        AND 'period_start' < `end`
)
</code>```

Title: Determine availability for resources on n date periods

Body:
One possible approach would be to create a temporary table, where you will place the periods you are interested in called periods_table:

| period_id | period_start        | period_end         |
|        1  | 2020-05-29 08:00:00 |2020-05-29 09:00:00 |
|        2  | 2020-05-29 09:00:00 |2020-05-29 10:00:00 |
|        3  | 2020-05-29 10:00:00 |2020-05-29 11:00:00 |
|        4  | 2020-05-29 11:00:00 |2020-05-29 12:00:00 |
    ... etc

And then you would match the periods against your values from bookings and resources:

SELECT name, period_start, period_end, count(period_id) FROM (
SELECT bookings.start, bookings.end JOIN resources ON
   resources.id = bookings.resource_id
) AS `subquery` JOIN periods_table WHERE
        period_end > `start`
        AND 'period_start' < `end`
)


问:
Incorrect display of data from two combined queries
I have two tables: Employees and Clients.
I wanted to make a query from two tables that do not have any relations, but for some reason the data is not displayed correctly.

worker:

users:

The Employees table doesn't have an employee with this type of data, and the Users table does, but I don't understand why the worker field appears in the results instead of the user field

答:
Alternative :</p>

```<code>SELECT worker.worker_id as worker, users.user_id as client
FROM worker,internet_magazine.users WHERE
worker.email='example@emai.ru' AND users.email='example@emai.ru'
</code>```

Body:
Alternative :

SELECT worker.worker_id as worker, users.user_id as client
FROM worker,internet_magazine.users WHERE
worker.email='example@emai.ru' AND users.email='example@emai.ru'


问:
How to implement Dump as the one provided by LinqPad?
Given (new [] {"a", "b"}).Dump(), LinqPad provides some very useful print results.

It seems that this extension method is a short hand for Console.WriteLine.

Question> how to implement this dump for myself?

答: You can grab the Object Dumper class that is included in the Visual C# 2008 Samples. It won't be in the pretty HTML format used by LINQPad and the other types of output it supports, but the purpose is similar.


问:
NodeJS Express Mongoose return empty []
I tried to make a MEAN stack app, but my API fails to give my requested data.

server.js file:

```<code>const express = require("express");
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
const port = process.env.PORT;
const dburi = process.env.DB_URI;

//Routes
const volcanoesRoute = require('./api/routes/volcano.routes');

mongoose.Promise = global.Promise;

mongoose.connect(
  dburi,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true,
  },
).then(
  () => {
    console.log('Connected to mongoDB');
  },
  (err) => console.log('Error connecting to mongoDB', err),
  { useNewUrlParser: true }
);

//Express app
const app = express();

app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
app.use('/api/vulcanoes', volcanoesRoute);
app.listen(port, () => {
  console.log(`running at port ${port}`);
});
</code>```

Routes file:

```<code>const express = require('express');
const volcanoController = require('../controllers/volcanoController');
const router = express.Router();

router.get('/getallvulcanoes', volcanoController.getAllVolcanoes);

module.exports = router;
</code>```

Controller file:

```<code>const VolcanoSchema = require('../models/volcano.models');

const getAllVulcanoes = (req, res) => {
    VolcanoSchema.find((err, results) => {
      if (err) {
        console.log(err);
        res.status(500).json({message: err});
      } else {
        res.status(200).json(results);
      }
    });
  };

  module.exports = {getAllVolcanoes};
</code>```

Model file

```<code>const mongoose = require('mongoose');

const VolcanoSchema = new mongoose.Schema({
    Volcano_name:{
        type: String,
    },
    Country:{
        type: String,
    },
    Type:{
        type: String,
    },
    Latitude:{
        type: Number,
    },
    Longtitude:{
        type: Number,
    },
    Elevation:{
        type: Number,
    },
});

module.exports = mongoose.model('Volcano', VolcanoSchema);
</code>```

The thing is that i have a working example but most of the code is decrepitated... but it the respond is always giving me this

It would be nice if someone point out what i am doing wrong

EDIT: I switched to postgresql for my database hopefully this will work

答:
You should fix the Controller (VulcanoSchema.find needs an empty object as parameter):

Controller file:

const VulcanoSchema = require('../models/vulcano.models');

const getAllVulcanoes = (req, res) => {
  VulcanoSchema.find({}, (err, results) => {
    if (err) {
      console.log(err);
      res.status(500).json({message: err});
    } else {
      res.status(200).json(results);
    }
  });
};

module.exports = {getAllVulcanoes};
```

Title: NodeJS Express Mongoose return empty []

Body:
I tried to make a MEAN stack app, but my API fails to give my requested data.

server.js file:

const express = require("express");
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
const port = process.env.PORT;
const dburi = process.env.DB_URI;

//Routes
const volcanoesRoute = require('./api/routes/volcano.routes');

mongoose.Promise = global.Promise;

mongoose.connect(
  dburi,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true,
  },
).then(
  () => {
    console.log('Connected to mongoDB');
  },
  (err) => console.log('Error connecting to mongoDB', err),
  { useNewUrlParser: true }
);

//Express app
const app = express();

app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
app.use('/api/vulcanoes', volcanoesRoute);
app.listen(port, () => {
  console.log(`running at port ${port}`);
});

Routes file:

const express = require('express');
const volcanoController = require('../controllers/volcanoController');
const router = express.Router();

router.get('/getallvulcanoes', volcanoController.getAllVolcanoes);

module.exports = router;

Controller file:

const VolcanoSchema = require('../models/volcano.models');

const getAllVulcanoes = (req, res) => {
    VolcanoSchema.find((err, results) => {
      if (err) {
        console.log(err);
        res.status(500).json({message: err});
      } else {
        res.status(200).json(results);
      }
    });
  };

  module.exports = {getAllVolcanoes};

Model file

const mongoose = require('mongoose');

const VolcanoSchema = new mongoose.Schema({
    Volcano_name:{
        type: String,
    },
    Country:{
        type: String,
    },
    Type:{
        type: String,
    },
    Latitude:{
        type: Number,
    },
    Longtitude:{
        type: Number,
    },
    Elevation:{
        type: Number,
    },
});

module.exports = mongoose.model('Volcano', VolcanoSchema);

The thing is that i have a working example but most of the code is decrepitated... but it the respond is always giving me this

It would be nice if someone point out what i am doing wrong

EDIT: I switched to postgresql for my database hopefully this will work


问:
What will be the equivalent JPA CriteriaBuilder for following query?
What will be JPA2 criteriaBuilder query for following? </p>

```<code>Select * from Transaction t1
where t1.version = (
    select max(t2.version)
    from Transaction t2
    where t1.id=t2.id
)
</code>```

答:
Something along the lines of:</p>

```<code>CriteriaQuery<Transaction> query = cb.createQuery(Transaction.class);
Root<Transaction> t1 = query.from(Transaction.class);

Subquery<Integer> maxVersion = query.subquery(Integer.class);
Root<Transaction> t2 = maxVersion.from(Transaction.class);
maxVersion.where(cb.eq(t1.get(Transaction_.id), t2.get(Transaction_.id));
maxVersion.select(cb.max(t2.get(Transaction_.version));

query.where(cb.eq(t1.get(Transaction_.version), maxVersion));
query.select(t1);
</code>```

Body:
What will be JPA2 criteriaBuilder query for following?

Select * from Transaction t1
where t1.version = (
    select max(t2.version)
    from Transaction t2
    where t1.id=t2.id
)

Body:
Something along the lines of:

CriteriaQuery<Transaction> query = cb.createQuery(Transaction.class);
Root<Transaction> t1 = query.from(Transaction.class);

Subquery<Integer> maxVersion = query.subquery(Integer.class);
Root<Transaction> t2 = maxVersion.from(Transaction.class);
maxVersion.where(cb.eq(t1.get(Transaction_.id), t2.get(Transaction_.id));
maxVersion.select(cb.max(t2.get(Transaction_.version));

query.where(cb.eq(t1.get(Transaction_.version), maxVersion));
query.select(t1);


问:
XML - simplexml_load_file - foreach
I need for my project echo xml data from xml

I use simplexml_load_file

I have

```<code>      <group>
        <admin>
          <id>605</id>
        </admin>
        <members>
          <id>2154</id>
          <id>2256</id>
          <id>3179</id>
        </menbers>
      </group>
      <group>
        <admin>
          ....
        </admin>
        <members>
          ...
          ...
        </members>
      </group>
</code>```

My code is

```<code>$soubor="platebniudaje.xml";
$xml = simplexml_load_file($soubor);

  foreach ($xml->group as $group) {
        echo $group->admin->id . "<br>";

        foreach ($group->members as $members) {
            echo $members->id . "<br>";
        }

  }
</code>```

My output is

```<code>605
2154
</code>```

but i need

```<code>605
2154
2256
3179
</code>```

Can you help me? Where is mistake?

答:
You can have one or more id's so you can loop those as well.

Note that there is a type in the xml </menbers>

```<code>foreach ($xml->group as $group) {
    echo $group->admin->id . PHP_EOL;
    foreach ($group->members as $member) {
        foreach($member->id as $id)
            echo $id . PHP_EOL;
    }
}
</code>```

Or the shorter version if members occurs only once as pointed out by @Nigel Ren

```<code>foreach ($xml->group as $group) {
    echo $group->admin->id . PHP_EOL;
    foreach ($group->members->id as $id)
        echo $id . PHP_EOL;
}
</code>```

Output

```<code>605
2154
2256
3179
</code>```

Php demo

Title: XML - simplexml_load_file - foreach

Body:
I need for my project echo xml data from xml

I use simplexml_load_file

I have

      <group>
        <admin>
          <id>605</id>
        </admin>
        <members>
          <id>2154</id>
          <id>2256</id>
          <id>3179</id>
        </menbers>
      </group>
      <group>
        <admin>
          ....
        </admin>
        <members>
          ...
          ...
        </members>
      </group>

My code is

$soubor="platebniudaje.xml";
$xml = simplexml_load_file($soubor);

  foreach ($xml->group as $group) {
        echo $group->admin->id . "
";

        foreach ($group->members as $members) {
            echo $members->id . "
";
        }

  }

My output is

605
2154

but i need

605
2154
2256
3179

Can you help me? Where is mistake?

Body:
You can have one or more id's so you can loop those as well.

Note that there is a type in the xml </menbers>

foreach ($xml->group as $group) {
    echo $group->admin->id . PHP_EOL;
    foreach ($group->members as $member) {
        foreach($member->id as $id)
            echo $id . PHP_EOL;
    }
}

Or the shorter version if members occurs only once as pointed out by @Nigel Ren

foreach ($xml->group as $group) {
    echo $group->admin->id . PHP_EOL;
    foreach ($group->members->id as $id)
        echo $id . PHP_EOL;
}

Output

605
2154
2256
3179

Php demo


答:
First of all check what you send: data message or notification message.
They may look the same, but depending on what type of message, the different method called.
Check this out: https://firebase.google.com/support/faq/#fcm-android-background

// Check if message contains a notification payload.

```<code>if (remoteMessage.getNotification() != null) {
  Map test = remoteMessage.getData();
  Log.d(TAG, "Message data payload: " + test);
</code>```

// Check if message contains a data payload.

```<code> if (remoteMessage.getData().size() > 0) {
    if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " +
           remoteMessage.getNotification().getBody());
</code>```

Title: Firebase push notification on new chat message

Body:
First of all check what you send: data message or notification message.
They may look the same, but depending on what type of message, the different method called.
Check this out: https://firebase.google.com/support/faq/#fcm-android-background

// Check if message contains a notification payload.

if (remoteMessage.getNotification() != null) {
  Map test = remoteMessage.getData();
  Log.d(TAG, "Message data payload: " + test);

// Check if message contains a data payload.

 if (remoteMessage.getData().size() > 0) {
    if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " +
           remoteMessage.getNotification().getBody());


问:
How to plot two different color scales for two geom_points from two different dataframes in ggplot2?
I am trying to plot two datasets on the same graph. Both data are plotted using geom_point, and I want to separately represent the sizes and color by the z values.

```<code>x <- c(2,3,4,5)
y <- c(1.1,1.2,1.3,1.4)
z <- c(1,2,2,3)
x3 <- c(4,5,6,7)
y3 <- c(3.1,3.2,3.3,3.2)
z3<- c(1,2,3,4)
p1 <- data.frame(x=x,y=y,z=z)
p3 <- data.frame(x=x3,y=y3,z=z3)

s <- ggplot()+
geom_point(data= p1, aes(x=x,y=y, color=z, size=z))+
geom_point(data=p3, aes(x3,y=y3, color=z, size=z3))
</code>```

How to I get continuous scale of colors and sizes separately to both geom_point? For example, z is scale_colour_gradient(low = "black", high = "red") and z3 is scale_colour_gradient(low = "light blue", high = "purple"). Similarly for sizes.

Thank you!

答:
One of the easy ways would be with the ggnewscale package:

library(ggplot2)
library(ggnewscale)

x <- c(2,3,4,5)
y <- c(1.1,1.2,1.3,1.4)
z <- c(1,2,2,3)
x3 <- c(4,5,6,7)
y3 <- c(3.1,3.2,3.3,3.2)
z3<- c(1,2,3,4)
p1 <- data.frame(x=x,y=y,z=z)
p3 <- data.frame(x=x3,y=y3,z=z3)

s <- ggplot()+
  geom_point(data= p1, aes(x=x,y=y, color=z, size=z))+
  scale_colour_gradient(low = "black", high = "red") +
  new_scale_colour() + # Define scales before initiating a new one
  scale_size() +
  new_scale("size") +
  geom_point(data=p3, aes(x3,y=y3, color=z, size=z3)) +
  scale_colour_gradient(low = "dodgerblue", high = "purple") +
  scale_size()
s
```

Created on 2020-05-28 by the reprex package (v0.3.0)

Body:
I am trying to plot two datasets on the same graph. Both data are plotted using geom_point, and I want to separately represent the sizes and color by the z values.

x <- c(2,3,4,5)
y <- c(1.1,1.2,1.3,1.4)
z <- c(1,2,2,3)
x3 <- c(4,5,6,7)
y3 <- c(3.1,3.2,3.3,3.2)
z3<- c(1,2,3,4)
p1 <- data.frame(x=x,y=y,z=z)
p3 <- data.frame(x=x3,y=y3,z=z3)

s <- ggplot()+
geom_point(data= p1, aes(x=x,y=y, color=z, size=z))+
geom_point(data=p3, aes(x3,y=y3, color=z, size=z3))

How to I get continuous scale of colors and sizes separately to both geom_point? For example, z is scale_colour_gradient(low = "black", high = "red") and z3 is scale_colour_gradient(low = "light blue", high = "purple"). Similarly for sizes.

Thank you!

Body:
One of the easy ways would be with the ggnewscale package:

library(ggplot2)
library(ggnewscale)

x <- c(2,3,4,5)
y <- c(1.1,1.2,1.3,1.4)
z <- c(1,2,2,3)
x3 <- c(4,5,6,7)
y3 <- c(3.1,3.2,3.3,3.2)
z3<- c(1,2,3,4)
p1 <- data.frame(x=x,y=y,z=z)
p3 <- data.frame(x=x3,y=y3,z=z3)

s <- ggplot()+
  geom_point(data= p1, aes(x=x,y=y, color=z, size=z))+
  scale_colour_gradient(low = "black", high = "red") +
  new_scale_colour() + # Define scales before initiating a new one
  scale_size() +
  new_scale("size") +
  geom_point(data=p3, aes(x3,y=y3, color=z, size=z3)) +
  scale_colour_gradient(low = "dodgerblue", high = "purple") +
  scale_size()
s

Created on 2020-05-28 by the reprex package (v0.3.0)


问:
Add elements of a list together python
I have this list

```<code>r1 = 2
r2 = 4
r3 = 5
r4 = 9
lst = [r1, r2, r3, r4]
</code>```

I want to create a new list which looks like this:

```<code>new_lst = [r1, r1+r2, r1+r2+r3, r1+r2+r3+r4]
</code>```

Except in the new_lst r1 is named "x1", r1+r2 named "x2 etc.

I'm currently doing this using:

```<code>new_lst = []
new_lst.append(sum(lst[0:1]))
new_lst.append(sum(lst[0:2]))
new_lst.append(sum(lst[0:3]))
new_lst.append(sum(lst[0:4]))
</code>```

And then refer to this list by saying if "n" is between 0 and x1, x1 and x1+x2 etc; print y. i.e.

```<code> if n >=0 and n <= new_lst[0]:
      print(y)
 elif n >=new_lst[0] and n <= new_lst[1]:
      print(z)
</code>```

答:
Why not simply use the cumulative sum function in numpy? </p>

```<code>import numpy as np

print(np.array([2,4,5,9]).cumsum())
</code>```

Title: Add elements of a list together python

Body:
I have this list

r1 = 2
r2 = 4
r3 = 5
r4 = 9
lst = [r1, r2, r3, r4]

I want to create a new list which looks like this:

new_lst = [r1, r1+r2, r1+r2+r3, r1+r2+r3+r4]

Except in the new_lst r1 is named "x1", r1+r2 named "x2 etc.

I'm currently doing this using:

new_lst = []
new_lst.append(sum(lst[0:1]))
new_lst.append(sum(lst[0:2]))
new_lst.append(sum(lst[0:3]))
new_lst.append(sum(lst[0:4]))

And then refer to this list by saying if "n" is between 0 and x1, x1 and x1+x2 etc; print y. i.e.

 if n >=0 and n <= new_lst[0]:
      print(y)
 elif n >=new_lst[0] and n <= new_lst[1]:
      print(z)

Body:
Why not simply use the cumulative sum function in numpy?

import numpy as np

print(np.array([2,4,5,9]).cumsum())


问:
Easy way to clamp Neural Network outputs between 0 and 1?
So I'm working on writing a GAN neural network and I want to set my network's output to 0 if it is less than 0 and 1 if it is greater than 1 and leave it unchanged otherwise. I'm pretty new to tensorflow, but I don't know of any tensorflow function or activation to do this without unwanted side effects. So I made my loss function so it calculates the loss as if the output was clamped, with this code:

```<code>def discriminator_loss(real_output, fake_output):
    real_output_clipped = min(max(real_output.numpy()[0],
    0), 1)
    fake_output_clipped = min(max(fake_output.numpy()[0],
    0), 1)

    real_clipped_tensor =
    tf.Variable([[real_output_clipped]], dtype = "float32")
    fake_clipped_tensor =
    tf.Variable([[fake_output_clipped]], dtype = "float32")

    real_loss = cross_entropy(tf.ones_like(real_output),
    real_clipped_tensor)
    fake_loss = cross_entropy(tf.zeros_like(fake_output),
    fake_clipped_tensor)

    total_loss = real_loss + fake_loss
    return total_loss
</code>```

but I get this error:

```<code>ValueError: No gradients provided for any variable: ['dense_50/kernel:0', 'dense_50/bias:0', 'dense_51/kernel:0', 'dense_51/bias:0', 'dense_52/kernel:0', 'dense_52/bias:0', 'dense_53/kernel:0', 'dense_53/bias:0'].
</code>```

Does anyone know a better way to do this, or a way to fix this error?

Thanks!

答:
TF probably does not know how to update your network weights based on this loss. The input of the cross entropy are tensors (variables) that are directly assigned from numpy arrays and are not connected to your actual network outputs.

If you want to perform operations on tensors that will remain within the graph and (hopefully) be differentiable, use the available TF operations. There's a "clip_by_value" operation described here: https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/clip_by_value.

E.g. real_output_clipped = tf.clip_by_value(real_output, clip_value_min=0, clip_value_max=1)

Body:
So I'm working on writing a GAN neural network and I want to set my network's output to 0 if it is less than 0 and 1 if it is greater than 1 and leave it unchanged otherwise. I'm pretty new to tensorflow, but I don't know of any tensorflow function or activation to do this without unwanted side effects. So I made my loss function so it calculates the loss as if the output was clamped, with this code:

def discriminator_loss(real_output, fake_output):
    real_output_clipped = min(max(real_output.numpy()[0],
    0), 1)
    fake_output_clipped = min(max(fake_output.numpy()[0],
    0), 1)

    real_clipped_tensor =
    tf.Variable([[real_output_clipped]], dtype = "float32")
    fake_clipped_tensor =
    tf.Variable([[fake_output_clipped]], dtype = "float32")

    real_loss = cross_entropy(tf.ones_like(real_output),
    real_clipped_tensor)
    fake_loss = cross_entropy(tf.zeros_like(fake_output),
    fake_clipped_tensor)

    total_loss = real_loss + fake_loss
    return total_loss

but I get this error:

ValueError: No gradients provided for any variable: ['dense_50/kernel:0', 'dense_50/bias:0', 'dense_51/kernel:0', 'dense_51/bias:0', 'dense_52/kernel:0', 'dense_52/bias:0', 'dense_53/kernel:0', 'dense_53/bias:0'].

Does anyone know a better way to do this, or a way to fix this error?

Thanks!


问:
regex – matching suffix same as given word
I'm using python3 with re module. I would like to remove address: from a start of a string, but I would also like to remove all of address suffixes in the beginning of a string:

'address: foobar' -> 'foobar'
'ddress: foobar' -> 'foobar'
'dress: foobar' -> 'foobar'
'ress: foobar' -> 'foobar'
'ess: foobar' -> 'foobar'
'ss: foobar' -> 'foobar'
's: foobar' -> 'foobar'
```

<p>I came up with this matching regex pattern:</p>

<pre class="lang-py prettyprint-override"><code>r'^(?:address|ddress|dress|ress|ess|ss|s)?[ :]+'
</code>```

But I'm wondering, is there a simpler (correct) way to do this with regex without manually repeating all suffixes?

答:
Your regex looks ok to me, but I come up with an alternative for fun.

You can use:

```<code>^((((((a)?d)?d)?r)?e)?s)?s
</code>```

I'm using capturing groups for readability, but you can use non capturing groups.

```<code>^(?:(?:(?:(?:(?:(?:a)?d)?d)?r)?e)?s)?s
</code>```

Working demo

Body:
I'm using python3 with re module. I would like to remove address: from a start of a string, but I would also like to remove all of address suffixes in the beginning of a string:

'address: foobar' -> 'foobar'
'ddress: foobar' -> 'foobar'
'dress: foobar' -> 'foobar'
'ress: foobar' -> 'foobar'
'ess: foobar' -> 'foobar'
'ss: foobar' -> 'foobar'
's: foobar' -> 'foobar'

I came up with this matching regex pattern:

r'^(?:address|ddress|dress|ress|ess|ss|s)?[ :]+'

But I'm wondering, is there a simpler (correct) way to do this with regex without manually repeating all suffixes?

Body:
Your regex looks ok to me, but I come up with an alternative for fun.

You can use:

^((((((a)?d)?d)?r)?e)?s)?s

I'm using capturing groups for readability, but you can use non capturing groups.

^(?:(?:(?:(?:(?:(?:a)?d)?d)?r)?e)?s)?s

Working demo


问:
How to reference a dynamic lambda ARN in AWS Step Functions written in the Serverless Framework?
EDIT: Just found this https://github.com/serverless-operations/serverless-step-functions/issues/209 Basically that example, but instead of hardcoding the ARN, I want to use a input variable, if that makes sense.

Here's the context:

Using Serverless' error destinations, an error payload is sent to SQS, which triggers a lambda that starts a state machine to perform a retry.

For example, if Lambda A fails, the failure is sent to SQS -> Lambda B which triggers a state machine to retry Lambda A.

I'm defining my state machine in Serverless.yml like so (This is what I've been trying so far):

```<code>stepFunctions:
  stateMachines:
    MyStateMachine:
      name: RetryLambdaMachine
      definition:
        Comment: Example to test retries
        StartAt: StepOne
        States:
          StepOne:
            Type: Task
            Resource: arn:aws:states:::lambda:invoke
            Parameters:
            - FunctionName.$: $$.lambdaArn
            #### ^^ This is where I need Lambda A to be referenced ####
            Retry:
            - ErrorEquals:
              - States.ALL
              MaxAttempts: 2
            Catch:
            - ErrorEquals: ["States.ALL"]
              Next: CatchAllFallback
            End: true
          CatchAllFallback:
            Type: Task
            Resource:
              Fn::GetAtt: [lambda_c, Arn]
            End: true
</code>```

Here is the error I get when I run serverless deploy:

```<code>Error: The CloudFormation template is invalid: [/Resources/RetryLambdasMachineRole/Type/Policies/0/PolicyDocument/Statement/0/Resource/0] 'null' values are not allowed in templates
</code>```

How do I reference Lambda A as a variable? I know that the error attributes will contain Lambda A's ARN, but how do I pass that to the state machine for the retry step?

Note: Lambda A is NOT defined within this Serverless.yml, it could come from anywhere. The ARN will be passed in as part of the error event coming from SQS, as stated above.

答:
I found out that my original code was actually pretty close. The only issue was that there was a hyphen in front of the FunctionName key and and extra '$' on lambdaArn.

```<code>    States:
      StepOne:
        Type: Task
        Resource: arn:aws:states:::lambda:invoke
        Parameters:
          FunctionName.$: $.lambdaArn
</code>```

This allows the lambda to be passed in as a dynamic resource.

Body:
EDIT: Just found this https://github.com/serverless-operations/serverless-step-functions/issues/209 Basically that example, but instead of hardcoding the ARN, I want to use a input variable, if that makes sense.

Here's the context:

Using Serverless' error destinations, an error payload is sent to SQS, which triggers a lambda that starts a state machine to perform a retry.

For example, if Lambda A fails, the failure is sent to SQS -> Lambda B which triggers a state machine to retry Lambda A.

I'm defining my state machine in Serverless.yml like so (This is what I've been trying so far):

stepFunctions:
  stateMachines:
    MyStateMachine:
      name: RetryLambdaMachine
      definition:
        Comment: Example to test retries
        StartAt: StepOne
        States:
          StepOne:
            Type: Task
            Resource: arn:aws:states:::lambda:invoke
            Parameters:
            - FunctionName.$: $$.lambdaArn
            #### ^^ This is where I need Lambda A to be referenced ####
            Retry:
            - ErrorEquals:
              - States.ALL
              MaxAttempts: 2
            Catch:
            - ErrorEquals: ["States.ALL"]
              Next: CatchAllFallback
            End: true
          CatchAllFallback:
            Type: Task
            Resource:
              Fn::GetAtt: [lambda_c, Arn]
            End: true

Here is the error I get when I run serverless deploy:

Error: The CloudFormation template is invalid: [/Resources/RetryLambdasMachineRole/Type/Policies/0/PolicyDocument/Statement/0/Resource/0] 'null' values are not allowed in templates

How do I reference Lambda A as a variable? I know that the error attributes will contain Lambda A's ARN, but how do I pass that to the state machine for the retry step?

Note: Lambda A is NOT defined within this Serverless.yml, it could come from anywhere. The ARN will be passed in as part of the error event coming from SQS, as stated above.

Body:
I found out that my original code was actually pretty close. The only issue was that there was a hyphen in front of the FunctionName key and and extra '$' on lambdaArn.

    States:
      StepOne:
        Type: Task
        Resource: arn:aws:states:::lambda:invoke
        Parameters:
          FunctionName.$: $.lambdaArn

This allows the lambda to be passed in as a dynamic resource.


问:
Counting Total Number of Elements in a List using Recursion
The Problem:

Count the number of elements in a List using recursion.

I wrote the following function:

def count_rec(arr, i):
    """
        This function takes List (arr) and Index Number
        then returns the count of number of elements in it
        using Recursion.
    """
    try:
        temp = arr[i]  # if element exists at i, continue
        return 1 + count_rec(arr, i+1)
    except IndexError:
        # if index error, that means, i == length of list
        return 0
```

I noticed some problems with it:

RecursionError (when the number of elements is more than 990)

Using a temp element (wasting memory..?)

Exception Handling (I feel like we shouldn't use it unless necessary)

If anyone can suggest how to improve the above solution or come up with an alternative one, It would be really helpful.

答:
you are prob looking for something like this</p>

```<code>def count_rec(arr):
    if arr == []:
        return 0
    return count_rec(arr[1:]) + 1
</code>```

Body:
The Problem:

Count the number of elements in a List using recursion.

I wrote the following function:

def count_rec(arr, i):
    """
        This function takes List (arr) and Index Number
        then returns the count of number of elements in it
        using Recursion.
    """
    try:
        temp = arr[i]  # if element exists at i, continue
        return 1 + count_rec(arr, i+1)
    except IndexError:
        # if index error, that means, i == length of list
        return 0

I noticed some problems with it:

RecursionError (when the number of elements is more than 990)

Using a temp element (wasting memory..?)

Exception Handling (I feel like we shouldn't use it unless necessary)

If anyone can suggest how to improve the above solution or come up with an alternative one, It would be really helpful.

Body:
you are prob looking for something like this

def count_rec(arr):
    if arr == []:
        return 0
    return count_rec(arr[1:]) + 1


问:
Application Security on Cloud static analysis not working for me
I need some help with using the Application Security on Cloud application.  I am trying to use the free plan to do a static scan.  I have installed the eclipse plugin and when attempting to scan a project I get this error:

A connection to the Static Analyzer scan manager service could not be established. Re-install Static Analyzer plug-ins and try again. If this problem persists, contact your IBM support representative.   During my set up I did select IBM Bluemix as the location for the service.  Set up instructions mentioned giving proxy details if running behind a proxy server.  I'm not aware of any proxies, I'm connected to the IBM network via ATT net client.

I have also tried scanning from within Bluemix console an app of mine that was connected to the Application Security on Cloud service.  The scan appeared to have started but never completed.

答: On Windows 10, deleting C:\Users\userName\.appscan solved the issue for me. After deleting that directory and restarting Eclipse, I was prompted for my ID and Secret on the next attempt and the connection succeeded.


问:
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
I wrote a custome listview along with search functionality. Code is as:

```<code>public class FaqActivity extends AppCompatActivity {
    ListView listView;
    ListViewAdapter adapter;
    String[] title;
    int[] icon;
    ArrayList<faqmodellist> arrayList = new ArrayList<>();

    private final String TAG =  FaqActivity.class.getCanonicalName();

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

        listView = findViewById(R.id.list_item);
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_n_back);
        setSupportActionBar(toolbar);

        title = new String[]{
                "Battery",
                "Cpu",
                "Display",
                "Memory",
                "Sensor"
        };
        icon = new int[]{R.drawable.ic_n_help};

        listView = findViewById(R.id.listView);

        for (int i = 0; i < title.length; i++) {
            faqmodellist model = new faqmodellist(title[i], icon[i]);
            Log.i(TAG, "onCreate: array is" + Arrays.toString(icon));
            //bind all strings in an array
            arrayList.add(model);
        }

        //pass results to listViewAdapter class
        adapter = new ListViewAdapter(this, arrayList);

        //bind the adapter to the listview
        listView.setAdapter(adapter);

    }

    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        MenuItem myActionMenuItem = menu.findItem(R.id.appSearchBar);
        final SearchView searchView = (SearchView) myActionMenuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (TextUtils.isEmpty(s)) {
                    adapter.filter("");
                    listView.clearTextFilter();
                } else {
                    adapter.filter(s);
                }
                return true;
            }
        });
        return true;
    }

}
</code>```

Custom listview adapter:

```<code>public class ListViewAdapter extends BaseAdapter {

    private Context mContext;
    private LayoutInflater inflater;
    private List<faqmodellist> modellist;
    private ArrayList<faqmodellist> arrayList;

    public ListViewAdapter(Context context, List<faqmodellist> modellist) {
        mContext = context;
        this.modellist = modellist;
        inflater = LayoutInflater.from(mContext);
        this.arrayList = new ArrayList<>();
        this.arrayList.addAll(modellist);
    }

    public static class ViewHolder{
        TextView mTitleTv;
        ImageView mIconIv;
    }

    @Override
    public int getCount() {
        return modellist.size();
    }

    @Override
    public Object getItem(int i) {
        return modellist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        ViewHolder holder;
        if (view==null){
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.item_listview, parent);

            //locate the views in row.xml
            holder.mTitleTv = view.findViewById(R.id.mainTitle);
            holder.mIconIv = view.findViewById(R.id.mainIcon);

            view.setTag(holder);

        }
        else {
            holder = (ViewHolder)view.getTag();
        }
        //set the results into textviews
        holder.mTitleTv.setText(modellist.get(position).getTitle());
        //set the result in imageview
        holder.mIconIv.setImageResource(modellist.get(position).getIcon());

        //listview item clicks
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (modellist.get(position).getTitle().equals("Battery")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Battery");
                    intent.putExtra("contentTv", "This is Battery detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Cpu")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Cpu");
                    intent.putExtra("contentTv", "This is Cpu detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Display")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Display");
                    intent.putExtra("contentTv", "This is Display detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Memory")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Memory");
                    intent.putExtra("contentTv", "This is Memory detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Sensor")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Sensor");
                    intent.putExtra("contentTv", "This is Sensor detail...");
                    mContext.startActivity(intent);
                }
            }
        });

        return view;
    }

    //filter
    public void filter(String charText){
        charText = charText.toLowerCase(Locale.getDefault());
        modellist.clear();
        if (charText.length()==0){
            modellist.addAll(arrayList);
        }
        else {
            for (faqmodellist model : arrayList){
                if (model.getTitle().toLowerCase(Locale.getDefault()).contains(charText)){
                    modellist.add(model);
                }
            }
        }
        notifyDataSetChanged();
    }

}
</code>```

When I run that code, I get this error:

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1

          at com.dell.helpmodule.screen.ui.activity.FaqActivity.onCreate(FaqActivity.java:52)

          at android.app.Activity.performCreate(Activity.java:7893)

          at android.app.Activity.performCreate(Activity.java:7880)

          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)

          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3279)

          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443)

          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)

          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)

          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)

          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)

          at android.os.Handler.dispatchMessage(Handler.java:107)

          at android.os.Looper.loop(Looper.java:224)

          at android.app.ActivityThread.main(ActivityThread.java:7520)

          at java.lang.reflect.Method.invoke(Native Method)

          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)

          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

There is only one element in image array, and array starts from position 0. How can I fix the error?

答:
You have only 1 item in icon array..
if you want to add same icon to all faqModelList items you should replace your model initialization in for loop to:</p>

```<code>faqmodellist model = new faqmodellist(title[i], R.drawable.ic_n_help);
</code>```

Body:
I wrote a custome listview along with search functionality. Code is as:

public class FaqActivity extends AppCompatActivity {
    ListView listView;
    ListViewAdapter adapter;
    String[] title;
    int[] icon;
    ArrayList<faqmodellist> arrayList = new ArrayList<>();

    private final String TAG =  FaqActivity.class.getCanonicalName();

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

        listView = findViewById(R.id.list_item);
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_n_back);
        setSupportActionBar(toolbar);

        title = new String[]{
                "Battery",
                "Cpu",
                "Display",
                "Memory",
                "Sensor"
        };
        icon = new int[]{R.drawable.ic_n_help};

        listView = findViewById(R.id.listView);

        for (int i = 0; i < title.length; i++) {
            faqmodellist model = new faqmodellist(title[i], icon[i]);
            Log.i(TAG, "onCreate: array is" + Arrays.toString(icon));
            //bind all strings in an array
            arrayList.add(model);
        }

        //pass results to listViewAdapter class
        adapter = new ListViewAdapter(this, arrayList);

        //bind the adapter to the listview
        listView.setAdapter(adapter);

    }

    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        MenuItem myActionMenuItem = menu.findItem(R.id.appSearchBar);
        final SearchView searchView = (SearchView) myActionMenuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (TextUtils.isEmpty(s)) {
                    adapter.filter("");
                    listView.clearTextFilter();
                } else {
                    adapter.filter(s);
                }
                return true;
            }
        });
        return true;
    }

}

Custom listview adapter:

public class ListViewAdapter extends BaseAdapter {

    private Context mContext;
    private LayoutInflater inflater;
    private List<faqmodellist> modellist;
    private ArrayList<faqmodellist> arrayList;

    public ListViewAdapter(Context context, List<faqmodellist> modellist) {
        mContext = context;
        this.modellist = modellist;
        inflater = LayoutInflater.from(mContext);
        this.arrayList = new ArrayList<>();
        this.arrayList.addAll(modellist);
    }

    public static class ViewHolder{
        TextView mTitleTv;
        ImageView mIconIv;
    }

    @Override
    public int getCount() {
        return modellist.size();
    }

    @Override
    public Object getItem(int i) {
        return modellist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        ViewHolder holder;
        if (view==null){
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.item_listview, parent);

            //locate the views in row.xml
            holder.mTitleTv = view.findViewById(R.id.mainTitle);
            holder.mIconIv = view.findViewById(R.id.mainIcon);

            view.setTag(holder);

        }
        else {
            holder = (ViewHolder)view.getTag();
        }
        //set the results into textviews
        holder.mTitleTv.setText(modellist.get(position).getTitle());
        //set the result in imageview
        holder.mIconIv.setImageResource(modellist.get(position).getIcon());

        //listview item clicks
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (modellist.get(position).getTitle().equals("Battery")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Battery");
                    intent.putExtra("contentTv", "This is Battery detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Cpu")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Cpu");
                    intent.putExtra("contentTv", "This is Cpu detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Display")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Display");
                    intent.putExtra("contentTv", "This is Display detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Memory")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Memory");
                    intent.putExtra("contentTv", "This is Memory detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Sensor")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Sensor");
                    intent.putExtra("contentTv", "This is Sensor detail...");
                    mContext.startActivity(intent);
                }
            }
        });

        return view;
    }

    //filter
    public void filter(String charText){
        charText = charText.toLowerCase(Locale.getDefault());
        modellist.clear();
        if (charText.length()==0){
            modellist.addAll(arrayList);
        }
        else {
            for (faqmodellist model : arrayList){
                if (model.getTitle().toLowerCase(Locale.getDefault()).contains(charText)){
                    modellist.add(model);
                }
            }
        }
        notifyDataSetChanged();
    }

}

When I run that code, I get this error:

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1

          at com.dell.helpmodule.screen.ui.activity.FaqActivity.onCreate(FaqActivity.java:52)

          at android.app.Activity.performCreate(Activity.java:7893)

          at android.app.Activity.performCreate(Activity.java:7880)

          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)

          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3279)

          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443)

          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)

          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)

          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)

          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)

          at android.os.Handler.dispatchMessage(Handler.java:107)

          at android.os.Looper.loop(Looper.java:224)

          at android.app.ActivityThread.main(ActivityThread.java:7520)

          at java.lang.reflect.Method.invoke(Native Method)

          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)

          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

There is only one element in image array, and array starts from position 0. How can I fix the error?

Body:
You have only 1 item in icon array..
if you want to add same icon to all faqModelList items you should replace your model initialization in for loop to:

faqmodellist model = new faqmodellist(title[i], R.drawable.ic_n_help);


答:
You can use pop() to do it.</p>

```<code>def count_r(l):
    if l==[]:
        return 0
    else:
        l.pop()
        return count_r(l)+1
</code>```

Title: Counting Total Number of Elements in a List using Recursion

Body:
You can use pop() to do it.

def count_r(l):
    if l==[]:
        return 0
    else:
        l.pop()
        return count_r(l)+1


问:
Xampp - mysql - Cannot create file xampp-control.ini, Access Denied
I use xampp for one month. But xampp yesterday  started making trouble like this
https://imgur.com/avRWXdb. That I uninstall and now install xampp and my sql is running. But now if i want to run xampp and click to xampp icon I always have to choose language: english / german. And if I want to end the program and I stop mysql, I see https://imgur.com/plIpPS4 (* Access Denied) and this: https://imgur.com/a/sEzGKW2 Then I must wain for program answer. I can end xampp. How to repair to normal working again? Thank´s</p>

答: xampp-control.ini file somehow become 'read only'. Just changing it to 'full control' solved my problem.