问:
How can I automatically parse tables spanning over multiple pages with Python
I want to parse a table (or multiple tables) spanning over several pages.
The way I did it below works but is is way too manual, and I would like it to automatically parse the tables from the different pages and combine them into one. The number of pages might not always be the same. </p>

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd

one = "https://rittresultater.no/nb/sb_tid/923?page=0&pv2=11027&pv1=U"
two = "https://rittresultater.no/nb/sb_tid/923?page=1&pv2=11027&pv1=U"
three = "https://rittresultater.no/nb/sb_tid/923?page=2&pv2=11027&pv1=U"

#parse the first page
html = urlopen(one)
soup = BeautifulSoup(html, "lxml")
table = soup.find_all(class_="table-condensed")
one = pd.read_html(str(table))[0]

#parse the second page
html = urlopen(two)
soup = BeautifulSoup(html, "lxml")
table = soup.find_all(class_="table-condensed")
two = pd.read_html(str(table))[0]

#parse thr third page
html = urlopen(three)
soup = BeautifulSoup(html, "lxml")
table = soup.find_all(class_="table-condensed")
three = pd.read_html(str(table))[0]

df = pd.concat([one,two,three], axis = 0)
df
</code>```

<p>Notice that the urls only differ in "page=X". Also the webpage itself contain links to eg. next page. </p>

答:
```<code>results = {}
for page_num in range(1, 10): #change depending on max page
    address = 'https://rittresultater.no/nb/sb_tid/923?page=' + \
               str(page_num) + '&pv2=11027&pv1=U'

    html = urlopen(address)
    soup = BeautifulSoup(html, 'lxml')
    table = soup.find_all(class='table-condensed')
    output = pd.read_html(str(table))[0]
    results[page_num] = output
</code>```

When its done use a list comprehension to do relevent thing to output, if it's the last line in your code but scaled up do this:

```<code>df = pd.concat([v for v in results.values()], axis = 0)
</code>```

Body:
I want to parse a table (or multiple tables) spanning over several pages.
The way I did it below works but is is way too manual, and I would like it to automatically parse the tables from the different pages and combine them into one. The number of pages might not always be the same.

from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd

one = "https://rittresultater.no/nb/sb_tid/923?page=0&pv2=11027&pv1=U"
two = "https://rittresultater.no/nb/sb_tid/923?page=1&pv2=11027&pv1=U"
three = "https://rittresultater.no/nb/sb_tid/923?page=2&pv2=11027&pv1=U"

#parse the first page
html = urlopen(one)
soup = BeautifulSoup(html, "lxml")
table = soup.find_all(class_="table-condensed")
one = pd.read_html(str(table))[0]

#parse the second page
html = urlopen(two)
soup = BeautifulSoup(html, "lxml")
table = soup.find_all(class_="table-condensed")
two = pd.read_html(str(table))[0]

#parse thr third page
html = urlopen(three)
soup = BeautifulSoup(html, "lxml")
table = soup.find_all(class_="table-condensed")
three = pd.read_html(str(table))[0]

df = pd.concat([one,two,three], axis = 0)
df

Notice that the urls only differ in "page=X". Also the webpage itself contain links to eg. next page.

Body:
results = {}
for page_num in range(1, 10): #change depending on max page
    address = 'https://rittresultater.no/nb/sb_tid/923?page=' + \
               str(page_num) + '&pv2=11027&pv1=U'

    html = urlopen(address)
    soup = BeautifulSoup(html, 'lxml')
    table = soup.find_all(class='table-condensed')
    output = pd.read_html(str(table))[0]
    results[page_num] = output

When its done use a list comprehension to do relevent thing to output, if it's the last line in your code but scaled up do this:

df = pd.concat([v for v in results.values()], axis = 0)


来源: stackexchange

问:
Should I use session for saving user data? Django
I'm new to django and I think sessions would be the best thing for my use case, but I'm not sure, maybe there are better possibilities?

This is my application simplified:
Users should be able to select any number of train connections out of a database, and my application returns the best average mobile phone operator for their connections.

My models would be the following:

User, in which all the connections are saved

Connection, in which the quality of the mobile net for different operators is saved

And to save the users (and thus their choosen connections) I would have used sessions, which save the user_id.

Is this possible and recommended?

答:
If you want the user's choices to persist longer than a single session, (i.e. I can come back to your app another time and be able to retrieve my choices), use a database to store it. You can look at https://tutorial.djangogirls.org/en/django_start_project/#set-up-a-database and https://tutorial.djangogirls.org/en/django_models/

Otherwise, if you do not want their choices to persist, then by all means use sessions.

ContentLicense: CC BY-SA 3.0


问:
How can I make this PowerShell script into one line
This PowerShell script works great, but I need it to be a one line script, how can I create the parameter objects inline?

```<code>$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}'
$trigger =  New-ScheduledTaskTrigger -Daily -At 9am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Reset IIS" -Description "Daily Reset IIS"
</code>```

e.g.

```<code>Register-ScheduledTask -Action `New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}'` -Trigger `New-ScheduledTaskTrigger -Daily -At 9am -TaskName "Reset IIS" -Description "Daily Reset IIS"`
</code>```

I've tried wrapping it in double quotes and with backticks and with curly braces but no luck so far.

答:
If you want to execute a subexpression wrap it in $()</p>

```<code>Register-ScheduledTask -Action $(New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}') -Trigger $(New-ScheduledTaskTrigger -Daily -At 9am) -TaskName "Reset IIS" -Description "Daily Reset IIS"
</code>```

Body:
This PowerShell script works great, but I need it to be a one line script, how can I create the parameter objects inline?

$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}'
$trigger =  New-ScheduledTaskTrigger -Daily -At 9am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Reset IIS" -Description "Daily Reset IIS"

e.g.

Register-ScheduledTask -Action `New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}'` -Trigger `New-ScheduledTaskTrigger -Daily -At 9am -TaskName "Reset IIS" -Description "Daily Reset IIS"`

I've tried wrapping it in double quotes and with backticks and with curly braces but no luck so far.

Body:
If you want to execute a subexpression wrap it in $()

Register-ScheduledTask -Action $(New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}') -Trigger $(New-ScheduledTaskTrigger -Daily -At 9am) -TaskName "Reset IIS" -Description "Daily Reset IIS"


问:
passing functions as arguments in ruby
I'm trying to wrap my head around functional programming in ruby and there doesn't seem to be much good documentation out there.

Essentially, I'm trying to write a combine function that would have a Haskell type signature of:

```<code>[a] -> [a] -> (a -> a -> a) -> [a]
</code>```

So

```<code>combine([1,2,3], [2,3,4], plus_func) => [3,5,7]
combine([1,2,3], [2,3,4], multiply_func) => [2,6,12]
</code>```

etc.

I found some stuff about using zip and map but that feels really ugly to use.

What would be the most "ruby" way of implementing something like this?

答:
A very naive aproach:

```<code>def combine(a1, a2)
  i = 0
  result = []
  while a1[i] && a2[i]
    result << yield(a1[i], a2[i])
    i+=1
  end
  result
end

sum = combine([1,2,3], [2,3,4]) {|x,y| x+y}
prod = combine([1,2,3], [2,3,4]) {|x,y| x*y}

p sum, prod

=>
[3, 5, 7]
[2, 6, 12]
</code>```

And with arbitrary parameters:

```<code>def combine(*args)
  i = 0
  result = []
  while args.all?{|a| a[i]}
    result << yield(*(args.map{|a| a[i]}))
    i+=1
  end
  result
end
</code>```

EDIT: I upvoted the zip/map solution, but here's a little improvement, what's ugly about it?

```<code>def combine(*args)
  args.first.zip(*args[1..-1]).map {|a| yield a}
end

sum = combine([1,2,3], [2,3,4], [3,4,5]) {|ary| ary.inject{|t,v| t+=v}}
prod = combine([1,2,3], [2,3,4], [3,4,5]) {|ary| ary.inject(1){|t,v| t*=v}}
p sum, prod
</code>```

OwnerDisplayName: Shalmanese

ContentLicense: CC BY-SA 2.5

Title: passing functions as arguments in ruby

Body:
I'm trying to wrap my head around functional programming in ruby and there doesn't seem to be much good documentation out there.

Essentially, I'm trying to write a combine function that would have a Haskell type signature of:

[a] -> [a] -> (a -> a -> a) -> [a]

So

combine([1,2,3], [2,3,4], plus_func) => [3,5,7]
combine([1,2,3], [2,3,4], multiply_func) => [2,6,12]

etc.

I found some stuff about using zip and map but that feels really ugly to use.

What would be the most "ruby" way of implementing something like this?

Body:
A very naive aproach:

def combine(a1, a2)
  i = 0
  result = []
  while a1[i] && a2[i]
    result << yield(a1[i], a2[i])
    i+=1
  end
  result
end

sum = combine([1,2,3], [2,3,4]) {|x,y| x+y}
prod = combine([1,2,3], [2,3,4]) {|x,y| x*y}

p sum, prod

=>
[3, 5, 7]
[2, 6, 12]

And with arbitrary parameters:

def combine(*args)
  i = 0
  result = []
  while args.all?{|a| a[i]}
    result << yield(*(args.map{|a| a[i]}))
    i+=1
  end
  result
end

EDIT: I upvoted the zip/map solution, but here's a little improvement, what's ugly about it?

def combine(*args)
  args.first.zip(*args[1..-1]).map {|a| yield a}
end

sum = combine([1,2,3], [2,3,4], [3,4,5]) {|ary| ary.inject{|t,v| t+=v}}
prod = combine([1,2,3], [2,3,4], [3,4,5]) {|ary| ary.inject(1){|t,v| t*=v}}
p sum, prod


问:
How I can read a paragraph from the keyboard and stored it in a linked list (each node has a one word)?
```<code>#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class node
{
private:
    string data;
    node *next;
public:
    node*head,*current,*tail;
    node()
    {
     head=current=tail=NULL;
    }
    void read()
    {
     string x;
     tail=new node;
     cin>>tail->data;
     tail->next=NULL;
     head=current=tail;
     cin>>x;
     while(x!=".")
     {
      current=new node;
      current->next=NULL;
      stringstream ss;//("plez help me");
      string s;
      //getline(cin,aa);
      while (getline(ss, s,' '))
        {
            cout << s << "\t";

        }
      current->data=s;
      tail->next=current;
      tail=tail->next;
      //cin>>x;
     }
    }
    void print()
    {
     current=head;
     while(current!=NULL)
     {
      cout<<current->data<<endl;
      current=current->next;
     }
    }
};
</code>```

答:
Unless this is a homework assignment, don't make your own linked-list class, just use std::list.

std::cin will input one word at a time by default.  Just call it multiple times, and it will read the source one word at a time.

Edit: your node class is trying to do too many things.  Each node has a pointer for next, head, current, and tail.  You're mixing the concept of the whole list, and a single node  within that list.

You should have a function (maybe call it addNode) which makes a new node, and inserts it after the last node.  Then call addNode from read.

You don't need to use a stringstream.  cin will separate based on spaces.

while(x!=".") won't stop at the end of a sentence unless the . appears all by itself:

```<code>Sample input: this is a test.  // this won't satisfy the test
              this is a test . // this will
</code>```

In the first example, the test will see "test.", and keep going.

Start simple: make a read function that works for a single word, first.

Body:
Unless this is a homework assignment, don't make your own linked-list class, just use std::list.

std::cin will input one word at a time by default.  Just call it multiple times, and it will read the source one word at a time.

Edit: your node class is trying to do too many things.  Each node has a pointer for next, head, current, and tail.  You're mixing the concept of the whole list, and a single node  within that list.

You should have a function (maybe call it addNode) which makes a new node, and inserts it after the last node.  Then call addNode from read.

You don't need to use a stringstream.  cin will separate based on spaces.

while(x!=".") won't stop at the end of a sentence unless the . appears all by itself:

Sample input: this is a test.  // this won't satisfy the test
              this is a test . // this will

In the first example, the test will see "test.", and keep going.

Start simple: make a read function that works for a single word, first.


问:
how to force scrapy exit when there is an exception
I wrote a crawler with Scrapy.

There is a function in the pipeline where I write my data to a database. I use the logging module to log runtime logs.

I found that when my string have Chinese logging.error() will throw an exception. But the crawler keeps running!

I know this is a minor error but if there is a critical exception I will miss it if crawler keeps running.

My question is: Is there a setting that I can force Scrapy stop when there is an exception?

答:
I don't know of a setting that would close the crawler on any exception, but you have at least a couple of options:

you can raise CloseSpider exception in a spider callback, maybe when you catch that exception you mention

you can call crawler.engine.close_spider(spider, 'some reason') if you have a reference to the crawler and spider object, for example in an extension. See how the CloseSpider extension is implemented (it's not the same as the CloseSpider exception).
You could hook this with the spider_error signal for example.


问:
Reading Program Memory In AHK
So I am working on a program to read values from a game (Mitos.is: The Game).
It is similiar to Agar.io

You have a size (mass), and I want to get the mass amount, it is a program, not an online game like Agar.io.

I have found this Auto Hotkey script:

```<code>#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

ReadMemory(MADDRESS=0,PROGRAM="",BYTES=4)
{
   Static OLDPROC, ProcessHandle
   VarSetCapacity(MVALUE, BYTES,0)
   If PROGRAM != %OLDPROC%
   {
      WinGet, pid, pid, % OLDPROC := PROGRAM
      ProcessHandle := ( ProcessHandle ? 0*(closed:=DllCall("CloseHandle"
      ,"UInt",ProcessHandle)) : 0 )+(pid ? DllCall("OpenProcess"
      ,"Int",16,"Int",0,"UInt",pid) : 0)
   }
   If (ProcessHandle) && DllCall("ReadProcessMemory","UInt",ProcessHandle,"UInt",MADDRESS,"Str",MVALUE,"UInt",BYTES,"UInt *",0)
   {    Loop % BYTES
            Result += *(&MVALUE + A_Index-1) << 8*(A_Index-1)
        Return Result
    }
   return !ProcessHandle ? "Handle Closed:" closed : "Fail"
}

mass := ReadMemory(Address here, "Mitos.is: The Game")

MsgBox, %mass%
</code>```

It works seamlessly but there is one slight problem, in Cheat Engine I took the liberty of finding the base address as shown below:

So I took the address circled here:

And inserted that into the program where it says "Address Here", correct me if this is not the right address, but when I restart the game and run my script it says "Fail", but in Cheat Engine the address is still valid. Help?

答:
Check the address if it changes after restarting the game, or do not restart game just run the script without restart and you haven't defined bytes so try following, </p>

```<code>        ReadMemory(MADDRESS=0, PROGRAM="", BYTES=4 )
mass := ReadMemory("0x123456", "Mitos.is: The Game", "4")
</code>```

<p>"PROGRAM" should be correct window title use spy to get correct window title, address has to be in hex value i.e. "0x15B29DD0", I don't know how your cheat engine reads program memory address.</p>

Title: Reading Program Memory In AHK

Body:
So I am working on a program to read values from a game (Mitos.is: The Game).
It is similiar to Agar.io

You have a size (mass), and I want to get the mass amount, it is a program, not an online game like Agar.io.

I have found this Auto Hotkey script:

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

ReadMemory(MADDRESS=0,PROGRAM="",BYTES=4)
{
   Static OLDPROC, ProcessHandle
   VarSetCapacity(MVALUE, BYTES,0)
   If PROGRAM != %OLDPROC%
   {
      WinGet, pid, pid, % OLDPROC := PROGRAM
      ProcessHandle := ( ProcessHandle ? 0*(closed:=DllCall("CloseHandle"
      ,"UInt",ProcessHandle)) : 0 )+(pid ? DllCall("OpenProcess"
      ,"Int",16,"Int",0,"UInt",pid) : 0)
   }
   If (ProcessHandle) && DllCall("ReadProcessMemory","UInt",ProcessHandle,"UInt",MADDRESS,"Str",MVALUE,"UInt",BYTES,"UInt *",0)
   {    Loop % BYTES
            Result += *(&MVALUE + A_Index-1) << 8*(A_Index-1)
        Return Result
    }
   return !ProcessHandle ? "Handle Closed:" closed : "Fail"
}

mass := ReadMemory(Address here, "Mitos.is: The Game")

MsgBox, %mass%

It works seamlessly but there is one slight problem, in Cheat Engine I took the liberty of finding the base address as shown below:

So I took the address circled here:

And inserted that into the program where it says "Address Here", correct me if this is not the right address, but when I restart the game and run my script it says "Fail", but in Cheat Engine the address is still valid. Help?

Body:
Check the address if it changes after restarting the game, or do not restart game just run the script without restart and you haven't defined bytes so try following,

        ReadMemory(MADDRESS=0, PROGRAM="", BYTES=4 )
mass := ReadMemory("0x123456", "Mitos.is: The Game", "4")

"PROGRAM" should be correct window title use spy to get correct window title, address has to be in hex value i.e. "0x15B29DD0", I don't know how your cheat engine reads program memory address.


问:
How do I highlight entire row instead of it's text-input border?

function valueE(e) {
  var newValue = e.target.value;
  var $radio = $(e.target);

  if ($radio.is('.Fr')) {
    $radio.closest('tr').find('.numFr').val(newValue);
  } else {
    $radio.closest('tr').find('.numIr').val(newValue);
  }
}

$(document).ready(function() {

  $('#showme').click(function() {
    validateNresult();
  })

  $('.allrb').change(valueE);

});

function validateNresult()
{
    var anyFieldIsEmpty = $(".numFr").filter(function() {
            return $.trim(this.value).length === 0 ;
        }).css("border","1px solid red");
    var anyFieldIsEmpty1 = $(".numIr").filter(function() {
            return $.trim(this.value).length === 0 ;
        }).css("border","1px solid red");

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    input[type=number]
    {
      width:25px;
      text-align: center;
    }</code>```

    content 1
    <input type="radio" name="Fr1" class="allrb Fr" value="0">
    <input type="radio" name="Fr1" class="allrb Fr" value="1">
    <input type="radio" name="Fr1" class="allrb Fr" value="2">
    <input type="radio" name="Fr1" class="allrb Fr" value="3">
    <input type="radio" name="Fr1" class="allrb Fr" value="4">
    <input type="radio" name="Ir1" class="allrb Ir" value="0" >
    <input type="radio" name="Ir1" class="allrb Ir" value="1" >
    <input type="radio" name="Ir1" class="allrb Ir" value="2" >
    <input type="radio" name="Ir1" class="allrb Ir" value="3" >
    <input type="radio" name="Ir1" class="allrb Ir" value="4" >
    <input type="number" name="numFr1" class="numFr" id="numFr1" disabled>
    <input type="number" name="numIr1" class="numIr" id="numIr1" disabled>

    content 2
    <input type="radio" name="Fr2" class="allrb Fr" value="0">
    <input type="radio" name="Fr2" class="allrb Fr" value="1">
    <input type="radio" name="Fr2" class="allrb Fr" value="2">
    <input type="radio" name="Fr2" class="allrb Fr" value="3">
    <input type="radio" name="Fr2" class="allrb Fr" value="4">
    <input type="radio" name="Ir2" class="allrb Ir" value="0" >
    <input type="radio" name="Ir2" class="allrb Ir" value="1" >
    <input type="radio" name="Ir2" class="allrb Ir" value="2" >
    <input type="radio" name="Ir2" class="allrb Ir" value="3" >
    <input type="radio" name="Ir2" class="allrb Ir" value="4" >
    <input type="number" name="numFr2" class="numFr" id="numFr2" disabled>
    <input type="number" name="numIr2" class="numIr" id="numIr2" disabled>

    content 3
    <input type="radio" name="Fr3" class="allrb Fr" value="0">
    <input type="radio" name="Fr3" class="allrb Fr" value="1">
    <input type="radio" name="Fr3" class="allrb Fr" value="2">
    <input type="radio" name="Fr3" class="allrb Fr" value="3">
    <input type="radio" name="Fr3" class="allrb Fr" value="4">
    <input type="radio" name="Ir3 Ir" class="allrb" value="0" >
    <input type="radio" name="Ir Ir3" class="allrb" value="1" >
    <input type="radio" name="Ir3 Ir" class="allrb" value="2" >
    <input type="radio" name="Ir3 Ir" class="allrb" value="3" >
    <input type="radio" name="Ir3 Ir" class="allrb" value="4" >
    <input type="number" name="numFr3" class="numFr" id="numFr3" disabled>
    <input type="number" name="numIr3" class="numIr" id="numIr3" disabled>

    content 4
    <input type="radio" name="Fr4" class="allrb Fr" value="0">
    <input type="radio" name="Fr4" class="allrb Fr" value="1">
    <input type="radio" name="Fr4" class="allrb Fr" value="2">
    <input type="radio" name="Fr4" class="allrb Fr" value="3">
    <input type="radio" name="Fr4" class="allrb Fr" value="4">
    <input type="radio" name="Ir4 Ir" class="allrb" value="0" >
    <input type="radio" name="Ir Ir4" class="allrb" value="1" >
    <input type="radio" name="Ir4 Ir" class="allrb" value="2" >
    <input type="radio" name="Ir4 Ir" class="allrb" value="3" >
    <input type="radio" name="Ir4 Ir" class="allrb" value="4" >
    <input type="number" name="numFr4" class="numFr" id="numFr4" disabled>
    <input type="number" name="numIr4" class="numIr" id="numIr4" disabled>

    content 5
    <input type="radio" name="Fr5" class="allrb Fr" value="0">
    <input type="radio" name="Fr5" class="allrb Fr" value="1">
    <input type="radio" name="Fr5" class="allrb Fr" value="2">
    <input type="radio" name="Fr5" class="allrb Fr" value="3">
    <input type="radio" name="Fr5" class="allrb Fr" value="4">
    <input type="radio" name="Ir5 Ir" class="allrb" value="0" >
    <input type="radio" name="Ir Ir5" class="allrb" value="1" >
    <input type="radio" name="Ir5 Ir" class="allrb" value="2" >
    <input type="radio" name="Ir5 Ir" class="allrb" value="3" >
    <input type="radio" name="Ir5 Ir" class="allrb" value="4" >
    <input type="number" name="numFr5" class="numFr" id="numFr5" disabled>
    <input type="number" name="numIr5" class="numIr" id="numIr5" disabled>

    <button class="btn btn-primary" id="showme" type="button">View Result</button>

```

I had the following radio box and input text field. My purpose was do a validation to ensure user had do the selection for all the radio box and cannot be blank, I don't know how to validation on the radio box, so I do on the input text field that are empty. I had the following jquery but it only highlight the input text field, my expectation is highlight entire row and it will jump to the row automatic when it had not be answered when I click the button. Thanks.

答:
Please check the updated code below.

Added one class invalid in css.

Looped through the row of table and checked if any of the input is blank, if yes add invalid class to row else remove the class.

Hope this is what you were looking for!

function valueE(e) {
  var newValue = e.target.value;
  var $radio = $(e.target);

  if ($radio.is('.Fr')) {
    $radio.closest('tr').find('.numFr').val(newValue);
  } else {
    $radio.closest('tr').find('.numIr').val(newValue);
  }
}

$(document).ready(function() {

  $('#showme').click(function() {
    validateNresult();
  })

  $('.allrb').change(valueE);

});

function validateNresult() {

  $.each($("tbody tr"), function(i, e) {
    var hasInvalidInputs = $(this).find(".numFr, .numIr").filter(function() {
      debugger
      return $.trim(this.value).length === 0;
    }).length > 0;

    if (hasInvalidInputs) {
      $(this).addClass("invalid");
    } else {
      $(this).removeClass("invalid");
    }

  });

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input[type=number] {
  width: 25px;
  text-align: center;
}

.invalid {
  outline: 1px solid red;
}</code>```

    content 1
    <input type="radio" name="Fr1" class="allrb Fr" value="0">
    <input type="radio" name="Fr1" class="allrb Fr" value="1">
    <input type="radio" name="Fr1" class="allrb Fr" value="2">
    <input type="radio" name="Fr1" class="allrb Fr" value="3">
    <input type="radio" name="Fr1" class="allrb Fr" value="4">
    <input type="radio" name="Ir1" class="allrb Ir" value="0" >
    <input type="radio" name="Ir1" class="allrb Ir" value="1" >
    <input type="radio" name="Ir1" class="allrb Ir" value="2" >
    <input type="radio" name="Ir1" class="allrb Ir" value="3" >
    <input type="radio" name="Ir1" class="allrb Ir" value="4" >
    <input type="number" name="numFr1" class="numFr" id="numFr1" disabled>
    <input type="number" name="numIr1" class="numIr" id="numIr1" disabled>

    content 2
    <input type="radio" name="Fr2" class="allrb Fr" value="0">
    <input type="radio" name="Fr2" class="allrb Fr" value="1">
    <input type="radio" name="Fr2" class="allrb Fr" value="2">
    <input type="radio" name="Fr2" class="allrb Fr" value="3">
    <input type="radio" name="Fr2" class="allrb Fr" value="4">
    <input type="radio" name="Ir2" class="allrb Ir" value="0" >
    <input type="radio" name="Ir2" class="allrb Ir" value="1" >
    <input type="radio" name="Ir2" class="allrb Ir" value="2" >
    <input type="radio" name="Ir2" class="allrb Ir" value="3" >
    <input type="radio" name="Ir2" class="allrb Ir" value="4" >
    <input type="number" name="numFr2" class="numFr" id="numFr2" disabled>
    <input type="number" name="numIr2" class="numIr" id="numIr2" disabled>

    content 3
    <input type="radio" name="Fr3" class="allrb Fr" value="0">
    <input type="radio" name="Fr3" class="allrb Fr" value="1">
    <input type="radio" name="Fr3" class="allrb Fr" value="2">
    <input type="radio" name="Fr3" class="allrb Fr" value="3">
    <input type="radio" name="Fr3" class="allrb Fr" value="4">
    <input type="radio" name="Ir3 Ir" class="allrb" value="0" >
    <input type="radio" name="Ir Ir3" class="allrb" value="1" >
    <input type="radio" name="Ir3 Ir" class="allrb" value="2" >
    <input type="radio" name="Ir3 Ir" class="allrb" value="3" >
    <input type="radio" name="Ir3 Ir" class="allrb" value="4" >
    <input type="number" name="numFr3" class="numFr" id="numFr3" disabled>
    <input type="number" name="numIr3" class="numIr" id="numIr3" disabled>

    content 4
    <input type="radio" name="Fr4" class="allrb Fr" value="0">
    <input type="radio" name="Fr4" class="allrb Fr" value="1">
    <input type="radio" name="Fr4" class="allrb Fr" value="2">
    <input type="radio" name="Fr4" class="allrb Fr" value="3">
    <input type="radio" name="Fr4" class="allrb Fr" value="4">
    <input type="radio" name="Ir4 Ir" class="allrb" value="0" >
    <input type="radio" name="Ir Ir4" class="allrb" value="1" >
    <input type="radio" name="Ir4 Ir" class="allrb" value="2" >
    <input type="radio" name="Ir4 Ir" class="allrb" value="3" >
    <input type="radio" name="Ir4 Ir" class="allrb" value="4" >
    <input type="number" name="numFr4" class="numFr" id="numFr4" disabled>
    <input type="number" name="numIr4" class="numIr" id="numIr4" disabled>

    content 5
    <input type="radio" name="Fr5" class="allrb Fr" value="0">
    <input type="radio" name="Fr5" class="allrb Fr" value="1">
    <input type="radio" name="Fr5" class="allrb Fr" value="2">
    <input type="radio" name="Fr5" class="allrb Fr" value="3">
    <input type="radio" name="Fr5" class="allrb Fr" value="4">
    <input type="radio" name="Ir5 Ir" class="allrb" value="0" >
    <input type="radio" name="Ir Ir5" class="allrb" value="1" >
    <input type="radio" name="Ir5 Ir" class="allrb" value="2" >
    <input type="radio" name="Ir5 Ir" class="allrb" value="3" >
    <input type="radio" name="Ir5 Ir" class="allrb" value="4" >
    <input type="number" name="numFr5" class="numFr" id="numFr5" disabled>
    <input type="number" name="numIr5" class="numIr" id="numIr5" disabled>

<button class="btn btn-primary" id="showme" type="button">View Result</button>

```

Body:
function valueE(e) {
  var newValue = e.target.value;
  var $radio = $(e.target);

  if ($radio.is('.Fr')) {
    $radio.closest('tr').find('.numFr').val(newValue);
  } else {
    $radio.closest('tr').find('.numIr').val(newValue);
  }
}

$(document).ready(function() {

  $('#showme').click(function() {
    validateNresult();
  })

  $('.allrb').change(valueE);

});

function validateNresult()
{
    var anyFieldIsEmpty = $(".numFr").filter(function() {
            return $.trim(this.value).length === 0 ;
        }).css("border","1px solid red");
    var anyFieldIsEmpty1 = $(".numIr").filter(function() {
            return $.trim(this.value).length === 0 ;
        }).css("border","1px solid red");

}

    input[type=number]
    {
      width:25px;
      text-align: center;
    }

    content 1
    <input type="radio" name="Fr1" class="allrb Fr" value="0">
    <input type="radio" name="Fr1" class="allrb Fr" value="1">
    <input type="radio" name="Fr1" class="allrb Fr" value="2">
    <input type="radio" name="Fr1" class="allrb Fr" value="3">
    <input type="radio" name="Fr1" class="allrb Fr" value="4">
    <input type="radio" name="Ir1" class="allrb Ir" value="0" >
    <input type="radio" name="Ir1" class="allrb Ir" value="1" >
    <input type="radio" name="Ir1" class="allrb Ir" value="2" >
    <input type="radio" name="Ir1" class="allrb Ir" value="3" >
    <input type="radio" name="Ir1" class="allrb Ir" value="4" >
    <input type="number" name="numFr1" class="numFr" id="numFr1" disabled>
    <input type="number" name="numIr1" class="numIr" id="numIr1" disabled>

    content 2
    <input type="radio" name="Fr2" class="allrb Fr" value="0">
    <input type="radio" name="Fr2" class="allrb Fr" value="1">
    <input type="radio" name="Fr2" class="allrb Fr" value="2">
    <input type="radio" name="Fr2" class="allrb Fr" value="3">
    <input type="radio" name="Fr2" class="allrb Fr" value="4">
    <input type="radio" name="Ir2" class="allrb Ir" value="0" >
    <input type="radio" name="Ir2" class="allrb Ir" value="1" >
    <input type="radio" name="Ir2" class="allrb Ir" value="2" >
    <input type="radio" name="Ir2" class="allrb Ir" value="3" >
    <input type="radio" name="Ir2" class="allrb Ir" value="4" >
    <input type="number" name="numFr2" class="numFr" id="numFr2" disabled>
    <input type="number" name="numIr2" class="numIr" id="numIr2" disabled>

    content 3
    <input type="radio" name="Fr3" class="allrb Fr" value="0">
    <input type="radio" name="Fr3" class="allrb Fr" value="1">
    <input type="radio" name="Fr3" class="allrb Fr" value="2">
    <input type="radio" name="Fr3" class="allrb Fr" value="3">
    <input type="radio" name="Fr3" class="allrb Fr" value="4">
    <input type="radio" name="Ir3 Ir" class="allrb" value="0" >
    <input type="radio" name="Ir Ir3" class="allrb" value="1" >
    <input type="radio" name="Ir3 Ir" class="allrb" value="2" >
    <input type="radio" name="Ir3 Ir" class="allrb" value="3" >
    <input type="radio" name="Ir3 Ir" class="allrb" value="4" >
    <input type="number" name="numFr3" class="numFr" id="numFr3" disabled>
    <input type="number" name="numIr3" class="numIr" id="numIr3" disabled>

    content 4
    <input type="radio" name="Fr4" class="allrb Fr" value="0">
    <input type="radio" name="Fr4" class="allrb Fr" value="1">
    <input type="radio" name="Fr4" class="allrb Fr" value="2">
    <input type="radio" name="Fr4" class="allrb Fr" value="3">
    <input type="radio" name="Fr4" class="allrb Fr" value="4">
    <input type="radio" name="Ir4 Ir" class="allrb" value="0" >
    <input type="radio" name="Ir Ir4" class="allrb" value="1" >
    <input type="radio" name="Ir4 Ir" class="allrb" value="2" >
    <input type="radio" name="Ir4 Ir" class="allrb" value="3" >
    <input type="radio" name="Ir4 Ir" class="allrb" value="4" >
    <input type="number" name="numFr4" class="numFr" id="numFr4" disabled>
    <input type="number" name="numIr4" class="numIr" id="numIr4" disabled>

    content 5
    <input type="radio" name="Fr5" class="allrb Fr" value="0">
    <input type="radio" name="Fr5" class="allrb Fr" value="1">
    <input type="radio" name="Fr5" class="allrb Fr" value="2">
    <input type="radio" name="Fr5" class="allrb Fr" value="3">
    <input type="radio" name="Fr5" class="allrb Fr" value="4">
    <input type="radio" name="Ir5 Ir" class="allrb" value="0" >
    <input type="radio" name="Ir Ir5" class="allrb" value="1" >
    <input type="radio" name="Ir5 Ir" class="allrb" value="2" >
    <input type="radio" name="Ir5 Ir" class="allrb" value="3" >
    <input type="radio" name="Ir5 Ir" class="allrb" value="4" >
    <input type="number" name="numFr5" class="numFr" id="numFr5" disabled>
    <input type="number" name="numIr5" class="numIr" id="numIr5" disabled>

    <button class="btn btn-primary" id="showme" type="button">View Result</button>

I had the following radio box and input text field. My purpose was do a validation to ensure user had do the selection for all the radio box and cannot be blank, I don't know how to validation on the radio box, so I do on the input text field that are empty. I had the following jquery but it only highlight the input text field, my expectation is highlight entire row and it will jump to the row automatic when it had not be answered when I click the button. Thanks.

Body:
Please check the updated code below.

Added one class invalid in css.

Looped through the row of table and checked if any of the input is blank, if yes add invalid class to row else remove the class.

Hope this is what you were looking for!

function valueE(e) {
  var newValue = e.target.value;
  var $radio = $(e.target);

  if ($radio.is('.Fr')) {
    $radio.closest('tr').find('.numFr').val(newValue);
  } else {
    $radio.closest('tr').find('.numIr').val(newValue);
  }
}

$(document).ready(function() {

  $('#showme').click(function() {
    validateNresult();
  })

  $('.allrb').change(valueE);

});

function validateNresult() {

  $.each($("tbody tr"), function(i, e) {
    var hasInvalidInputs = $(this).find(".numFr, .numIr").filter(function() {
      debugger
      return $.trim(this.value).length === 0;
    }).length > 0;

    if (hasInvalidInputs) {
      $(this).addClass("invalid");
    } else {
      $(this).removeClass("invalid");
    }

  });

}

input[type=number] {
  width: 25px;
  text-align: center;
}

.invalid {
  outline: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover table-responsive" id="tab">
  <tr id="alertr1" name="v">
    <td width="200px" id="text">content 1</td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr1" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr1" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb Ir" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr1" class="numFr" id="numFr1" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr1" class="numIr" id="numIr1" disabled></td>
  </tr>

  <tr id="alertr2" name="v">
    <td width="200px" id="text">content 2</td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr2" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr2" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb Ir" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr2" class="numFr" id="numFr2" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr2" class="numIr" id="numIr2" disabled></td>
  </tr>

  <tr id="alertr3" name="v">
    <td width="200px" id="text">content 3</td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr3" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr3" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir Ir3" class="allrb" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3 Ir" class="allrb" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr3" class="numFr" id="numFr3" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr3" class="numIr" id="numIr3" disabled></td>
  </tr>

  <tr id="alertr4" name="v">
    <td width="200px" id="text">content 4</td>
    <td width="40px"><label><input type="radio" name="Fr4" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr4" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr4" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr4" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr4" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir4 Ir" class="allrb" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir Ir4" class="allrb" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir4 Ir" class="allrb" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir4 Ir" class="allrb" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir4 Ir" class="allrb" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr4" class="numFr" id="numFr4" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr4" class="numIr" id="numIr4" disabled></td>
  </tr>

  <tr id="alertr5" name="v">
    <td width="200px" id="text">content 5</td>
    <td width="40px"><label><input type="radio" name="Fr5" class="allrb Fr" value="0"></label></td>
    <td width="40px"><label><input type="radio" name="Fr5" class="allrb Fr" value="1"></label></td>
    <td width="40px"><label><input type="radio" name="Fr5" class="allrb Fr" value="2"></label></td>
    <td width="40px"><label><input type="radio" name="Fr5" class="allrb Fr" value="3"></label></td>
    <td width="30px"><label><input type="radio" name="Fr5" class="allrb Fr" value="4"></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir5 Ir" class="allrb" value="0" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir Ir5" class="allrb" value="1" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir5 Ir" class="allrb" value="2" ></label></td>
    <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir5 Ir" class="allrb" value="3" ></label></td>
    <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir5 Ir" class="allrb" value="4" ></label></td>
    <td width="30px"><input type="number" name="numFr5" class="numFr" id="numFr5" disabled></td>
    <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr5" class="numIr" id="numIr5" disabled></td>
  </tr>
</table>

<button class="btn btn-primary" id="showme" type="button">View Result</button>
<p style="float:right;position:absolute;margin-left:700px;margin-top:10px;" id="alertmessage"></p>


问:
how to get each data from a parseJSON array
I am trying to draw a linechart by using Google chart API, and I am use PHP codeignitor to retrieve data from mySQL database.

So far, I am able to retrieve the data, but I just couldn't parse the Json data, and fill them into linechart. below is the view I am actually loaded.

```<code><html>
<head>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
  <script type="text/javascript">
    var BASE_URL = "<?php echo base_url(); ?>";
    </script>
 <script type="text/javascript">
  // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(drawChart);

function drawChart() {

     $.ajax({

   type: 'POST',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "json",

    success: function (data1) {
    // Create our data table out of JSON data loaded from server.
    var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('string', 'solid');
  var jsonData = $.parseJSON(data1);

  for (var i = 0; i < jsonData.length; i++) {
        data.addRows([jsonData[i].timeline, jsonData[i].solid_t1]);
  }
  var options = {

    title: 'Solid chart',
    width: 900,
    height: 500,

  };

  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
   }
});
}
  </script>
</head>
<body>

  <div id="line_chart"></div>
</body>
</html>
</code>```

Here under is the function getdata in my controller:

```<code>    function getdata(){
  $this->load->model('Chart');
  $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();
    print_r(json_encode($data, true));
}
</code>```

I tried to output the json_encode data, and I am able to get the result below:

```<code>[{"timeline":"430","solid_t1":"12"},{"timeline":"030","solid_t1":"8.1"},{"timeline":"830","solid_t1":"32"},{"timeline":"1230","solid_t1":"10"},{"timeline":"1630","solid_t1":"100"},{"timeline":"2030","solid_t1":"8"}]
</code>```

Can someone help me on this, thanks.

Update

Hi Guys, I put the function in my model here, maybe because my query result is array, not a object?

```<code>function getdata_solid(){
  $this->db->select('timeline');
  $this->db->select('solid_t1');
  $this->db->from("varnish_mvs");
  $this->db->where('date_selected', '2017-03-25');
  //$this->db->where('timeline', $timeline);
  $query = $this->db->get();
  return $query->result_array();

}
</code>```

Final Update: I finally solved this issue by changing the way of loading google chart functions. here under are my final working codes. I hope it may help for someone who has the same issue.

```<code>$(document).ready(function() {

     $.ajax({

   type: 'POST',
    //url: 'http://localhost/charts/charts/getdata',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "JSON",
    success: function (data1) {

     // alert(data1);
       // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(function(){
    drawChart(data1);
  });

   }
});

     function drawChart(data1) {

        var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('number', 'solid_t1');
  var dataArray = [];
  /*$.each(data1, function(i, obj){
    dataArray.push([obj.timeline, parseInt(obj.solid_t1)]);
  });*/
  var jsonData = $.parseJSON(data1);
   for (var i = 0; i < jsonData.length; i++) {
        dataArray.push([jsonData[i].timeline, parseInt(jsonData[i].solid_t1)]);
      }
  //dataArray.push([jsonData[0].timeline, parseInt(jsonData[0].solid_t1)], [jsonData[1].timeline, parseInt(jsonData[1].solid_t1)])
  //dataArray.push(['2', 3], ['6', 5]);
  alert(dataArray);
  data.addRows(dataArray);
  var options = {
    title:'Solid chart',
    width: 900,
    height: 500,
  };
  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
     }

});
</code>```

答:
Assuming the response from the PHP script is JSON data then you could probably process the response data like this.

```<code>function drawChart() {
    $.ajax({
        type: 'POST',
        url: BASE_URL + 'index.php/Chart_varnish/getdata',
        dataType: 'json',
        success: function(response) {
            var dataTbl = new google.visualization.DataTable();
                /* a number for at least 1 column is req'd ? */
                dataTbl.addColumn('string', 'timeline');
                dataTbl.addColumn('string', 'solid');

            /* iterate through the response data */
            for( var n in response ){
                if( response[n] && typeof(response[n])=='object' ){
                    dataTbl.addRows( response[n].timeline, response[n].solid_t1 );
                }
            }
            var options = {
                title: 'Solid chart',
                width: 900,
                height: 500,

            };
            var chart = new google.visualization.LineChart( document.getElementById('line_chart') );
                chart.draw( dataTbl, options );
        }
    });
}
</code>```

The PHP script should simply use json_encode - the second argument can be a bitwise combination of flags ( predefined constants ) rather than a simple true/false - it is the json_decode function that uses /true/false as it's 2nd argument.

```<code>function getdata(){
    $this->load->model('Chart');
    $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();

    /* echo rather than print_r */
    echo json_encode( $data );
}
</code>```

Body:
I am trying to draw a linechart by using Google chart API, and I am use PHP codeignitor to retrieve data from mySQL database.

So far, I am able to retrieve the data, but I just couldn't parse the Json data, and fill them into linechart. below is the view I am actually loaded.

Here under is the function getdata in my controller:

    function getdata(){
  $this->load->model('Chart');
  $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();
    print_r(json_encode($data, true));
}

I tried to output the json_encode data, and I am able to get the result below:

[{"timeline":"430","solid_t1":"12"},{"timeline":"030","solid_t1":"8.1"},{"timeline":"830","solid_t1":"32"},{"timeline":"1230","solid_t1":"10"},{"timeline":"1630","solid_t1":"100"},{"timeline":"2030","solid_t1":"8"}]

Can someone help me on this, thanks.

Update

Hi Guys, I put the function in my model here, maybe because my query result is array, not a object?

function getdata_solid(){
  $this->db->select('timeline');
  $this->db->select('solid_t1');
  $this->db->from("varnish_mvs");
  $this->db->where('date_selected', '2017-03-25');
  //$this->db->where('timeline', $timeline);
  $query = $this->db->get();
  return $query->result_array();

}

Final Update: I finally solved this issue by changing the way of loading google chart functions. here under are my final working codes. I hope it may help for someone who has the same issue.

$(document).ready(function() {

     $.ajax({

   type: 'POST',
    //url: 'http://localhost/charts/charts/getdata',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "JSON",
    success: function (data1) {

     // alert(data1);
       // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(function(){
    drawChart(data1);
  });

   }
});

     function drawChart(data1) {

        var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('number', 'solid_t1');
  var dataArray = [];
  /*$.each(data1, function(i, obj){
    dataArray.push([obj.timeline, parseInt(obj.solid_t1)]);
  });*/
  var jsonData = $.parseJSON(data1);
   for (var i = 0; i < jsonData.length; i++) {
        dataArray.push([jsonData[i].timeline, parseInt(jsonData[i].solid_t1)]);
      }
  //dataArray.push([jsonData[0].timeline, parseInt(jsonData[0].solid_t1)], [jsonData[1].timeline, parseInt(jsonData[1].solid_t1)])
  //dataArray.push(['2', 3], ['6', 5]);
  alert(dataArray);
  data.addRows(dataArray);
  var options = {
    title:'Solid chart',
    width: 900,
    height: 500,
  };
  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
     }

});

Body:
Assuming the response from the PHP script is JSON data then you could probably process the response data like this.

function drawChart() {
    $.ajax({
        type: 'POST',
        url: BASE_URL + 'index.php/Chart_varnish/getdata',
        dataType: 'json',
        success: function(response) {
            var dataTbl = new google.visualization.DataTable();
                /* a number for at least 1 column is req'd ? */
                dataTbl.addColumn('string', 'timeline');
                dataTbl.addColumn('string', 'solid');

            /* iterate through the response data */
            for( var n in response ){
                if( response[n] && typeof(response[n])=='object' ){
                    dataTbl.addRows( response[n].timeline, response[n].solid_t1 );
                }
            }
            var options = {
                title: 'Solid chart',
                width: 900,
                height: 500,

            };
            var chart = new google.visualization.LineChart( document.getElementById('line_chart') );
                chart.draw( dataTbl, options );
        }
    });
}

The PHP script should simply use json_encode - the second argument can be a bitwise combination of flags ( predefined constants ) rather than a simple true/false - it is the json_decode function that uses /true/false as it's 2nd argument.

function getdata(){
    $this->load->model('Chart');
    $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();

    /* echo rather than print_r */
    echo json_encode( $data );
}


问:
Compilation Error for Webpack
I just started working on reactjs, wrote my first config file and seem to get this error. Posted an imiage of the cmd error as well.
My webpack.config.js:

```<code>var webpack = require('webpack');
var path = require('path');

module.exports = {

entry:{
    app: './src/app.js'
},
output:{
    filename: 'public/build/bundle.js',
    sourceMapFileName: 'public/build/bundle.map'
},
devtool: '#source-map',
module: {
    loaders:
    [
        {
            test: /\.jsx?$/,
            exclude: /(node_modules)/,
            loader: 'babel',
            query: {
                presets: ['react','es2015']
            }
        }
     ]
   }
}
</code>```

Error while compiling using command 'webpack'

答: I think it should be a lowercase n in sourceMapFileName so instead it should be sourceMapFilename

Title: Compilation Error for Webpack

Body:
I just started working on reactjs, wrote my first config file and seem to get this error. Posted an imiage of the cmd error as well.
My webpack.config.js:

var webpack = require('webpack');
var path = require('path');

module.exports = {

entry:{
    app: './src/app.js'
},
output:{
    filename: 'public/build/bundle.js',
    sourceMapFileName: 'public/build/bundle.map'
},
devtool: '#source-map',
module: {
    loaders:
    [
        {
            test: /\.jsx?$/,
            exclude: /(node_modules)/,
            loader: 'babel',
            query: {
                presets: ['react','es2015']
            }
        }
     ]
   }
}

Error while compiling using command 'webpack'


问:
Javascript , encodeURI failed to encode round bracket "("
I have cookie value which contains round bracket " e.g: demo (1)"
When I try to encode with encodeURI , the round bracket ( is not encoded to %28 , what is the alternative to encode the special characters like round brackets</p>

答:
encodeURI() encodes special characters, except: , / ? : @ & = + $ #.
One can use encodeURIComponent() to encode the above character.

You can write custom method to encode ( to %28.

Example :

```<code>var uri = "my test.asp?(name";
var res = encodeURI(uri);
res.replace("(", "%28");
</code>```

As pointed out in the comment below, string#replace will remove the first occurrence, one can use string#replaceAll i.e. res.replaceAll("(", "%28") or string#replace with global flag i.e. res.replace(/\(/g, "%28")  to remove all occurrences.

const uri = "my test.asp?(n(a(m(e",
      res = encodeURI(uri);
console.log(res.replaceAll("(", "%28"));```

NOTE :
encodeURI() will not encode: ~!@#$&*()=:/,;?+'

encodeURIComponent() will not encode: ~!*()'

Body:
encodeURI() encodes special characters, except: , / ? : @ & = + $ #.
One can use encodeURIComponent() to encode the above character.

You can write custom method to encode ( to %28.

Example :

var uri = "my test.asp?(name";
var res = encodeURI(uri);
res.replace("(", "%28");

As pointed out in the comment below, string#replace will remove the first occurrence, one can use string#replaceAll i.e. res.replaceAll("(", "%28") or string#replace with global flag i.e. res.replace(/\(/g, "%28")  to remove all occurrences.

const uri = "my test.asp?(n(a(m(e",
      res = encodeURI(uri);
console.log(res.replaceAll("(", "%28"));

NOTE :
encodeURI() will not encode: ~!@#$&*()=:/,;?+'

encodeURIComponent() will not encode: ~!*()'

ContentLicense: CC BY-SA 4.0


问:
Show this element without having code repeating each time
I'm showing / hidding data from Json on click of a marker which is working totally great.</p>

答:
In a shorter way you can iterate over the json object keys using Object.keys() and Array.prototype.forEach():

```<code>$.getJSON('js/data.json', function (json) { // <-- json variable
  Object.keys(json).forEach(function (country) {
    $(".marker." + country.toLowerCase()).on("click", function () {
      $("#show").html(
        "Image: <img src=" + json[country][0].image + ">" +
        "| Description: <h1>" + json[country][0].description) + "</h1>";
    });
  });
});
</code>```

Body:
In a shorter way you can iterate over the json object keys using Object.keys() and Array.prototype.forEach():

$.getJSON('js/data.json', function (json) { // <-- json variable
  Object.keys(json).forEach(function (country) {
    $(".marker." + country.toLowerCase()).on("click", function () {
      $("#show").html(
        "Image: <img src=" + json[country][0].image + ">" +
        "| Description: <h1>" + json[country][0].description) + "</h1>";
    });
  });
});


问:
How to run python scripts using gimpfu from command line?
I'm trying to use functions of gimp 2.8.22 to convert a pdf to jpeg and i want to do that with a python script using the gimpfu library from my windows cmd (i have installed python 3.6.1).

Right now, i't trying to do that with an example script:

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

# Hello World in GIMP Python

from gimpfu import *

def hello_world(initstr, font, size, color) :
    # First do a quick sanity check on the font
    if font == 'Comic Sans MS' :
        initstr = "Comic Sans? Are you sure?"

    # Make a new image. Size 10x10 for now -- we'll resize later.
    img = gimp.Image(1, 1, RGB)

    # Save the current foreground color:
    pdb.gimp_context_push()

    # Set the text color
    gimp.set_foreground(color)

    # Create a new text layer (-1 for the layer means create a new layer)
    layer = pdb.gimp_text_fontname(img, None, 0, 0, initstr, 10,
                                   True, size, PIXELS, font)

    # Resize the image to the size of the layer
    img.resize(layer.width, layer.height, 0, 0)

    # Background layer.
    # Can't add this first because we don't know the size of the text layer.
    background = gimp.Layer(img, "Background", layer.width, layer.height,
                            RGB_IMAGE, 100, NORMAL_MODE)
    background.fill(BACKGROUND_FILL)
    img.add_layer(background, 1)

    # Create a new image window
    gimp.Display(img)
    # Show the new image window
    gimp.displays_flush()

    # Restore the old foreground color:
    pdb.gimp_context_pop()

register(
    "python_fu_hello_world",
    "Hello world image",
    "Create a new image with your text string",
    "Akkana Peck",
    "Akkana Peck",
    "2010",
    "Hello world (Py)...",
    "",      # Create a new image, don't work on an existing one
    [
        (PF_STRING, "string", "Text string", 'Hello, world!'),
        (PF_FONT, "font", "Font face", "Sans"),
        (PF_SPINNER, "size", "Font size", 50, (1, 3000, 1)),
        (PF_COLOR, "color", "Text color", (1.0, 0.0, 0.0))
    ],
    [],
    hello_world, menu="<Image>/File/Create")

main()
</code>```

I try to run the script from my cmd like this:

```<code>gimp-2.8 --no-interface --batch '(python_fu_hello_world RUN-NONINTERACTIVE "Hello" Arial 50 red)' -b '(gimp-quit 1)'
</code>```

However, no matter what i do, i always geht the same error message:

(gimp-2.8:1020): LibGimpBase-WARNING **: gimp-2.8: gimp_wire_read():
  error

edit: Ok, thanks. I left out the interface statement and I also tried out the most simple example to figure out whats wrong:

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

# Hello World in GIMP Python

from gimpfu import *

def hello_world():
 gimp.message("Hello, GIMP world!\n")

register(
 "hello_world",
 'A simple Python-Fu "Hello, World" plug-in',
 'When run this plug-in prints "Hello, GIMP world!" in a dialog box.',
 "Tony Podlaski",
 "Tony Podlaski 2017. MIT License",
 "2017",
 "Hello World",
 "",
 [],
 [],
 hello_world,
 menu="<Image>/Filters/HelloWorld",
)

main()
</code>```

The script actually works when i run it from Gimp itself, but when i try to run it from my cmd, Gimp opens with another cmd saying: Error: ( : 1) eval: unbound variable: hello_world

Does someone know what i'm missing here?

答:
Because the script you are using creates the image and then shows it in a window.... But you are calling Gimp with the --no-interface flag so the window is not shown.

IMHO to convert from PDF to JPEG, ImageMagick's convert command would be a lot simpler.

Also, in Windows Gimp comes with its own built-in Python 2.7 interpreter, so you have to write your Python code for that version, and there is no need to install another one.

Body:
I'm trying to use functions of gimp 2.8.22 to convert a pdf to jpeg and i want to do that with a python script using the gimpfu library from my windows cmd (i have installed python 3.6.1).

Right now, i't trying to do that with an example script:

#!/usr/bin/env python

# Hello World in GIMP Python

from gimpfu import *

def hello_world(initstr, font, size, color) :
    # First do a quick sanity check on the font
    if font == 'Comic Sans MS' :
        initstr = "Comic Sans? Are you sure?"

    # Make a new image. Size 10x10 for now -- we'll resize later.
    img = gimp.Image(1, 1, RGB)

    # Save the current foreground color:
    pdb.gimp_context_push()

    # Set the text color
    gimp.set_foreground(color)

    # Create a new text layer (-1 for the layer means create a new layer)
    layer = pdb.gimp_text_fontname(img, None, 0, 0, initstr, 10,
                                   True, size, PIXELS, font)

    # Resize the image to the size of the layer
    img.resize(layer.width, layer.height, 0, 0)

    # Background layer.
    # Can't add this first because we don't know the size of the text layer.
    background = gimp.Layer(img, "Background", layer.width, layer.height,
                            RGB_IMAGE, 100, NORMAL_MODE)
    background.fill(BACKGROUND_FILL)
    img.add_layer(background, 1)

    # Create a new image window
    gimp.Display(img)
    # Show the new image window
    gimp.displays_flush()

    # Restore the old foreground color:
    pdb.gimp_context_pop()

register(
    "python_fu_hello_world",
    "Hello world image",
    "Create a new image with your text string",
    "Akkana Peck",
    "Akkana Peck",
    "2010",
    "Hello world (Py)...",
    "",      # Create a new image, don't work on an existing one
    [
        (PF_STRING, "string", "Text string", 'Hello, world!'),
        (PF_FONT, "font", "Font face", "Sans"),
        (PF_SPINNER, "size", "Font size", 50, (1, 3000, 1)),
        (PF_COLOR, "color", "Text color", (1.0, 0.0, 0.0))
    ],
    [],
    hello_world, menu="<Image>/File/Create")

main()

I try to run the script from my cmd like this:

gimp-2.8 --no-interface --batch '(python_fu_hello_world RUN-NONINTERACTIVE "Hello" Arial 50 red)' -b '(gimp-quit 1)'

However, no matter what i do, i always geht the same error message:

(gimp-2.8:1020): LibGimpBase-WARNING **: gimp-2.8: gimp_wire_read():
  error

edit: Ok, thanks. I left out the interface statement and I also tried out the most simple example to figure out whats wrong:

#!/usr/bin/env python

# Hello World in GIMP Python

from gimpfu import *

def hello_world():
 gimp.message("Hello, GIMP world!\n")

register(
 "hello_world",
 'A simple Python-Fu "Hello, World" plug-in',
 'When run this plug-in prints "Hello, GIMP world!" in a dialog box.',
 "Tony Podlaski",
 "Tony Podlaski 2017. MIT License",
 "2017",
 "Hello World",
 "",
 [],
 [],
 hello_world,
 menu="<Image>/Filters/HelloWorld",
)

main()

The script actually works when i run it from Gimp itself, but when i try to run it from my cmd, Gimp opens with another cmd saying: Error: ( : 1) eval: unbound variable: hello_world

Does someone know what i'm missing here?


问:
Validation in MEAN stack .....?
I am developing a MEAN stack application but i stuck at validation(user-inputs). I know the client-side validations are done in Angular-JS but i am confused where to validate on server side. Either to use mongooose for validations or don't do any validation on mongooose(just store) do validations only in server(Node/express using some modules) or  validate on both server-level and database-level....????

What should i do pls help me choose which practice is best.....????

Thanks.

答:
Banking just on mongoose validation is not enough. Your routes must be secured to not let invalid data pass through to mongoose validation.

The best place for this validation is middleware.

```<code>router.get('/', validateParameters, controller.index);
</code>```

The function takes req, res and next. Call next if req parameters are valid, else respond with 400 status code. This way, only valid call reaches the end point.

```<code>function validateParameters(req, res, next){
  // if req.params/req.body/req.query is valid
  // return next();
  // else return res.status(400).end;
}
</code>```

As to actually how to validate, you can check express-validator package, which gives you lots of options to validate req body, query and params. One good option is creating a schema for each route and just passing that schema to validateParameters function and validating it with one of req.check(schema) (to check all), req.checkQuery(schema), req.checkBody(schema) orreq.checkParams(schema), depending on where your parameters are.

Title: Validation in MEAN stack .....?

Body:
Banking just on mongoose validation is not enough. Your routes must be secured to not let invalid data pass through to mongoose validation.

The best place for this validation is middleware.

router.get('/', validateParameters, controller.index);

The function takes req, res and next. Call next if req parameters are valid, else respond with 400 status code. This way, only valid call reaches the end point.

function validateParameters(req, res, next){
  // if req.params/req.body/req.query is valid
  // return next();
  // else return res.status(400).end;
}

As to actually how to validate, you can check express-validator package, which gives you lots of options to validate req body, query and params. One good option is creating a schema for each route and just passing that schema to validateParameters function and validating it with one of req.check(schema) (to check all), req.checkQuery(schema), req.checkBody(schema) orreq.checkParams(schema), depending on where your parameters are.


问:
SSRS 2012 Report Page Breaks
Wondering if someone can point me in the right direction.  I currently have a report with 5 sub sections of data, each surrounded with a Rectangle.

I am wanting each sub section to appear on a new page and then be able to export to Excel and each section to appear on a new Tab.

I set Page Break / Break Location in each Rectangle to "Start" and label the PageName to what I want to call the Tab.  When I run the report the 4 subsections show correctly but I am left with a blank page before I get the 5 section, but when I export it to Excel it appears correctly.

What I want is 5 pages in the report for each section and when exporting I want 5 tabs, can someone tell me where I am going wrong with setting the pagebreaks if that is indeed what I am doing incorrectly.

Thanks

答:
As you are successfully exporting to Excel, but not the report viewer, this suggests your report and page sizes are not correctly set up on your 4th subsection.

When you have report elements that are slightly too large for your report page, the parts that 'overhang' will generate a new page of just the part that overhangs.  This is often a very small amount of white space, so it looks like the page is completely blank.  When you are exporting to formats such as excel, this does not matter so you correctly see the page breaks as new sheets.

To check whether this is the case, add borders and fills of different colours to all your rectangles and then run the report.  On your 4th 'blank' page, if you see any colours or borders you will know which rectangle or report element is growing beyond its page.

Title: SSRS 2012 Report Page Breaks


问:
multiple clicks on custom tableViewCell
I have a custom tableView cell, When I click on the cell the height of the cell increases (the cell expands):

```<code> var selectedIndex:IndexPath?
    var isExpanded = false

    func didExpandCell(){

        self.isExpanded = !isExpanded
        self.TableView.reloadRows(at: [selectedIndex!], with: .automatic)
    }

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       self.selectedIndex = indexPath
        self.didExpandCell()
    }
</code>```

I would like to click the cell a second time and segue to another view controller; is this possible?

```<code>self.performSegue(withIdentifier: "details", sender: tableView)
</code>```

答:
This is a different way other than checking for isExpanded state:

In didSelectRowAt, put a condition to check whether selected cell's height is equal to the expanded cell height (For ex., if the expanded cell height is set to 100 static). If YES, then call performSegue

The following is just a pseudocode for the logic:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

   let cell = getCellForIndexPath(indexPath)

   if cell.frame.size.height == 100 { // 100 is assumed to be static height for expanded cell. If it is dynamic, compare with normal cell height
      performSegue()
   } else {
      self.didExpandCell()
   }
}
</code>```

Title: multiple clicks on custom tableViewCell

Body:
I have a custom tableView cell, When I click on the cell the height of the cell increases (the cell expands):

 var selectedIndex:IndexPath?
    var isExpanded = false

    func didExpandCell(){

        self.isExpanded = !isExpanded
        self.TableView.reloadRows(at: [selectedIndex!], with: .automatic)
    }

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       self.selectedIndex = indexPath
        self.didExpandCell()
    }

I would like to click the cell a second time and segue to another view controller; is this possible?

self.performSegue(withIdentifier: "details", sender: tableView)

Body:
This is a different way other than checking for isExpanded state:

In didSelectRowAt, put a condition to check whether selected cell's height is equal to the expanded cell height (For ex., if the expanded cell height is set to 100 static). If YES, then call performSegue

The following is just a pseudocode for the logic:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

   let cell = getCellForIndexPath(indexPath)

   if cell.frame.size.height == 100 { // 100 is assumed to be static height for expanded cell. If it is dynamic, compare with normal cell height
      performSegue()
   } else {
      self.didExpandCell()
   }
}


问:
How to overlap layouts/views within LinearLayout?
I would like to create layout that looks like this:

Layout1and Layout2 are some layouts of any kind, nested in a parent LinearLayout. The LinearLayout is necessary to give both child layouts a 50% height by using layout_weight.

The red squares should be Buttons which overlap both Layout1and Layout2 and are centered between the two layouts.

Of course this could achived by using RelativeLayout as parent instead but then I would loose the possibility to use layout_weight...

If I keep using LinearLayout, it seems to be impossible to let the buttons overlap the two other layouts.

Furthermore the buttons cannot be siblings of the two layouts but need to be nested inside a common container layout that takes care of the horizontal positioning (e.g. a LinearLayout with horizontal orientation).

Any idea how to solve this?

I already tried to place the buttons inside Layout1 (or Layout2), place them below the bottom and use android:clipChildren=false, but this had no effect. The button where simple cut in half.

Edit:
Splitting the height between the two layouts 50/50 is just one version. Another view uses the same basic layout but splits the height 70/30 between the two layouts. The buttons should always be centered between the two layouts. Sorry for not pointing this out earlier.

Layout Code:

```<code><!-- parent/root layout -->
<LinearLayout
    ...
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    ... >

    <!-- Layout1 -->
    <LinearLayout
        android:layout_weight="1"
        ... />

    <!-- Buttons -->
    <LinearLayout
        android:orientation="horizontal"
        ... >

        <Button ... />
        <Button ... />
        <Button ... />

    </LinearLayout>

    <!-- Layout2 -->
    <LinearLayout
        android:layout_weight="1"
        ... />

</LinearLayout>
</code>```

答:
Here you can use this:
Position the imageviews according to your requirement</p>

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_test"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#e2e2"
            android:layout_weight="1"
            >

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#Ed1c24"
            android:layout_weight="1"
            >

        </LinearLayout>
    </LinearLayout>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/imageView"
        android:layout_marginStart="48dp"
        android:layout_centerVertical="true"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/imageView1"
        android:layout_toEndOf="@+id/imageView"
        android:layout_marginStart="48dp"
        android:layout_centerVertical="true"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/imageView3"
        android:layout_toEndOf="@+id/imageView1"
        android:layout_marginStart="38dp"
        android:layout_centerVertical="true"
        />

</RelativeLayout>
</code>```

Body:
I would like to create layout that looks like this:

Layout1and Layout2 are some layouts of any kind, nested in a parent LinearLayout. The LinearLayout is necessary to give both child layouts a 50% height by using layout_weight.

The red squares should be Buttons which overlap both Layout1and Layout2 and are centered between the two layouts.

Of course this could achived by using RelativeLayout as parent instead but then I would loose the possibility to use layout_weight...

If I keep using LinearLayout, it seems to be impossible to let the buttons overlap the two other layouts.

Furthermore the buttons cannot be siblings of the two layouts but need to be nested inside a common container layout that takes care of the horizontal positioning (e.g. a LinearLayout with horizontal orientation).

Any idea how to solve this?

I already tried to place the buttons inside Layout1 (or Layout2), place them below the bottom and use android:clipChildren=false, but this had no effect. The button where simple cut in half.

Edit:
Splitting the height between the two layouts 50/50 is just one version. Another view uses the same basic layout but splits the height 70/30 between the two layouts. The buttons should always be centered between the two layouts. Sorry for not pointing this out earlier.

Layout Code:

<LinearLayout
    ...
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    ... >

    <LinearLayout
        android:layout_weight="1"
        ... />

    <LinearLayout
        android:orientation="horizontal"
        ... >

        <Button ... />
        <Button ... />
        <Button ... />

    </LinearLayout>

    <LinearLayout
        android:layout_weight="1"
        ... />

</LinearLayout>

Body:
Here you can use this:
Position the imageviews according to your requirement

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_test"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#e2e2"
            android:layout_weight="1"
            >

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#Ed1c24"
            android:layout_weight="1"
            >

        </LinearLayout>
    </LinearLayout>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/imageView"
        android:layout_marginStart="48dp"
        android:layout_centerVertical="true"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/imageView1"
        android:layout_toEndOf="@+id/imageView"
        android:layout_marginStart="48dp"
        android:layout_centerVertical="true"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/imageView3"
        android:layout_toEndOf="@+id/imageView1"
        android:layout_marginStart="38dp"
        android:layout_centerVertical="true"
        />

</RelativeLayout>


问:
What is the best way to store XML data in an Excel file
I am looking for a way to store XML data in an Excel file.
The data should be completely hidden to the user, it should not be in a cell or comment, even hidden.
Also, the data should be preserved when the user opens and then saves the file with Excel.
I am not looking for a way to map cells to external XML data. The XML data should be inside the xlsx file.

The data will be entered using a C# tool, not Excel itself.

答:
The .xlsx file is actually just a compression archive (zip file) so if you truly want to add a hidden file then you could just add a .xml file to the archive. That way Excel wouldn't even know it was there.

Rename a .xlsx file to .zip, extract it, add your file, then select the contents of the .zip file and re-archive them. Rename to .xlsx and you'll have your hidden .xml file inside there.
(NOTE: Do not zip the top-level folder, only the contents)

You can do this in C# using a zip library like SharpZipLib:
http://www.sharpdevelop.net/OpenSource/SharpZipLib/

UPDATE: This "hidden" file will not be preserved if the user saves the file from within Excel. The best idea I can come up with for that scenario is to invoke the code as part of a VBA macro embedded in the sheet.

This link contains useful information about manipulating the parts of an Office package: http://msdn.microsoft.com/en-us/library/aa982683.aspx

The core.xml and app.xml (in the docProps folder) contain the document properties and might be a good location to store additional xml information.


问:
AppData / Similar for all OS : C++?
I'm looking to store some "preferences" for my C++ application.

Under windows I know I have to use the "AppData" folder, but I need the equivalent for Linux and OsX.

Is there some library or portable way to get such information in C++ ?

Here is the code I use currently:

```<code>#ifdef VD_OS_WINDOWS
    LPWSTR wszPath = NULL;
    HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_CREATE, NULL, &wszPath);

    _bstr_t bstrPath(wszPath);
    std::string strPath((char*)bstrPath);
    CoTaskMemFree(wszPath);

    return strPath;
#else
    char* path = getenv("XDG_CONFIG_HOME");
    if (!path)
        getenv("HOME") + ".local/share";

    return string(path);
#endif
</code>```

Thanks

答:
Historically on Linux the program stores its configuration data in a hidden file or folder (one beginning with a dot .) in the $HOME directory.

So something like:

```<code>$HOME/.my_prog_data.conf
</code>```

or

```<code>$HOME/.my_prog_data/config.conf
</code>```

In a more recent effort to clean up the $HOME directory nowadays programs tend to either use $HOME/.config or $HOME/.local/share rather than $HOME itself.

Title: AppData / Similar for all OS : C++?

Body:
I'm looking to store some "preferences" for my C++ application.

Under windows I know I have to use the "AppData" folder, but I need the equivalent for Linux and OsX.

Is there some library or portable way to get such information in C++ ?

Here is the code I use currently:

#ifdef VD_OS_WINDOWS
    LPWSTR wszPath = NULL;
    HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_CREATE, NULL, &wszPath);

    _bstr_t bstrPath(wszPath);
    std::string strPath((char*)bstrPath);
    CoTaskMemFree(wszPath);

    return strPath;
#else
    char* path = getenv("XDG_CONFIG_HOME");
    if (!path)
        getenv("HOME") + ".local/share";

    return string(path);
#endif

Thanks

Body:
Historically on Linux the program stores its configuration data in a hidden file or folder (one beginning with a dot .) in the $HOME directory.

So something like:

$HOME/.my_prog_data.conf

or

$HOME/.my_prog_data/config.conf

In a more recent effort to clean up the $HOME directory nowadays programs tend to either use $HOME/.config or $HOME/.local/share rather than $HOME itself.


问:
View variable value by hovering mouse over it in debug
Is it possible to setup Idea to show variable toString() value when I hover a mouse over it like in Visual Studio?

答: Go to Preferences > Build, execution, deployment > Debugger > Data Views and enable show value tooltip on code selection.


问:
python new line in txt file
I have written some code to save usernames, passwords and email addresses in a text file.
by reading an email from an input text file and writing it with the other information to an output text file.

However, in the output file, new-lines are appearing after the email.

For example:

```<code>abcd@gmail.com
,name,user,pass
</code>```

After changing the order of "email" and "name" it is happening again:

```<code>name,abcd@gmail.com
,user,pass.
</code>```

My email file looks like:

```<code>abcd@gmail.com
abcde@gmail.com
...
</code>```

How do I fix this issue?
Thanks in advance

My code:

```<code>line=""
driver = webdriver.Firefox()
f=open(r'C:\Users\11\Desktop\emailes.txt','r')

while True:
    password=id_generator()
    username=checkname()
    email=f.readline()
    if username !="":
            f2=open(r'C:\Users\11\Desktop\info.txt','a')
            f2.write(  email + "," + username + "," + username + "," +
            password)
            f2.write("\n")
            driver.get("xxxx")
            assert "xxxx" in driver.title
            driver.implicitly_wait(5)
            elem=driver.find_element_by_name("email")
            elem.clear
            elem.send_keys(email)
            elem=driver.find_element_by_name("fullName")
            elem.clear
            elem.send_keys(username)
            elem=driver.find_element_by_name("username")
            elem.clear
            elem.send_keys(username)
            elem=driver.find_element_by_name("password")
            elem.clear
            elem.send_keys(password)
            elem.send_keys(Keys.RETURN)
            f2.close()
f.close()
</code>```

答:
The issue is the string returned by the readline function will include the \n character.

Change:

```<code>email=f.readline()
</code>```

to

```<code>email=f.readline().strip()
</code>```

Title: python new line in txt file

Body:
I have written some code to save usernames, passwords and email addresses in a text file.
by reading an email from an input text file and writing it with the other information to an output text file.

However, in the output file, new-lines are appearing after the email.

For example:

abcd@gmail.com
,name,user,pass

After changing the order of "email" and "name" it is happening again:

name,abcd@gmail.com
,user,pass.

My email file looks like:

abcd@gmail.com
abcde@gmail.com
...

How do I fix this issue?
Thanks in advance

My code:

line=""
driver = webdriver.Firefox()
f=open(r'C:\Users\11\Desktop\emailes.txt','r')

while True:
    password=id_generator()
    username=checkname()
    email=f.readline()
    if username !="":
            f2=open(r'C:\Users\11\Desktop\info.txt','a')
            f2.write(  email + "," + username + "," + username + "," +
            password)
            f2.write("\n")
            driver.get("xxxx")
            assert "xxxx" in driver.title
            driver.implicitly_wait(5)
            elem=driver.find_element_by_name("email")
            elem.clear
            elem.send_keys(email)
            elem=driver.find_element_by_name("fullName")
            elem.clear
            elem.send_keys(username)
            elem=driver.find_element_by_name("username")
            elem.clear
            elem.send_keys(username)
            elem=driver.find_element_by_name("password")
            elem.clear
            elem.send_keys(password)
            elem.send_keys(Keys.RETURN)
            f2.close()
f.close()

Body:
The issue is the string returned by the readline function will include the \n character.

Change:

email=f.readline()

to

email=f.readline().strip()


问:
Getting number of characters in a unicode string in python
How can I get the number of codepoints in a string which may contain unicode characters 3 byte long. https://unicode-table.com/

For example for "I❤U" I would like to get 3.

Doing len(str) returns the number of bytes, so for the above example I would get 5.

答:
In my env, I tried your code. But my result of len("I❤U") is 3.</p>

```<code>>>> len("I❤U")
3
>>>
</code>```

Body:
In my env, I tried your code. But my result of len("I❤U") is 3.

>>> len("I❤U")
3
>>>


问:
Clear localStorage on every refresh in angular 2
I am storing a token in localStorage after authentication, but i need to delete it and redirect to some router each time i do a refresh.

I have no ideea how to do it in angular. I am using a very hacky way using plain js.

```<code>window.addEventListener('load', function (e) {
  if (window.sessionStorage !== null && (window.location.href.indexOf('/signin') === -1 &&  window.location.href.indexOf('confirm-user') === -1)) {
    window.sessionStorage.clear();
    window.location.href = '/signin';
  }
});
</code>```

I was thinking of adding an authentication guard, but i'm sure there should be a more angular way of doing this.

答:
I would suggest to create some auth service to store your token as a plain variable and a Guard to prevent redirects to secured pages without token. You can implement it in one service:

```<code>@Injectable()
export class AuthService implements CanActivate, CanActivateChild {
    token:String;
    canActivateChild = this.canActivate;
    constructor(private router: Router) {}
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (!this.token) {
            this.router.navigate(['/signin']);
            return false;
        }
        return true;
    }
}

export const ROUTES: Routes = [{
    path: 'signup',
    component: SignupComponent
}, {
    path: 'securedpath',
    component: SecuredComponent,
    canActivateChild: [AuthService],
    canActivate: [AuthService]
}]
</code>```

But this service should be singleton. Keep it in mind. Declare it in providers list of your app.module (or core.module if your using Jonh Papa's styleguide)

Body:
I am storing a token in localStorage after authentication, but i need to delete it and redirect to some router each time i do a refresh.

I have no ideea how to do it in angular. I am using a very hacky way using plain js.

window.addEventListener('load', function (e) {
  if (window.sessionStorage !== null && (window.location.href.indexOf('/signin') === -1 &&  window.location.href.indexOf('confirm-user') === -1)) {
    window.sessionStorage.clear();
    window.location.href = '/signin';
  }
});

I was thinking of adding an authentication guard, but i'm sure there should be a more angular way of doing this.

Body:
I would suggest to create some auth service to store your token as a plain variable and a Guard to prevent redirects to secured pages without token. You can implement it in one service:

@Injectable()
export class AuthService implements CanActivate, CanActivateChild {
    token:String;
    canActivateChild = this.canActivate;
    constructor(private router: Router) {}
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (!this.token) {
            this.router.navigate(['/signin']);
            return false;
        }
        return true;
    }
}

export const ROUTES: Routes = [{
    path: 'signup',
    component: SignupComponent
}, {
    path: 'securedpath',
    component: SecuredComponent,
    canActivateChild: [AuthService],
    canActivate: [AuthService]
}]

But this service should be singleton. Keep it in mind. Declare it in providers list of your app.module (or core.module if your using Jonh Papa's styleguide)


问:
how to force scrapy exit when there is an exception
I wrote a crawler with Scrapy.

There is a function in the pipeline where I write my data to a database. I use the logging module to log runtime logs.

I found that when my string have Chinese logging.error() will throw an exception. But the crawler keeps running!

I know this is a minor error but if there is a critical exception I will miss it if crawler keeps running.

My question is: Is there a setting that I can force Scrapy stop when there is an exception?

答:
In the process_item function of your spider you have an instance of spider.

To solve your problem you could catch the exceptions when you insert your data, then neatly stop you spider if you catch a certain exeption like this:

```<code> def process_item(self, item, spider):
    try:
        #Insert your item here
    except YourExceptionName:
        spider.crawler.engine.close_spider(self, reason='finished')
</code>```

Body:
In the process_item function of your spider you have an instance of spider.

To solve your problem you could catch the exceptions when you insert your data, then neatly stop you spider if you catch a certain exeption like this:

 def process_item(self, item, spider):
    try:
        #Insert your item here
    except YourExceptionName:
        spider.crawler.engine.close_spider(self, reason='finished')


问:
Rewriting of SQL query without Row_Number so that It could be mapped to Hibernate
Schema:

Table A: AID(PK), RECEIVE_DATE

Table B: BID(PK), AID(FK), MESSAGE, ITEMID, ITEMTYPE

Tables A-to-B have a one-to-many mapping.

Here is a working SQL query (in SQL Server) to find out the latest message grouped by ITEMID i.e for different ITEMID (of ITEMTYPE say as 'XYZ').

```<code>SELECT
    result.MESSAGE, result.ITEMID
FROM
    (SELECT
         *,
         ROW_NUMBER() OVER (PARTITION BY B.ITEMID ORDER BY A.RECEIVE_DATE desc) AS rn
    FROM
        A
    JOIN
        B ON A.AID = B.AID
    WHERE
        B.OBJREFTYPE = 'XYZ'
        AND B.SUBJECT IS NOT NULL) result
WHERE
    result.rn = 1
</code>```

Is it possible to rewrite this query without using ROW_NUMBER?

答:
Perhaps you can use something like this:</p>

```<code>SELECT
    b.MESSAGE, b.ITEMID
from a
inner join b on b.aid = a.aid
where a.receive_date in (select max(receive_date)
                                            from a a1
                                            inner join b b1 on b1.aid = a1.aid
                                            where b1.itemid = b.itemid
                                            );
</code>```

Body:
Schema:

Table A: AID(PK), RECEIVE_DATE

Table B: BID(PK), AID(FK), MESSAGE, ITEMID, ITEMTYPE

Tables A-to-B have a one-to-many mapping.

Here is a working SQL query (in SQL Server) to find out the latest message grouped by ITEMID i.e for different ITEMID (of ITEMTYPE say as 'XYZ').

SELECT
    result.MESSAGE, result.ITEMID
FROM
    (SELECT
         *,
         ROW_NUMBER() OVER (PARTITION BY B.ITEMID ORDER BY A.RECEIVE_DATE desc) AS rn
    FROM
        A
    JOIN
        B ON A.AID = B.AID
    WHERE
        B.OBJREFTYPE = 'XYZ'
        AND B.SUBJECT IS NOT NULL) result
WHERE
    result.rn = 1

Is it possible to rewrite this query without using ROW_NUMBER?

Body:
Perhaps you can use something like this:

SELECT
    b.MESSAGE, b.ITEMID
from a
inner join b on b.aid = a.aid
where a.receive_date in (select max(receive_date)
                                            from a a1
                                            inner join b b1 on b1.aid = a1.aid
                                            where b1.itemid = b.itemid
                                            );