问:
Use Logstash with HTML log
I'm new to Logstash, trying to use it to parse a HTML log file.
I need to output only the log lines, i.e. ignore preceding JS, CSS and HTML that are also included in the file.
A log line in the file looks like this:

```<code><tr bgcolor="tomato"><td>Jan 28<br>13:52:25.692</td><td>Jan 28<br>13:52:23.950</td><td>qtp114615276-1648 [POST] [call_id:-8009072655119858507]</td><td>REST</td><td>sa</td><td>0.0.0.0</td><td>ERR</td><td>ProjectValidator.validate(36)</td><td>Project does not exist</td></tr>
</code>```

I have no problem getting all the lines, but I would like to have an output which contains only the relevant ones, without HTML tags, and looks something like that:

```<code>{
  "db_timestamp": "2015-01-28 13:52:25.692",
  "server_timestamp": "2015-01-28 13:52:25.950",
  "node": "qtp114615276-1648 [POST] [call_id:-8009072655119858507]",
  "thread": "REST",
  "user": "sa",
  "ip": "0.0.0.0",
  "level": "ERR",
  "method": "ProjectValidator.validate(36)",
  "message": "Project does not exist"
}
</code>```

My Logstash configuration is:

```<code>input {
  file {
    type => "request"
    path => "<some path>/*.log"
    start_position => "beginning"
  }
  file {
    type => "log"
    path => "<some path>/*.html"
    start_position => "beginning"
  }
}
filter {
  if [type] == "log" {
    grok {
        match => [ WHAT SHOULD I PUT HERE??? ]
    }
  }
}
output {
  stdout {}
  if [type] == "request" {
    http {
        http_method => "post"
        url => "http://<some url>"
        mapping =>  ["type", "request", "host" ,"%{host}", "timestamp", "%{@timestamp}", "message", "%{message}"]
    }
  }
  if [type] == "log" {
    http {
        http_method => "post"
        url => "http://<some url>"
        mapping =>  [ ALSO WHAT SHOULD I PUT HERE??? ]
    }
  }
}
</code>```

Is there a way to do that? So far I haven't found any relevant documentation or samples.

Thanks!

答:
For anyone parsing HP ALM logs, the following Logstash filter will do the work:

```<code>   grok {
        break_on_match => true
        match => [ "message", "<tr bgcolor=.*><td>%{MONTH:db_date_mon}%{SPACE}%{MONTHDAY:db_date_day}<br>%{TIME:db_date_time}<\/td><td>%{MONTH:alm_date_mon}%{SPACE}%{MONTHDAY:alm_date_day}<br>%{TIME:alm_date_time}<\/td><td>(?<thread_col1>.*?)<\/td><td>(?<request_type>.*?)<\/td><td>(?<login>.*?)<\/td><td>(?<ip>.*?)<\/td><td>(?<level>.*?)<\/td><td>(?<method>.*?)<\/td><td>(?m:(?<log_message>.*?))</td></tr>" ]
        }
    mutate {
        add_field => ["db_date", "%{db_date_mon} %{db_date_day}"]
        add_field => ["alm_date", "%{alm_date_mon} %{alm_date_day}"]
        remove_field => [ "db_date_mon", "db_date_day", "alm_date_mon", "alm_date_day"  ]
        gsub => [
           "log_message", "<br>", "
           "
           ]
        gsub => [
           "log_message", "<p>", "   "
           ]

        }
</code>```

Tested and working fine with Logstash 2.4.0

Title: Use Logstash with HTML log

Body:
I'm new to Logstash, trying to use it to parse a HTML log file.
I need to output only the log lines, i.e. ignore preceding JS, CSS and HTML that are also included in the file.
A log line in the file looks like this:

Jan 28
13:52:25.692	Jan 28
13:52:23.950	qtp114615276-1648 [POST] [call_id:-8009072655119858507]	REST	sa	0.0.0.0	ERR	ProjectValidator.validate(36)	Project does not exist

I have no problem getting all the lines, but I would like to have an output which contains only the relevant ones, without HTML tags, and looks something like that:

{
  "db_timestamp": "2015-01-28 13:52:25.692",
  "server_timestamp": "2015-01-28 13:52:25.950",
  "node": "qtp114615276-1648 [POST] [call_id:-8009072655119858507]",
  "thread": "REST",
  "user": "sa",
  "ip": "0.0.0.0",
  "level": "ERR",
  "method": "ProjectValidator.validate(36)",
  "message": "Project does not exist"
}

My Logstash configuration is:

input {
  file {
    type => "request"
    path => "<some path>/*.log"
    start_position => "beginning"
  }
  file {
    type => "log"
    path => "<some path>/*.html"
    start_position => "beginning"
  }
}
filter {
  if [type] == "log" {
    grok {
        match => [ WHAT SHOULD I PUT HERE??? ]
    }
  }
}
output {
  stdout {}
  if [type] == "request" {
    http {
        http_method => "post"
        url => "http://<some url>"
        mapping =>  ["type", "request", "host" ,"%{host}", "timestamp", "%{@timestamp}", "message", "%{message}"]
    }
  }
  if [type] == "log" {
    http {
        http_method => "post"
        url => "http://<some url>"
        mapping =>  [ ALSO WHAT SHOULD I PUT HERE??? ]
    }
  }
}

Is there a way to do that? So far I haven't found any relevant documentation or samples.

Thanks!

Body:
For anyone parsing HP ALM logs, the following Logstash filter will do the work:

   grok {
        break_on_match => true
        match => [ "message", "<tr bgcolor=.*><td>%{MONTH:db_date_mon}%{SPACE}%{MONTHDAY:db_date_day}<br>%{TIME:db_date_time}<\/td><td>%{MONTH:alm_date_mon}%{SPACE}%{MONTHDAY:alm_date_day}<br>%{TIME:alm_date_time}<\/td><td>(?<thread_col1>.*?)<\/td><td>(?<request_type>.*?)<\/td><td>(?<login>.*?)<\/td><td>(?<ip>.*?)<\/td><td>(?<level>.*?)<\/td><td>(?<method>.*?)<\/td><td>(?m:(?<log_message>.*?))</td></tr>" ]
        }
    mutate {
        add_field => ["db_date", "%{db_date_mon} %{db_date_day}"]
        add_field => ["alm_date", "%{alm_date_mon} %{alm_date_day}"]
        remove_field => [ "db_date_mon", "db_date_day", "alm_date_mon", "alm_date_day"  ]
        gsub => [
           "log_message", "<br>", "
           "
           ]
        gsub => [
           "log_message", "<p>", "   "
           ]

        }

Tested and working fine with Logstash 2.4.0


来源: stackexchange

问:
Perl File::Copy is not actually copying the file
Quick synopsis: Let's say there are multiple of the same file type in one directory (in this example, 10 .txt files). I am trying to use Perl's copy function to copy 5 of them into a new directory, then zip up that directory.

The code works...except the folder that is supposed to have the .txt files copied, doesn't actually have anything in it, and I don't know why. Here is my complete code:

```<code>#!/usr/bin/perl
use strict;
use warnings;

use File::Copy;

my $source_dir = "C:\\Users\\user\\Documents\\test";
my $dest_dir = "C:\\Users\\user\\Desktop\\files";
my $count = 0;

opendir(DIR, $source_dir) or die $!;
system('mkdir files');

while (my $file = readdir(DIR)) {
    print "$file\n";
    if ($count eq 5) {
        last;
    }

    if ($file =~ /\.txt/) {
        copy("$file", "$dest_dir/$file");
        $count++;
    }
}

closedir DIR;

system('"C:\Program Files\Java\jdk1.8.0_66\bin\jar.exe" -cMf files.zip files');

system('del /S /F /Q files');
system('rmdir files');
</code>```

Everything works...the directory files is created, then zipped up into files.zip...when I open the zip file, the files directory is empty, so it's as if the copy statement didn't copy anything over.

In the $source_dir are 10 .txt files, like this (for testing purposes):

test1.txt

test2.txt

test3.txt

test4.txt

test5.txt

test6.txt

test7.txt

test8.txt

test9.txt

test10.txt

The files don't actually get copied over...NOTE: the print "$file\n" was added for testing, and it indeed is printing out test1.txt, test2.txt, etc. up to test6.txt so I know that it is finding the files, just not copying them over.

Any thoughts as to where I'm going wrong?

答:
I think there is a typo in your script:
    system('mkdir files');
should be:
    system("mkdir $dest_dir");

but, the real issue is that you are not using the full path of the source file. Change your copy to:
    copy("$source_dir/$file", $dest_dir);

and see if that helps.
You might also want to look at: File::Path and Archive::Zip, they would eliminate the system calls.

ContentLicense: CC BY-SA 3.0

Body:
Quick synopsis: Let's say there are multiple of the same file type in one directory (in this example, 10 .txt files). I am trying to use Perl's copy function to copy 5 of them into a new directory, then zip up that directory.

The code works...except the folder that is supposed to have the .txt files copied, doesn't actually have anything in it, and I don't know why. Here is my complete code:

#!/usr/bin/perl
use strict;
use warnings;

use File::Copy;

my $source_dir = "C:\\Users\\user\\Documents\\test";
my $dest_dir = "C:\\Users\\user\\Desktop\\files";
my $count = 0;

opendir(DIR, $source_dir) or die $!;
system('mkdir files');

while (my $file = readdir(DIR)) {
    print "$file\n";
    if ($count eq 5) {
        last;
    }

    if ($file =~ /\.txt/) {
        copy("$file", "$dest_dir/$file");
        $count++;
    }
}

closedir DIR;

system('"C:\Program Files\Java\jdk1.8.0_66\bin\jar.exe" -cMf files.zip files');

system('del /S /F /Q files');
system('rmdir files');

Everything works...the directory files is created, then zipped up into files.zip...when I open the zip file, the files directory is empty, so it's as if the copy statement didn't copy anything over.

In the $source_dir are 10 .txt files, like this (for testing purposes):

test1.txt

test2.txt

test3.txt

test4.txt

test5.txt

test6.txt

test7.txt

test8.txt

test9.txt

test10.txt

The files don't actually get copied over...NOTE: the print "$file\n" was added for testing, and it indeed is printing out test1.txt, test2.txt, etc. up to test6.txt so I know that it is finding the files, just not copying them over.

Any thoughts as to where I'm going wrong?


问:
How To define arguments in ironpython for the Microsoft.SqlServer.SMO.Scripter.Script Class
I want to script my database objects using the ironpython code below:

```<code>import sys
import clr

database_name  = r'localhost\SQLEXPRESS'
dir_assemblies = r'D:\programfiles\Microsoft SQL Server\100\SDK\Assemblies'

# Import SMO Namespace
sys.path.append(dir_assemblies)
clr.AddReferenceToFile('Microsoft.SqlServer.Smo.dll')
import Microsoft.SqlServer.Management.Smo as SMO

db       = SMO.Server(database_name)
scripter = SMO.Scripter(db)

for database in db.Databases:
    for table in database.Tables:
        # TypeError: expected Array[Urn], got Table
        scripter.Script(table)
</code>```

When executing this code, I get the following error:

```<code>File "SMOtest2.py", line 18, in <module>
TypeError: expected Array[Urn], got Table
</code>```

The SMO.Scripter.doc gives me the following information:

```<code>Script(self: Scripter, urns: Array[Urn]) -> StringCollection
Script(self: Scripter, list: UrnCollection) -> StringCollection
Script(self: Scripter, objects: Array[SqlSmoObject]) -> StringCollection
</code>```

I tried creating an Array[Urn] or an Array[SqlSmoObject] but without any succes.

Does anyone have an idea how I can create the right argument for the SMO.Scripter.Script Class?

I want to write the VB code below in python.
Taken from: http://msdn.microsoft.com/en-us/library/ms162160(v=SQL.90).aspx

```<code>'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks database.
Dim db As Database
db = srv.Databases("AdventureWorks")
'Define a Scripter object and set the required scripting options.
Dim scrp As Scripter
scrp = New Scripter(srv)
scrp.Options.ScriptDrops = False
scrp.Options.WithDependencies = True
'Iterate through the tables in database and script each one. Display the script.
'Note that the StringCollection type needs the System.Collections.Specialized namespace to be included.
Dim tb As Table
Dim smoObjects(1) As Urn
For Each tb In db.Tables
    smoObjects = New Urn(0) {}
    smoObjects(0) = tb.Urn
    If tb.IsSystemObject = False Then
        Dim sc As StringCollection
        sc = scrp.Script(smoObjects)
        Dim st As String
        For Each st In sc
            Console.WriteLine(st)
        Next
    End If
Next
</code>```

答:
I found the solution:

```<code>arg=System.Array[SMO.SqlSmoObject]([table])
</code>```

The full script looks like:

```<code>import sys
import clr
# import .NET Array
import System.Array

database_name  = r'localhost\SQLEXPRESS'
dir_assemblies = r'D:\programfiles\Microsoft SQL Server\100\SDK\Assemblies'

# Import SMO Namespace
sys.path.append(dir_assemblies)
clr.AddReferenceToFile('Microsoft.SqlServer.Smo.dll')
import Microsoft.SqlServer.Management.Smo as SMO

db       = SMO.Server(database_name)
scripter = SMO.Scripter(db)

for database in db.Databases:
    for table in database.Tables:
        # create a .NET Array as an argument for the scripter
        arg=System.Array[SMO.SqlSmoObject]([table])
        script = scripter.Script(arg)
        #output script
        for line in script:
            print line
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to script my database objects using the ironpython code below:

import sys
import clr

database_name  = r'localhost\SQLEXPRESS'
dir_assemblies = r'D:\programfiles\Microsoft SQL Server\100\SDK\Assemblies'

# Import SMO Namespace
sys.path.append(dir_assemblies)
clr.AddReferenceToFile('Microsoft.SqlServer.Smo.dll')
import Microsoft.SqlServer.Management.Smo as SMO

db       = SMO.Server(database_name)
scripter = SMO.Scripter(db)

for database in db.Databases:
    for table in database.Tables:
        # TypeError: expected Array[Urn], got Table
        scripter.Script(table)

When executing this code, I get the following error:

File "SMOtest2.py", line 18, in <module>
TypeError: expected Array[Urn], got Table

The SMO.Scripter.doc gives me the following information:

Script(self: Scripter, urns: Array[Urn]) -> StringCollection
Script(self: Scripter, list: UrnCollection) -> StringCollection
Script(self: Scripter, objects: Array[SqlSmoObject]) -> StringCollection

I tried creating an Array[Urn] or an Array[SqlSmoObject] but without any succes.

Does anyone have an idea how I can create the right argument for the SMO.Scripter.Script Class?

I want to write the VB code below in python.
Taken from: http://msdn.microsoft.com/en-us/library/ms162160(v=SQL.90).aspx

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks database.
Dim db As Database
db = srv.Databases("AdventureWorks")
'Define a Scripter object and set the required scripting options.
Dim scrp As Scripter
scrp = New Scripter(srv)
scrp.Options.ScriptDrops = False
scrp.Options.WithDependencies = True
'Iterate through the tables in database and script each one. Display the script.
'Note that the StringCollection type needs the System.Collections.Specialized namespace to be included.
Dim tb As Table
Dim smoObjects(1) As Urn
For Each tb In db.Tables
    smoObjects = New Urn(0) {}
    smoObjects(0) = tb.Urn
    If tb.IsSystemObject = False Then
        Dim sc As StringCollection
        sc = scrp.Script(smoObjects)
        Dim st As String
        For Each st In sc
            Console.WriteLine(st)
        Next
    End If
Next

Body:
I found the solution:

arg=System.Array[SMO.SqlSmoObject]([table])

The full script looks like:

import sys
import clr
# import .NET Array
import System.Array

database_name  = r'localhost\SQLEXPRESS'
dir_assemblies = r'D:\programfiles\Microsoft SQL Server\100\SDK\Assemblies'

# Import SMO Namespace
sys.path.append(dir_assemblies)
clr.AddReferenceToFile('Microsoft.SqlServer.Smo.dll')
import Microsoft.SqlServer.Management.Smo as SMO

db       = SMO.Server(database_name)
scripter = SMO.Scripter(db)

for database in db.Databases:
    for table in database.Tables:
        # create a .NET Array as an argument for the scripter
        arg=System.Array[SMO.SqlSmoObject]([table])
        script = scripter.Script(arg)
        #output script
        for line in script:
            print line


问:
P-values in a "pairwise.prop.test" from the stats package on R using a Bonferroni correction
First time asking a question. I have done my best to conduct my own searches and have looked at the manual. I hope I am not posting a repeat or an off-topic.

I have an output from using the pairwise.prop.test with a bonferroni correction using:

pairwise.prop.test(fishingsept13,p.adjust.method = 'bonferroni')

It came out just fine and ran smoothly.

My question is more on the interpretation of the p-values printed. I know that the Bonferroni correction for my data would be that anything less than 0.01 is significant. These are my results:

I assume that I would interpret them with my known Bonferonni and determine their significance from there. I'm paranoid that I am assuming wrong.

答:
Actually, the pairwise comparison functions in R already correct the p values for you. The p.adjust.method argument you used told R to perform a multiple comparisons correction by the Bonferroni method. Since you performed 3 separate comparisons, the p values you see have already been multiplied by 3: you don't have to adjust your significance threshold. To see for yourself, look what happens when you run

pairwise.prop.test(fishingsept13,p.adjust.method = 'none')


问:
bash no parameters for $(function parameters)
I want to create a script that use basic (prompt and confirm) functions multiple times, when I try to set the return to any variable the function ignore the parameters

```<code>function promp() {
    echo $*
    read response
    echo $response
}
function confirm() {
    echo $*
    read -rp $'(y/N) : ' -ei $'N' key;
    case "$key" in
        [yY][eE][sS]|[yY])
            echo true
            ;;
        *)
            echo false
            ;;
    esac
}

IS_RESPONSE=$(confirm "SOME QUESTION")
STRING_RESPONSE=$(promp "WRITE SOMETHING")
echo $IS_RESPONSE
echo $STRING_RESPONSE
</code>```

Expected:

```<code>SOME QUESTION
(y/N) : N
WRITE SOMETHING
#<< "some text"
false
some text
</code>```

Obtained:

```<code>(y/N) : N
#<< "some text"
SOME QUESTION false
WRITE SOMETHING some text
</code>```

I know the problem is the echo within the function is part of the variable data, but I want to get this printed.

How can I do this or which is the best way to do this

答:
Your functions are called in context of command substitution:

```<code>STRING_RESPONSE=$(promp "WRITE SOMETHING")
</code>```

So the standard output of the promp "WRITE SOMETHING" command is attached to the context of the variable assignment.

However, the standard error is still attached to the terminal. If you redirect the output of echo to the file descriptor 2, then the output will be displayed to the user just when the echo is called, e.g.:

```<code>function promp() {
    echo >&2 "$*"
    read response
    echo "$response"
}
</code>```

Another way is to use -p option: read -p "Your prompt: " which prints the prompt string to the standard error as well.

Body:
I want to create a script that use basic (prompt and confirm) functions multiple times, when I try to set the return to any variable the function ignore the parameters

function promp() {
    echo $*
    read response
    echo $response
}
function confirm() {
    echo $*
    read -rp $'(y/N) : ' -ei $'N' key;
    case "$key" in
        [yY][eE][sS]|[yY])
            echo true
            ;;
        *)
            echo false
            ;;
    esac
}

IS_RESPONSE=$(confirm "SOME QUESTION")
STRING_RESPONSE=$(promp "WRITE SOMETHING")
echo $IS_RESPONSE
echo $STRING_RESPONSE

Expected:

SOME QUESTION
(y/N) : N
WRITE SOMETHING
#<< "some text"
false
some text

Obtained:

(y/N) : N
#<< "some text"
SOME QUESTION false
WRITE SOMETHING some text

I know the problem is the echo within the function is part of the variable data, but I want to get this printed.

How can I do this or which is the best way to do this

Body:
Your functions are called in context of command substitution:

STRING_RESPONSE=$(promp "WRITE SOMETHING")

So the standard output of the promp "WRITE SOMETHING" command is attached to the context of the variable assignment.

However, the standard error is still attached to the terminal. If you redirect the output of echo to the file descriptor 2, then the output will be displayed to the user just when the echo is called, e.g.:

function promp() {
    echo >&2 "$*"
    read response
    echo "$response"
}

Another way is to use -p option: read -p "Your prompt: " which prints the prompt string to the standard error as well.


问:
How to use espresso to press a setPositiveButton type AlertDialog button
If I want to press ADD button, I tried:

onView(withText("ADD")).perform(click())

as well as

```<code>onView(withText("ADD"))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
                .perform(click());
</code>```

But none of them work well

答: The Espresso withText() is case sensitive.  You are checking for 'ADD' in the test, but setting the value to 'Add' in the construction of your dialog. If 'ADD' shows up visually in your UI, that's likely due to a style or textallcaps being set on your textView, but Espresso is actually looking for the underlying text value set on the widget.

Body:
If I want to press ADD button, I tried:

onView(withText("ADD")).perform(click())

as well as

onView(withText("ADD"))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
                .perform(click());

But none of them work well


问:
Use of Global Variables in Python
Why the value of variable is not changing while using global in function.

Am i missing something?

```<code>class testglobal():
    a=2
    print(a)

    def change():

        global a
        a = 5

    change()
    print(a)
</code>```

答:
First: If your variable is inside a class, it's not a global variable.
You have to declare it outside of any function/method/class.

Second: The identation of your class is wrong. Inside a class, start with 4 spaces or a tab.

Title: Use of Global Variables in Python

Body:
Why the value of variable is not changing while using global in function.

Am i missing something?

class testglobal():
    a=2
    print(a)

    def change():

        global a
        a = 5

    change()
    print(a)


问:
ambiguity between double quotes and single quotes in javascript
var myStr = 'This string has "double quotes" in it. And "probably" lots of them';

The value in using one or the other has to do with the need to escape quotes of the same type. Unless they are escaped, you cannot have more than one pair of whichever quote type begins a string.?? //what does it mean??

//Error i got:-
Remove all the backslashes ()
You should have two single quotes ' and four double quotes "
Only remove the backslashes \ used to escape quotes.

can anyone tell what should i do to make it correct?

答:
It means that while using single quotes or double quotes do the same thing, if you try to wrap your entire string in single quotes, you won't be able to use single quotes in middle of your string without using \

What the backslash does is called "escaping", which tells javascript that you want to use that quotation mark as part of the string, and not to mark the beginning or end of a string


问:
PySwip read(X) function on python
when i put this in python

```<code>from pyswip import *
read = Functor("read",1)
X=Variable()
call(read(X))
</code>```

the response is a prolog shell

```<code>|:
</code>```

how to make a raw_input instead of the prolog shell?

Thanks

答:
To do that you will need to register a new foreign function and call it from prolog code. This python3 example may help you (with this python3 version pyswip):

```<code>from pyswip import Prolog, registerForeign, Atom

def py_read(*a):
    a[0].unify(input("PyInput:"))
    return True

registerForeign(py_read, arity=1)
result = list(Prolog.query('py_read(X)'))
print(result[0]['X'])
</code>```

Title: PySwip read(X) function on python

Body:
when i put this in python

from pyswip import *
read = Functor("read",1)
X=Variable()
call(read(X))

the response is a prolog shell

|:

how to make a raw_input instead of the prolog shell?

Thanks

Body:
To do that you will need to register a new foreign function and call it from prolog code. This python3 example may help you (with this python3 version pyswip):

from pyswip import Prolog, registerForeign, Atom

def py_read(*a):
    a[0].unify(input("PyInput:"))
    return True

registerForeign(py_read, arity=1)
result = list(Prolog.query('py_read(X)'))
print(result[0]['X'])


问:
Tab+ViewPager not updating instead shows weird warning expected state 3 found 2
I have a mainactivity which includes a TabLayout with ViewPager

I have added 3 tabs and each tab has separate fragments which contains a recyclerview, and these recyclerviews has a checkbox that should be simultaneously updated/refreshed whenever i swipe the viewpager(i save checked positions in shared preference and updates via shared preference).

My problem here is whenever i check a checkbox in tab1, tab2 is not updating/refreshing until i scroll down the Recyclerview. and tab3 is working fine.
and i am getting a weird warning in logcat too.

```<code> 03-05 09:35:53.345 4317-4327/com.example.rubin W/art: Suspending all threads took: 6.805ms
    03-05 09:35:58.310 4317-4317/com.example.rubin W/FragmentManager: moveToState: Fragment state for Tab3{10a5f1f0 #2 id=0x7f0d00b6} not updated inline; expected state 3 found 2
    03-05 09:36:01.363 4317-4317/com.example.rubin W/FragmentManager: moveToState: Fragment state for Tab1{2d9aa887 #1 id=0x7f0d00b6} not updated inline; expected state 3 found 2
</code>```

My PagerAdapter

```<code>public class PagerAdapter1 extends FragmentStatePagerAdapter {
    int mNumOfTabs;
    public PagerAdapter1(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
               return new Tab1();
            case 1:
               return new Tab2();
            case 2:
               return new Tab3();

            default:
                return null;

        }
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}
</code>```

Tablayout OnPageChangelistener

```<code>final PagerAdapter1 adapter = new PagerAdapter1
                (getSupportFragmentManager(), tabLayout1.getTabCount(), getApplicationContext());
        viewPager1.setAdapter(adapter);
        viewPager1.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout1));
        tabLayout1.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager1.setCurrentItem(tab.getPosition());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }
</code>```

code for each fragments.

```<code> public class Tab1 extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.home_tab1_recycler, container, false);
            RecyclerView rv = (RecyclerView) v.findViewById(R.id.home_recyclerview);
            LinearLayoutManager llm = new LinearLayoutManager(getContext());
            rv.setLayoutManager(llm);
            rv.setHasFixedSize(true); // to improve performance
            rv.setAdapter(new HomeManager()); // the projectdatabase manager is assigner to the RV
            return v;
        }

        public class HomeManager extends RecyclerView.Adapter<HomeManager.RecyclerViewHolder> {
    int Length,h;
 View v1;
        ArrayList<String> PROJECT_ID = new ArrayList<String>();
Set<String> set;
        List<String> selected;
     public class RecyclerViewHolder extends RecyclerView.ViewHolder {
     CheckBox mCheck;
      RecyclerViewHolder(final View itemView) {
                    super(itemView);
      mCheck = (CheckBox) itemView.findViewById(R.id.PROJECT_fav);
     SharedPreferences pref = getContext().getSharedPreferences("MirSP", Context.MODE_PRIVATE);
                    set = pref.getStringSet("FAV", null);
      if (set != null) {
                        selected = new ArrayList<String>(set);
                    } else {
                        selected = new ArrayList<String>();
                    }
    mCheck.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
     h = getAdapterPosition();
    check = PROJECT_ID.get(h); // for saving the project id from json.
     if (selected.contains(check)) {
                                    selected.remove(check);
                                    mCheck.setBackgroundResource(R.drawable.ic_favorite_white1_24dp);
                                    Snackbar snackbar = Snackbar.make(v, "Property Unfavorited", Snackbar.LENGTH_SHORT);
                                    snackbar.show();
                                } else {
                                    selected.add(check);
                                    mCheck.setBackgroundResource(R.drawable.ic_favorite_white_24dp);
                                    Snackbar snackbar = Snackbar.make(v, "Property Favorited", Snackbar.LENGTH_SHORT);
                                    snackbar.show();

                                }
                                Log.e("HF update checked", String.valueOf(selected));
                                Set<String> set = new HashSet<String>();
                                set.addAll(selected);
                                SharedPreferences pref = getContext().getSharedPreferences("MirSP", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = pref.edit();
                                editor.putStringSet("FAV", set);
                                editor.commit();
                            }
         }
                    });
     @Override
            public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
                v1 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerview_item, viewGroup, false);
                return new RecyclerViewHolder(v1);
            }

            @Override
            public void onBindViewHolder(final RecyclerViewHolder viewHolder, int i) {
    SharedPreferences pref = getContext().getSharedPreferences("MirSP", Context.MODE_PRIVATE);
                set = pref.getStringSet("FAV", null);
                if (set != null) {
                    selected = new ArrayList<String>(set);
                } else {
                    selected = new ArrayList<String>();
                }
                Log.e("HF update UI", String.valueOf(selected));
    if (String.valueOf(selected).contains(String.valueOf(PROJECT_ID.get(i)))) {
                        viewHolder.mCheck.setBackgroundResource(R.drawable.ic_favorite_white_24dp);
                    } else {
                        viewHolder.mCheck.setBackgroundResource(R.drawable.ic_favorite_white1_24dp);
                    }
                }
     @Override
            public int getItemCount() {
                //Code for Total length of json
                return Length;
            }
</code>```

答: In view pager adjacent tabs are loaded simultaneously. So your actions in tab 1 will not be reflected in tab 2 since its already loaded. You should be using Broadcast receivers to solve this issue. Broadcast a event in tab 1 and receive the event in tab 2</p>

Body:
I have a mainactivity which includes a TabLayout with ViewPager

I have added 3 tabs and each tab has separate fragments which contains a recyclerview, and these recyclerviews has a checkbox that should be simultaneously updated/refreshed whenever i swipe the viewpager(i save checked positions in shared preference and updates via shared preference).

My problem here is whenever i check a checkbox in tab1, tab2 is not updating/refreshing until i scroll down the Recyclerview. and tab3 is working fine.
and i am getting a weird warning in logcat too.

 03-05 09:35:53.345 4317-4327/com.example.rubin W/art: Suspending all threads took: 6.805ms
    03-05 09:35:58.310 4317-4317/com.example.rubin W/FragmentManager: moveToState: Fragment state for Tab3{10a5f1f0 #2 id=0x7f0d00b6} not updated inline; expected state 3 found 2
    03-05 09:36:01.363 4317-4317/com.example.rubin W/FragmentManager: moveToState: Fragment state for Tab1{2d9aa887 #1 id=0x7f0d00b6} not updated inline; expected state 3 found 2

My PagerAdapter

public class PagerAdapter1 extends FragmentStatePagerAdapter {
    int mNumOfTabs;
    public PagerAdapter1(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
               return new Tab1();
            case 1:
               return new Tab2();
            case 2:
               return new Tab3();

            default:
                return null;

        }
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

Tablayout OnPageChangelistener

final PagerAdapter1 adapter = new PagerAdapter1
                (getSupportFragmentManager(), tabLayout1.getTabCount(), getApplicationContext());
        viewPager1.setAdapter(adapter);
        viewPager1.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout1));
        tabLayout1.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager1.setCurrentItem(tab.getPosition());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

code for each fragments.

 public class Tab1 extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.home_tab1_recycler, container, false);
            RecyclerView rv = (RecyclerView) v.findViewById(R.id.home_recyclerview);
            LinearLayoutManager llm = new LinearLayoutManager(getContext());
            rv.setLayoutManager(llm);
            rv.setHasFixedSize(true); // to improve performance
            rv.setAdapter(new HomeManager()); // the projectdatabase manager is assigner to the RV
            return v;
        }

        public class HomeManager extends RecyclerView.Adapter<HomeManager.RecyclerViewHolder> {
    int Length,h;
 View v1;
        ArrayList<String> PROJECT_ID = new ArrayList<String>();
Set<String> set;
        List<String> selected;
     public class RecyclerViewHolder extends RecyclerView.ViewHolder {
     CheckBox mCheck;
      RecyclerViewHolder(final View itemView) {
                    super(itemView);
      mCheck = (CheckBox) itemView.findViewById(R.id.PROJECT_fav);
     SharedPreferences pref = getContext().getSharedPreferences("MirSP", Context.MODE_PRIVATE);
                    set = pref.getStringSet("FAV", null);
      if (set != null) {
                        selected = new ArrayList<String>(set);
                    } else {
                        selected = new ArrayList<String>();
                    }
    mCheck.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
     h = getAdapterPosition();
    check = PROJECT_ID.get(h); // for saving the project id from json.
     if (selected.contains(check)) {
                                    selected.remove(check);
                                    mCheck.setBackgroundResource(R.drawable.ic_favorite_white1_24dp);
                                    Snackbar snackbar = Snackbar.make(v, "Property Unfavorited", Snackbar.LENGTH_SHORT);
                                    snackbar.show();
                                } else {
                                    selected.add(check);
                                    mCheck.setBackgroundResource(R.drawable.ic_favorite_white_24dp);
                                    Snackbar snackbar = Snackbar.make(v, "Property Favorited", Snackbar.LENGTH_SHORT);
                                    snackbar.show();

                                }
                                Log.e("HF update checked", String.valueOf(selected));
                                Set<String> set = new HashSet<String>();
                                set.addAll(selected);
                                SharedPreferences pref = getContext().getSharedPreferences("MirSP", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = pref.edit();
                                editor.putStringSet("FAV", set);
                                editor.commit();
                            }
         }
                    });
     @Override
            public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
                v1 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerview_item, viewGroup, false);
                return new RecyclerViewHolder(v1);
            }

            @Override
            public void onBindViewHolder(final RecyclerViewHolder viewHolder, int i) {
    SharedPreferences pref = getContext().getSharedPreferences("MirSP", Context.MODE_PRIVATE);
                set = pref.getStringSet("FAV", null);
                if (set != null) {
                    selected = new ArrayList<String>(set);
                } else {
                    selected = new ArrayList<String>();
                }
                Log.e("HF update UI", String.valueOf(selected));
    if (String.valueOf(selected).contains(String.valueOf(PROJECT_ID.get(i)))) {
                        viewHolder.mCheck.setBackgroundResource(R.drawable.ic_favorite_white_24dp);
                    } else {
                        viewHolder.mCheck.setBackgroundResource(R.drawable.ic_favorite_white1_24dp);
                    }
                }
     @Override
            public int getItemCount() {
                //Code for Total length of json
                return Length;
            }


问:
Split dataset to training, cross-validation and test dataset in R. ifelse returns unexpected result
I want to write a function that will split a dataframe to train, cross-validation and test sets.

My code is the following, exemplified by a small dataset:

```<code>    library(ISLR)
    library(data.table)
    data <- Auto

    seed <- 12
    train <- 0.7
    test <- 0.6

    # Function_split_test_train_regression <- function(data, train, test, seed){

      set.seed(seed)
      setDT(data)
      data[, index := row.names(data)]
      train_index <- sample(data$index, train * nrow(data))
      test_index <- ifelse(test == 1, setdiff(data$index, train_index),
                                      sample(setdiff(data$index, train_index),  test * length(setdiff(data$index, train_index))))
    # etc
    #}
</code>```

At this point I make some checks and I get a surprising to me result:

```<code>       > test == 1
        [1] FALSE
        > sample(setdiff(data$index, train_index),
                 test * length(setdiff(data$index, train_index)))
         [1] "225" "186" "41"  "381" "356" "178" "147" "158" "21"  "259" "207" "159" "250" "167" "128" "218" "271" "197" "376" "19"  "77"
        [22] "205" "46"  "3"   "212" "238" "61"  "11"  "68"  "130" "200" "274" "127" "305" "201" "32"  "48"  "184" "290" "349" "155" "370"
        [43] "366" "333" "243" "161" "108" "65"  "125" "306" "357" "189" "337" "118" "364" "6"   "149" "87"  "252" "194" "362" "383" "93"
        [64] "38"  "18"  "322" "220" "307" "60"  "353"
        > test_index <- ifelse(test == 1, setdiff(data$index, train_index),
    sample(setdiff(data$index, train_index),
          test * length(setdiff(data$index, train_index))))
        > test_index
        [1] "219"
</code>```

Why iflese returns 219 rather than the value of the second argument (since the condition test == 1 evaluates to FALSE) ?

Your advice will be appreciated.

================================================================================

EDIT

Following the suggestion made in the comments I changed the code replacing the name test with the name test_fraction but the problem remained.  The new code:

```<code>library(ISLR)
library(data.table)
data <- Auto

seed <- 12
train_fraction <- 0.7
test_fraction <- 0.6

# Function_split_test_crossval_train_regr <- function(data, train, test, seed){

  set.seed(seed)
  setDT(data)
  data[, index := row.names(data)]
  train_index <- sample(data$index, train_fraction * nrow(data))
  test_index <- ifelse(test_fraction == 1, setdiff(data$index, train_index), sample(setdiff(data$index, train_index),
                                                     test_fraction * length(setdiff(data$index, train_index))))
#}
</code>```

The results:

```<code>> train_index
  [1] "119" "118" "143" "344" "293" "341" "305" "95"  "82"  "58"  "226" "35"  "363" "111" "84"  "137" "24"  "151" "381" "110" "93"
 [22] "198" "133" "6"   "112" "228" "62"  "36"  "165" "353" "271" "385" "322" "291" "316" "268" "333" "37"  "377" "176" "343" "281"
 [43] "245" "75"  "238" "183" "215" "68"  "274" "64"  "224" "391" "26"  "83"  "66"  "308" "1"   "372" "161" "170" "300" "52"  "30"
 [64] "15"  "57"  "148" "312" "311" "194" "367" "27"  "342" "260" "181" "163" "171" "193" "210" "327" "248" "172" "263" "47"  "351"
 [85] "166" "292" "278" "61"  "116" "204" "309" "200" "96"  "330" "383" "346" "249" "368" "41"  "38"  "235" "4"   "77"  "273" "191"
[106] "212" "99"  "31"  "286" "79"  "184" "284" "267" "374" "355" "358" "124" "114" "335" "70"  "203" "379" "14"  "287" "67"  "34"
[127] "340" "127" "91"  "222" "240" "387" "357" "242" "310" "347" "142" "103" "105" "117" "189" "361" "177" "126" "392" "5"   "317"
[148] "174" "352" "87"  "234" "147" "202" "261" "277" "214" "290" "339" "109" "43"  "120" "169" "318" "56"  "94"  "115" "314" "320"
[169] "276" "237" "296" "307" "23"  "186" "360" "146" "313" "152" "206" "328" "60"  "195" "69"  "107" "97"  "92"  "325" "20"  "362"
[190] "157" "101" "10"  "192" "134" "251" "259" "2"   "29"  "265" "331" "144" "63"  "384" "81"  "338" "364" "213" "380" "150" "48"
[211] "54"  "354" "187" "283" "356" "389" "72"  "32"  "121" "376" "33"  "359" "349" "239" "241" "232" "196" "74"  "156" "201" "390"
[232] "326" "285" "51"  "131" "304" "85"  "45"  "336" "280" "178" "128" "98"  "275" "246" "65"  "39"  "188" "55"  "90"  "197" "9"
[253] "173" "40"  "295" "149" "230" "140" "135" "236" "21"  "369" "301" "220" "122" "253" "208" "388" "159" "282" "88"  "158" "167"
[274] "257"
> sample(setdiff(data$index, train_index),
+                                                      test_fraction * length(setdiff(data$index, train_index)))
 [1] "337" "378" "164" "225" "16"  "44"  "221" "179" "25"  "28"  "324" "175" "139" "154" "17"  "252" "211" "155" "233" "162" "130"
[22] "216" "255" "190" "365" "373" "73"  "207" "42"  "3"   "348" "227" "49"  "12"  "53"  "315" "199" "256" "129" "375" "205" "18"
[43] "289" "168" "264" "160" "145" "382" "136" "302" "185" "323" "100" "270" "113" "294" "247" "345" "209" "104" "321" "7"   "138"
[64] "78"  "386" "366" "298" "231" "86"  "19"
> test_fraction == 1
[1] FALSE
> test_index <- ifelse(test_fraction == 1, setdiff(data$index, train_index), sample(setdiff(data$index, train_index),
+                                                      test_fraction * length(setdiff(data$index, train_index))))
> test_index
[1] "28"
</code>```

答:
I have no idea why this is happening, I hope someone come with an explanation.

But I found a solution to your problem. You need to pass the arguments to the object inside the ifelse():

```<code>ifelse(

    test_fraction == 1,

    test_index <- setdiff(data$index, train_index),

    test_index <- sample(setdiff(data$index, train_index),test_fraction * length(setdiff(data$index, train_index)))

  )
</code>```

I don't if this is bad practice or not, but it works. It also can be used to assign multiple conditions in the conditions like my answer here.

Body:
I want to write a function that will split a dataframe to train, cross-validation and test sets.

My code is the following, exemplified by a small dataset:

    library(ISLR)
    library(data.table)
    data <- Auto

    seed <- 12
    train <- 0.7
    test <- 0.6

    # Function_split_test_train_regression <- function(data, train, test, seed){

      set.seed(seed)
      setDT(data)
      data[, index := row.names(data)]
      train_index <- sample(data$index, train * nrow(data))
      test_index <- ifelse(test == 1, setdiff(data$index, train_index),
                                      sample(setdiff(data$index, train_index),  test * length(setdiff(data$index, train_index))))
    # etc
    #}

At this point I make some checks and I get a surprising to me result:

       > test == 1
        [1] FALSE
        > sample(setdiff(data$index, train_index),
                 test * length(setdiff(data$index, train_index)))
         [1] "225" "186" "41"  "381" "356" "178" "147" "158" "21"  "259" "207" "159" "250" "167" "128" "218" "271" "197" "376" "19"  "77"
        [22] "205" "46"  "3"   "212" "238" "61"  "11"  "68"  "130" "200" "274" "127" "305" "201" "32"  "48"  "184" "290" "349" "155" "370"
        [43] "366" "333" "243" "161" "108" "65"  "125" "306" "357" "189" "337" "118" "364" "6"   "149" "87"  "252" "194" "362" "383" "93"
        [64] "38"  "18"  "322" "220" "307" "60"  "353"
        > test_index <- ifelse(test == 1, setdiff(data$index, train_index),
    sample(setdiff(data$index, train_index),
          test * length(setdiff(data$index, train_index))))
        > test_index
        [1] "219"

Why iflese returns 219 rather than the value of the second argument (since the condition test == 1 evaluates to FALSE) ?

Your advice will be appreciated.

================================================================================

EDIT

Following the suggestion made in the comments I changed the code replacing the name test with the name test_fraction but the problem remained.  The new code:

library(ISLR)
library(data.table)
data <- Auto

seed <- 12
train_fraction <- 0.7
test_fraction <- 0.6

# Function_split_test_crossval_train_regr <- function(data, train, test, seed){

  set.seed(seed)
  setDT(data)
  data[, index := row.names(data)]
  train_index <- sample(data$index, train_fraction * nrow(data))
  test_index <- ifelse(test_fraction == 1, setdiff(data$index, train_index), sample(setdiff(data$index, train_index),
                                                     test_fraction * length(setdiff(data$index, train_index))))
#}

The results:

> train_index
  [1] "119" "118" "143" "344" "293" "341" "305" "95"  "82"  "58"  "226" "35"  "363" "111" "84"  "137" "24"  "151" "381" "110" "93"
 [22] "198" "133" "6"   "112" "228" "62"  "36"  "165" "353" "271" "385" "322" "291" "316" "268" "333" "37"  "377" "176" "343" "281"
 [43] "245" "75"  "238" "183" "215" "68"  "274" "64"  "224" "391" "26"  "83"  "66"  "308" "1"   "372" "161" "170" "300" "52"  "30"
 [64] "15"  "57"  "148" "312" "311" "194" "367" "27"  "342" "260" "181" "163" "171" "193" "210" "327" "248" "172" "263" "47"  "351"
 [85] "166" "292" "278" "61"  "116" "204" "309" "200" "96"  "330" "383" "346" "249" "368" "41"  "38"  "235" "4"   "77"  "273" "191"
[106] "212" "99"  "31"  "286" "79"  "184" "284" "267" "374" "355" "358" "124" "114" "335" "70"  "203" "379" "14"  "287" "67"  "34"
[127] "340" "127" "91"  "222" "240" "387" "357" "242" "310" "347" "142" "103" "105" "117" "189" "361" "177" "126" "392" "5"   "317"
[148] "174" "352" "87"  "234" "147" "202" "261" "277" "214" "290" "339" "109" "43"  "120" "169" "318" "56"  "94"  "115" "314" "320"
[169] "276" "237" "296" "307" "23"  "186" "360" "146" "313" "152" "206" "328" "60"  "195" "69"  "107" "97"  "92"  "325" "20"  "362"
[190] "157" "101" "10"  "192" "134" "251" "259" "2"   "29"  "265" "331" "144" "63"  "384" "81"  "338" "364" "213" "380" "150" "48"
[211] "54"  "354" "187" "283" "356" "389" "72"  "32"  "121" "376" "33"  "359" "349" "239" "241" "232" "196" "74"  "156" "201" "390"
[232] "326" "285" "51"  "131" "304" "85"  "45"  "336" "280" "178" "128" "98"  "275" "246" "65"  "39"  "188" "55"  "90"  "197" "9"
[253] "173" "40"  "295" "149" "230" "140" "135" "236" "21"  "369" "301" "220" "122" "253" "208" "388" "159" "282" "88"  "158" "167"
[274] "257"
> sample(setdiff(data$index, train_index),
+                                                      test_fraction * length(setdiff(data$index, train_index)))
 [1] "337" "378" "164" "225" "16"  "44"  "221" "179" "25"  "28"  "324" "175" "139" "154" "17"  "252" "211" "155" "233" "162" "130"
[22] "216" "255" "190" "365" "373" "73"  "207" "42"  "3"   "348" "227" "49"  "12"  "53"  "315" "199" "256" "129" "375" "205" "18"
[43] "289" "168" "264" "160" "145" "382" "136" "302" "185" "323" "100" "270" "113" "294" "247" "345" "209" "104" "321" "7"   "138"
[64] "78"  "386" "366" "298" "231" "86"  "19"
> test_fraction == 1
[1] FALSE
> test_index <- ifelse(test_fraction == 1, setdiff(data$index, train_index), sample(setdiff(data$index, train_index),
+                                                      test_fraction * length(setdiff(data$index, train_index))))
> test_index
[1] "28"

Body:
I have no idea why this is happening, I hope someone come with an explanation.

But I found a solution to your problem. You need to pass the arguments to the object inside the ifelse():

ifelse(

    test_fraction == 1,

    test_index <- setdiff(data$index, train_index),

    test_index <- sample(setdiff(data$index, train_index),test_fraction * length(setdiff(data$index, train_index)))

  )

I don't if this is bad practice or not, but it works. It also can be used to assign multiple conditions in the conditions like my answer here.


问:
Create multiindex from existing dataframe
I've spent hours browsing everywhere now to try to create a multiindex from dataframe in pandas. This is the dataframe I have (posting excel sheet mockup. I do have this in pandas dataframe):

And this is what I want:

I have tried

```<code>newmulti = currentDataFrame.set_index(['user_id','account_num'])
</code>```

But it returns a dataframe, not a multiindex. Also, I could not figure out how to make 'user_id' level 0 and 'account_num' level 1. I think this must be trivial but I've read so many posts, tutorials, etc. and still could not figure it out. Partly because I'm a very visual person and most posts are not. Please help!

答:
Use pd.MultiIndex.from_arrays

```<code>lvl0 = currentDataFrame.user_id.values
lvl1 = currentDataFrame.account_num.values

midx = pd.MultiIndex.from_arrays([lvl0, lvl1], names=['level 0', 'level 1'])
</code>```

Body:
I've spent hours browsing everywhere now to try to create a multiindex from dataframe in pandas. This is the dataframe I have (posting excel sheet mockup. I do have this in pandas dataframe):

And this is what I want:

I have tried

newmulti = currentDataFrame.set_index(['user_id','account_num'])

But it returns a dataframe, not a multiindex. Also, I could not figure out how to make 'user_id' level 0 and 'account_num' level 1. I think this must be trivial but I've read so many posts, tutorials, etc. and still could not figure it out. Partly because I'm a very visual person and most posts are not. Please help!

Body:
Use pd.MultiIndex.from_arrays

lvl0 = currentDataFrame.user_id.values
lvl1 = currentDataFrame.account_num.values

midx = pd.MultiIndex.from_arrays([lvl0, lvl1], names=['level 0', 'level 1'])


问:
Django--- Allowing Users to only edit their profile
I want to allow User to only edit their profile. This is my URL:

```<code>url(r'^profile/(?P<pk>[0-9]+)/$', views.UserUpdate.as_view(), name='profile')
</code>```

Now when the user click on 'my  profile' they will get their own profile which they can edit but if they manually edit the urlpath in browser and enter other user's id like below, they can view and edit other User's profile

```<code>http://127.0.0.1:8000/profile/1/
</code>```

this is my view

```<code>class UserUpdate(UpdateView):
model = Profile
fields = ['personal_info','job_title','department', 'location','expertise', 'user_photo','phone_number','contact_facebook','contact_linkedin','contact_skype']
template_name = 'user_form.html'
success_url = reverse_lazy('index')
</code>```

Now in user_form.html I have checked if the user is authenticated so that only logged in user can view the profile page but still logged in User can view other user's profile.

```<code>{% if user.is_authenticated %}
                    <h3> {{ user.first_name }}'s Profile</h3>
                    <form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                    {% include 'form-template.html' %}
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type = "submit" class="btn btn-success">Submit</button>
                            <a href={%  url 'index' %}><input type="button" class = " col-sm-offset-2 btn btn-warning " name="cancel" value="Cancel" /></a>
                        </div>
                    </div>
                    </form>
</code>```

This is my model:

```<code>class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
personal_info = models.TextField(blank=True)
job_title = models.CharField(max_length=100, blank=True)
department = models.CharField(max_length=100, blank=True)
location = models.CharField(max_length=100, blank=True)
expertise = models.TextField(blank=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{5,15}$', message="Phone number must be entered in the format: '+123456'. Between 5 and 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=16, blank=True)
contact_skype = models.URLField(null=True, blank=True)
contact_facebook = models.URLField(null=True, blank=True)
contact_linkedin = models.URLField(null=True, blank=True)
user_photo = models.ImageField(upload_to='../media/img', blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()
</code>```

How can I restrict logged in user to only edit their profile? I know there are lot of similar questions and possible duplicate in stack overflow but none seemed to help my case.

Thanks in advance

答:
You can just remove the pk from your url like so

```<code>url(r'^profile/$', views.UserUpdate.as_view(), name='profile')
</code>```

And then only fetch the user's profile

```<code>class UserUpdate(UpdateView):
    model = Profile
    fields = ['personal_info','job_title','department', 'location','expertise', 'user_photo','phone_number','contact_facebook','contact_linkedin','contact_skype']
    template_name = 'user_form.html'
    success_url = reverse_lazy('index')

    def get_object(self):
        return self.request.user.profile
</code>```

That way you ensure, that the profile view is only ever loaded with the user's own profile.

On an additional note, you then might want to restrict the view to only allow logged in users.

Body:
I want to allow User to only edit their profile. This is my URL:

url(r'^profile/(?P<pk>[0-9]+)/$', views.UserUpdate.as_view(), name='profile')

Now when the user click on 'my  profile' they will get their own profile which they can edit but if they manually edit the urlpath in browser and enter other user's id like below, they can view and edit other User's profile

http://127.0.0.1:8000/profile/1/

this is my view

class UserUpdate(UpdateView):
model = Profile
fields = ['personal_info','job_title','department', 'location','expertise', 'user_photo','phone_number','contact_facebook','contact_linkedin','contact_skype']
template_name = 'user_form.html'
success_url = reverse_lazy('index')

Now in user_form.html I have checked if the user is authenticated so that only logged in user can view the profile page but still logged in User can view other user's profile.

{% if user.is_authenticated %}

 {{ user.first_name }}'s Profile

                    <form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                    {% include 'form-template.html' %}

                            <button type = "submit" class="btn btn-success">Submit</button>
                            <input type="button" class = " col-sm-offset-2 btn btn-warning " name="cancel" value="Cancel" />

                    </form>

This is my model:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
personal_info = models.TextField(blank=True)
job_title = models.CharField(max_length=100, blank=True)
department = models.CharField(max_length=100, blank=True)
location = models.CharField(max_length=100, blank=True)
expertise = models.TextField(blank=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{5,15}$', message="Phone number must be entered in the format: '+123456'. Between 5 and 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=16, blank=True)
contact_skype = models.URLField(null=True, blank=True)
contact_facebook = models.URLField(null=True, blank=True)
contact_linkedin = models.URLField(null=True, blank=True)
user_photo = models.ImageField(upload_to='../media/img', blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

How can I restrict logged in user to only edit their profile? I know there are lot of similar questions and possible duplicate in stack overflow but none seemed to help my case.

Thanks in advance

Body:
You can just remove the pk from your url like so

url(r'^profile/$', views.UserUpdate.as_view(), name='profile')

And then only fetch the user's profile

class UserUpdate(UpdateView):
    model = Profile
    fields = ['personal_info','job_title','department', 'location','expertise', 'user_photo','phone_number','contact_facebook','contact_linkedin','contact_skype']
    template_name = 'user_form.html'
    success_url = reverse_lazy('index')

    def get_object(self):
        return self.request.user.profile

That way you ensure, that the profile view is only ever loaded with the user's own profile.

On an additional note, you then might want to restrict the view to only allow logged in users.


问:
jQuery load body from external HTML
I'm using jQuery and trying to load the body from an external HTML file.

It works if I try to load some div:

$('body').load('example.html #content');

But I'm unable to do something like this:

$('body').load('example.html body');

答:
When you use load without a selector, it strips the , , and  tags, but leaves all of the children of  and  intact, including title, script, and style tags. However, when you use a selector, it is applied after the body tag is stripped, so it's impossible to match against it.

Instead, wrap all of your body content inside another tag, and select that tag instead:

```<code><html><head><title>Hello!</title</head>
<body>
  <div id="jquery-load-point">
    ... <!-- rest of body content -->
  </div>
</body>
</html>
</code>```

Now, you can load it like this:

```<code>$("#destination").load("http://my.url/to/page #jquery-load-point");
</code>```

ContentLicense: CC BY-SA 4.0

Title: jQuery load body from external HTML

Body:
When you use load without a selector, it strips the <html>, <head>, and <body> tags, but leaves all of the children of <head> and <body> intact, including title, script, and style tags. However, when you use a selector, it is applied after the body tag is stripped, so it's impossible to match against it.

Instead, wrap all of your body content inside another tag, and select that tag instead:

<html><head><title>Hello!</title</head>
<body>
  <div id="jquery-load-point">
    ... <!-- rest of body content -->
  </div>
</body>
</html>

Now, you can load it like this:

$("#destination").load("http://my.url/to/page #jquery-load-point");


问:
How to read particular range to last line of file using PowerShell?
How to read particular range of line ie if my file have 100 lines and I want to read the lines from 80 to last line of file using PowerShell?here I'm not sure about how many lines are available in the file.</p>

答:
Or just get the last 20 lines:

```<code>Get-Content -Path 'C:\temp\test.txt' -Tail 20
</code>```

If you want to find out how many lines the file has so that you can use that to decide what to read, this could help:

```<code>$lines = Get-Content -Path 'C:\temp\test.txt'
$lines.count
</code>```

So if you decide you want to get for example the last half of the lines you could do something like this:

```<code>$lines = Get-Content -Path 'C:\temp\test.txt'
$half = [math]::Round($lines.count/2)
Select-Object -InputObject $lines -Last $half
</code>```

Body:
Or just get the last 20 lines:

Get-Content -Path 'C:\temp\test.txt' -Tail 20

If you want to find out how many lines the file has so that you can use that to decide what to read, this could help:

$lines = Get-Content -Path 'C:\temp\test.txt'
$lines.count

So if you decide you want to get for example the last half of the lines you could do something like this:

$lines = Get-Content -Path 'C:\temp\test.txt'
$half = [math]::Round($lines.count/2)
Select-Object -InputObject $lines -Last $half


问:
New iPhone App - How to Choose which Xcode Template to Use?
In general I'd like to understand which templates to use when, when I'm making new iPhone apps.  Could anyone offer some guidelines, tips, rules-of-thumb?

Also, how much should I agonize over this?  If I start off with the wrong one, can I add the missing pieces manually, is it hard?

For reference here are the choices I'm seeing:

Navigation-Based Application

OpenGL ES Application

Tab Bar Application

Utility Application

View-Based Application

Window-Based Application

答:
Also note - there aren't that many templates.
Create a new project for each one, Build and Run immediately, and you'll get an idea what you need.</p>

OwnerDisplayName: Greg

OwnerDisplayName: Rhubarb


问:
meteor runs production mode by default on local machine
As noted on meteor forum, my projects seem to run in production mode by default on my local machine without me explicitly telling it to, I tried reinstalling meteor that didn't work, it is set to production mode on every project I create, can someone assist reverting this. I need meteor to be in development mode on my local machine.

Thanks.

答: I am not sure what the problem was here but I managed to solve the problem by just restarting my PC then ran my meteor projects, voila meteor is back to development mode.</p>


问:
Find out specific Exception
Apologies for the lack of information...

Is there a way to find out what is the specific Exception that is causing a call to throw the Exception?

Currently, I am catching all the Exceptions by doing catch(Exception e) but I know this is not good practices at all.

Is there a way to know from the Exception what is the specific one that caused the issue so I can be more granular?

答:
Option 1 - Documentation

Read the documentation of the method you are calling, if it is a Framework Class type (like SqlConnection.Open) the thrown exceptions are well documented.

Option 2 - Discover them at Run Time

If its a 3rd party library and documentation is limited then check the Exception at runtime using exception.GetType() and then add known exceptions you want to handle as catch blocks.

Personally I prefer to not add catch blocks at all where I am not sure if an Exception will materialize or not. If/When it does the debugger will break (if it is set to break) or you have a global catch all that logs and rethrows. Then you get the type and update your code accordingly. Where you add such a global Exception logger depends on the type of application you are developing. If you go the route of a global logger do take note that you 1) rethrow the Exception so the app breaks at runtime and not swallow it and 2) rethrow using throw; syntax (not throw ex;).

Title: Find out specific Exception


问:
Automating update_post_meta
So i have been working on this legacy code and I'm trying to improve it a bit. I have this piece of code, which saves a bunch of custom fields from a post.

```<code>if(isset($_REQUEST['unidade-dir1-cargo'])){
    update_post_meta($post_id, 'unidade-dir1-cargo', sanitize_text_field($_POST['unidade-dir1-cargo']));
    update_post_meta($post_id, 'unidade-dir1-nome', sanitize_text_field($_POST['unidade-dir1-nome']));
    update_post_meta($post_id, 'unidade-dir1-email', sanitize_text_field($_POST['unidade-dir1-email']));
}
if(isset($_REQUEST['unidade-dir2-cargo'])){
    update_post_meta($post_id, 'unidade-dir2-cargo', sanitize_text_field($_POST['unidade-dir2-cargo']));
    update_post_meta($post_id, 'unidade-dir2-nome', sanitize_text_field($_POST['unidade-dir2-nome']));
    update_post_meta($post_id, 'unidade-dir2-email', sanitize_text_field($_POST['unidade-dir2-email']));
}
if(isset($_REQUEST['unidade-dir3-cargo'])){
    update_post_meta($post_id, 'unidade-dir3-cargo', sanitize_text_field($_POST['unidade-dir3-cargo']));
    update_post_meta($post_id, 'unidade-dir3-nome', sanitize_text_field($_POST['unidade-dir3-nome']));
    update_post_meta($post_id, 'unidade-dir3-email', sanitize_text_field($_POST['unidade-dir3-email']));
}
if(isset($_REQUEST['unidade-dir4-cargo'])){
    update_post_meta($post_id, 'unidade-dir4-cargo', sanitize_text_field($_POST['unidade-dir4-cargo']));
    update_post_meta($post_id, 'unidade-dir4-nome', sanitize_text_field($_POST['unidade-dir4-nome']));
    update_post_meta($post_id, 'unidade-dir4-email', sanitize_text_field($_POST['unidade-dir4-email']));
}
if(isset($_REQUEST['unidade-dir5-cargo'])){
    update_post_meta($post_id, 'unidade-dir5-cargo', sanitize_text_field($_POST['unidade-dir5-cargo']));
    update_post_meta($post_id, 'unidade-dir5-nome', sanitize_text_field($_POST['unidade-dir5-nome']));
    update_post_meta($post_id, 'unidade-dir5-email', sanitize_text_field($_POST['unidade-dir5-email']));
}
</code>```

And it works. I've tried to change it into this, but it doest't work. Does anyone have an idea why?

```<code>$no_directors = 5;
$fields = array('cargo', 'nome', 'email');
for($i=1; $i<=$no_directors; $i++){
    foreach($fields as $field){
        $label = 'unidade-dir'.$i.'-'.$field;
        if(isset($_REQUEST[$label])){
            update_post_meta($post_id, $label, sanitize_text_field($_POST[$label]));
        }
    }
}
</code>```

答:
```<code> $no_directors = 5;
$fields = array('cargo', 'nome', 'email');
for($i=1; $i<=$no_directors; $i++){
    foreach($fields as $field){
        $label = "unidade-dir$i-$field";
        if(isset($_REQUEST[$label])){
            update_post_meta($post_id, $label, sanitize_text_field($_POST[$label]));
        }
    }
}
</code>```

Title: Automating update_post_meta

Body:
So i have been working on this legacy code and I'm trying to improve it a bit. I have this piece of code, which saves a bunch of custom fields from a post.

if(isset($_REQUEST['unidade-dir1-cargo'])){
    update_post_meta($post_id, 'unidade-dir1-cargo', sanitize_text_field($_POST['unidade-dir1-cargo']));
    update_post_meta($post_id, 'unidade-dir1-nome', sanitize_text_field($_POST['unidade-dir1-nome']));
    update_post_meta($post_id, 'unidade-dir1-email', sanitize_text_field($_POST['unidade-dir1-email']));
}
if(isset($_REQUEST['unidade-dir2-cargo'])){
    update_post_meta($post_id, 'unidade-dir2-cargo', sanitize_text_field($_POST['unidade-dir2-cargo']));
    update_post_meta($post_id, 'unidade-dir2-nome', sanitize_text_field($_POST['unidade-dir2-nome']));
    update_post_meta($post_id, 'unidade-dir2-email', sanitize_text_field($_POST['unidade-dir2-email']));
}
if(isset($_REQUEST['unidade-dir3-cargo'])){
    update_post_meta($post_id, 'unidade-dir3-cargo', sanitize_text_field($_POST['unidade-dir3-cargo']));
    update_post_meta($post_id, 'unidade-dir3-nome', sanitize_text_field($_POST['unidade-dir3-nome']));
    update_post_meta($post_id, 'unidade-dir3-email', sanitize_text_field($_POST['unidade-dir3-email']));
}
if(isset($_REQUEST['unidade-dir4-cargo'])){
    update_post_meta($post_id, 'unidade-dir4-cargo', sanitize_text_field($_POST['unidade-dir4-cargo']));
    update_post_meta($post_id, 'unidade-dir4-nome', sanitize_text_field($_POST['unidade-dir4-nome']));
    update_post_meta($post_id, 'unidade-dir4-email', sanitize_text_field($_POST['unidade-dir4-email']));
}
if(isset($_REQUEST['unidade-dir5-cargo'])){
    update_post_meta($post_id, 'unidade-dir5-cargo', sanitize_text_field($_POST['unidade-dir5-cargo']));
    update_post_meta($post_id, 'unidade-dir5-nome', sanitize_text_field($_POST['unidade-dir5-nome']));
    update_post_meta($post_id, 'unidade-dir5-email', sanitize_text_field($_POST['unidade-dir5-email']));
}

And it works. I've tried to change it into this, but it doest't work. Does anyone have an idea why?

$no_directors = 5;
$fields = array('cargo', 'nome', 'email');
for($i=1; $i<=$no_directors; $i++){
    foreach($fields as $field){
        $label = 'unidade-dir'.$i.'-'.$field;
        if(isset($_REQUEST[$label])){
            update_post_meta($post_id, $label, sanitize_text_field($_POST[$label]));
        }
    }
}


问:
Should I use Webview or Android widgets for webbased Android Application?
I'm planning a project which will uses JSON objects to display data on andorid mobile.

My application is some what similar to facebook application for android. It seems making detailed ui like facebook's like,comment will be time time consuming & webview seems to be better option in this case ?
need your suggestion.

I'm also planning same app to be developed on iPhone as well.

Refrence link

答:
Android has enough support for JSON that you can easily use the native widgets for your application. By using native widgets, the Joe Default user will have a more normal (expected) user experience, since most of the application will work just like any other Android application works.

Another thing to take into consideration that by using native widgets, it will probably be easier to add support for different UI sizes (portrait and landscape mode in various sizes can be a pain to get right in a single webview).


问:
Error when build NDK of AndEngine example
I'm trying to build AndEngine sample on my MacOS Android Studio 2.3.2.
But get this error. Cannot figure out what is the problem. Strange thing is the same project build normally on Windows, same version of Android Studio.

```<code>> FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':andEngine:externalNativeBuildRelease'.
> Build command failed.
  Error while executing process /Users/apple/Library/Android/sdk/ndk-bundle/ndk-build with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/Android.mk

  NDK_APPLICATION_MK=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/Application.mk APP_ABI=mips NDK_ALL_ABIS=mips NDK_DEBUG=0 APP_PLATFORM=android-9 NDK_OUT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/obj NDK_LIBS_OUT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/lib /Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/obj/local/mips/libandengine.so}
  Android NDK: android-9 is unsupported. Using minimum supported version android-14.
  [mips] Compile++      : andengine_shared <= BufferUtils.cpp
  /Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/src/BufferUtils.cpp:13:2: error: use of undeclared identifier 'memcpy'
          memcpy(bufferAddress, dataAddress + pOffset, pLength << 2);
          ^
</code>```

My Application.mk file:

```<code># Build both ARMv5TE and ARMv7-A and x86 machine code.
APP_ABI := armeabi armeabi-v7a x86
APP_STL := gnustl_shared
</code>```

And Android.mk:

```<code>LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE             := andengine_shared
LOCAL_MODULE_FILENAME    := libandengine
LOCAL_CFLAGS             := -Werror
LOCAL_SRC_FILES          := src/GLES20Fix.c \
                             src/BufferUtils.cpp
LOCAL_LDLIBS             := -lGLESv2
LOCAL_EXPORT_C_INCLUDES  := $(LOCAL_PATH)/src

include $(BUILD_SHARED_LIBRARY)
</code>```

答:
Android Studio overrides some settings in your Application.mk file. For example, it overrides APP_ABI. You should add

```<code>defaultConfig {
    ...
    externalNativeBuild {
        ndkBuild {
            abiFilters "armeabi", "armeabi-v7a", "x86"
        }
    }
}
</code>```

to your app/build.gradle. You should not be worried about the warning that minimum supported version is android-14, but please note that NDK r15, which is currently still in beta.

Body:
I'm trying to build AndEngine sample on my MacOS Android Studio 2.3.2.
But get this error. Cannot figure out what is the problem. Strange thing is the same project build normally on Windows, same version of Android Studio.

> FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':andEngine:externalNativeBuildRelease'.
> Build command failed.
  Error while executing process /Users/apple/Library/Android/sdk/ndk-bundle/ndk-build with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/Android.mk

  NDK_APPLICATION_MK=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/Application.mk APP_ABI=mips NDK_ALL_ABIS=mips NDK_DEBUG=0 APP_PLATFORM=android-9 NDK_OUT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/obj NDK_LIBS_OUT=/Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/lib /Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/build/intermediates/ndkBuild/release/obj/local/mips/libandengine.so}
  Android NDK: android-9 is unsupported. Using minimum supported version android-14.
  [mips] Compile++      : andengine_shared <= BufferUtils.cpp
  /Users/apple/Documents/workspace/AndroidStudio/AndEngineExamples-GLES2/andEngine/src/main/jni/src/BufferUtils.cpp:13:2: error: use of undeclared identifier 'memcpy'
          memcpy(bufferAddress, dataAddress + pOffset, pLength << 2);
          ^

My Application.mk file:

# Build both ARMv5TE and ARMv7-A and x86 machine code.
APP_ABI := armeabi armeabi-v7a x86
APP_STL := gnustl_shared

And Android.mk:

LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE             := andengine_shared
LOCAL_MODULE_FILENAME    := libandengine
LOCAL_CFLAGS             := -Werror
LOCAL_SRC_FILES          := src/GLES20Fix.c \
                             src/BufferUtils.cpp
LOCAL_LDLIBS             := -lGLESv2
LOCAL_EXPORT_C_INCLUDES  := $(LOCAL_PATH)/src

include $(BUILD_SHARED_LIBRARY)

Body:
Android Studio overrides some settings in your Application.mk file. For example, it overrides APP_ABI. You should add

defaultConfig {
    ...
    externalNativeBuild {
        ndkBuild {
            abiFilters "armeabi", "armeabi-v7a", "x86"
        }
    }
}

to your app/build.gradle. You should not be worried about the warning that minimum supported version is android-14, but please note that NDK r15, which is currently still in beta.


问:
side by side div centered using bootstrap 4
I have two div's sitting side by side, but are not centered inside of its div but rather stay on the left of its row. I am trying to make it responsive and centered as the screen size is being adjusted here is my code.

```<code>  <div class="connectdiv">
   <div class="row">
    <div class="col-xs-6 text-center" "col-sm-6" >
     <h2 id="connect"><u>Connect</u></h2>
       <a target="_blank" href="https://www.instagram.com/balt_jitsu19/"><i class="fa fa-instagram fa-lg"></i></a>
       <a href="mailto:baltznunez@gmail.com"><i class="fa fa-envelope fa-lg"></i></a>
       <a target="_blank" href="https://www.freecodecamp.com/armbar1"><i class="fa fa-free-code-camp fa-lg"></i></a>
       <a target="_blank" href="http://github.com/baltz1"><i class="fa fa-github fa-lg"></i></a>
    </div>

  <div class="col-xs-6 text-center" "col-sm-6">
   <h2 id="connect"><u>Made With</u></h2>
     <i class="fa fa-html5 fa-2x"></i>
     <i class="fa fa-css3 fa-2x"></i>
     <a href="https://icons8.com"><img src="https://png.icons8.com/icons8/ios7/32/" title="Icons8" width="32" height="32"></a>
     <img src="https://png.icons8.com/gimp/ios7/25/" title="GIMP" width="25" height="25">
   </div>
  </div>
 </div>
</code>```

My Css

```<code>#connect{
  color:rgb(255, 255, 255);
  font-family:'Oleo Script Swash Caps', cursive;
  text-shadow:5px 1px 0px rgb(0, 0, 0);
  font-size:35px;
}
.connectdiv{
  padding:20px;
  width:100%;
  margin:5px auto;
}
</code>```

if it helps i have here on codepen https://codepen.io/balt1/pen/VbYweZ?editors=0100

答:
About extra quotes already was written (class="col-xs-6 text-center" "col-sm-6")

 But one more point, Bootstrap4 hasn't col-xs-* class, instead it's col-* class for extra small screens!

You need to write

class col-sm-6 nothing changes, because Bootstrap mobile first!

Bootstrap4 docs

Body:
I have two div's sitting side by side, but are not centered inside of its div but rather stay on the left of its row. I am trying to make it responsive and centered as the screen size is being adjusted here is my code.

Connect

Made With

My Css

#connect{
  color:rgb(255, 255, 255);
  font-family:'Oleo Script Swash Caps', cursive;
  text-shadow:5px 1px 0px rgb(0, 0, 0);
  font-size:35px;
}
.connectdiv{
  padding:20px;
  width:100%;
  margin:5px auto;
}

if it helps i have here on codepen https://codepen.io/balt1/pen/VbYweZ?editors=0100

Body:
About extra quotes already was written (class="col-xs-6 text-center" "col-sm-6")

 But one more point, Bootstrap4 hasn't col-xs-* class, instead it's col-* class for extra small screens!

You need to write <div class="col-6 text-center">
class col-sm-6 nothing changes, because Bootstrap mobile first!

Bootstrap4 docs


答:
You have to use either single quotes or double quotes for the outermost quotes to for the string.  Inside the string you can use the other type of quote or escape the quote.</p>

```<code>var myStr1 = 'This string has "double quotes" in it. And "probably" lots of them';    //Works!
var myStr2 = 'This string has \'double quotes\' in it. And "probably" lots of them';    //Works!
var myStr3 = 'This string has 'double quotes' in it. And "probably" lots of them';    //Doesn't work
</code>```

Title: ambiguity between double quotes and single quotes in javascript

Body:
var myStr = 'This string has "double quotes" in it. And "probably" lots of them';

The value in using one or the other has to do with the need to escape quotes of the same type. Unless they are escaped, you cannot have more than one pair of whichever quote type begins a string.?? //what does it mean??

//Error i got:-
Remove all the backslashes ()
You should have two single quotes ' and four double quotes "
Only remove the backslashes \ used to escape quotes.

can anyone tell what should i do to make it correct?

Body:
You have to use either single quotes or double quotes for the outermost quotes to for the string.  Inside the string you can use the other type of quote or escape the quote.

var myStr1 = 'This string has "double quotes" in it. And "probably" lots of them';    //Works!
var myStr2 = 'This string has \'double quotes\' in it. And "probably" lots of them';    //Works!
var myStr3 = 'This string has 'double quotes' in it. And "probably" lots of them';    //Doesn't work


问:
Python Shell Scripting. Chain Unix OpenSSL Commands
I am trying to write a simple Python shell script that will take user input of server name and port number and route it into an OpenSSL command that shows SSL certificate expiration info.

I am using the subprocess module, however I am unclear of the proper method of chaining the command with user entered information.

The full command is:

```<code>echo | openssl s_client -servername www.google.com -connect www.google.com:443 2>/dev/null | openssl x509 -noout -dates
</code>```

Output of command (which is what I want the script to output):

```<code>notBefore=May 31 16:57:23 2017 GMT
notAfter=Aug 23 16:32:00 2017 GMT
</code>```

My code:

```<code>#!/usr/bin/env python
import subprocess

server_name = raw_input("Enter server name: ")
port_number = raw_input("Enter port number: ")

def display_cert_info(servername, portnum):
    pn = str(server_name + ":" + port_number)
    cmd = ["echo", "|", "openssl", "s_client", "-servername", str(servername), "-connect", pn, "2>/dev/null", "|", "openssl", "x509", "-noout", "-dates"]

    info = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = info.communicate()[0]
    print(output)

display_cert_info(server_name, port_number)
</code>```

Any help is appreciated!

答: Unlike in a shell, standard in, standard out, and standard error are all handled by Popen's stdin, stdout and stderr arguments. You can therefore discard the first two command elements (echo |). Then you'll want to run a separate process with the last command in the pipeline taking the output from the first command into its stdin. In general you don't use shell pipes when running in another language, but instead use the language's own piping (or streaming) mechanism.

Body:
I am trying to write a simple Python shell script that will take user input of server name and port number and route it into an OpenSSL command that shows SSL certificate expiration info.

I am using the subprocess module, however I am unclear of the proper method of chaining the command with user entered information.

The full command is:

echo | openssl s_client -servername www.google.com -connect www.google.com:443 2>/dev/null | openssl x509 -noout -dates

Output of command (which is what I want the script to output):

notBefore=May 31 16:57:23 2017 GMT
notAfter=Aug 23 16:32:00 2017 GMT

My code:

#!/usr/bin/env python
import subprocess

server_name = raw_input("Enter server name: ")
port_number = raw_input("Enter port number: ")

def display_cert_info(servername, portnum):
    pn = str(server_name + ":" + port_number)
    cmd = ["echo", "|", "openssl", "s_client", "-servername", str(servername), "-connect", pn, "2>/dev/null", "|", "openssl", "x509", "-noout", "-dates"]

    info = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = info.communicate()[0]
    print(output)

display_cert_info(server_name, port_number)

Any help is appreciated!


问:
How to Add colnames to all dataframe in a list
Suppose I have a list of dataframes, like this

data = list(data.frame(arb = rep(paste(sample(LETTERS, 5), collapse = ""), 5), value = round(rnorm(5, 270, 50), 1)),  data.frame(arb = rep(paste(sample(LETTERS, 5), collapse = ""), 7), value = round(rnorm(7, 190, 70), 1)) )

```<code>> data
[[1]]
    arb value
1 LIPXQ 244.5
2 LIPXQ 191.1
3 LIPXQ 237.2
4 LIPXQ 349.7
5 LIPXQ 175.3

[[2]]
    arb value
1 JVLWF 188.8
2 JVLWF 194.8
3 JVLWF 234.2
4 JVLWF 196.5
5 JVLWF 202.9
6 JVLWF 211.2
7 JVLWF 203.9
</code>```

How do I change the column names to "Treatment" and "Doses" with lapply?
Alternatively, how do I change the name of "arb" column with a list of column names for example colname = c("1nm", "2nm")

答:
We can use setNames

```<code>data <- lapply(data, setNames, c("Treatment", "Doses"))
</code>```

For the second case

```<code>data <- Map(function(x,y,z) setNames(x, c(y,z)), data, c("1nm", "2nm"), "Doses")
</code>```

Body:
Suppose I have a list of dataframes, like this

data = list(data.frame(arb = rep(paste(sample(LETTERS, 5), collapse = ""), 5), value = round(rnorm(5, 270, 50), 1)),  data.frame(arb = rep(paste(sample(LETTERS, 5), collapse = ""), 7), value = round(rnorm(7, 190, 70), 1)) )

> data
[[1]]
    arb value
1 LIPXQ 244.5
2 LIPXQ 191.1
3 LIPXQ 237.2
4 LIPXQ 349.7
5 LIPXQ 175.3

[[2]]
    arb value
1 JVLWF 188.8
2 JVLWF 194.8
3 JVLWF 234.2
4 JVLWF 196.5
5 JVLWF 202.9
6 JVLWF 211.2
7 JVLWF 203.9

How do I change the column names to "Treatment" and "Doses" with lapply?
Alternatively, how do I change the name of "arb" column with a list of column names for example colname = c("1nm", "2nm")

Body:
We can use setNames

data <- lapply(data, setNames, c("Treatment", "Doses"))

For the second case

data <- Map(function(x,y,z) setNames(x, c(y,z)), data, c("1nm", "2nm"), "Doses")


问:
Python/Scrapy scraping from Techcrunch
I am trying to build a spider to scrape some Data from the website Techcrunch - Heartbleed search

my tought was to give a tag when executing the spider from the command line (example: Heartbleed). The spider should then search trough all the associated search results, open each link and get the data contained within.

```<code>import scrapy

class TechcrunchSpider(scrapy.Spider):
    name = "tech_search"

    def start_requests(self):
        url = 'https://techcrunch.com/'
        tag = getattr(self, 'tag', None)
        if tag is not None:
            url = url + '?s=' + tag
        yield scrapy.Request(url, self.parse)

    def parse(self, response):
        pass
</code>```

this code can be executed with : scrapy crawl tech_search -s DOWNLOAD_DELAY=1.5 -o tech_search.jl -a tag=EXAMPLEINPUT"

Getting the data from the individual pages is not the problem, but actually getting the url to them is(from the search page linked above):

the thing is , when looking at the source Html file (Ctrl + u) of the Search site(link above), then i cant find anything about the searched elements(example : "What Is Heartbleed? The Video"). Any suggestions how to obtain these elements?

答: I suggest that you define your scrapy class along the lines shown in this answer but using the PhantomJS selenium headless browser. The essential problem is that when scrapy downloads those pages it uses javascript code to build the HTML (DOM) that you see but cannot access via the route you have chosen.

Title: Python/Scrapy scraping from Techcrunch

Body:
I am trying to build a spider to scrape some Data from the website Techcrunch - Heartbleed search

my tought was to give a tag when executing the spider from the command line (example: Heartbleed). The spider should then search trough all the associated search results, open each link and get the data contained within.

import scrapy

class TechcrunchSpider(scrapy.Spider):
    name = "tech_search"

    def start_requests(self):
        url = 'https://techcrunch.com/'
        tag = getattr(self, 'tag', None)
        if tag is not None:
            url = url + '?s=' + tag
        yield scrapy.Request(url, self.parse)

    def parse(self, response):
        pass

this code can be executed with : scrapy crawl tech_search -s DOWNLOAD_DELAY=1.5 -o tech_search.jl -a tag=EXAMPLEINPUT"

Getting the data from the individual pages is not the problem, but actually getting the url to them is(from the search page linked above):

the thing is , when looking at the source Html file (Ctrl + u) of the Search site(link above), then i cant find anything about the searched elements(example : "What Is Heartbleed? The Video"). Any suggestions how to obtain these elements?


问:
Visual analytic with graphs, maps etc from my user data?
I have lot of data stored about my users and now I can build user analytics from this data to provide meaningful data back to my users. I can output this as normal text which is ok but I want to display bargraphs, charts, world maps, etc...

So the question is how do i take all the data from my tables and add in all these graphs /maps? Do i need some software packages or do i need to "code" the graphs/maps? If software packages then are there any open source I can use?

The data saved includes user logs like visits, browsers etc along with lot of business activity details so i want to show my users like top 10 clients, top countries they came from, top products, top customers etc.

My platform is: MySQL and codeignitor PHP.
I do not have a data wearhouse built but that can be done once i have a plan for how I can output all this data visually so it looks good.

答: Are you trying to write code that generates dynamically updated analyses?   or are you just trying to conduct the analysis over a set time period and 'post' it so that your users can view the results of the analysis? For the latter, you need is a statistical package (like R or even Excel if you want it quick and dirty).  For the former, you are going to need an API (like Google Chart).</p>


问:
What is an "active" uniform block in OpenGL
The OpenGL documentation is not very clear about what is an active uniform block (versus those are not active). So my understanding is it is about them being referenced/used in a shader program... or is it!

Consider the following shader program:

Vertex Shader

```<code>#version 300 es
precision highp float;

layout(std140) uniform globals
{
    mat4 world_view_proj;
};

layout(std140) uniform foo
{
    vec3 bar;
};

layout(std140) uniform dog
{
    vec3 cat;
};

layout(location = 0) in vec4 position0;
layout(location = 4) in lowp vec4 color0;
out lowp vec4 v_color;

void main ( )
{
    v_color = color0;
    gl_Position = position0 * world_view_proj;
}
</code>```

Fragment Shader

```<code>#version 300 es
precision highp float;

in lowp vec4 v_color;
layout(location = 0) out lowp vec4 frag_color;

void main()
{
    frag_color = v_color;
}
</code>```

Even though I don't use foo or dog uniform blocks, a query to get the number of active uniform blocks...

```<code>GLint count = 0;
glGetProgramiv(program, GL_ACTIVE_UNIFORM_BLOCKS, &count);
for (auto i = 0; i < count; ++i) {
    ...
}
</code>```

...always returns 3 for this shader program. I get the same result whether I run on Android, iOS or WebGL2. I haven't tested on desktop OpenGL (versus OpenGL ES 3.0) but I don't expect a different result (but I guess it could?).

So what does it means for a uniform block to be active then?

And is there a way to only retrieve used uniform blocks (skip unused ones)?

Thanks!

答:
A uniform block that is not in use may be optimized out by the implementation. But it may not as well; that's all up to the implementation. OpenGL does not require implementations to optimize out unused uniforms or blocks; it simply allows for the possibility.

There is no way to guaranteeably fetch which uniform blocks are in use.

Body:
The OpenGL documentation is not very clear about what is an active uniform block (versus those are not active). So my understanding is it is about them being referenced/used in a shader program... or is it!

Consider the following shader program:

Vertex Shader

#version 300 es
precision highp float;

layout(std140) uniform globals
{
    mat4 world_view_proj;
};

layout(std140) uniform foo
{
    vec3 bar;
};

layout(std140) uniform dog
{
    vec3 cat;
};

layout(location = 0) in vec4 position0;
layout(location = 4) in lowp vec4 color0;
out lowp vec4 v_color;

void main ( )
{
    v_color = color0;
    gl_Position = position0 * world_view_proj;
}

Fragment Shader

#version 300 es
precision highp float;

in lowp vec4 v_color;
layout(location = 0) out lowp vec4 frag_color;

void main()
{
    frag_color = v_color;
}

Even though I don't use foo or dog uniform blocks, a query to get the number of active uniform blocks...

GLint count = 0;
glGetProgramiv(program, GL_ACTIVE_UNIFORM_BLOCKS, &count);
for (auto i = 0; i < count; ++i) {
    ...
}

...always returns 3 for this shader program. I get the same result whether I run on Android, iOS or WebGL2. I haven't tested on desktop OpenGL (versus OpenGL ES 3.0) but I don't expect a different result (but I guess it could?).

So what does it means for a uniform block to be active then?

And is there a way to only retrieve used uniform blocks (skip unused ones)?

Thanks!


问:
Get types implementing interface in ASP.NET Core web application
I am trying to port some of my plain ASP.NET (MVC) code to the ASP.NET Core web application. My code looked like this:

```<code>    System.Web.Compilation.BuildManager.GetReferencedAssemblies()
       .Cast<System.Reflection.Assembly>()
       .SelectMany(
           a => a.GetTypes()).Where(type => typeof(IGoogleSitemap).IsAssignableFrom(type)
        )
        .ToList();
</code>```

But I am not getting that to work on ASP.NET Core (1.1). For one thing Assembly does not have GetReferencedAssemblies() only GetEntryAssembly(). And GetEntryAssembly().GetReferencedAssemblies() gives me a list of AssemblyName instead of Assembly objects.

Basically I am looking for all controllers implementing the IGoogleSitemap interface (defined in a separate assembly).

答:
I found a (terribly inefficient) way of achieving this,

```<code>var all =
        Assembly
        .GetEntryAssembly()
        .GetReferencedAssemblies()
        .Select(Assembly.Load)
        .SelectMany(x => x.DefinedTypes)
        .Where(type => typeof(ICloudProvider).IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
    var t = ti.AsType();
    if (!t.Equals(typeof(ICloudProvider)))
    {
        // do work
    }
}
</code>```

I am worried about the cost of the Assembly.Load part, but this will probably get my work done for now - as I only need the Fully Qualified Name of all the classes that implements ICloudProvider.

Body:
I am trying to port some of my plain ASP.NET (MVC) code to the ASP.NET Core web application. My code looked like this:

    System.Web.Compilation.BuildManager.GetReferencedAssemblies()
       .Cast<System.Reflection.Assembly>()
       .SelectMany(
           a => a.GetTypes()).Where(type => typeof(IGoogleSitemap).IsAssignableFrom(type)
        )
        .ToList();

But I am not getting that to work on ASP.NET Core (1.1). For one thing Assembly does not have GetReferencedAssemblies() only GetEntryAssembly(). And GetEntryAssembly().GetReferencedAssemblies() gives me a list of AssemblyName instead of Assembly objects.

Basically I am looking for all controllers implementing the IGoogleSitemap interface (defined in a separate assembly).

Body:
I found a (terribly inefficient) way of achieving this,

var all =
        Assembly
        .GetEntryAssembly()
        .GetReferencedAssemblies()
        .Select(Assembly.Load)
        .SelectMany(x => x.DefinedTypes)
        .Where(type => typeof(ICloudProvider).IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
    var t = ti.AsType();
    if (!t.Equals(typeof(ICloudProvider)))
    {
        // do work
    }
}

I am worried about the cost of the Assembly.Load part, but this will probably get my work done for now - as I only need the Fully Qualified Name of all the classes that implements ICloudProvider.