问:
python pandas: set a value of column based on another value of a column in a list
I have a dataframe like as following:

```<code>        f1              f2              class              n
0   weekly_return   0.155796               ab            weekly
1   monthly_return  0.153907               ab            monthly
2   volume_ratio    0.123844               NaN           volume
3   margin_selling_balance  0.115411       ad            margin
4   margin_debt_balance 0.107883           ae            margin
5   rv_ratio    0.077373                   NaN            rv
..................................................................
</code>```

and there is a list named lst_n as following:

```<code>lst_n = ['rv', 'ag', 'rg', ...........]
</code>```

I want to set the the value of class column of this dataframe to 'class_a' if the value of n is in the lst_n. For example the fifth rows, the n is rv which is in the n list(lst_n), so the value of class is set to 'class_a'.
My code is following, but there is error:

```<code>  lst_n = ['rv', 'ag', 'rg', ...........]
  df.loc[df.n is in lst_n, 'class'] = 'class_a'
</code>```

but there is error:

```<code>df.loc[df.n is in lst_n, 'class'] = 'class_a'
                           ^
SyntaxError: invalid syntax
</code>```

thanks!

答:
You need isin for mask:

```<code>lst_n = ['rv', 'ag', 'rg']
df.loc[df['n'].isin(lst_n), 'class'] = 'class_a'
print (df)
                       f1        f2    class        n
0           weekly_return  0.155796       ab   weekly
1          monthly_return  0.153907       ab  monthly
2            volume_ratio  0.123844      NaN   volume
3  margin_selling_balance  0.115411       ad   margin
4     margin_debt_balance  0.107883       ae   margin
5                rv_ratio  0.077373  class_a       rv
</code>```

Another solution with Series.mask:

```<code>df['class'] = df['class'].mask(df.n.isin(lst_n), 'class_a')
print (df)
                       f1        f2    class        n
0           weekly_return  0.155796       ab   weekly
1          monthly_return  0.153907       ab  monthly
2            volume_ratio  0.123844      NaN   volume
3  margin_selling_balance  0.115411       ad   margin
4     margin_debt_balance  0.107883       ae   margin
5                rv_ratio  0.077373  class_a       rv
</code>```

Body:
I have a dataframe like as following:

        f1              f2              class              n
0   weekly_return   0.155796               ab            weekly
1   monthly_return  0.153907               ab            monthly
2   volume_ratio    0.123844               NaN           volume
3   margin_selling_balance  0.115411       ad            margin
4   margin_debt_balance 0.107883           ae            margin
5   rv_ratio    0.077373                   NaN            rv
..................................................................

and there is a list named lst_n as following:

lst_n = ['rv', 'ag', 'rg', ...........]

I want to set the the value of class column of this dataframe to 'class_a' if the value of n is in the lst_n. For example the fifth rows, the n is rv which is in the n list(lst_n), so the value of class is set to 'class_a'.
My code is following, but there is error:

  lst_n = ['rv', 'ag', 'rg', ...........]
  df.loc[df.n is in lst_n, 'class'] = 'class_a'

but there is error:

df.loc[df.n is in lst_n, 'class'] = 'class_a'
                           ^
SyntaxError: invalid syntax

thanks!

Body:
You need isin for mask:

lst_n = ['rv', 'ag', 'rg']
df.loc[df['n'].isin(lst_n), 'class'] = 'class_a'
print (df)
                       f1        f2    class        n
0           weekly_return  0.155796       ab   weekly
1          monthly_return  0.153907       ab  monthly
2            volume_ratio  0.123844      NaN   volume
3  margin_selling_balance  0.115411       ad   margin
4     margin_debt_balance  0.107883       ae   margin
5                rv_ratio  0.077373  class_a       rv

Another solution with Series.mask:

df['class'] = df['class'].mask(df.n.isin(lst_n), 'class_a')
print (df)
                       f1        f2    class        n
0           weekly_return  0.155796       ab   weekly
1          monthly_return  0.153907       ab  monthly
2            volume_ratio  0.123844      NaN   volume
3  margin_selling_balance  0.115411       ad   margin
4     margin_debt_balance  0.107883       ae   margin
5                rv_ratio  0.077373  class_a       rv


来源: stackexchange

问:
What kind of vulnerabilities involve the attacker sending "php://input"?
My site was just bombarded by an attacker trying to pass "php://input" into any GET/POST variable they could think of. If this is trying to take advantage of a vulnerability, I'm unaware of it. What could this user be trying to exploit?</p>

答: This is probably an attempt to force evaluation of PHP code passed through raw request data - seems a bit hopeful though.</p>

ContentLicense: CC BY-SA 2.5


问:
Libgdx - how to properly dispose sound files
When should a sound effect be disposed of?

I'm a bit confused about sound effects vs music.  With music, I just dispose of it when a level is complete as I have the music just repeat until the end of the level and then that music is no longer used.  With sound effects, they play for a short time so I'm not sure what happens when one is done and a new one plays of the same sound.

For example, the player character can shoot a gun and each time the shoot sound plays.  So if the player shoots 6 times, is that sound effect handled like 6 separate sounds which need to be disposed of or is a sound file only to be disposed of once when no longer needed regardless of how many times it is used?

答:
You don't need to dispose of it each time it's played. Just dispose it when you dispose your other game assets (ie call it from the Game dispose method when the game is being disposed).

When the player shoots 6 times, the sound will be played 6 times concurrently.
From the javadoc:

Plays the sound. If the sound is already playing, it will be played again, concurrently.

But there aren't 6 different sounds you should be disposing or anything like that.

So to answer your question: is a sound file only to be disposed of once when no longer needed regardless of how many times it is used?

Yes.

ContentLicense: CC BY-SA 3.0


问:
How to cast List<Object> to List<MyClass>
This does not compile, any suggestion appreciated.

```<code> ...
  List<Object> list = getList();
  return (List<Customer>) list;
</code>```

Compiler says: cannot cast List<Object> to List<Customer>

答:
You can create a new List and add the elements to it: </p>

<p>For example: </p>

```<code>List<A> a = getListOfA();
List<Object> newList = new ArrayList<>();
newList.addAll(a);
</code>```

Body:
This does not compile, any suggestion appreciated.

 ...
  List<Object> list = getList();
  return (List<Customer>) list;

Compiler says: cannot cast List<Object> to List<Customer>

Body:
You can create a new List and add the elements to it:

For example:

List<A> a = getListOfA();
List<Object> newList = new ArrayList<>();
newList.addAll(a);


问:
How can I find out what files have changed in the post-checkout hook in git?
I'm only new to git and I'm looking at the post-checkout hook.

As I understand it the following command will restore "filename" from the latest commit:

```<code>git checkout -- filename
</code>```

When I get control in post-checkout I get 3 arguments, namely 2 SHAs and a type.

Both the SHAs are the same, namely the SHA of the last commit and type has a value of 0 which means a checkout of a file occurred.

But home do I find out what file was checked out?

答:
The documentation says:

The hook is given three parameters:

the ref of the previous HEAD,

the ref of the new HEAD (which may or may not have changed), and

a flag indicating whether the checkout was a branch checkout (changing branches, flag=1) or a file checkout (retrieving a file from the index, flag=0).

In your case, your HEAD has not changed. You might have some modified files initialized back to the HEAD content, but other than that, all files already checked out are still checked out:

```<code>git show --pretty="" --name-only HEAD
</code>```

Since you have not changed branches, the flag is set to 0, even if all files were already checked out. So there is no easy way to see which ones were modified and reset to HEAD content.

The key is: that post-checkout hook cannot affect the outcome of 'git checkout'.

On other words, the index and working tree already reflect their final state (and don't remember what was there before)

If you need a list of files reset by a git checkout ., it is best to do first a git stash.

Then a git checkout: your post-checkout hook can then use git stash show in order to list the files that were present before the checkout.

Body:
I'm only new to git and I'm looking at the post-checkout hook.

As I understand it the following command will restore "filename" from the latest commit:

git checkout -- filename

When I get control in post-checkout I get 3 arguments, namely 2 SHAs and a type.

Both the SHAs are the same, namely the SHA of the last commit and type has a value of 0 which means a checkout of a file occurred.

But home do I find out what file was checked out?

Body:
The documentation says:

The hook is given three parameters:

the ref of the previous HEAD,

the ref of the new HEAD (which may or may not have changed), and

a flag indicating whether the checkout was a branch checkout (changing branches, flag=1) or a file checkout (retrieving a file from the index, flag=0).

In your case, your HEAD has not changed. You might have some modified files initialized back to the HEAD content, but other than that, all files already checked out are still checked out:

git show --pretty="" --name-only HEAD

Since you have not changed branches, the flag is set to 0, even if all files were already checked out. So there is no easy way to see which ones were modified and reset to HEAD content.

The key is: that post-checkout hook cannot affect the outcome of 'git checkout'.

On other words, the index and working tree already reflect their final state (and don't remember what was there before)

If you need a list of files reset by a git checkout ., it is best to do first a git stash.

Then a git checkout: your post-checkout hook can then use git stash show in order to list the files that were present before the checkout.


问:
Checking ftp return codes from Unix script
I am currently creating an overnight job that calls a Unix script which in turn creates and transfers a file using ftp.  I would like to check all possible return codes.  The man page for ftp doesn't list return codes.  Does anyone know where to find a list?  Anyone with experience with this?  We have other scripts that grep for certain return strings in the log, and they send an email when in error.  However, they often miss unanticipated codes.
I am then putting the reason into the log and the email.

答:
I wrote a script to transfer only one file at a time and in that script use grep to check for the 226 Transfer complete message. If it finds it, grep returns 0.

```<code>ftp -niv < "$2"_ftp.tmp | grep "^226 "
</code>```

Body:
I wrote a script to transfer only one file at a time and in that script use grep to check for the 226 Transfer complete message. If it finds it, grep returns 0.

ftp -niv < "$2"_ftp.tmp | grep "^226 "


问:
How to append more data in tooltip of graph in chart.js
Recently i have work on showing data from database table in a graph using chart.js. and in that graph tooltip, there are 2 data are showing But now i also want to combine 3rd data in that tooltip.

Like:

customer in Jaunary 2016

monthly contomers for year 2016: -4.5

loss 15%(3rd one)

Below is a snap for current graph

And here is also a db table data screenshot

Here is my code

```<code>    $(document).ready(function(){
    $.ajax({
        url: "<?php base_url();?>/charts/getsome",
        method: "GET",
        success: function(data) {
            console.log(data);
            var data = JSON.parse(data);
            var month = [];
            var customers = [];

            for(var i in data) {
                month.push("Customer in " + data[i].apply_month);
                customers.push(data[i].no_customers);
            }
            var chartdata = {
                labels: month,
                datasets : [
                    {
                        label: 'monthly customers for Year 2016',
                        backgroundColor: 'rgba(200, 200, 200, 0.75)',
                        borderColor: 'rgba(200, 200, 200, 0.75)',
                        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                        hoverBorderColor: 'rgba(200, 200, 200, 1)',
                        data: customers,
                        fill: false
                    }

                ]
            };

            // alert(chartdata);

            var frame = $("#mycanvas");

            var barGraph = new Chart(frame, {
                type: 'line',
                data: chartdata
            });
        },
        error: function(data) {
            console.log(data);
        }
    });
});
</code>```

Now please suggest me, how can i append 3rd data in these tooltips. Thanks :)

答:
You can achieve this using afterBody callback function of tooltips ...

```<code>options: {
   tooltips: {
      callbacks: {
         afterBody: function(t, d) {
            return 'loss 15%';  // return a string that you wish to append
         }
      }
   },
   ...
}
</code>```

Here is a working example ...

var ctx = document.getElementById("myChart").getContext('2d');

var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
      datasets: [{
         label: 'Standard Rating',
         data: [1, 2, 3, 4, 5, 6],
         backgroundColor: 'rgba(209, 230, 245, 0.5)',
         borderColor: 'rgba(56, 163, 236, 1)',
         borderWidth: 1
      }]
   },
   options: {
      responsive: false,
      tooltips: {
         callbacks: {
            afterBody: function(t, d) {
               return 'loss 15%'; //return a string that you wish to append
            }
         }
      },
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="350" height="200"></canvas></code>```

Body:
Recently i have work on showing data from database table in a graph using chart.js. and in that graph tooltip, there are 2 data are showing But now i also want to combine 3rd data in that tooltip.

Like:

customer in Jaunary 2016

monthly contomers for year 2016: -4.5

loss 15%(3rd one)

Below is a snap for current graph

And here is also a db table data screenshot

Here is my code

    $(document).ready(function(){
    $.ajax({
        url: "<?php base_url();?>/charts/getsome",
        method: "GET",
        success: function(data) {
            console.log(data);
            var data = JSON.parse(data);
            var month = [];
            var customers = [];

            for(var i in data) {
                month.push("Customer in " + data[i].apply_month);
                customers.push(data[i].no_customers);
            }
            var chartdata = {
                labels: month,
                datasets : [
                    {
                        label: 'monthly customers for Year 2016',
                        backgroundColor: 'rgba(200, 200, 200, 0.75)',
                        borderColor: 'rgba(200, 200, 200, 0.75)',
                        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                        hoverBorderColor: 'rgba(200, 200, 200, 1)',
                        data: customers,
                        fill: false
                    }

                ]
            };

            // alert(chartdata);

            var frame = $("#mycanvas");

            var barGraph = new Chart(frame, {
                type: 'line',
                data: chartdata
            });
        },
        error: function(data) {
            console.log(data);
        }
    });
});

Now please suggest me, how can i append 3rd data in these tooltips. Thanks :)

Body:
You can achieve this using afterBody callback function of tooltips ...

options: {
   tooltips: {
      callbacks: {
         afterBody: function(t, d) {
            return 'loss 15%';  // return a string that you wish to append
         }
      }
   },
   ...
}

Here is a working example ...

var ctx = document.getElementById("myChart").getContext('2d');

var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
      datasets: [{
         label: 'Standard Rating',
         data: [1, 2, 3, 4, 5, 6],
         backgroundColor: 'rgba(209, 230, 245, 0.5)',
         borderColor: 'rgba(56, 163, 236, 1)',
         borderWidth: 1
      }]
   },
   options: {
      responsive: false,
      tooltips: {
         callbacks: {
            afterBody: function(t, d) {
               return 'loss 15%'; //return a string that you wish to append
            }
         }
      },
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="350" height="200"></canvas>


问:
C++ vector std::bad_alloc error in a program
I was trying to sort a vector having user defined data type having two values, on the basis of one. But i get the error of bad_alloc. this is the code :

```<code>#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct s{
int value;
int weight;
};

bool comp(s a , s b){
return a.value>b.value;
}

int main(){
vector <s> p;
s temp;
int n;
cin>>n;
while(n>=1){
    cin>>temp.value;
    cin>>temp.weight;
    p.push_back(temp);
}
sort(p.begin(), p.end(), comp);
vector <s> :: iterator it;
for(it = p.begin(); it != p.end();it++){
    *it = temp;
    cout<<temp.value<<endl;
}

}
</code>```

on running :

terminate called after throwing an instance of 'std::bad_alloc'
    what():  std::bad_alloc

can anyone help?

答:
Problems that I see:

Infinite loop

In the loop

```<code>while ( n >= 1)
{
   ...
}
</code>```

you are not changing the value of n. If n is greater 1 than at start of the loop, the loop will never end.

Not checking the status of input

You have

```<code> cin >> temp.value;
 cin >> temp.weight;
</code>```

You are not checking whether those calls succeeded. You are assuming that they did and proceeding to use temp.

Wrong way assignment

In the final loop, you are using

```<code>*it = temp;
</code>```

That will change the vector, not extract the value from the vector.

Here's an updated version of main that should work.

```<code>int main()
{
   vector <s> p;
   s temp;
   int n;
   cin>>n;
   while(n>=1)
   {
      // If there is a problem reading, break.
      if ( !(cin>>temp.value) )
      {
         break;
      }

      // If there is a problem reading, break.
      if ( !(cin>>temp.weight) )
      {
         break;
      }

      p.push_back(temp);

      // Decrement n
      --n;
   }

   sort(p.begin(), p.end(), comp);
   vector <s> :: iterator it;
   for(it = p.begin(); it != p.end();it++)
   {
      // Extract the value from the vector and print it.
      temp = *it;
      cout<<temp.value<<endl;
   }
}
</code>```

Body:
I was trying to sort a vector having user defined data type having two values, on the basis of one. But i get the error of bad_alloc. this is the code :

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct s{
int value;
int weight;
};

bool comp(s a , s b){
return a.value>b.value;
}

int main(){
vector <s> p;
s temp;
int n;
cin>>n;
while(n>=1){
    cin>>temp.value;
    cin>>temp.weight;
    p.push_back(temp);
}
sort(p.begin(), p.end(), comp);
vector <s> :: iterator it;
for(it = p.begin(); it != p.end();it++){
    *it = temp;
    cout<<temp.value<<endl;
}

}

on running :

terminate called after throwing an instance of 'std::bad_alloc'
    what():  std::bad_alloc

can anyone help?

Body:
Problems that I see:

Infinite loop

In the loop

while ( n >= 1)
{
   ...
}

you are not changing the value of n. If n is greater 1 than at start of the loop, the loop will never end.

Not checking the status of input

You have

 cin >> temp.value;
 cin >> temp.weight;

You are not checking whether those calls succeeded. You are assuming that they did and proceeding to use temp.

Wrong way assignment

In the final loop, you are using

*it = temp;

That will change the vector, not extract the value from the vector.

Here's an updated version of main that should work.

int main()
{
   vector <s> p;
   s temp;
   int n;
   cin>>n;
   while(n>=1)
   {
      // If there is a problem reading, break.
      if ( !(cin>>temp.value) )
      {
         break;
      }

      // If there is a problem reading, break.
      if ( !(cin>>temp.weight) )
      {
         break;
      }

      p.push_back(temp);

      // Decrement n
      --n;
   }

   sort(p.begin(), p.end(), comp);
   vector <s> :: iterator it;
   for(it = p.begin(); it != p.end();it++)
   {
      // Extract the value from the vector and print it.
      temp = *it;
      cout<<temp.value<<endl;
   }
}


问:
Google OAuth for standalone web app errors with disallowed_useragent
Up until recently, I had a standalone web app (e.g. Add to Homescreen) successfully authenticating users with Google's OAuth. Apparently they recently made changes and are not going to allow native web-views to initiate OAuth flows. This is problematic. Of course, I had an app set up in the developer console that was authorized to do this but in my futzing around I accidentally deleted it before realizing this change had happened.

How can I use Google OAuth within a standalone web app?

答:
In the end, I was never able to find an old project with an ID that would work. So I had to get creative. Instead of asking users to "add to homescreen" as step 1, I ask them to sign in first. Then, I take them to a page who's URL works once to sign them in (they're account is empty and my app doesn't send emails, so the security risk is nominal). The URL they end up adding to their homescreen signs them in the first time it's used.

To try it out, try signing up for While, a to-do list app, on an iPhone.


问:
CSV reference data in Azure Stream Analytics
I have a stream analytics application where events are JSON encoded and look like this

```<code>{customerID: 45, state:"S2" , timestamp:"2017-06-06 14:19:21.77"}
{customerID: 74, state:"S2" , timestamp:"2017-06-06 14:19:26.61"}
{customerID: 79, state:"S2" , timestamp:"2017-06-06 14:19:28.50"}
{customerID: 10, state:"D" , timestamp:"2017-06-06 14:19:31.79"}
{customerID: 70, state:"S2" , timestamp:"2017-06-06 14:19:31.93"}
{customerID: 37, state:"S2" , timestamp:"2017-06-06 14:19:32.17"}
{customerID: 41, state:"D" , timestamp:"2017-06-06 14:19:33.48"}
</code>```

I have reference data for customers in a CSV file that looks like this:

```<code>"CUST_ID", "Age", "Rich"
1, "50", "Y"
2, "22", "N"
</code>```

I load the data files in the aforementioned formats and test the following query

```<code>select A.[CUSTOMERID], A.[state], B.[AGE], B.[GENDER_CODE] from clickstream A timestamp by A.[TIMESTAMP] left join refdata B on A.[CUSTOMERID]=B.[CUST_ID]
</code>```

I get the following error message with no details:

Now, the same query works perfectly if the data reference data is represented as JSON. Is there a working example I can have a look at with CSV reference data?

答:
I have reference data for customers in a CSV file

When we create input, we need to specify Event serialization format which let Stream Analytics know which serialization format (JSON, CSV, or Avro) we're using for incoming data streams. Please check the Event serialization format of your input refdata, and make sure if it is set to CSV.

Body:
I have a stream analytics application where events are JSON encoded and look like this

{customerID: 45, state:"S2" , timestamp:"2017-06-06 14:19:21.77"}
{customerID: 74, state:"S2" , timestamp:"2017-06-06 14:19:26.61"}
{customerID: 79, state:"S2" , timestamp:"2017-06-06 14:19:28.50"}
{customerID: 10, state:"D" , timestamp:"2017-06-06 14:19:31.79"}
{customerID: 70, state:"S2" , timestamp:"2017-06-06 14:19:31.93"}
{customerID: 37, state:"S2" , timestamp:"2017-06-06 14:19:32.17"}
{customerID: 41, state:"D" , timestamp:"2017-06-06 14:19:33.48"}

I have reference data for customers in a CSV file that looks like this:

"CUST_ID", "Age", "Rich"
1, "50", "Y"
2, "22", "N"

I load the data files in the aforementioned formats and test the following query

select A.[CUSTOMERID], A.[state], B.[AGE], B.[GENDER_CODE] from clickstream A timestamp by A.[TIMESTAMP] left join refdata B on A.[CUSTOMERID]=B.[CUST_ID]

I get the following error message with no details:

Now, the same query works perfectly if the data reference data is represented as JSON. Is there a working example I can have a look at with CSV reference data?


问:
Convert an Integer to a String and Trim in 1 Step
I'm wondering if it's possible to convert an integer to a string and trim it within one step.

I have the following object:

currentForm

```<code>{
id:1,
name:"Abusicus",
value:12203,
period:"Morning",
favoriteSnack:"      "
....
}
</code>```

I need to find a way to check if the values are empty ("") or have something in it.

Eg. favoriteSnack would be considered empty since it's just white space. Currently I use this to check for white space:

```<code>var validInput = currentForm.every( v => currentForm[v] && currentForm[v].trim().length);
</code>```

But this does not work on fields with values that are integers. I want to do something like this: (Convert the integers to strings and then do a check on all the values)

```<code>var validInput = currentForm.every( v => currentForm[v] && currentForm[v].toString().trim().length);
</code>```

Is something like this possible?

答:
As I see your object is that, an object, not an array, to use every, first I would map all the keys and cast to a string with + '', then check the condition, like this:

```<code>var validInput = Object.keys(currentForm)
  .map( v => currentForm[v] + '')
  .every( v => v.trim().length);
</code>```

jsfiddle in action here

Hope this helps.

Body:
I'm wondering if it's possible to convert an integer to a string and trim it within one step.

I have the following object:

currentForm

{
id:1,
name:"Abusicus",
value:12203,
period:"Morning",
favoriteSnack:"      "
....
}

I need to find a way to check if the values are empty ("") or have something in it.

Eg. favoriteSnack would be considered empty since it's just white space. Currently I use this to check for white space:

var validInput = currentForm.every( v => currentForm[v] && currentForm[v].trim().length);

But this does not work on fields with values that are integers. I want to do something like this: (Convert the integers to strings and then do a check on all the values)

var validInput = currentForm.every( v => currentForm[v] && currentForm[v].toString().trim().length);

Is something like this possible?

Body:
As I see your object is that, an object, not an array, to use every, first I would map all the keys and cast to a string with + '', then check the condition, like this:

var validInput = Object.keys(currentForm)
  .map( v => currentForm[v] + '')
  .every( v => v.trim().length);

jsfiddle in action here

Hope this helps.


问:
Saving a camera's preview to a bitmap
I need a little help with getting my camera to work right.

What I'm trying to do is have the user take a picture that will then be used in another activity as the view's background. It is important not to have any skewing, and ideally the image would fill the entire background with the highest resolution possible.

I've been having a heck of a time trying to get the outputted picture of my camera to be oriented properly and be the same aspect of the display. So I took some time to think of exactly what I needed to do, and I don't think I need the normal saved image at all.

What I came up with is that I need a surface view to display the preview, and an overlay for some text and a capture button. When the user "takes the picture" it should autofocus, and then I need to capture the preview (under the screen overlays) to a bitmap to use in the other activity.

*Should I extend a SurfaceView for my preview and add it to a XML layout that contains the overlays?

*How do I save the SurfaceView's image to a bitmap?

Thanks.

答:
Matt,
One basic question ,and excuse my naivety, wouldnt it just be easier to use the built in camera to the Android through an Intent? It is doable, I've done it before.</p>

Title: Saving a camera's preview to a bitmap


问:
Cakephp echo username into page title
I am currently learning Cakephp and have made a profile page of which displays the username on it. You can only access this page when logged in so when you are on this page, I wish to display the username of the user in the HTML page title. This is also because your profile page is visible to other users.

At the moment to get the page headers I have used.

```<code><title><?php echo $this->fetch('title'); ?> | Site Name</title>

<? $this->assign('title', 'Profile')?>
</code>```

And to display the username on the page currently I have:

```<code><?php echo $user['User']['user_name']; ?>
</code>```

I have attempted to combine these two into something like shown below but clearly that's not working. Any ideas?

```<code><? $this->assign('title', '<?php echo $user['User']['user_name']; ?>')?>
</code>```

Thanks!

答:
Mistake in the concatenation, change this in your .ctp

```<code><? $this->assign('title', '<?php echo $user['User']['user_name']; ?>')?>
</code>```

to this

```<code><? $this->assign('title', $user['User']['user_name'])?>
</code>```

Later on add this in your layout

<title><?php echo $this->fetch('title'); ?> | Site Name</title>

This will work :)

Title: Cakephp echo username into page title

Body:
I am currently learning Cakephp and have made a profile page of which displays the username on it. You can only access this page when logged in so when you are on this page, I wish to display the username of the user in the HTML page title. This is also because your profile page is visible to other users.

At the moment to get the page headers I have used.

<title><?php echo $this->fetch('title'); ?> | Site Name</title>

<? $this->assign('title', 'Profile')?>

And to display the username on the page currently I have:

<?php echo $user['User']['user_name']; ?>

I have attempted to combine these two into something like shown below but clearly that's not working. Any ideas?

<? $this->assign('title', '<?php echo $user['User']['user_name']; ?>')?>

Thanks!

Body:
Mistake in the concatenation, change this in your .ctp

<? $this->assign('title', '<?php echo $user['User']['user_name']; ?>')?>

to this

<? $this->assign('title', $user['User']['user_name'])?>

Later on add this in your layout

<title><?php echo $this->fetch('title'); ?> | Site Name</title>

This will work :)


问:
Get Id from url() in angular
How to get id from url()
This is my url

```<code>http://localhost:59113/Project/EditProject?id=2
</code>```

I did it using jquery..

```<code>var url = document.URL;
        var id = /id=([^&]+)/.exec(url)[1];
        var result = id ? id : ' ';
</code>```

But I need to do it using angular.Can anyone help me?
I tried this too(updated part)

```<code> var app = angular
                .module("intranet_App", [])
                    app.config("$routeProvider", function ($routeProvider) {
                        $routeProvider.when('/view1/:param1/:param2', {
                            templateUrl: 'Project/EditProject.html',
                            controller: 'myCtrl'
                        })
                    })
                    .controller("myCtrl", ["$scope", "$http", "$location", "$route",  function ($scope, $http, $location, $route) {
                    // alert($location.id)
                    var a = $route.current.params;
                    alert(a.id)
                }])
</code>```

答:
$location.search() will return an object of key-value pairs.
in your case:You could access this value directly with $location.search().id

Title: Get Id from url() in angular

Body:
How to get id from url()
This is my url

http://localhost:59113/Project/EditProject?id=2

I did it using jquery..

var url = document.URL;
        var id = /id=([^&]+)/.exec(url)[1];
        var result = id ? id : ' ';

But I need to do it using angular.Can anyone help me?
I tried this too(updated part)

 var app = angular
                .module("intranet_App", [])
                    app.config("$routeProvider", function ($routeProvider) {
                        $routeProvider.when('/view1/:param1/:param2', {
                            templateUrl: 'Project/EditProject.html',
                            controller: 'myCtrl'
                        })
                    })
                    .controller("myCtrl", ["$scope", "$http", "$location", "$route",  function ($scope, $http, $location, $route) {
                    // alert($location.id)
                    var a = $route.current.params;
                    alert(a.id)
                }])


问:
Installation problems with Ruby 2.4.1 on Mac OS/X only
I'm seeing persistent test failures, but only on Ruby 2.4.1, and only on Mac OS/X.  The code being tested works fine locally with Ruby 2.4.1 on Mac OS/X, and the problems appear to be an Ruby installation failure, not a build failure.

Is there a problem with travis-ci here?

https://travis-ci.org/rubys/nokogumbo/builds/238363298
https://travis-ci.org/rubys/nokogumbo/builds/238371578

The failure in question:

Libraries missing for ruby-2.4.1: /usr/local/opt/openssl@1.1/lib/libcrypto.1.1.dylib,/usr/local/opt/openssl@1.1/lib/libssl.1.1.dylib. Refer to your system manual for installing libraries

答: Seems to be an acknowledged travis bug: https://github.com/travis-ci/travis-ci/issues/7848</p>


问:
Can't write to XML file from WCF service hosted in IIS 7.5
I have a simple WCF service library hosted in IIS 7.5 running on my local machine. The service is supposed to read and write to an xml file in the root of the sites directory. Running in VS2010 with the test client this works fine. When I call my IIS hosted service from a winforms client the service can't write or read from the xml file. I guess my question is why can't my WCF service write to a XML file when it is hosted in IIS but has no problems running in debug?</p>

答: Turns out my problem was that I hadn't changed my working directory from C:\windows\system32\inetsrv\ to my application's physical directory. Adding "AppDomain.CurrentDomain.BaseDirectory &" to my file path took care of it.</p>


答:
If you need a bit of performance, you can use np.where. </p>

```<code>df['class'] = np.where(df.n.isin(lst_n), 'class_a', df['class'])

df
Out[942]:
                       f1        f2    class        n
0           weekly_return  0.155796       ab   weekly
1          monthly_return  0.153907       ab  monthly
2            volume_ratio  0.123844      NaN   volume
3  margin_selling_balance  0.115411       ad   margin
4     margin_debt_balance  0.107883       ae   margin
5                rv_ratio  0.077373  class_a       rv
</code>```

Title: python pandas: set a value of column based on another value of a column in a list

Body:
I have a dataframe like as following:

        f1              f2              class              n
0   weekly_return   0.155796               ab            weekly
1   monthly_return  0.153907               ab            monthly
2   volume_ratio    0.123844               NaN           volume
3   margin_selling_balance  0.115411       ad            margin
4   margin_debt_balance 0.107883           ae            margin
5   rv_ratio    0.077373                   NaN            rv
..................................................................

and there is a list named lst_n as following:

lst_n = ['rv', 'ag', 'rg', ...........]

I want to set the the value of class column of this dataframe to 'class_a' if the value of n is in the lst_n. For example the fifth rows, the n is rv which is in the n list(lst_n), so the value of class is set to 'class_a'.
My code is following, but there is error:

  lst_n = ['rv', 'ag', 'rg', ...........]
  df.loc[df.n is in lst_n, 'class'] = 'class_a'

but there is error:

df.loc[df.n is in lst_n, 'class'] = 'class_a'
                           ^
SyntaxError: invalid syntax

thanks!

Body:
If you need a bit of performance, you can use np.where.

df['class'] = np.where(df.n.isin(lst_n), 'class_a', df['class'])

df
Out[942]:
                       f1        f2    class        n
0           weekly_return  0.155796       ab   weekly
1          monthly_return  0.153907       ab  monthly
2            volume_ratio  0.123844      NaN   volume
3  margin_selling_balance  0.115411       ad   margin
4     margin_debt_balance  0.107883       ae   margin
5                rv_ratio  0.077373  class_a       rv


问:
How to do i create a unique page for each row in database with PHP?
Let's say, I enter a row in MySQL database with this form:

```<code><form action="add.php" method="post">
<input type="text" name="title" />
<input type="submit"/>
</form>
</code>```

Now, I want to make a page URL like this: example.com/title
And when someone open it, the database show that particular row.

答:
You could try something like this to generate "different" page using one file only(example.com/title.php)

Loop through your database to get all data while creating a  for each of them:

```<code>foreach ($retrieveResult as $result) {
    echo '<a href="example.com/title.php?name='.$result['title'].'">'.$result['title'].'</a>';
}
</code>```

This will generate something like this:

```<code><a href="example.com/title.php?name=titleA">titleA</a>
<a href="example.com/title.php?name=titleB">titleB</a>
<a href="example.com/title.php?name=titleC">titleC</a>
<a href="example.com/title.php?name=titleD">titleD</a>
</code>```

To get the value of name in the url, use $_GET in title.php

```<code>$title = "";
if(isset($_GET['name')){
    $title = $_GET['name'];
}
</code>```

Now put $title in a SELECT query to retrieve all data that has the title of $title, then display it in title.php. With this you will have a dynamic page.

Body:
Let's say, I enter a row in MySQL database with this form:

<form action="add.php" method="post">
<input type="text" name="title" />
<input type="submit"/>
</form>

Now, I want to make a page URL like this: example.com/title
And when someone open it, the database show that particular row.

Body:
You could try something like this to generate "different" page using one file only(example.com/title.php)

Loop through your database to get all data while creating a <a> for each of them:

foreach ($retrieveResult as $result) {
    echo '<a href="example.com/title.php?name='.$result['title'].'">'.$result['title'].'</a>';
}

This will generate something like this:

<a href="example.com/title.php?name=titleA">titleA</a>
<a href="example.com/title.php?name=titleB">titleB</a>
<a href="example.com/title.php?name=titleC">titleC</a>
<a href="example.com/title.php?name=titleD">titleD</a>

To get the value of name in the url, use $_GET in title.php

$title = "";
if(isset($_GET['name')){
    $title = $_GET['name'];
}

Now put $title in a SELECT query to retrieve all data that has the title of $title, then display it in title.php. With this you will have a dynamic page.


问:
Why am I getting "operation not permitted" when trying to install a Linux kernel module?
I'm having some trouble when trying to run a very simple piece of code and couldn't find out what the reason could be.

I am getting

operation not permitted

when trying to install a Linux kernel module from a .ko file (KO_NAME).

This is an excerpt of the code:

```<code>if (strcmp(argv[1], "-init")==0) {

    fd=open(KO_NAME, O_RDONLY|O_CLOEXEC);
    if (fd<0) {
      perror("Error");
      printf("Error number: %d\n", errno);
    } else {
      printf("fd: %d\n", fd);
    }
    uid=getuid();
    if (uid!=ROOT_UID) {
      printf("Error: not root\n");
      return -1;
    }
    if (access(KO_NAME, F_OK)==-1) {
      printf("Error: File \"%s\" doesn't exist\n", argv[2]);
      return -1;
    }
    rc=syscall(__NR_finit_module, fd, "", 0);
      close(fd);
      if (rc!=0) {
          perror("Error");
          printf("rc=%d\n", rc);
          printf("Error number: %d\n", errno);
      }
</code>```

and this is the result when run:

```<code>fd: 3

rc=-1

Error number: 1
</code>```

Why am I getting Error number 1?

operation not permitted

答:
I had "Operation not permitted" errors installing Linux kernels too. I am running Sophos Anti-Virus, which has a known bug. "30s delay of file create and "Operation not permitted" errors with fanotify and cifs – This is a kernel issue and Sophos is working with the Linux community to fix this issue"

To get around this problem I disable sophos-av before and enable it after each Linux kernel install. I have only experienced this problem during Linux kernel install and not during common updates.

sudo /opt/sophos-av/bin/savdctl disable

Run Update Manager and install Linux kernel.

sudo /opt/sophos-av/bin/savdctl enable

Body:
I'm having some trouble when trying to run a very simple piece of code and couldn't find out what the reason could be.

I am getting

operation not permitted

when trying to install a Linux kernel module from a .ko file (KO_NAME).

This is an excerpt of the code:

if (strcmp(argv[1], "-init")==0) {

    fd=open(KO_NAME, O_RDONLY|O_CLOEXEC);
    if (fd<0) {
      perror("Error");
      printf("Error number: %d\n", errno);
    } else {
      printf("fd: %d\n", fd);
    }
    uid=getuid();
    if (uid!=ROOT_UID) {
      printf("Error: not root\n");
      return -1;
    }
    if (access(KO_NAME, F_OK)==-1) {
      printf("Error: File \"%s\" doesn't exist\n", argv[2]);
      return -1;
    }
    rc=syscall(__NR_finit_module, fd, "", 0);
      close(fd);
      if (rc!=0) {
          perror("Error");
          printf("rc=%d\n", rc);
          printf("Error number: %d\n", errno);
      }

and this is the result when run:

fd: 3

rc=-1

Error number: 1

Why am I getting Error number 1?

operation not permitted


问:
how to convert folder into Zip file in codeigniter where folder contains some image file
i have some doubts in zipping the folder in codeigniter.Actually i have some image files in the folder and i was trying to zip this folder in codegiter. I have view file where i have written "Download all file" button. On clicking this button i have to take the folder and zip it.
My view file:
I have written the button "Download All Files" inside the anchor tag.

```<code><tr>
    <td align="right">
        <?php  if(isset($AppData) && !empty($AppData)) {
          $applicantNo = $AppData[0]['appid']; ?>
        <a href='<?php echo base_url("admin/downloadAllFileZip/$applicantNo");?>'><input type="submit" name="download" value="Download All Files" /></a>
         <?php } ?>

    </td>
   </tr>
</code>```

Controller code:
Inside admin.php controller file i have the below method

```<code>public function downloadAllFileZip($appId)
    {

        $path = file_get_contents(base_url().'files/'.$appId);
        $applicant_id = $appId;
        $this->zip->add_data($applicant_id,$path);
        $this->zip->archive('/files/'.$applicant_id);
        $this->zip->download($applicant_id);

    }
</code>```

But when I am clicking the " Download all file " button the popup window for zipping is comming and after downloading its showing 1kb file but there is no image on that file. I can able to zip single image file as a zip file but not able to zip the entire folder. Please help me how to do this.

答:
add your all file like this. For Ex:</p>

```<code>foreach ($query->result() as $row)
{
    $this->zip->read_file($row->filename);
}

$this->zip->download('files_backup.zip');
</code>```

Body:
i have some doubts in zipping the folder in codeigniter.Actually i have some image files in the folder and i was trying to zip this folder in codegiter. I have view file where i have written "Download all file" button. On clicking this button i have to take the folder and zip it.
My view file:
I have written the button "Download All Files" inside the anchor tag.

        <?php  if(isset($AppData) && !empty($AppData)) {
          $applicantNo = $AppData[0]['appid']; ?>
        <a href='<?php echo base_url("admin/downloadAllFileZip/$applicantNo");?>'><input type="submit" name="download" value="Download All Files" />
         <?php } ?>

Controller code:
Inside admin.php controller file i have the below method

public function downloadAllFileZip($appId)
    {

        $path = file_get_contents(base_url().'files/'.$appId);
        $applicant_id = $appId;
        $this->zip->add_data($applicant_id,$path);
        $this->zip->archive('/files/'.$applicant_id);
        $this->zip->download($applicant_id);

    }

But when I am clicking the " Download all file " button the popup window for zipping is comming and after downloading its showing 1kb file but there is no image on that file. I can able to zip single image file as a zip file but not able to zip the entire folder. Please help me how to do this.

Body:
add your all file like this. For Ex:

foreach ($query->result() as $row)
{
    $this->zip->read_file($row->filename);
}

$this->zip->download('files_backup.zip');


问:
Angular.js autocomplete with $http.get TypeError: Cannot read property 'success' of undefined
With this code i always get TypeError: Cannot read property 'success' of undefined.
I've tried also with .then instead of .success but i get the same error.
After plus than ten hours of googling i'm a little bit desperate...

Html:

```<code><div ng-controller="search_interest" layout="column">
    <md-chips ng-model="ctrl.selectedVegetables" md-autocomplete-snap md-require-match>
        <md-autocomplete
            md-selected-item="selectedItem"
            md-search-text="searchText"
            md-items="item in getInterest(searchText)"
            md-item-text="item.name"
            placeholder="Search for a vegetable">
            <span md-highlight-text="searchText">{{item.name}} :: {{item.type}}</span>
        </md-autocomplete>
        <md-chip-template>
            <span>
            <strong>{{$chip.name}}</strong>
            <em>({{$chip.type}})</em>
            </span>
        </md-chip-template>
    </md-chips>
</div>
</code>```

And the js:

```<code>var app = angular.module('autocomplete_app', ['ngMaterial']);

app.controller('search_interest',
    function($scope, $http){
        $scope.searchText = '';
        $scope.selectedItem = undefined;
        function getInterest($scope){
            $http.get("someurl.php?query=" + $scope.searchText)
                .success(function(data){
                    $scope.interest = data;
                    console.log('data', JSON.stringify(data));
                });
        };
    });
</code>```

答:
Simply use basic autocomplete

https://material.angularjs.org/latest/api/directive/mdAutocomplete

directive then customise on your own.

HTML

```<code><md-autocomplete md-selected-item="selectedItem" md-search-text="searchText" md-items="item in querySearch(searchText)" md-item-text="item.display">
   <md-item-template>
      <span md-highlight-text="searchText">{{item.display}}</span>
   </md-item-template>
   <md-not-found>No matches found.</md-not-found>
</md-autocomplete>
</code>```

working fine.

Body:
With this code i always get TypeError: Cannot read property 'success' of undefined.
I've tried also with .then instead of .success but i get the same error.
After plus than ten hours of googling i'm a little bit desperate...

Html:

    <md-chips ng-model="ctrl.selectedVegetables" md-autocomplete-snap md-require-match>
        <md-autocomplete
            md-selected-item="selectedItem"
            md-search-text="searchText"
            md-items="item in getInterest(searchText)"
            md-item-text="item.name"
            placeholder="Search for a vegetable">
            {{item.name}} :: {{item.type}}
        </md-autocomplete>
        <md-chip-template>

            {{$chip.name}}
            ({{$chip.type}})

        </md-chip-template>
    </md-chips>

And the js:

var app = angular.module('autocomplete_app', ['ngMaterial']);

app.controller('search_interest',
    function($scope, $http){
        $scope.searchText = '';
        $scope.selectedItem = undefined;
        function getInterest($scope){
            $http.get("someurl.php?query=" + $scope.searchText)
                .success(function(data){
                    $scope.interest = data;
                    console.log('data', JSON.stringify(data));
                });
        };
    });

Body:
Simply use basic autocomplete

https://material.angularjs.org/latest/api/directive/mdAutocomplete

directive then customise on your own.

HTML

<md-autocomplete md-selected-item="selectedItem" md-search-text="searchText" md-items="item in querySearch(searchText)" md-item-text="item.display">
   <md-item-template>
      <span md-highlight-text="searchText">{{item.display}}</span>
   </md-item-template>
   <md-not-found>No matches found.</md-not-found>
</md-autocomplete>

working fine.


问:
Android : RecyclerView adapter doesn't load data after Permission Check
RecyclerView adapter doesn't load data on first launch after Permission check. I have to re-tap the tab to get the data.

I have already visited/tried these links -

-- RecyclerView doesn't load data in first launch using FirebaseRecyclerAdapter

-- RecyclerView doesn't load items on first start of activity

Here's code -

onCreateView -

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_third, container, false);

recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

if (checkAndRequestPermissions()) {
    loadAudio();
}

return view;
}
</code>```

onRequestPermissionResult -

```<code>loadAudio() //  call to method if permission granted
</code>```

loadAudio() -

```<code>private void loadAudio() {
ContentResolver contentResolver = getActivity().getContentResolver();
... /** accessing contents */ ...

   if (cursor != null) {
        cursor.close();
      }
  initRecyclerView();
 }
</code>```

initRecyclerView -

```<code>private void initRecyclerView() {

// To check if this method called at first time tab click
// which it doesn't.
System.out.println("==== mAudioList ==="+mAudioList+"::");
// ------

if (mAudioList != null && mAudioList.size() > 0) {
    AudioAdapter adapter = new AudioAdapter(mAudioList, getActivity());
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(linearLayoutManager);
    DIviderItemDecoration dividerItemDecoration = new DIviderItemDecoration(getContext(), linearLayoutManager.getOrientation());
    recyclerView.addItemDecoration(dividerItemDecoration);

    // thought this would help
    adapter.notifyDataSetChanged();

    recyclerView.setAdapter(adapter);
}
}
</code>```

onRequestPermissionResult -

```<code>@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {

    String TAG = "LOG_PERMISSION";
    Log.d(TAG, "Permission callback called-------");
    switch (requestCode) {
        case REQUEST_ID_MULTIPLE_PERMISSIONS: {

            Map<String, Integer> perms = new HashMap<>();
            // Initialize the map with both permissions
            perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
            // Fill with actual results from user
            if (grantResults.length > 0) {
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for both permissions

                if (perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        ) {
                    Log.d(TAG, "Phone state and storage permissions granted");
                    loadAudio();
                } else {
                    Log.d(TAG, "Some permissions are not granted ask again ");
                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
                        showDialogOK("Phone state and storage permissions required for this app",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        switch (which) {
                                            case DialogInterface.BUTTON_POSITIVE:
                                                checkAndRequestPermissions();
                                                break;
                                            case DialogInterface.BUTTON_NEGATIVE:
                                                // proceed with logic by disabling the related features or quit the app.
                                                break;
                                        }
                                    }
                                });
                    }
                    else {
                        Toast.makeText(getContext(), "Go to settings and enable permissions", Toast.LENGTH_LONG)
                                .show();
                    }
                }
            }
        }
    }

}
</code>```

I don't know how to fix this. Please, Any help would be Appreciated.
Already asked this question here - question but that didn't worked.

Note : There's no code in my other fragment lifecycle methods.

答:
Finally! I got the answer.
The problem is not with the permission but with onRequestPermissionResult as it's not getting callback!

This answer helped me.

```<code>@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(/**fragmentContainer*/);
    if (fragment != null) {
        fragment.onRequestPermissionsResult(requestCode&0xff, permissions, grantResults);
    }
}
</code>```

Though they originally answered for Nested Fragment but it also work for top-level fragments.
If anyone else having same problem then check it out.

Please visit the above link to know how it works.

Body:
RecyclerView adapter doesn't load data on first launch after Permission check. I have to re-tap the tab to get the data.

I have already visited/tried these links -

-- RecyclerView doesn't load data in first launch using FirebaseRecyclerAdapter

-- RecyclerView doesn't load items on first start of activity

Here's code -

onCreateView -

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_third, container, false);

recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

if (checkAndRequestPermissions()) {
    loadAudio();
}

return view;
}

onRequestPermissionResult -

loadAudio() //  call to method if permission granted

loadAudio() -

private void loadAudio() {
ContentResolver contentResolver = getActivity().getContentResolver();
... /** accessing contents */ ...

   if (cursor != null) {
        cursor.close();
      }
  initRecyclerView();
 }

initRecyclerView -

private void initRecyclerView() {

// To check if this method called at first time tab click
// which it doesn't.
System.out.println("==== mAudioList ==="+mAudioList+"::");
// ------

if (mAudioList != null && mAudioList.size() > 0) {
    AudioAdapter adapter = new AudioAdapter(mAudioList, getActivity());
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(linearLayoutManager);
    DIviderItemDecoration dividerItemDecoration = new DIviderItemDecoration(getContext(), linearLayoutManager.getOrientation());
    recyclerView.addItemDecoration(dividerItemDecoration);

    // thought this would help
    adapter.notifyDataSetChanged();

    recyclerView.setAdapter(adapter);
}
}

onRequestPermissionResult -

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {

    String TAG = "LOG_PERMISSION";
    Log.d(TAG, "Permission callback called-------");
    switch (requestCode) {
        case REQUEST_ID_MULTIPLE_PERMISSIONS: {

            Map<String, Integer> perms = new HashMap<>();
            // Initialize the map with both permissions
            perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
            // Fill with actual results from user
            if (grantResults.length > 0) {
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for both permissions

                if (perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        ) {
                    Log.d(TAG, "Phone state and storage permissions granted");
                    loadAudio();
                } else {
                    Log.d(TAG, "Some permissions are not granted ask again ");
                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
                        showDialogOK("Phone state and storage permissions required for this app",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        switch (which) {
                                            case DialogInterface.BUTTON_POSITIVE:
                                                checkAndRequestPermissions();
                                                break;
                                            case DialogInterface.BUTTON_NEGATIVE:
                                                // proceed with logic by disabling the related features or quit the app.
                                                break;
                                        }
                                    }
                                });
                    }
                    else {
                        Toast.makeText(getContext(), "Go to settings and enable permissions", Toast.LENGTH_LONG)
                                .show();
                    }
                }
            }
        }
    }

}

I don't know how to fix this. Please, Any help would be Appreciated.
Already asked this question here - question but that didn't worked.

Note : There's no code in my other fragment lifecycle methods.

Body:
Finally! I got the answer.
The problem is not with the permission but with onRequestPermissionResult as it's not getting callback!

This answer helped me.

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(/**fragmentContainer*/);
    if (fragment != null) {
        fragment.onRequestPermissionsResult(requestCode&0xff, permissions, grantResults);
    }
}

Though they originally answered for Nested Fragment but it also work for top-level fragments.
If anyone else having same problem then check it out.

Please visit the above link to know how it works.


问:
Alternatives to browser.alarms for Edge extensions
I ported an extension from Chrome to Microsoft Edge.The extension works properly in Chrome, but in Edge it has some issues.

One of these issues is that Edge does not support browser.alarms.

For Edge extensions, what are the alternatives to using browser.alarms?

答: I did all the research and came to the conclusion that alarms can be replaced simply using the setTimeout function of JavaScript . The function written in browser.alarms.onAlarm.addListener should be written in the 1st parameter of setTimeout() function and currently for clearing the cache programmatically  access to browser internal functionality is required which is currently not implemented in Microsoft Edge .</p>


问:
Need to filter out all columns which have null,0 or empty values in sql server from a group of tables
I have a bunch of tables about 50 of them and from all of those tables I am trying to figure out a way to filter all the columns which have 0 null or empty values in them. Not sure if sys.tables or Information_schema.tables would have any such function to suffice this.Like here the last column have null values for all rows so for each table I  supply in my query I need all such column with table name</p>

答:
```<code>SELECT table_name FROM INFORMATION_SCHEMA.TABLES
  WHERE table_schema = 'db_name'
  [AND table_name LIKE 'wild']

SHOW TABLES
  FROM db_name
  [LIKE 'wild']
</code>```


问:
javascript - Disable Browser Window Resize, when Browser window resized to certain width
I am working on a script where i want to restrict the resize of browser window when we resize the browser to width 320px. The screen should not shrink below 320px.

Here is my code!!

```<code>        var waitForFinalEvent = (function() {
          var timers = {};
          return function(callback, ms, uniqueId) {
            if (!uniqueId) {
              uniqueId = "Don't call this twice without a uniqueId" ;
            }
            if (timers[uniqueId]) {
              clearTimeout(timers[uniqueId]);
            }
            timers[uniqueId] = setTimeout(callback, ms);
          };
        })();

        // Usage
        $(window).resize(function() {
          var output = $('.output');
          $(output).text('RESIZING...');
          // Wait for it...
          waitForFinalEvent(function() {
            $(output).text('EVENT FIRED!');
            //...
          }, 500, "some unique string");
        });
</code>```

答:
Try this

```<code>$(window).resize(function(){
    if ($(window).width() <= 320) {
       window.resizeTo(300 ,$(window).height());
    }
});
</code>```

If your window is resized to less than 320 force the window to resize to 320 x whatever the current height is.

Body:
I am working on a script where i want to restrict the resize of browser window when we resize the browser to width 320px. The screen should not shrink below 320px.

Here is my code!!

        var waitForFinalEvent = (function() {
          var timers = {};
          return function(callback, ms, uniqueId) {
            if (!uniqueId) {
              uniqueId = "Don't call this twice without a uniqueId" ;
            }
            if (timers[uniqueId]) {
              clearTimeout(timers[uniqueId]);
            }
            timers[uniqueId] = setTimeout(callback, ms);
          };
        })();

        // Usage
        $(window).resize(function() {
          var output = $('.output');
          $(output).text('RESIZING...');
          // Wait for it...
          waitForFinalEvent(function() {
            $(output).text('EVENT FIRED!');
            //...
          }, 500, "some unique string");
        });

Body:
Try this

$(window).resize(function(){
    if ($(window).width() <= 320) {
       window.resizeTo(300 ,$(window).height());
    }
});

If your window is resized to less than 320 force the window to resize to 320 x whatever the current height is.


问:
script onload/onerror with IE(for lazy loading) problems
I'm rebuilding my lazy loader module to accept asyncronus request but i have a BIG problem:

internet explorer don't support script.onload/onerror!!!

The old script did globally eval the target script source read with an ajax sync call,
it works very well,it's cross browser and i can make it async editing 1 variable but it's very tricky to debug(ALL the source code is executed in one single line and the browser gives not to much infos about the errors,dividing the code by line with a regexp is IMPOSSIBLE because js have blocks with infinite depth and regexp are simply not good at this).

This is the code that i use to create the script(a classic):

```<code>var script = document.createElement('script');
script.type = 'text/javascript';
script.src =name;
script.name =name;
script.async = true;
script.onload=<my_onload_code>;
script.onerror=<my_onerror_code>;
</code>```

it won't work on IE because it doesen't support onload and onerror with the script;

the code below is a fix but works only if the script isn't async

```<code>if(script.onreadystatechange!==undefined)//only IE T_T
            script.onreadystatechange = function() {
                    if (script.readyState == 'loaded')//ERROR LOADING
                        <my_onerror_code>;
                    else
                    if(script.readyState == 'complete')//loaded
                        <my_onload_code>;

            };
</code>```

i can test it every X milliseconds until the script is loaded but it's an ugly solution and i want to avoid it.

EDIT: this is the code i tryed to check every X ms if the script is loaded, it's not that bad and it works better than ajax;the problem is that i can't know if the script is loaded with success or with error(onload or onerror).

```<code>var script = document.createElement('script');
script.type = 'text/javascript';
script.src =name;
script.name =name;
script.async = true;

    script.onload=function(){Lazy_loader.onload(this);};
    script.onerror=function(){Lazy_loader.onerror(this);};

    if(script.onreadystatechange!==undefined){//ie fix T_T
        script.timer=setInterval(function(){
                    if (script.readyState == 'loaded' || script.readyState == 'complete')}//ERROR LOADING

                        if(LOADED???)//loaded
                            Lazy_loader.onload(script);
                        else
                            Lazy_loader.onerror(script);

                        clearInterval(script.timer);
                    }

                    },100);

    }

document.getElementsByTagName('head')[0].appendChild(script);
</code>```

i tryed to use addEventListener/attachEvent functions but it didn't seem to work(even using addEvent functions from the web)

summarizing the options seems to be:

Use AJAX and global eval to load the script(debugging hell)

Use AJAX and global eval only with IE(may be a solution,i don't use IE)

Use AJAX and global eval only if the script contains errors(i need to check timings problems because with my code i "simulate" syncronous code even if the call is async)

Test script.onreadystatechange (only on IE) every X time until it's loaded(UGLY!!!)

Use window.onload : AVOID,it need to charge ALL the page,i need to call it when ONLY one script is launched(see details on endpage)

Add a code on the source of each script (AVOID like said on endpage)

fix the script.onload for IE(using addEventListener/attachEvent?!?)

PLEASE PAY ATTENTION:

i don't want to use window.onload because it's fired only when ALL the page is loaded,i need to fire it when only the target script is loaded(my lazy loading script is a lot more complex so please don't ask why);

i DO NOT WANT to use ANY third party library(like jquery,prototype,etc.),

i don't even want to edit the target script source(like when using JSPON or adding a script to alert that the script is loaded).

Hope that's not too much!
Thanks.

答:
ignore the junk below. the nextSibling thing was a result of being in the debugger and wasn't really reproducible in the real world. instead, i would have to recommend checking out www.requirejs.org

it provides a method that is about as close to an include or import statement as you could find in js.

this is a totally goofball solution, and i will be following this thread for comments about why this works, but here goes how i fixed this without a timer.
```var url = load_obj.url;
var callback  = load_obj.callback;
var head = document.getElementsByTagName('head')[0];
var appendage;
var complete = false;<br/>
appendage = document.createElement('script');
appendage.type = 'text/javascript';
appendage.onload = appendage.onreadystatechange = function() {
if (!complete && (!this.readyState || this.readyState === 'complete' || (this.readyState === 'loaded' && this.nextSibling != null))) {
    console.log('loaded via all');
    complete = true;
    if (callback)
        callback();
    //remove listeners
    appendage.onload = appendage.onreadystatechange = null;
} else if (this.readyState === 'loaded' && this.nextSibling == null) {
    console.log('error via ie');
}
appendage.onerror = function() {
    console.log('error via everything else');
}
appendage.src = url;```

like i said i don't know WHY nextSibling is null on a 404'd attempt, but if the js url was correct, nextSibling had a value.

Body:
I'm rebuilding my lazy loader module to accept asyncronus request but i have a BIG problem:

internet explorer don't support script.onload/onerror!!!

The old script did globally eval the target script source read with an ajax sync call,
it works very well,it's cross browser and i can make it async editing 1 variable but it's very tricky to debug(ALL the source code is executed in one single line and the browser gives not to much infos about the errors,dividing the code by line with a regexp is IMPOSSIBLE because js have blocks with infinite depth and regexp are simply not good at this).

This is the code that i use to create the script(a classic):

var script = document.createElement('script');
script.type = 'text/javascript';
script.src =name;
script.name =name;
script.async = true;
script.onload=<my_onload_code>;
script.onerror=<my_onerror_code>;

it won't work on IE because it doesen't support onload and onerror with the script;

the code below is a fix but works only if the script isn't async

if(script.onreadystatechange!==undefined)//only IE T_T
            script.onreadystatechange = function() {
                    if (script.readyState == 'loaded')//ERROR LOADING
                        <my_onerror_code>;
                    else
                    if(script.readyState == 'complete')//loaded
                        <my_onload_code>;

            };

i can test it every X milliseconds until the script is loaded but it's an ugly solution and i want to avoid it.

EDIT: this is the code i tryed to check every X ms if the script is loaded, it's not that bad and it works better than ajax;the problem is that i can't know if the script is loaded with success or with error(onload or onerror).

var script = document.createElement('script');
script.type = 'text/javascript';
script.src =name;
script.name =name;
script.async = true;

    script.onload=function(){Lazy_loader.onload(this);};
    script.onerror=function(){Lazy_loader.onerror(this);};

    if(script.onreadystatechange!==undefined){//ie fix T_T
        script.timer=setInterval(function(){
                    if (script.readyState == 'loaded' || script.readyState == 'complete')}//ERROR LOADING

                        if(LOADED???)//loaded
                            Lazy_loader.onload(script);
                        else
                            Lazy_loader.onerror(script);

                        clearInterval(script.timer);
                    }

                    },100);

    }

document.getElementsByTagName('head')[0].appendChild(script);

i tryed to use addEventListener/attachEvent functions but it didn't seem to work(even using addEvent functions from the web)

summarizing the options seems to be:

Use AJAX and global eval to load the script(debugging hell)

Use AJAX and global eval only with IE(may be a solution,i don't use IE)

Use AJAX and global eval only if the script contains errors(i need to check timings problems because with my code i "simulate" syncronous code even if the call is async)

Test script.onreadystatechange (only on IE) every X time until it's loaded(UGLY!!!)

Use window.onload : AVOID,it need to charge ALL the page,i need to call it when ONLY one script is launched(see details on endpage)

Add a code on the source of each script (AVOID like said on endpage)

fix the script.onload for IE(using addEventListener/attachEvent?!?)

PLEASE PAY ATTENTION:

i don't want to use window.onload because it's fired only when ALL the page is loaded,i need to fire it when only the target script is loaded(my lazy loading script is a lot more complex so please don't ask why);

i DO NOT WANT to use ANY third party library(like jquery,prototype,etc.),

i don't even want to edit the target script source(like when using JSPON or adding a script to alert that the script is loaded).

Hope that's not too much!
Thanks.

Body:
ignore the junk below. the nextSibling thing was a result of being in the debugger and wasn't really reproducible in the real world. instead, i would have to recommend checking out www.requirejs.org

it provides a method that is about as close to an include or import statement as you could find in js.

this is a totally goofball solution, and i will be following this thread for comments about why this works, but here goes how i fixed this without a timer.

var url = load_obj.url;
var callback  = load_obj.callback;
var head = document.getElementsByTagName('head')[0];
var appendage;
var complete = false;

appendage = document.createElement('script');
appendage.type = 'text/javascript';
appendage.onload = appendage.onreadystatechange = function() {
if (!complete && (!this.readyState || this.readyState === 'complete' || (this.readyState === 'loaded' && this.nextSibling != null))) {
    console.log('loaded via all');
    complete = true;
    if (callback)
        callback();
    //remove listeners
    appendage.onload = appendage.onreadystatechange = null;
} else if (this.readyState === 'loaded' && this.nextSibling == null) {
    console.log('error via ie');
}
appendage.onerror = function() {
    console.log('error via everything else');
}
appendage.src = url;

like i said i don't know WHY nextSibling is null on a 404'd attempt, but if the js url was correct, nextSibling had a value.


问:
php: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it
I have create register and login form using php. And i had took the source from google.

So i have added all the corresponding code, when run index.php.

It shows,

```<code>SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
</code>```

I tried for fixing this problem using stackoverflow and google, still can't to rectify.

I Am using xampp. In xampp control panel, apache and mysql modules are running. and apache port is 80,443 and mysql port is 3306.

May i know, any other my mistake?..

Can someone help me? Any help would be appreciated.

Thanks in advance.

This is my config.php:

```<code><?php
ob_start();
session_start();

//set timezone
date_default_timezone_set('Europe/London');

//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','register');

//application address
define('DIR','http://domain.com/');
define('SITEEMAIL','noreply@domain.com');

try {

    //create PDO connection
    $db = new PDO("mysql:host=".DBHOST.";port=8889;dbname=".DBNAME, DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {
    //show error
    echo '<p class="bg-danger">'.$e->getMessage().'</p>';
    exit;
}

//include the user class, pass in the database connection
include('classes/user.php');
$user = new User($db);
?>
</code>```

答:
I suffered this error too.
I did following things:
1. find out the port number used by mysql. In phpmyadmin, I ran the following sql:

```<code>show variables;
</code>```

it shows a list of variables of mysql. scroll down, you will find port number.

I edited the php code like this:

$dsn = 'mysql:host=127.0.0.1;port=3307; dbname=learnphpfast';

it worked like a charm!

Body:
I have create register and login form using php. And i had took the source from google.

So i have added all the corresponding code, when run index.php.

It shows,

SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.

I tried for fixing this problem using stackoverflow and google, still can't to rectify.

I Am using xampp. In xampp control panel, apache and mysql modules are running. and apache port is 80,443 and mysql port is 3306.

May i know, any other my mistake?..

Can someone help me? Any help would be appreciated.

Thanks in advance.

This is my config.php:

<?php
ob_start();
session_start();

//set timezone
date_default_timezone_set('Europe/London');

//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','register');

//application address
define('DIR','http://domain.com/');
define('SITEEMAIL','noreply@domain.com');

try {

    //create PDO connection
    $db = new PDO("mysql:host=".DBHOST.";port=8889;dbname=".DBNAME, DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {
    //show error
    echo '
'.$e->getMessage().'
';
    exit;
}

//include the user class, pass in the database connection
include('classes/user.php');
$user = new User($db);
?>

Body:
I suffered this error too.
I did following things:
1. find out the port number used by mysql. In phpmyadmin, I ran the following sql:

show variables;

it shows a list of variables of mysql. scroll down, you will find port number.

I edited the php code like this:

$dsn = 'mysql:host=127.0.0.1;port=3307; dbname=learnphpfast';

it worked like a charm!


问:
How to convert "jar" to Linux executable file?
I know how to convert "jar" to windows executable file(.exe). But I want to know how to convert "jar" to Linux executable file(.?). I have searched google but didn't get exact answer what i want, help to do this.</p>

答:
You can always run a jar file by doing java -jar myFile.jar.

However, to make the jar file itself executable, you need to set the executable bit, as the message hints. chmod +x /path/to/your/file/myFile.jar will accomplish this.

After that you can do ./myFile.jar to run it.

man chmod will provide you with information about how chmod works.

Source: How can I make a .jar file executable?  on AskUbuntu. Answer by Gary


问:
Multiple definition when compiling
I have these files:

```<code>main.cpp
headers.h
calculator.h
calculator.cpp
Supported_operators.h
Supported_operators.c
My_Operations.h
My_Operations.cpp
</code>```

My headers.h file has (apart from std libs): #include "Supported_operators.h" and finally my Supported_operators.h has the following:

```<code>#ifndef CALCULATOR_SUPPORTED_OPERATORS_H
#define CALCULATOR_SUPPORTED_OPERATORS_H

#include "headers.h"
//using directives
class Supported_operator {
//stuff
};

list<Supported_operator> supportedOps = {
                                        Supported_operator('+', 2, 'l'),
                                        Supported_operator('-', 2, 'l'),
                                        Supported_operator('*', 3, 'l'),
                                        Supported_operator('/', 3, 'l'),
                                        Supported_operator('^', 4, 'r')
                                        };

#endif //CALCULATOR_SUPPORTED_OPERATORS_H
</code>```

When I try to compile the program, the compilator says multiple definition of supportedOps[abi:cxx11] at my main().

How do I solve this problem?

Context: I'm trying to make a calculator. Have to split string input into tokens. If token is an operator, do certain operations depending on that operator. So I have to create a container of SupportedOperators and then check if tokened operator is supported and what are its properties.

EDIT 2: My headers.h file now includes const list<Supported_operator> supportedOps; and my Supported_operators.cpp now has list<Supported_operator> supportedOps = { }; but then the headers.h triggers error list does not name a type.

EDIT 3: Changing the declaration in headers.h to extern const std::list<> supportedOps; now results in a new set of errors - Supported_operator was not declared in that scope. I thought I had this covered with #include "Supported_operators.h where Supported_operator is declared. Am I assuming correctly the compilers doesn't know of class Supported_operator yet? How do I work around this?

答:
You should leave list<Supported_operator> supportedOps; in the header and add

```<code>Supported_operator('+', 2, 'l'),
        Supported_operator('-', 2, 'l'),
        Supported_operator('*', 3, 'l'),
        Supported_operator('/', 3, 'l'),
        Supported_operator('^', 4, 'r')
        };
</code>```

to your Supported_operators.c(pp)

Title: Multiple definition when compiling

Body:
I have these files:

main.cpp
headers.h
calculator.h
calculator.cpp
Supported_operators.h
Supported_operators.c
My_Operations.h
My_Operations.cpp

My headers.h file has (apart from std libs): #include "Supported_operators.h" and finally my Supported_operators.h has the following:

#ifndef CALCULATOR_SUPPORTED_OPERATORS_H
#define CALCULATOR_SUPPORTED_OPERATORS_H

#include "headers.h"
//using directives
class Supported_operator {
//stuff
};

list<Supported_operator> supportedOps = {
                                        Supported_operator('+', 2, 'l'),
                                        Supported_operator('-', 2, 'l'),
                                        Supported_operator('*', 3, 'l'),
                                        Supported_operator('/', 3, 'l'),
                                        Supported_operator('^', 4, 'r')
                                        };

#endif //CALCULATOR_SUPPORTED_OPERATORS_H

When I try to compile the program, the compilator says multiple definition of supportedOps[abi:cxx11] at my main().

How do I solve this problem?

Context: I'm trying to make a calculator. Have to split string input into tokens. If token is an operator, do certain operations depending on that operator. So I have to create a container of SupportedOperators and then check if tokened operator is supported and what are its properties.

EDIT 2: My headers.h file now includes const list<Supported_operator> supportedOps; and my Supported_operators.cpp now has list<Supported_operator> supportedOps = { }; but then the headers.h triggers error list does not name a type.

EDIT 3: Changing the declaration in headers.h to extern const std::list<> supportedOps; now results in a new set of errors - Supported_operator was not declared in that scope. I thought I had this covered with #include "Supported_operators.h where Supported_operator is declared. Am I assuming correctly the compilers doesn't know of class Supported_operator yet? How do I work around this?

Body:
You should leave list<Supported_operator> supportedOps; in the header and add

Supported_operator('+', 2, 'l'),
        Supported_operator('-', 2, 'l'),
        Supported_operator('*', 3, 'l'),
        Supported_operator('/', 3, 'l'),
        Supported_operator('^', 4, 'r')
        };

to your Supported_operators.c(pp)