问:
Bio.Blast (NCBIWWW) on multiple sequences fails and stalls
I am trying to parse a few dozen sequences through BLAST, using Bio.Blast with NCBIWWW, in Python 2.7. Not a problem there with one or a couple sequences, but the NCBIWWW.qblast() always stops after about 5-7 iterative BLAST searches. Importantly, the program does not crash and exit with an error - it just stalls, and freezes for ever. I have to exit the application manually. This is not a problem with Internet connection, either - no errors that would suggest this.

I have no idea what is wrong. Is there a mistake in my code that prevents multiple BLAST searches, or are there alternative algorithms for this purpose?

My code:

```<code>    from Bio.Blast import NCBIWWW
    import urllib

    def load_uniprot_fasta(identifier): #loads fasta file for a given UniProt identifier
        link = "http://www.uniprot.org/uniprot/" + identifier + ".fasta"

        f = urllib.urlopen(link)
        content = f.read()
        print content
        print "\n"
        new_file = open(str(identifier)+".seq", "w")
        new_file.write(content)

    evalue = 0.00001

    id_list = open("list.list", "r") #this file is a list of UniProt identifiers, every line is a new identifier

    for line in id_list:

        uniprot_id = ""
        uniprot_id = str(line).strip("\n")
        load_uniprot_fasta(uniprot_id) #creates a <uniprot_id>.fasta file
        fasta_object = open(str(uniprot_id)+".seq").read()
        result_handle = NCBIWWW.qblast("blastp", "swissprot", fasta_object)
        print "SUCCESS\n"
</code>```

答:
I don't see any intentional delay in your code -- have you read the NCBI BLAST Usage Guidlines:

The NCBI BLAST servers are a shared resource. We give priority to
  interactive users. ... To avoid problems, API users should comply with
  the following guidelines:

Do not contact the server more often than once every 10 seconds.

Do not poll for any single RID more often than once a minute.

Use the URL parameter email and tool, so that the NCBI can contact you if
there is a problem.

Run scripts weekends or between 9 pm and 5 am
Eastern time on weekdays if more than 50 searches will be
submitted.

Although NCBIWWW has a delay mechanism for how often it checks for results from a query, I don't see that it adds delays between queries. I'm not saying this is definitely your issue, but you could be outside the NCBI guidelines.  Another piece of advice I've seen with respect to this issue:

DO NOT submit searches that contain only single sequence! You need to
  batch the query and submit a set in a single search request.

Body:
I am trying to parse a few dozen sequences through BLAST, using Bio.Blast with NCBIWWW, in Python 2.7. Not a problem there with one or a couple sequences, but the NCBIWWW.qblast() always stops after about 5-7 iterative BLAST searches. Importantly, the program does not crash and exit with an error - it just stalls, and freezes for ever. I have to exit the application manually. This is not a problem with Internet connection, either - no errors that would suggest this.

I have no idea what is wrong. Is there a mistake in my code that prevents multiple BLAST searches, or are there alternative algorithms for this purpose?

My code:

    from Bio.Blast import NCBIWWW
    import urllib

    def load_uniprot_fasta(identifier): #loads fasta file for a given UniProt identifier
        link = "http://www.uniprot.org/uniprot/" + identifier + ".fasta"

        f = urllib.urlopen(link)
        content = f.read()
        print content
        print "\n"
        new_file = open(str(identifier)+".seq", "w")
        new_file.write(content)

    evalue = 0.00001

    id_list = open("list.list", "r") #this file is a list of UniProt identifiers, every line is a new identifier

    for line in id_list:

        uniprot_id = ""
        uniprot_id = str(line).strip("\n")
        load_uniprot_fasta(uniprot_id) #creates a <uniprot_id>.fasta file
        fasta_object = open(str(uniprot_id)+".seq").read()
        result_handle = NCBIWWW.qblast("blastp", "swissprot", fasta_object)
        print "SUCCESS\n"


来源: stackexchange

问:
Why am I obtaining these warning messages into the page of an old Joomla website?
I am not so into PHP and I have the following problem.

I reinstalled an old Joomla website (it is an old version of the CMS that I have to upgrade) on my local server (XAMPP).

The problem is that now I obtain some warning message like this into the pages:

```<code>Strict Standards: Only variables should be assigned by reference in C:\xampp\htdocs\erusma\plugins\content\embed_google_docs_viewer\embed_google_docs_viewer.php on line 61
</code>```

The website works fine but somewhere I have these warning. I think that maybe is something related to the PHP log settings or something like this.

What can I do to avoid these links? (I can't change the code)

答:
Here are a few options (listed in increasing level of difficulty):

Ignore the warning messages as they are likely doing no harm especially on local host.

Suppress the warning messages via the appropriate option in Joomla Global Configuration and/or directives in php.ini or .htaccess files.

Downgrade PHP to an earlier version.

Upgrade Joomla / third party extensions to later versions.

Fix the code.

ContentLicense: CC BY-SA 3.0

Body:
I am not so into PHP and I have the following problem.

I reinstalled an old Joomla website (it is an old version of the CMS that I have to upgrade) on my local server (XAMPP).

The problem is that now I obtain some warning message like this into the pages:

Strict Standards: Only variables should be assigned by reference in C:\xampp\htdocs\erusma\plugins\content\embed_google_docs_viewer\embed_google_docs_viewer.php on line 61

The website works fine but somewhere I have these warning. I think that maybe is something related to the PHP log settings or something like this.

What can I do to avoid these links? (I can't change the code)


问:
GDB x/i get wrong address
```<code>#include <stdio.h>

int main(int argc, char* argv[])
{
    printf("Hello world");
    return 0;
}
</code>```

I was using GDB to debug this program, after running several si command,

```<code>gdb-peda$
[----------------------------------registers-----------------------------------]
...
[-------------------------------------code-------------------------------------]
   0x4003ec:    add    BYTE PTR [rax],al
   0x4003ee:    add    BYTE PTR [rax],al
   0x4003f0:    push   QWORD PTR [rip+0x200c12]        # 0x601008
=> 0x4003f6:    jmp    QWORD PTR [rip+0x200c14]        # 0x601010
 | 0x4003fc:    nop    DWORD PTR [rax+0x0]
 | 0x400400 <printf@plt>:   jmp    QWORD PTR [rip+0x200c12]        # 0x601018
 | 0x400406 <printf@plt+6>: push   0x0
 | 0x40040b <printf@plt+11>:    jmp    0x4003f0
 |->   0x7ffff7dee870 <_dl_runtime_resolve_avx>:    push   rbx
       0x7ffff7dee871 <_dl_runtime_resolve_avx+1>:  mov    rbx,rsp
       0x7ffff7dee874 <_dl_runtime_resolve_avx+4>:  and    rsp,0xffffffffffffffe0
       0x7ffff7dee878 <_dl_runtime_resolve_avx+8>:  sub    rsp,0x180
                                                                  JUMP is taken
[------------------------------------stack-------------------------------------]
...
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
0x00000000004003f6 in ?? ()
</code>```

When i tried to show the instructions in *0x601010, i got an error, because GDB was using the wrong address (0xfffffffff7dee870), however, when using x/g command, the address (0x00007ffff7dee870) is correct.

```<code>gdb-peda$ x/4i *0x601010
   0xfffffffff7dee870:  Cannot access memory at address 0xfffffffff7dee870
gdb-peda$ x/g 0x601010
0x601010:   0x00007ffff7dee870
gdb-peda$ x/8xb 0x601010
0x601010:   0x70    0xe8    0xde    0xf7    0xff    0x7f    0x00    0x00
gdb-peda$ x/4i 0x00007ffff7dee870
   0x7ffff7dee870 <_dl_runtime_resolve_avx>:    push   rbx
   0x7ffff7dee871 <_dl_runtime_resolve_avx+1>:  mov    rbx,rsp
   0x7ffff7dee874 <_dl_runtime_resolve_avx+4>:  and    rsp,0xffffffffffffffe0
   0x7ffff7dee878 <_dl_runtime_resolve_avx+8>:  sub    rsp,0x180
</code>```

Can anyone explain the reason?

Thanks!

答:
This: x/4i *0x601010 is equivalent to x/4i (long) *(int*)0x601010. It loads (truncates) integer 0xf7dee870 from memory location 0x601010, then sign-extends it to long 0xfffffffff7dee870, and then tries to read instructions at this (bogus) address.

You want: x/4i *(long*)0x601010 or x/4i {long*}0x601010.

Title: GDB x/i get wrong address

Body:
#include <stdio.h>

int main(int argc, char* argv[])
{
    printf("Hello world");
    return 0;
}

I was using GDB to debug this program, after running several si command,

gdb-peda$
[----------------------------------registers-----------------------------------]
...
[-------------------------------------code-------------------------------------]
   0x4003ec:    add    BYTE PTR [rax],al
   0x4003ee:    add    BYTE PTR [rax],al
   0x4003f0:    push   QWORD PTR [rip+0x200c12]        # 0x601008
=> 0x4003f6:    jmp    QWORD PTR [rip+0x200c14]        # 0x601010
 | 0x4003fc:    nop    DWORD PTR [rax+0x0]
 | 0x400400 <printf@plt>:   jmp    QWORD PTR [rip+0x200c12]        # 0x601018
 | 0x400406 <printf@plt+6>: push   0x0
 | 0x40040b <printf@plt+11>:    jmp    0x4003f0
 |->   0x7ffff7dee870 <_dl_runtime_resolve_avx>:    push   rbx
       0x7ffff7dee871 <_dl_runtime_resolve_avx+1>:  mov    rbx,rsp
       0x7ffff7dee874 <_dl_runtime_resolve_avx+4>:  and    rsp,0xffffffffffffffe0
       0x7ffff7dee878 <_dl_runtime_resolve_avx+8>:  sub    rsp,0x180
                                                                  JUMP is taken
[------------------------------------stack-------------------------------------]
...
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
0x00000000004003f6 in ?? ()

When i tried to show the instructions in *0x601010, i got an error, because GDB was using the wrong address (0xfffffffff7dee870), however, when using x/g command, the address (0x00007ffff7dee870) is correct.

gdb-peda$ x/4i *0x601010
   0xfffffffff7dee870:  Cannot access memory at address 0xfffffffff7dee870
gdb-peda$ x/g 0x601010
0x601010:   0x00007ffff7dee870
gdb-peda$ x/8xb 0x601010
0x601010:   0x70    0xe8    0xde    0xf7    0xff    0x7f    0x00    0x00
gdb-peda$ x/4i 0x00007ffff7dee870
   0x7ffff7dee870 <_dl_runtime_resolve_avx>:    push   rbx
   0x7ffff7dee871 <_dl_runtime_resolve_avx+1>:  mov    rbx,rsp
   0x7ffff7dee874 <_dl_runtime_resolve_avx+4>:  and    rsp,0xffffffffffffffe0
   0x7ffff7dee878 <_dl_runtime_resolve_avx+8>:  sub    rsp,0x180

Can anyone explain the reason?

Thanks!


问:
Conflicting log4j configuration files in referenced java projects using eclipse. No log output from Spring as a result
I have two projects in eclipse - a Java project (let's call it Project A) and a Dynamic Web Project (Project B). Both projects use log4j and both have their own configuration files(as it is now, Project A uses a log4j.properties file and Project B a log4j.xml file). I require Project A to call code from Project B, so in Project A's build path, Project B is added as a required project. This seems to confuse log4j, as it loads it's configuration from Project B's log4j.xml file instead of Project A's log4j.properties. To combat this, I added the line "-Dlog4j.configuration=log4j.properties" in my launch configuration, which seems to work. Indeed, the formatting of the logger output is now as described in Project A's log4j.properties.

Both projects also use spring for database connections. The problem I am faced with now is that all logging output from spring seems to be missing. If I remove Project B from Project A's build path the problem goes away and I see the log output from Spring in the console. Is there something inherently wrong with my approach here? If not, any suggestions to make Spring's log output appear in the console while keeping Project B in Project A's build path?

Sorry for the long winded explanation. Any suggestions would be very appreciated.

答:
It sounds like you have have the log4j config file for Project B in the classpath. In both projects, make sure the config file is not in the classpath and use the -Dlog4j.configuration technique instead.

Usually, for things like this I try not to have multiple log4j files. If both projects have standalone Java main()s, then you may want to consider having a 'common' project for both projects that contains common configuration files like log4j.

ContentLicense: CC BY-SA 2.5


问:
Download csv from codeigniter mysql
I think I'm missing something obvious. I'm trying to export a dataset from a MySQL query to CSV without printing it to the browser.

Here's my code:

```<code><?php

$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

$data = file_get_contents('php://output'); // Read the file's contents
$name = 'data.csv';
force_download($name, $data);
fclose($fp);

?>
</code>```

$stories is my array created from the MySQL query.

Currently everything prints to the browser with no errors and no download but I would like to force a CSV download. How can I do this?

final working code:

```<code> $this->load->helper('download');

    $list = $stories;
    $fp = fopen('php://output', 'w');
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
        }

    $data = file_get_contents('php://output');
    $name = 'data.csv';

    // Build the headers to push out the file properly.
    header('Pragma: public');     // required
    header('Expires: 0');         // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private',false);
    header('Content-Disposition: attachment; filename="'.basename($name).'"');  // Add the file name
    header('Content-Transfer-Encoding: binary');
    header('Connection: close');
    exit();

    force_download($name, $data);
    fclose($fp);
</code>```

答:
i am use this and its work </p>

```<code>  header('Content-Type: text/csv; charset=utf-8');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header("Content-Disposition: attachment; filename=backup" . date('y-m-d') . ".csv");
            header('Last-Modified: ' . date('D M j G:i:s T Y'));
            $outss = fopen("php://output", "w");
            $this->db->order_by('ID', 'DESC');
            $query = $this->db->get('urls');
            foreach ($query->result_array() as $rows) {
                fputcsv($outss, $rows);
            }
            fclose($outss);
            return;
</code>```

Title: Download csv from codeigniter mysql

Body:
I think I'm missing something obvious. I'm trying to export a dataset from a MySQL query to CSV without printing it to the browser.

Here's my code:

<?php

$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

$data = file_get_contents('php://output'); // Read the file's contents
$name = 'data.csv';
force_download($name, $data);
fclose($fp);

?>

$stories is my array created from the MySQL query.

Currently everything prints to the browser with no errors and no download but I would like to force a CSV download. How can I do this?

final working code:

 $this->load->helper('download');

    $list = $stories;
    $fp = fopen('php://output', 'w');
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
        }

    $data = file_get_contents('php://output');
    $name = 'data.csv';

    // Build the headers to push out the file properly.
    header('Pragma: public');     // required
    header('Expires: 0');         // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private',false);
    header('Content-Disposition: attachment; filename="'.basename($name).'"');  // Add the file name
    header('Content-Transfer-Encoding: binary');
    header('Connection: close');
    exit();

    force_download($name, $data);
    fclose($fp);

Body:
i am use this and its work

  header('Content-Type: text/csv; charset=utf-8');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header("Content-Disposition: attachment; filename=backup" . date('y-m-d') . ".csv");
            header('Last-Modified: ' . date('D M j G:i:s T Y'));
            $outss = fopen("php://output", "w");
            $this->db->order_by('ID', 'DESC');
            $query = $this->db->get('urls');
            foreach ($query->result_array() as $rows) {
                fputcsv($outss, $rows);
            }
            fclose($outss);
            return;


问:
Call a function inside promise
I'm trying to find a way to call the method pageLoader.fetch twice in this promise. I already tried to separate it in a new promise but I get undefined when I try to get the variable links[0]. How to do this?</p>

```<code>pageLoader
  .fetch(url)
  .then(function(data) {
    links = html.orderdList(data);
  })
  .then(function() {
    return pageLoader.fetch(links[0]);
    //links[0] is undefined in the next line!?
  })
  .then(
    pageLoader
      .fetch(links[0])
      .then(function(innerLinks) {
        calLinks = html.unorderList(innerLinks);
      })
      .then(function() {
        return pageLoader.fetch("http:///example.com");
      })
      .catch(function(error) {
        console.log(error);
      })
  );
</code>```

答:
The line .then(pageLoader.fetch(links[0])...) is not doing what you probably want it to be doing. Calling it like that is the equivalent of doing this:

```<code>var myCallback = pageLoader.fetch(links[0]).then().then().catch();

pageLoader
  .fetch(url)
  .then(function(data) {
    links = html.orderdList(data);
  })
  .then(function() {
    return pageLoader.fetch(links[0]);
  })
  .then(myCallback)
</code>```

Your second fetch is actually being immediately executed before everything else and the result of that is being passed as the callback. You probably want to not call that code until the first fetch has happened, so you'll want to wrap it in a function (like with your other .then() statements).

I might also suggest that you could greatly simplify your code:

```<code>pageLoader
  .fetch(url)
  .then(function(data) {
    // this is called when the first fetch() returns
    links = html.orderdList(data);
    return pageLoader.fetch(links[0]);
    // returning a promise means that following .then()
    // statements will act on the returned promise rather than the original
  })
  .then(function(innerLinks) {
    // this is called when the second fetch() returns
    calLinks = html.unorderList(innerLinks);
    return pageLoader.fetch("http:///example.com");
  })
  .catch(function() {
    // this is called if the original promise or any of
    // the promises returned in the .then() callbacks throw errors
  });
</code>```

I found this article to be very helpful in explaining the best ways to use Promises, and some of the mistakes that can happen: https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

Title: Call a function inside promise

Body:
I'm trying to find a way to call the method pageLoader.fetch twice in this promise. I already tried to separate it in a new promise but I get undefined when I try to get the variable links[0]. How to do this?

pageLoader
  .fetch(url)
  .then(function(data) {
    links = html.orderdList(data);
  })
  .then(function() {
    return pageLoader.fetch(links[0]);
    //links[0] is undefined in the next line!?
  })
  .then(
    pageLoader
      .fetch(links[0])
      .then(function(innerLinks) {
        calLinks = html.unorderList(innerLinks);
      })
      .then(function() {
        return pageLoader.fetch("http:///example.com");
      })
      .catch(function(error) {
        console.log(error);
      })
  );

Body:
The line .then(pageLoader.fetch(links[0])...) is not doing what you probably want it to be doing. Calling it like that is the equivalent of doing this:

var myCallback = pageLoader.fetch(links[0]).then().then().catch();

pageLoader
  .fetch(url)
  .then(function(data) {
    links = html.orderdList(data);
  })
  .then(function() {
    return pageLoader.fetch(links[0]);
  })
  .then(myCallback)

Your second fetch is actually being immediately executed before everything else and the result of that is being passed as the callback. You probably want to not call that code until the first fetch has happened, so you'll want to wrap it in a function (like with your other .then() statements).

I might also suggest that you could greatly simplify your code:

pageLoader
  .fetch(url)
  .then(function(data) {
    // this is called when the first fetch() returns
    links = html.orderdList(data);
    return pageLoader.fetch(links[0]);
    // returning a promise means that following .then()
    // statements will act on the returned promise rather than the original
  })
  .then(function(innerLinks) {
    // this is called when the second fetch() returns
    calLinks = html.unorderList(innerLinks);
    return pageLoader.fetch("http:///example.com");
  })
  .catch(function() {
    // this is called if the original promise or any of
    // the promises returned in the .then() callbacks throw errors
  });

I found this article to be very helpful in explaining the best ways to use Promises, and some of the mistakes that can happen: https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html


问:
Count with WHERE clause from two tables in Oracle?
I have two tables, one called STUDENTS and the other CLASSES. I have to select all the students that are from the same class of one student, and this student has his own number id, and through this number id that I have to select everything.

```<code>TABLE STUDENTS

nr_rgm
nm_name
nm_father
nm_mother
dt_birth
id_sex

TABLE CLASSES

cd_class
nr_schoolyear
cd_school
cd_degree
nr_series
cd_class
cd_period
</code>```

So I tried something like that :

```<code>SELECT count(*) FROM students, classes WHERE id_sex = 'M' AND
cd_class = (SELECT cd_class FROM classes WHERE nr_rgm = '12150');
</code>```

But then it points an error, and the error is the follow :

single-row subquery returns more than one row

So, how can I make this work ?

答:
I think what you really would want to do is to simply join the two tables together rather than issuing a sub select:

```<code>SELECT count(*)
 FROM students s, classes c
  WHERE s.id_sex = 'M' AND c.nr_rgm = '12150' AND s.cd_class = c.cd_class;
</code>```

This way you just tell the database: Please count all the occurrences where my students.id_sex = 'M' and my classes.nr_rgm = '12150' AND all found studends.cd_class match those of my classes.cd_class.

The reason why your statement above fails is because the ordinary = operation, when not used in a join, will only expect one single value, like you do with s.id_sex='M' while your statement returns multiple values. To cope with that you have to use the IN operator which operates on lists.

However, you can and will achieve the very same with just joining the two tables together, and it will be much more efficient on bigger data sets.

One more note to the example above. If classes.nr_rgm is a field of data type NUMBER, don't use the ' around the value 12150 as it will lead to implicit type conversion. With other words, '12150' is a string and will have to be converted to NUMBER first before doing a comparison.

Body:
I have two tables, one called STUDENTS and the other CLASSES. I have to select all the students that are from the same class of one student, and this student has his own number id, and through this number id that I have to select everything.

TABLE STUDENTS

nr_rgm
nm_name
nm_father
nm_mother
dt_birth
id_sex

TABLE CLASSES

cd_class
nr_schoolyear
cd_school
cd_degree
nr_series
cd_class
cd_period

So I tried something like that :

SELECT count(*) FROM students, classes WHERE id_sex = 'M' AND
cd_class = (SELECT cd_class FROM classes WHERE nr_rgm = '12150');

But then it points an error, and the error is the follow :

single-row subquery returns more than one row

So, how can I make this work ?

Body:
I think what you really would want to do is to simply join the two tables together rather than issuing a sub select:

SELECT count(*)
 FROM students s, classes c
  WHERE s.id_sex = 'M' AND c.nr_rgm = '12150' AND s.cd_class = c.cd_class;

This way you just tell the database: Please count all the occurrences where my students.id_sex = 'M' and my classes.nr_rgm = '12150' AND all found studends.cd_class match those of my classes.cd_class.

The reason why your statement above fails is because the ordinary = operation, when not used in a join, will only expect one single value, like you do with s.id_sex='M' while your statement returns multiple values. To cope with that you have to use the IN operator which operates on lists.

However, you can and will achieve the very same with just joining the two tables together, and it will be much more efficient on bigger data sets.

One more note to the example above. If classes.nr_rgm is a field of data type NUMBER, don't use the ' around the value 12150 as it will lead to implicit type conversion. With other words, '12150' is a string and will have to be converted to NUMBER first before doing a comparison.


问:
Computation theory - DFA
i want to design a DFA of an alphabet {x,y,z} which accepts words with a number of 'z' multiples of 3 (eg "xzyyxzzyy")

Does anybody knows how? or which is the language that accepts it?

答:
You will need three states to keep track of the number of z's seen, modulo three; the states will cycle through each other on input z, and the one for #z(w) = 0 (mod 3) will be the only accepting state.

To allow any arbitrary x's and y's, each state can loop to itself on these inputs.

You might use q0, q1 and q2 for the states, making q0 the initial state and only accepting state. Then, you have three transitions f(qi, z) = wh where j = i + 1 (mod 3), three transitions f(q, x) = q and three transitions f(q, y) = q for a total of nine transitions.

Title: Computation theory - DFA


问:
How to use a word at end of function signature?
I'm trying to write a delegate interface like this:

```<code>// This delegate is just a sample. It could be any delegate.
// What's important here is the third function's signature.
protocol MyViewDelegate {
    func myView(_ myView: MyView, didDoSomething something: String)
    func myView(_ myView: MyView, didDoAnotherThing thing: String at: Date)
    func myView(_ myView: MyView, didDoYetSomethingElse)
}
</code>```

However, the third function is invalid syntax. It's used to notify the delegate that some specific event happened, so the signature is important and I want to keep all function signatures consistent.

Question: What's the recommended signature for the third function?

答:
It may not be very satisfying, but you simply can't do that. There is lots of precedent for writing these kinds of methods like this:

```<code>func myViewDidAskUserName(_ myView: MyView)
</code>```

For example, a common one from Apple:

```<code>func applicationDidFinishLaunching(_ application: UIApplication)
</code>```

Body:
I'm trying to write a delegate interface like this:

// This delegate is just a sample. It could be any delegate.
// What's important here is the third function's signature.
protocol MyViewDelegate {
    func myView(_ myView: MyView, didDoSomething something: String)
    func myView(_ myView: MyView, didDoAnotherThing thing: String at: Date)
    func myView(_ myView: MyView, didDoYetSomethingElse)
}

However, the third function is invalid syntax. It's used to notify the delegate that some specific event happened, so the signature is important and I want to keep all function signatures consistent.

Question: What's the recommended signature for the third function?

Body:
It may not be very satisfying, but you simply can't do that. There is lots of precedent for writing these kinds of methods like this:

func myViewDidAskUserName(_ myView: MyView)

For example, a common one from Apple:

func applicationDidFinishLaunching(_ application: UIApplication)


问:
JobService not starting after every minute

MyActivity.java

```<code>JobInfo jobInfo = new JobInfo.Builder(jobId,
            new ComponentName(getApplicationContext(), MyService.class))
            .setPeriodic(TimeUnit.MINUTES.toMillis(1))
            .setPersisted(true)
            .build();
    JobScheduler scheduler =
            (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    int s = scheduler.schedule(jobInfo);
</code>```

MyService.java

```<code>public class MyService extends JobService{
@Override
public boolean onStartJob(JobParameters params) {
    Log.v("SUCCESS", "Job started!");
    jobFinished(params, true);
    return false;
}

@Override
public boolean onStopJob(JobParameters params) {
    return false;
}
</code>```

I was trying to create a jobService that runs after every minute but if I put 1 in the method  .setPeriodic(TimeUnit.MINUTES.toMillis(1)), it does not seems to work however if i put 15 in it it seems to work fine. can anyone tell me how i can kick off myservice after every minute with Jobservice ?

答: Minimum interval for JobScheduler is 15 mins that's why 1 min interval is not working and 15 min is working

Body:
MyActivity.java

JobInfo jobInfo = new JobInfo.Builder(jobId,
            new ComponentName(getApplicationContext(), MyService.class))
            .setPeriodic(TimeUnit.MINUTES.toMillis(1))
            .setPersisted(true)
            .build();
    JobScheduler scheduler =
            (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    int s = scheduler.schedule(jobInfo);

MyService.java

public class MyService extends JobService{
@Override
public boolean onStartJob(JobParameters params) {
    Log.v("SUCCESS", "Job started!");
    jobFinished(params, true);
    return false;
}

@Override
public boolean onStopJob(JobParameters params) {
    return false;
}

I was trying to create a jobService that runs after every minute but if I put 1 in the method  .setPeriodic(TimeUnit.MINUTES.toMillis(1)), it does not seems to work however if i put 15 in it it seems to work fine. can anyone tell me how i can kick off myservice after every minute with Jobservice ?


问:
Latex Plot wrong Graph
You guys have an idea why latex plots the wrong function?

This is my function:

```<code>     \draw [scale=0.5,domain=-3:3,smooth,variable=\x] plot (\x,0.5*\x^4 - 3*\x^2+ 4) node[right] {$f(x)=0.5*x^4 - 3*x^2 + 4$};
</code>```

and this is the result:
Latex Graph

But is should look like this:
Right Graph

Thank you

答:
In tikz, parentheses are required to properly square negative numbers.

```<code>\draw [scale=0.5,domain=-3:3,smooth,variable=\x] plot (\x,{0.5*(\x)^4 - 3*(\x)^2+ 4}) node[right] {$f(x)=0.5*x^4 - 3*x^2 + 4$};
</code>```

This should produce what
you wanted.

Title: Latex Plot wrong Graph

Body:
You guys have an idea why latex plots the wrong function?

This is my function:

     \draw [scale=0.5,domain=-3:3,smooth,variable=\x] plot (\x,0.5*\x^4 - 3*\x^2+ 4) node[right] {$f(x)=0.5*x^4 - 3*x^2 + 4$};

and this is the result:
Latex Graph

But is should look like this:
Right Graph

Thank you

Body:
In tikz, parentheses are required to properly square negative numbers.

\draw [scale=0.5,domain=-3:3,smooth,variable=\x] plot (\x,{0.5*(\x)^4 - 3*(\x)^2+ 4}) node[right] {$f(x)=0.5*x^4 - 3*x^2 + 4$};

This should produce what
you wanted.


问:
code to mesh the area of overlapping
I'm using clipper library to determine the area of overlapping of two polygons in C++. After finding the overlapping area, I'm meshing it, or overlap it again with a grid that has a uniform step size (in this case, 0.06). Here is my code:

```<code>#include "cohesive.h"
#include "clipper.h"

int main() {

    using namespace ClipperLib;

    //Clipper library used to get the overlapping vertices
    Paths subj(1), clip(1), solution, clip1(1), mesh;
    //define 'subject' polygon
    subj[0] <<
    IntPoint(0*1e5,3*1e5) << IntPoint(3*1e5,4*1e5) <<
    IntPoint(3*1e5,-1*1e5) << IntPoint(0*1e5,0*1e5);

    //define 'clipping' polygon
    clip[0] <<
    IntPoint(-2*1e5,2*1e5) << IntPoint(2*1e5,2*1e5) <<
    IntPoint(2*1e5,-2*1e5) << IntPoint(-2*1e5,-2*1e5);

    //perform intersection ...
    Clipper c;
    c.AddPaths(subj, ptSubject, true);
    c.AddPaths(clip, ptClip, true);
    c.Execute(ctIntersection, solution, pftNonZero, pftNonZero);

    //size or number of vertices for the overlapping area
    int size = 0.0;
    vector<double> Xp;
    vector<double> Yp;
    if (solution.size() > 0)
    {
    size = solution[0].size();
    for (int k = 0; k < size; k++) {
    Xp.push_back(solution[0][k].X/1e5);
    Yp.push_back(solution[0][k].Y/1e5);
                                    }
    }

    //the overlapping area ---- Function to get the area of a polygon
    double A_lap = polygonArea(Xp, Yp, size);

    //Sort the Xs and Ys
    sort(Xp.begin(),Xp.end());
    sort(Yp.begin(),Yp.end());

    //The range of the mesh
    double xrange = Xp[size-1] - Xp[0];
    double yrange = Yp[size-1] - Yp[0];

    cout << "x range is  " << xrange << endl;
    cout << "y range is  " << yrange << endl;

    //Step to be used in the mesh (both X and Y)
    //Here the step is 30% of the particle size
    //The maximum soil particle size is 0.2
    double step = 0.3*0.2;
    int no = ((xrange >= yrange)?xrange:yrange)/step;

    //vectors xs and ys are the coordinates of the grid to be used in meshing
    vector<double> xs, ys;
    for (int k1 = 0 ; k1 < no+2 ; k1++) {

        xs.push_back(Xp[0]+k1*step);
        ys.push_back(Yp[0]+k1*step);
                                        }
    for (int i = 0; i < no+1; i++){
        for (int j = 0; j < no+1; j++){
            double A_lap1 = 0.0;
            int size1 = 0;
            clip1[0] << IntPoint(xs[i]*1e5,ys[j]*1e5) << IntPoint(xs[i]*1e5,ys[j+1]*1e5) <<
            IntPoint(xs[i+1]*1e5,ys[j+1]*1e5) << IntPoint(xs[i+1]*1e5,ys[j]*1e5);

            Clipper c1;
            c1.AddPaths(solution, ptSubject, true);
            c1.AddPaths(clip1, ptClip, true);
            c1.Execute(ctIntersection, mesh, pftNonZero, pftNonZero);
            vector<double> Xp1;
            vector<double> Yp1;
            if (mesh.size() > 0) {
              size1 = mesh[0].size();
               for (int k2 = 0; k2 < size1; k2++) {
               Xp1.push_back(mesh[0][k2].X/1e5);
               Yp1.push_back(mesh[0][k2].Y/1e5);
                                                  }

            //the overlapping area
            A_lap1 = polygonArea(Xp1, Yp1, size1);
            vector<double> Areas;
            Areas.push_back(A_lap1);
                                 }
            clip1.clear(); Xp1.clear(); Yp1.clear(); A_lap1 = 0.0; mesh.clear();
                                     }
                                 }
    return 0;
}
</code>```

I'm interested in getting a vector that has the overlapping of the big area with the grids. The code generates an error of (vector subscript is out of range) using microsoft visual studio 2010. Can you please help in this?

答:
Never mind guys! I got it!!

The code for meshing works very well. You just need to add:
Paths clip1(1), mesh;

after:
for (int j = 0; j < no + 1; j++) {

Title: code to mesh the area of overlapping

Body:
I'm using clipper library to determine the area of overlapping of two polygons in C++. After finding the overlapping area, I'm meshing it, or overlap it again with a grid that has a uniform step size (in this case, 0.06). Here is my code:

#include "cohesive.h"
#include "clipper.h"

int main() {

    using namespace ClipperLib;

    //Clipper library used to get the overlapping vertices
    Paths subj(1), clip(1), solution, clip1(1), mesh;
    //define 'subject' polygon
    subj[0] <<
    IntPoint(0*1e5,3*1e5) << IntPoint(3*1e5,4*1e5) <<
    IntPoint(3*1e5,-1*1e5) << IntPoint(0*1e5,0*1e5);

    //define 'clipping' polygon
    clip[0] <<
    IntPoint(-2*1e5,2*1e5) << IntPoint(2*1e5,2*1e5) <<
    IntPoint(2*1e5,-2*1e5) << IntPoint(-2*1e5,-2*1e5);

    //perform intersection ...
    Clipper c;
    c.AddPaths(subj, ptSubject, true);
    c.AddPaths(clip, ptClip, true);
    c.Execute(ctIntersection, solution, pftNonZero, pftNonZero);

    //size or number of vertices for the overlapping area
    int size = 0.0;
    vector<double> Xp;
    vector<double> Yp;
    if (solution.size() > 0)
    {
    size = solution[0].size();
    for (int k = 0; k < size; k++) {
    Xp.push_back(solution[0][k].X/1e5);
    Yp.push_back(solution[0][k].Y/1e5);
                                    }
    }

    //the overlapping area ---- Function to get the area of a polygon
    double A_lap = polygonArea(Xp, Yp, size);

    //Sort the Xs and Ys
    sort(Xp.begin(),Xp.end());
    sort(Yp.begin(),Yp.end());

    //The range of the mesh
    double xrange = Xp[size-1] - Xp[0];
    double yrange = Yp[size-1] - Yp[0];

    cout << "x range is  " << xrange << endl;
    cout << "y range is  " << yrange << endl;

    //Step to be used in the mesh (both X and Y)
    //Here the step is 30% of the particle size
    //The maximum soil particle size is 0.2
    double step = 0.3*0.2;
    int no = ((xrange >= yrange)?xrange:yrange)/step;

    //vectors xs and ys are the coordinates of the grid to be used in meshing
    vector<double> xs, ys;
    for (int k1 = 0 ; k1 < no+2 ; k1++) {

        xs.push_back(Xp[0]+k1*step);
        ys.push_back(Yp[0]+k1*step);
                                        }
    for (int i = 0; i < no+1; i++){
        for (int j = 0; j < no+1; j++){
            double A_lap1 = 0.0;
            int size1 = 0;
            clip1[0] << IntPoint(xs[i]*1e5,ys[j]*1e5) << IntPoint(xs[i]*1e5,ys[j+1]*1e5) <<
            IntPoint(xs[i+1]*1e5,ys[j+1]*1e5) << IntPoint(xs[i+1]*1e5,ys[j]*1e5);

            Clipper c1;
            c1.AddPaths(solution, ptSubject, true);
            c1.AddPaths(clip1, ptClip, true);
            c1.Execute(ctIntersection, mesh, pftNonZero, pftNonZero);
            vector<double> Xp1;
            vector<double> Yp1;
            if (mesh.size() > 0) {
              size1 = mesh[0].size();
               for (int k2 = 0; k2 < size1; k2++) {
               Xp1.push_back(mesh[0][k2].X/1e5);
               Yp1.push_back(mesh[0][k2].Y/1e5);
                                                  }

            //the overlapping area
            A_lap1 = polygonArea(Xp1, Yp1, size1);
            vector<double> Areas;
            Areas.push_back(A_lap1);
                                 }
            clip1.clear(); Xp1.clear(); Yp1.clear(); A_lap1 = 0.0; mesh.clear();
                                     }
                                 }
    return 0;
}

I'm interested in getting a vector that has the overlapping of the big area with the grids. The code generates an error of (vector subscript is out of range) using microsoft visual studio 2010. Can you please help in this?


问:
How i can get the last id of INSERT query when i'm using an external php file for doing all type of querys?
How i can get the last id of INSERT query when i'm using an external php file for doing all type of querys?
I have this class in php:

```<code>class DBManager
{
    private $db;
    private $queryResult;

    public static function getInsetance()
    {
        static $inst = null;
        if ($inst === null) {
            $inst = new DBManager();
        }
        return $inst;
    }

    private function __construct()
    {
        $this->db = mysqli_connect('localhost', 'root', '', 'mydb');
        if (mysqli_connect_errno()) {
            echo 'DB CONNECTION ERROR';
            die;
        } else {
            mysqli_query($this->db, 'SET NAMES UTF8');

        }
    }

    public function _destruct()
    {
        mysqli_close($this->db);
    }

    /**
     * @param $query
     * @return bool|mysqli_result
     */
    public function runQuery($query)
    {
        return $this->queryResult = mysqli_query($this->db, $query);
    }

    /**
     * @return mysql_result
     */
    public function getLastQueryResult()
    {
        return $this->queryResult;
    }
}
</code>```

And in another file, I want to do some different query. I want to get the last id of INSERT query in this code:

```<code>session_start();
require 'DBManager.php';

$db = DBManager::getInsetance();

    $query = "INSERT INTO `test`(`creator`, `name`) VALUES
             ('$creatorid','$name')";

    $result = $db->runQuery($query);
</code>```

答:
Have you tried this?

```<code>$last_id = $db->insert_id;
</code>```

Source

Body:
How i can get the last id of INSERT query when i'm using an external php file for doing all type of querys?
I have this class in php:

class DBManager
{
    private $db;
    private $queryResult;

    public static function getInsetance()
    {
        static $inst = null;
        if ($inst === null) {
            $inst = new DBManager();
        }
        return $inst;
    }

    private function __construct()
    {
        $this->db = mysqli_connect('localhost', 'root', '', 'mydb');
        if (mysqli_connect_errno()) {
            echo 'DB CONNECTION ERROR';
            die;
        } else {
            mysqli_query($this->db, 'SET NAMES UTF8');

        }
    }

    public function _destruct()
    {
        mysqli_close($this->db);
    }

    /**
     * @param $query
     * @return bool|mysqli_result
     */
    public function runQuery($query)
    {
        return $this->queryResult = mysqli_query($this->db, $query);
    }

    /**
     * @return mysql_result
     */
    public function getLastQueryResult()
    {
        return $this->queryResult;
    }
}

And in another file, I want to do some different query. I want to get the last id of INSERT query in this code:

session_start();
require 'DBManager.php';

$db = DBManager::getInsetance();

    $query = "INSERT INTO `test`(`creator`, `name`) VALUES
             ('$creatorid','$name')";

    $result = $db->runQuery($query);

Body:
Have you tried this?

$last_id = $db->insert_id;

Source


问:
pset8: "This RSS feed URL is deprecated" is returned in every JSON object returned. What does this mean?
From the execution of the function of articles in application.py, I am able to get the JSON of articles, however the first link is always that of the Google news headlines page and title is always This RSS feed URL is deprecated. I am suppose to return a JSON object of 5 news links, after the user clicks on a selected marker on the Google Map (which fires "geo" which is the postal code of the place marked by the selected marker).

As such:

```<code>  {
    "link": "https://news.google.com/news",
    "title": "This RSS feed URL is deprecated"
  }

  {
    "link": "http://news.google.com/news/url?
sa=t&fd=R&ct2=us&usg=AFQjCNHkxhtDRE9JHS9dxvxZigP-pPRMrQ&clid=c3a7d30bb8a4878e06b80cf16b898331&ei=hU0KWpDlIoa38QWkp6PgBw&url=http://cambridge.wickedlocal.com/news/20171113/cambridge-students-transform-foundry-building-into-public-safety-training-site",
    "title": "Cambridge students transform Foundry Building into public safety training site - Wicked Local Cambridge"
  }
]
</code>```

Is it because of my code and if yes, what leads to the return of this link and what does the title 'This RSS feed URL is deprecated' mean?

Here's my code for articles:

```<code>@app.route("/articles", methods=["GET"])
def articles():
    """Look up articles for geo."""
    # Get the postal code from geo in the HTML.
    geo = request.args.get("geo")
    if not geo:
        raise RunTimeError("missing geo")

    else:
        articles = lookup(geo)
        articles_list = []
        if len(articles) > 5:
            for i in range(0, 5):
                articles_list.append(articles[i])
            return jsonify(articles_list)
        else:
            return jsonify(articles_list)
</code>```

Turns out if I change the "for-loop"'s range to (1,6), it'll return me the right articles! But I don't understand why the first article will always be that of the homepage of Google News?

答:
It's because Google News is deprecating RSS feed URLs in favour of making some necessary improvement to the system. It is not related to your code in any way.

There's an article on the matter here.

Body:
From the execution of the function of articles in application.py, I am able to get the JSON of articles, however the first link is always that of the Google news headlines page and title is always This RSS feed URL is deprecated. I am suppose to return a JSON object of 5 news links, after the user clicks on a selected marker on the Google Map (which fires "geo" which is the postal code of the place marked by the selected marker).

As such:

  {
    "link": "https://news.google.com/news",
    "title": "This RSS feed URL is deprecated"
  }

  {
    "link": "http://news.google.com/news/url?
sa=t&fd=R&ct2=us&usg=AFQjCNHkxhtDRE9JHS9dxvxZigP-pPRMrQ&clid=c3a7d30bb8a4878e06b80cf16b898331&ei=hU0KWpDlIoa38QWkp6PgBw&url=http://cambridge.wickedlocal.com/news/20171113/cambridge-students-transform-foundry-building-into-public-safety-training-site",
    "title": "Cambridge students transform Foundry Building into public safety training site - Wicked Local Cambridge"
  }
]

Is it because of my code and if yes, what leads to the return of this link and what does the title 'This RSS feed URL is deprecated' mean?

Here's my code for articles:

@app.route("/articles", methods=["GET"])
def articles():
    """Look up articles for geo."""
    # Get the postal code from geo in the HTML.
    geo = request.args.get("geo")
    if not geo:
        raise RunTimeError("missing geo")

    else:
        articles = lookup(geo)
        articles_list = []
        if len(articles) > 5:
            for i in range(0, 5):
                articles_list.append(articles[i])
            return jsonify(articles_list)
        else:
            return jsonify(articles_list)

Turns out if I change the "for-loop"'s range to (1,6), it'll return me the right articles! But I don't understand why the first article will always be that of the homepage of Google News?


问:
How to save worksheets as CSV files in UTF-8 format with Excel for Mac 2011?
I have the following Excel VBA script which I use in Excel for Mac 2011 to export all the worksheets of an Excel file to .csv files.

```<code>Sub save_all_csv()
    On Error Resume Next
    Dim ExcelFileName As String
    ExcelFileName = ThisWorkbook.Name
    For Each objWorksheet In ThisWorkbook.Worksheets
        ExcelFileNameWithoutExtension = RemoveExtension(ExcelFileName)
        CsvFileName = ExcelFileNameWithoutExtension & "__" & objWorksheet.Name & ".csv"
        Application.DisplayAlerts = False
        objWorksheet.SaveAs Filename:="data:storage:original_excel:" & CsvFileName, FileFormat:=xlCSV, CreateBackup:=False
        Application.DisplayAlerts = True
    Next
    Application.DisplayAlerts = False
    Application.Quit
End Sub
Function RemoveExtension(strFileName As String)
    strFileName = Replace(strFileName, ".xlsx", "")
    strFileName = Replace(strFileName, ".xls", "")
    RemoveExtension = strFileName
End Function
</code>```

The problem is that they save as Western Mac OS Roman which I can't get to convert to UTF-8 via PHP, so I would like to have VBA save these files in UTF-8 format in the first place.

I've found some solutions for saving text from VBA via a Stream object and with CreateObject but it's apparently not possibile on the Mac to use CreateObject to write directly to files.

How can I save worksheets as CSV files in UTF-8 format with Excel for Mac 2011?

答:
I think you're right that you'll have to do the file creation yourself, and I'm quite sure you can't use CreateObject to make streams. However, you may want to look into using Open, Write etc (lots of examples around, but  here's one). I'd make a very small experimental one first, just to check what encoding that ends up with, though.

Chris

Body:
I have the following Excel VBA script which I use in Excel for Mac 2011 to export all the worksheets of an Excel file to .csv files.

Sub save_all_csv()
    On Error Resume Next
    Dim ExcelFileName As String
    ExcelFileName = ThisWorkbook.Name
    For Each objWorksheet In ThisWorkbook.Worksheets
        ExcelFileNameWithoutExtension = RemoveExtension(ExcelFileName)
        CsvFileName = ExcelFileNameWithoutExtension & "__" & objWorksheet.Name & ".csv"
        Application.DisplayAlerts = False
        objWorksheet.SaveAs Filename:="data:storage:original_excel:" & CsvFileName, FileFormat:=xlCSV, CreateBackup:=False
        Application.DisplayAlerts = True
    Next
    Application.DisplayAlerts = False
    Application.Quit
End Sub
Function RemoveExtension(strFileName As String)
    strFileName = Replace(strFileName, ".xlsx", "")
    strFileName = Replace(strFileName, ".xls", "")
    RemoveExtension = strFileName
End Function

The problem is that they save as Western Mac OS Roman which I can't get to convert to UTF-8 via PHP, so I would like to have VBA save these files in UTF-8 format in the first place.

I've found some solutions for saving text from VBA via a Stream object and with CreateObject but it's apparently not possibile on the Mac to use CreateObject to write directly to files.

How can I save worksheets as CSV files in UTF-8 format with Excel for Mac 2011?


问:
MySQL record between fixed date range
I have an small application which was build with CodeIgniter 3 and need to perform a report which will be converted to Chart.js. The report should be in yearly basis but at given specific date every month. The requirement are all data count must be from 4th to 3rd monthly. Like this:

For example January Report would be from 4th January to 3rd February, 4th February to 3rd March,... and so on.

I have created a MySQL query but I'm stuck on how to get the date too date. My Query are as follows:

```<code>SELECT DATE_FORMAT(odd_date_created, '%Y') as 'year',
DATE_FORMAT(odd_date_created, '%m') as 'month',
COUNT(odd_id) as 'total', status
FROM odd_data
WHERE status = $id and
GROUP BY DATE_FORMAT(odd_date_created, '%Y%m'), status
</code>```

I'm new to MySQl. Could somebody help me on this. I'm stuck where should I put the date to date query.

答:
Firstly I want to caution you not to use "between" with the following when you come to join your data, use this method instead data.date >= r.period_start_dt and data.date < r.period_end_dt

Secondly I am assuming your data does have dates or timestamps and that will fall between the calculated ranges that follow:

```<code>set @year :=2017;

select
       *
from (
        select
               start_dt + INTERVAL m.n MONTH     period_start_dt
             , start_dt + INTERVAL m.n + 1 MONTH period_end_dt
        from (
               select str_to_date(concat(@year,'-01-04'),'%Y-%m-%d') start_dt ) seed
        cross join (select 0 n union all
                    select 1 union all
                    select 2 union all
                    select 3 union all
                    select 4 union all
                    select 5 union all
                    select 6 union all
                    select 7 union all
                    select 8 union all
                    select 9 union all
                    select 10 union all
                    select 11
                   ) m
     ) r
## LEFT JOIN YOUR DATA
## ON data.date >= r.period_start_dt and data.date < r.period_end_dt
</code>```

Example ranges: (produce you own at this demo: http://rextester.com/CHTKSA95303 )

```<code>nb dd.mm.yyyy (.de format)
+----+---------------------+---------------------+
|    |   period_start_dt   |    period_end_dt    |
+----+---------------------+---------------------+
|  1 | 04.01.2017 00:00:00 | 04.02.2017 00:00:00 |
|  2 | 04.02.2017 00:00:00 | 04.03.2017 00:00:00 |
|  3 | 04.03.2017 00:00:00 | 04.04.2017 00:00:00 |
|  4 | 04.04.2017 00:00:00 | 04.05.2017 00:00:00 |
|  5 | 04.05.2017 00:00:00 | 04.06.2017 00:00:00 |
|  6 | 04.06.2017 00:00:00 | 04.07.2017 00:00:00 |
|  7 | 04.07.2017 00:00:00 | 04.08.2017 00:00:00 |
|  8 | 04.08.2017 00:00:00 | 04.09.2017 00:00:00 |
|  9 | 04.09.2017 00:00:00 | 04.10.2017 00:00:00 |
| 10 | 04.10.2017 00:00:00 | 04.11.2017 00:00:00 |
| 11 | 04.11.2017 00:00:00 | 04.12.2017 00:00:00 |
| 12 | 04.12.2017 00:00:00 | 04.01.2018 00:00:00 |
+----+---------------------+---------------------+
</code>```

Title: MySQL record between fixed date range

Body:
I have an small application which was build with CodeIgniter 3 and need to perform a report which will be converted to Chart.js. The report should be in yearly basis but at given specific date every month. The requirement are all data count must be from 4th to 3rd monthly. Like this:

For example January Report would be from 4th January to 3rd February, 4th February to 3rd March,... and so on.

I have created a MySQL query but I'm stuck on how to get the date too date. My Query are as follows:

SELECT DATE_FORMAT(odd_date_created, '%Y') as 'year',
DATE_FORMAT(odd_date_created, '%m') as 'month',
COUNT(odd_id) as 'total', status
FROM odd_data
WHERE status = $id and
GROUP BY DATE_FORMAT(odd_date_created, '%Y%m'), status

I'm new to MySQl. Could somebody help me on this. I'm stuck where should I put the date to date query.

Body:
Firstly I want to caution you not to use "between" with the following when you come to join your data, use this method instead data.date >= r.period_start_dt and data.date < r.period_end_dt

Secondly I am assuming your data does have dates or timestamps and that will fall between the calculated ranges that follow:

set @year :=2017;

select
       *
from (
        select
               start_dt + INTERVAL m.n MONTH     period_start_dt
             , start_dt + INTERVAL m.n + 1 MONTH period_end_dt
        from (
               select str_to_date(concat(@year,'-01-04'),'%Y-%m-%d') start_dt ) seed
        cross join (select 0 n union all
                    select 1 union all
                    select 2 union all
                    select 3 union all
                    select 4 union all
                    select 5 union all
                    select 6 union all
                    select 7 union all
                    select 8 union all
                    select 9 union all
                    select 10 union all
                    select 11
                   ) m
     ) r
## LEFT JOIN YOUR DATA
## ON data.date >= r.period_start_dt and data.date < r.period_end_dt

Example ranges: (produce you own at this demo: http://rextester.com/CHTKSA95303 )

nb dd.mm.yyyy (.de format)
+----+---------------------+---------------------+
|    |   period_start_dt   |    period_end_dt    |
+----+---------------------+---------------------+
|  1 | 04.01.2017 00:00:00 | 04.02.2017 00:00:00 |
|  2 | 04.02.2017 00:00:00 | 04.03.2017 00:00:00 |
|  3 | 04.03.2017 00:00:00 | 04.04.2017 00:00:00 |
|  4 | 04.04.2017 00:00:00 | 04.05.2017 00:00:00 |
|  5 | 04.05.2017 00:00:00 | 04.06.2017 00:00:00 |
|  6 | 04.06.2017 00:00:00 | 04.07.2017 00:00:00 |
|  7 | 04.07.2017 00:00:00 | 04.08.2017 00:00:00 |
|  8 | 04.08.2017 00:00:00 | 04.09.2017 00:00:00 |
|  9 | 04.09.2017 00:00:00 | 04.10.2017 00:00:00 |
| 10 | 04.10.2017 00:00:00 | 04.11.2017 00:00:00 |
| 11 | 04.11.2017 00:00:00 | 04.12.2017 00:00:00 |
| 12 | 04.12.2017 00:00:00 | 04.01.2018 00:00:00 |
+----+---------------------+---------------------+


问:
@ControllerAdvice exception handler method not get called
I am working on sample demo application for Exception Handling in Spring MVC.I am trying Exception Handling With @ControllerAdvice

I followed steps as describe in this link.

But when i run my application i get the following error

```<code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.test.core.ApplicationException
</code>```

For more details following are the classes I am working on

ApplicationException.java

```<code>public class ApplicationException extends RuntimeException{

/**
 *
 */
private static final long serialVersionUID = -9061684361606685158L;
private ErrorStatus errorStatus;
private int msgNumber;
private Object []args;

public ApplicationException(){}

public ApplicationException(ErrorStatus errorStatus, int msgNumber,
        Object[] args) {
    this.errorStatus = errorStatus;
    this.msgNumber = msgNumber;
    this.args = args;
  }
    //getter setters
}
</code>```

Controller class

ApplicationExceptionController.java

```<code> @Controller
@RequestMapping("/exception")
public class ApplicationExceptionController {

@RequestMapping(value="/error",method=RequestMethod.GET)
@ResponseBody
public void helloException()
{
    throw new ApplicationException(ErrorStatus.NotFound,1,new Object[]{"Website"});

  //here ErrorStatus is a enum class
}
}
</code>```

And here is the GlobalExceptionHandler class

GlobalExceptionHandler.java

```<code>@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler
public void notFount(){
    System.out.println("----------CaughtApplicationException-----------");
}
}
</code>```

dispatcher-servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation=
    "http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<context:component-scan  base-package="com.test.controller,com.test.core" />
<mvc:annotation-driven />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
     <list> <ref bean="jsonConverter"/></list>
    </property>
</bean>

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
     <property name="supportedMediaTypes" value="application/json" />
</bean>
</code>```

I run above application with       http://localhost:8080/SpringExceptionHandling/exception/error this url

But I get the following Exception

```<code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.test.core.ApplicationException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

root cause

com.test.core.ApplicationException
com.test.controller.ApplicationExceptionController.helloException(ApplicationExceptionController.java:19)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
</code>```

I go through @ControllerAdvice exception handler method are not get called this link but still stuck with the same problem
Please help me to get the solution.I am not getting the actual cause for this exception.

答:
In my case, the handler method is not called because of additional parameter in the method signature.

Not working:

```<code>@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handle404(HttpServletRequest request, Exception e,  @RequestHeader(value = "referer", required = false) final String referer) {
    ...
}
</code>```

The referer parameter is what caused the handler method not being called. The problem is solved after removing the parameter.

Works:

```<code>@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handle404(HttpServletRequest request, Exception e) {
    ...
}
</code>```

Body:
I am working on sample demo application for Exception Handling in Spring MVC.I am trying Exception Handling With @ControllerAdvice

I followed steps as describe in this link.

But when i run my application i get the following error

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.test.core.ApplicationException

For more details following are the classes I am working on

ApplicationException.java

public class ApplicationException extends RuntimeException{

/**
 *
 */
private static final long serialVersionUID = -9061684361606685158L;
private ErrorStatus errorStatus;
private int msgNumber;
private Object []args;

public ApplicationException(){}

public ApplicationException(ErrorStatus errorStatus, int msgNumber,
        Object[] args) {
    this.errorStatus = errorStatus;
    this.msgNumber = msgNumber;
    this.args = args;
  }
    //getter setters
}

Controller class

ApplicationExceptionController.java

 @Controller
@RequestMapping("/exception")
public class ApplicationExceptionController {

@RequestMapping(value="/error",method=RequestMethod.GET)
@ResponseBody
public void helloException()
{
    throw new ApplicationException(ErrorStatus.NotFound,1,new Object[]{"Website"});

  //here ErrorStatus is a enum class
}
}

And here is the GlobalExceptionHandler class

GlobalExceptionHandler.java

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler
public void notFount(){
    System.out.println("----------CaughtApplicationException-----------");
}
}

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation=
    "http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<context:component-scan  base-package="com.test.controller,com.test.core" />
<mvc:annotation-driven />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
     <list> <ref bean="jsonConverter"/></list>
    </property>
</bean>

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
     <property name="supportedMediaTypes" value="application/json" />
</bean>

I run above application with       http://localhost:8080/SpringExceptionHandling/exception/error this url

But I get the following Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.test.core.ApplicationException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

root cause

com.test.core.ApplicationException
com.test.controller.ApplicationExceptionController.helloException(ApplicationExceptionController.java:19)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

I go through @ControllerAdvice exception handler method are not get called this link but still stuck with the same problem
Please help me to get the solution.I am not getting the actual cause for this exception.

Body:
In my case, the handler method is not called because of additional parameter in the method signature.

Not working:

@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handle404(HttpServletRequest request, Exception e,  @RequestHeader(value = "referer", required = false) final String referer) {
    ...
}

The referer parameter is what caused the handler method not being called. The problem is solved after removing the parameter.

Works:

@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handle404(HttpServletRequest request, Exception e) {
    ...
}


问:
how to modify the background of a select2 when no value is captured
I have a select2 which is as follows:

```<code><section>
                            <div class="row">
                                <div class="form-group">
                                    <label class="col col-2">ConceptoPrueba</label>
                                    <div class="col col-10">
                                        <select name="Prueba" id="Prueba" style="width: 100%" class="select2" runat="server">
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </section>
</code>```

And when I do not capture value, I want it to change color red indicating that it is mandatory
I have this in the validation works:

```<code> function Validar() {
            if ($("#ctl00_contenido_Prueba").val() == null || $("#ctl00_contenido_Prueba").val() == "0") {
                ShowError("Concepto", "El concepto es obligatorio.");
                $('#ctl00_contenido_Prueba').parent().removeClass('state-success').addClass("state-error");
                $('#ctl00_contenido_Prueba').removeClass('valid');
            }};
</code>```

the validation is correct but I do not reliza the change of color someone can support me

答:
I didn't see any #ctl00_contenido_Prueba id in your HTML code

To get the value from select:

$( "#Prueba" ).val();

Body:
I have a select2 which is as follows:

                                    ConceptoPrueba

                                        <select name="Prueba" id="Prueba" style="width: 100%" class="select2" runat="server">
                                        </select>

And when I do not capture value, I want it to change color red indicating that it is mandatory
I have this in the validation works:

 function Validar() {
            if ($("#ctl00_contenido_Prueba").val() == null || $("#ctl00_contenido_Prueba").val() == "0") {
                ShowError("Concepto", "El concepto es obligatorio.");
                $('#ctl00_contenido_Prueba').parent().removeClass('state-success').addClass("state-error");
                $('#ctl00_contenido_Prueba').removeClass('valid');
            }};

the validation is correct but I do not reliza the change of color someone can support me


问:
Saving dotchart with shiny
Do you see any mistake here?
the ggsave works, but png(file=file) part not - it saves empty white image.

```<code>output$savePlotAmount <- downloadHandler(
    filename = "amount.png",
    content = function(file) {
      if(input$plotType == "dot"){
        png(file = file)
        plotAmount()
        dev.off()
      }else{
        ggsave(plotAmount(), filename = file)
      }

    })
</code>```

I spent "hours" on trying to repair it but I don't know what's going on. Sorry that the example is not reproductible, but it is to hard to reproduct all app.

EDIT:
What is plotAmount():

```<code>plotAmount <- reactive({
    if(input$plotType == "violin") {
      plotAmount <- ggplot(values$x, aes_string(x = input$groupedBy, y = input$yVariableContinous)) +
        geom_violin() +
        ggtitle(paste0(input$yVariableContinous, " grouped by ", input$groupedBy)) +
        scale_y_continuous(limits = c(0, quantile(values$x[,input$yVariableContinous] , 0.95, na.rm = T)))
    }
    if(input$plotType == "boxplot") {
      plotAmount <- ggplot(values$x, aes_string(x = input$groupedBy, y = input$yVariableContinous)) +
        geom_boxplot(outlier.shape = NA) +
        ggtitle(paste0(input$yVariableContinous, " grouped by ", input$groupedBy)) +
        scale_y_continuous(limits = c(0, quantile(values$x[,input$yVariableContinous] , 0.95, na.rm = T)))
    }
    if(input$plotType == "dot") {
      var <- ifelse(input$groupedBy == 1, input$xVariable, input$groupedBy)
      agregat <- aggregate(x = values$x[,input$yVariableContinous], by = list(g = values$x[,var], xx = values$x[,input$xVariable]), FUN = input$valueAs)
      dotchart(agregat$x, labels = agregat$xx,
               groups = as.factor(agregat$g),
               color = brewer.pal(9,"Set1")[as.numeric(as.factor(agregat$g))],
               xlab = "salary",
               cex = .75,
               main = paste0(input$yVariableContinous, " for ", input$xVariable,
                             "\ngrouped by ", input$groupedBy),
               xlim = c(min(values$x[,input$yVariableContinous], na.rm = T), quantile(values$x[,input$yVariableContinous] , 0.95, na.rm = T)),
               pch = 16
      )
    }
</code>```

答: ggplot2 plots need to be print()'d to render.

Title: Saving dotchart with shiny

Body:
Do you see any mistake here?
the ggsave works, but png(file=file) part not - it saves empty white image.

output$savePlotAmount <- downloadHandler(
    filename = "amount.png",
    content = function(file) {
      if(input$plotType == "dot"){
        png(file = file)
        plotAmount()
        dev.off()
      }else{
        ggsave(plotAmount(), filename = file)
      }

    })

I spent "hours" on trying to repair it but I don't know what's going on. Sorry that the example is not reproductible, but it is to hard to reproduct all app.

EDIT:
What is plotAmount():

plotAmount <- reactive({
    if(input$plotType == "violin") {
      plotAmount <- ggplot(values$x, aes_string(x = input$groupedBy, y = input$yVariableContinous)) +
        geom_violin() +
        ggtitle(paste0(input$yVariableContinous, " grouped by ", input$groupedBy)) +
        scale_y_continuous(limits = c(0, quantile(values$x[,input$yVariableContinous] , 0.95, na.rm = T)))
    }
    if(input$plotType == "boxplot") {
      plotAmount <- ggplot(values$x, aes_string(x = input$groupedBy, y = input$yVariableContinous)) +
        geom_boxplot(outlier.shape = NA) +
        ggtitle(paste0(input$yVariableContinous, " grouped by ", input$groupedBy)) +
        scale_y_continuous(limits = c(0, quantile(values$x[,input$yVariableContinous] , 0.95, na.rm = T)))
    }
    if(input$plotType == "dot") {
      var <- ifelse(input$groupedBy == 1, input$xVariable, input$groupedBy)
      agregat <- aggregate(x = values$x[,input$yVariableContinous], by = list(g = values$x[,var], xx = values$x[,input$xVariable]), FUN = input$valueAs)
      dotchart(agregat$x, labels = agregat$xx,
               groups = as.factor(agregat$g),
               color = brewer.pal(9,"Set1")[as.numeric(as.factor(agregat$g))],
               xlab = "salary",
               cex = .75,
               main = paste0(input$yVariableContinous, " for ", input$xVariable,
                             "\ngrouped by ", input$groupedBy),
               xlim = c(min(values$x[,input$yVariableContinous], na.rm = T), quantile(values$x[,input$yVariableContinous] , 0.95, na.rm = T)),
               pch = 16
      )
    }


问:
How do I add a parameter to a method in my interface in C# without breaking clients?
I wrote a public interface in my C# application that has the following method:

```<code>IMimic OpenMimic(string mimicPath, string frameModel, string branch, int regionId);
</code>```

I also wrote an abstract base class that implements this interface, and at the same time, I wrote a public sealed class that implements this base class.

Now, I need to add a parameter to this method like this:

```<code>IMimic OpenMimic(string mimicPath, string frameModel, string branch, int regionId, IAlsContext mimicContext);
</code>```

This implies I need to make changes to my base class and also my sealed implementation.

Right now, there are client applications (written by other teams in my organization) that use this class and call the old version of this method. If I change this method, I'm forced to change the interface as well.

Won't this break the clients? Is this an example of a typical breaking change? How can I fix it so that clients don't break? The problem is that this new parameter is a required parameter and I'm not an expert in interface programming.

Thanks,

答:
Won't this break the clients?

Yep.

Is this an example of a typical breaking change?

Yep.

How can I fix it so that clients don't break?

You never, ever, ever change a public interface that a client depends on.

Write a new interface -- possibly one that extends the old interface -- and with a new method that has the right signature.

Then implement your classes to implement the new and the old interface. You might have to use an explicit interface method to do so.

The clients keep on working; they can choose to move to the new interface on their schedule.

You might also consider marking the old interface as "obsolete" in the next version, and then remove it the version after that.

The problem is that this new parameter is a required parameter and I'm not an expert in interface programming.

Well, now you know more about interface programming than you did yesterday!

Body:
I wrote a public interface in my C# application that has the following method:

IMimic OpenMimic(string mimicPath, string frameModel, string branch, int regionId);

I also wrote an abstract base class that implements this interface, and at the same time, I wrote a public sealed class that implements this base class.

Now, I need to add a parameter to this method like this:

IMimic OpenMimic(string mimicPath, string frameModel, string branch, int regionId, IAlsContext mimicContext);

This implies I need to make changes to my base class and also my sealed implementation.

Right now, there are client applications (written by other teams in my organization) that use this class and call the old version of this method. If I change this method, I'm forced to change the interface as well.

Won't this break the clients? Is this an example of a typical breaking change? How can I fix it so that clients don't break? The problem is that this new parameter is a required parameter and I'm not an expert in interface programming.

Thanks,


问:
How to recover lost svn password?
I just finished reading about passwords in "Version Control with Subversion" but could not find the solution for a lost and forgotten password.
Is there a way to recover a lost svn password?</p>

答:
As you've probably read, there are many ways of setting up a Subversion server.

svnserve

This is the simplest option. Passwords are stored in a plain text file on the server. Recovery is trivial.

svnserve over SSH

Subversion is not involved in the authentication process, that is delegated to SSH. All SSH "forgotten password" problems can be solved.

Apache server

Subversion is not involved in the authentication process, that is delegated to Apache. There are many different authentication methods available for Apache, all of which have some kind of recovery process.

Title: How to recover lost svn password?


问:
How can I loop through a Spark data frame
How can I loop through a Spark data frame?
I have a data frame that consists of:

time, id, direction
10, 4, True  //here 4 enters --> (4,)
20, 5, True  //here 5 enters --> (4,5)
34, 5, False //here 5 leaves --> (4,)
67, 6, True  //here 6 enters --> (4,6)
78, 6, False //here 6 leaves --> (4,)
99, 4, False //here 4 leaves --> ()
```

<p>it is sorted by time and now I would like to step through and accumulate the valid ids. The ids enter on direction==True and exit on direction==False</p>

<p>so the resulting RDD should look like this</p>

<pre class="lang-none prettyprint-override"><code>time, valid_ids
(10, (4,))
(20, (4,5))
(34, (4,))
(67, (4,6))
(78, (4,)
(99, ())
</code>```

I know that this will not parallelize, but the df is not that big. So how could this be done in Spark/Scala?

答:
Use of var is not recommended for scala developers but still I am posting answer using var

```<code>var collectArray = Array.empty[Int]
df.rdd.collect().map(row => {
  if(row(2).toString.equalsIgnoreCase("true")) collectArray = collectArray :+ row(1).asInstanceOf[Int]
  else collectArray = collectArray.drop(1)
  (row(0), collectArray.toList)
})
</code>```

this should give you result as

```<code>(10,List(4))
(20,List(4, 5))
(34,List(5))
(67,List(5, 6))
(78,List(6))
(99,List())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I loop through a Spark data frame?
I have a data frame that consists of:

time, id, direction
10, 4, True  //here 4 enters --> (4,)
20, 5, True  //here 5 enters --> (4,5)
34, 5, False //here 5 leaves --> (4,)
67, 6, True  //here 6 enters --> (4,6)
78, 6, False //here 6 leaves --> (4,)
99, 4, False //here 4 leaves --> ()

it is sorted by time and now I would like to step through and accumulate the valid ids. The ids enter on direction==True and exit on direction==False

so the resulting RDD should look like this

time, valid_ids
(10, (4,))
(20, (4,5))
(34, (4,))
(67, (4,6))
(78, (4,)
(99, ())

I know that this will not parallelize, but the df is not that big. So how could this be done in Spark/Scala?

Body:
Use of var is not recommended for scala developers but still I am posting answer using var

var collectArray = Array.empty[Int]
df.rdd.collect().map(row => {
  if(row(2).toString.equalsIgnoreCase("true")) collectArray = collectArray :+ row(1).asInstanceOf[Int]
  else collectArray = collectArray.drop(1)
  (row(0), collectArray.toList)
})

this should give you result as

(10,List(4))
(20,List(4, 5))
(34,List(5))
(67,List(5, 6))
(78,List(6))
(99,List())


问:
flexigrid select row by selectedIndex
i need help, how to trSelected by index on flexigrid?

```<code>$("#myTable td").prop("selectedIndex",3).addClass("trSelected")
</code>```

not working

答:
At the first, please add your code for more information.

in Jquery, you can use :nth-child(n|even|odd|formula) if you are going to implement index searching.

For example:

```<code>$("#myTable td selectedIndex:nth-child(3)");
</code>```

Above code get the third child of myTable -> td -> selectedIndex (The first element has the index number 1)

Title: flexigrid select row by selectedIndex

Body:
i need help, how to trSelected by index on flexigrid?

$("#myTable td").prop("selectedIndex",3).addClass("trSelected")

not working

Body:
At the first, please add your code for more information.

in Jquery, you can use :nth-child(n|even|odd|formula) if you are going to implement index searching.

For example:

$("#myTable td selectedIndex:nth-child(3)");

Above code get the third child of myTable -> td -> selectedIndex (The first element has the index number 1)


问:
How to display results from a JavaScript function to an html element
I am having trouble figuring out how to display values from a JavaScript to a table in HTML. I am trying to display just the even numbers between a starting number and a ending number. I believe my functions are correct but for some reason the values do not display on the page when submitted. Any help would be awesome. Thanks

function clearErrors() {
  for (var loopCounter = 0; loopCounter < document.forms["displayEvens"].elements.length; loopCounter++) {
    if (document.forms["displayEvens"].elements[loopCounter]
      .parentElement.className.indexOf("has-") != -1) {

      document.forms["displayEvens"].elements[loopCounter]
        .parentElement.className = "form-group";
    }
  }
}

function resetForm() {
  clearErrors();
  document.forms["displayEvens"]["startingNumber"].value = "";
  document.forms["displayEvens"]["endingNumber"].value = "";
  document.forms["displayEvens"]["step"].value = "";
  document.getElementById("results").style.display = "none";
  document.getElementById("submitButton").innerText = "DisplayEvens";
  document.forms["displayEvens"]["startingNumber"].focus();
}

function displayEvens(startingNumber, endingNumber, step) {

  var startingNumber =
    parseInt(document.getElementById("startingNum").value);
  var endingNumber = parseInt(document.getElementById("endingNum").value);
  var step = parseInt(document.getElementById("stepNum").value);
  var evenNums = [];
  for (var i = startingNumber; i < endingNumber; i += step) {
    if (i % 2 == 0) {
      evenNums.push(i);
    }
  }
  document.getElementById("evens").innerText = evenNums;
}

function validateItems() {
  clearErrors();
  displayEvens(startingNumber, endingNumber, step);

  console.trace("got here!");

  //var startingNumber = document.forms["displayEvens"]
  ["startingNumber"].value;
  //var endingNumber = document.forms["displayEvens"]
  ["endingNumber"].value;
  //var step = document.forms["displayEvens"]["step"].value;
  if (startingNumber == "" || isNaN(startingNumber)) {
    alert("Starting Number must be filled in with a number.");
    document.forms["displayEvens"]["startingNumber"]
      .parentElement.className = "form-group has-error";
    document.forms["displayEvens"]["startingNumber"].focus();
    return false;
  }
  if (endingNumber == "" || isNaN(endingNumber)) {
    alert("Ending Number must be filled in with a number.");
    document.forms["displayEvens"]["endingNumber"]
      .parentElement.className = "form-group has-error"
    document.forms["displayEvens"]["endingNumber"].focus();
    return false;
  }
  if (endingNumber <= startingNumber) {
    alert("Ending Number must be greater than the Starting number.");
    document.forms["displayEvens"]["endingNumber"]
      .parentElement.className = "form-group has-error"
    document.forms["displayEvens"]["endingNumber"].focus();
    return false;
  }
  if (step == "" || isNaN(step)) {
    alert("Step Number must be filled in with a number.");
    document.forms["displayEvens"]["step"]
      .parentElement.className = "form-group has-error"
    document.forms["displayEvens"]["step"].focus();
    return false;
  }
  if (step < 0) {
    alert("Step Number must be filled in with a positive number.");
    document.forms["displayEvens"]["step"]
      .parentElement.className = "form-group has-error"
    document.forms["displayEvens"]["step"].focus();
    return false;
  }

  //document.getElementById("results").style.display = "block";
  //document.getElementById("submitButton").innerText = "Recalculate";
  document.getElementById("startingNum").innerText =
    Number(startingNumber);
  document.getElementById("endingNum").innerText = Number(endingNumber);
  document.getElementById("stepNum").innerText = Number(step);
  document.getElementById("evens").innerText = Number(evenNums);
  return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <script type="text/JavaScript" src="displayEvens.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

</head>

<body>
  <div class="container">
    <h1>Display Evens</h1>
    <form name="displayEvens" onsubmit="return validateItems();" onreset="resetForm();">
      <div class="form-group row">
        <label for="startingNumber" class="col-sm-2 col-form-
    label">Starting Number</label>
        <div class="col-sm-10">
          <input type="number" class="form-control" ` id="startingNumber" ` placeholder="Enter a number" />
        </div>
      </div>
      <div class="form-group row">
        <label for="endingNumber" class="col-sm-2 col-form-`
    label">Ending`
    Number</label>
        <div class="col-sm-10">
          <input type="number" class="form-control" id="endingNumber" placeholder="Enter a number" />
        </div>
      </div>
      <div class="form-group row">
        <label for="step" class="col-sm-2 col-form-
    label">Step</label>
        <div class="col-sm-10">
          <input type="number" class="form-control" id="step" placeholder="Enter a number" />
        </div>
      </div>
      <button type="submit" id="submitButton" class="btn btn-
    default">Display Evens</button>
      <button type="reset" id="resetButton" class="btn">Reset</button>
    </form>
    </br>
    <table id="results" class="table table-striped">
      <thead>
        <tr>
          <td>Even numbers between <span id="startingNum"></span> and
            <span id="endingNum"></span> by <span id="stepNum"></span></td>
          <th>Result</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><span id="evens"></span></td>
      </tbody>
    </table>
  </div>
  <!--<div id="results" style="display:none;">
        <h3>Results:</h3>
        <span id="evens"></span>
        <h3>Your Starting Number:</h3>
        <span id="start"></span></br>
        <h3>Your Ending Number:</h3>
        <span id="end"></span></br>
        <h3>Your Step Number:</h3>
        <span id="step"></span>
    </div>-->
</body>

</html></code>```

答:
There's a fundamental issue wrong with your html. You are using the same id attribute on multiple elements. The id attribute should be used only on one element because it is a unique identifier.

Also when you have cleaned that up you can change your line

document.getElementById("endingNum").innerText = Number(endingNumber);

replace it with

document.getElementById("endingNum").append(Number(endingNumber))

instead

Body:
I am having trouble figuring out how to display values from a JavaScript to a table in HTML. I am trying to display just the even numbers between a starting number and a ending number. I believe my functions are correct but for some reason the values do not display on the page when submitted. Any help would be awesome. Thanks

function clearErrors() {
  for (var loopCounter = 0; loopCounter < document.forms["displayEvens"].elements.length; loopCounter++) {
    if (document.forms["displayEvens"].elements[loopCounter]
      .parentElement.className.indexOf("has-") != -1) {

      document.forms["displayEvens"].elements[loopCounter]
        .parentElement.className = "form-group";
    }
  }
}

function resetForm() {
  clearErrors();
  document.forms["displayEvens"]["startingNumber"].value = "";
  document.forms["displayEvens"]["endingNumber"].value = "";
  document.forms["displayEvens"]["step"].value = "";
  document.getElementById("results").style.display = "none";
  document.getElementById("submitButton").innerText = "DisplayEvens";
  document.forms["displayEvens"]["startingNumber"].focus();
}

function displayEvens(startingNumber, endingNumber, step) {

  var startingNumber =
    parseInt(document.getElementById("startingNum").value);
  var endingNumber = parseInt(document.getElementById("endingNum").value);
  var step = parseInt(document.getElementById("stepNum").value);
  var evenNums = [];
  for (var i = startingNumber; i < endingNumber; i += step) {
    if (i % 2 == 0) {
      evenNums.push(i);
    }
  }
  document.getElementById("evens").innerText = evenNums;
}

function validateItems() {
  clearErrors();
  displayEvens(startingNumber, endingNumber, step);

  console.trace("got here!");

  //var startingNumber = document.forms["displayEvens"]
  ["startingNumber"].value;
  //var endingNumber = document.forms["displayEvens"]
  ["endingNumber"].value;
  //var step = document.forms["displayEvens"]["step"].value;
  if (startingNumber == "" || isNaN(startingNumber)) {
    alert("Starting Number must be filled in with a number.");
    document.forms["displayEvens"]["startingNumber"]
      .parentElement.className = "form-group has-error";
    document.forms["displayEvens"]["startingNumber"].focus();
    return false;
  }
  if (endingNumber == "" || isNaN(endingNumber)) {
    alert("Ending Number must be filled in with a number.");
    document.forms["displayEvens"]["endingNumber"]
      .parentElement.className = "form-group has-error"
    document.forms["displayEvens"]["endingNumber"].focus();
    return false;
  }
  if (endingNumber <= startingNumber) {
    alert("Ending Number must be greater than the Starting number.");
    document.forms["displayEvens"]["endingNumber"]
      .parentElement.className = "form-group has-error"
    document.forms["displayEvens"]["endingNumber"].focus();
    return false;
  }
  if (step == "" || isNaN(step)) {
    alert("Step Number must be filled in with a number.");
    document.forms["displayEvens"]["step"]
      .parentElement.className = "form-group has-error"
    document.forms["displayEvens"]["step"].focus();
    return false;
  }
  if (step < 0) {
    alert("Step Number must be filled in with a positive number.");
    document.forms["displayEvens"]["step"]
      .parentElement.className = "form-group has-error"
    document.forms["displayEvens"]["step"].focus();
    return false;
  }

  //document.getElementById("results").style.display = "block";
  //document.getElementById("submitButton").innerText = "Recalculate";
  document.getElementById("startingNum").innerText =
    Number(startingNumber);
  document.getElementById("endingNum").innerText = Number(endingNumber);
  document.getElementById("stepNum").innerText = Number(step);
  document.getElementById("evens").innerText = Number(evenNums);
  return false;
}

<!DOCTYPE html>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

Display Evens

    <form name="displayEvens" onsubmit="return validateItems();" onreset="resetForm();">

        Starting Number

          <input type="number" class="form-control" ` id="startingNumber" ` placeholder="Enter a number" />

        Ending`
    Number

          <input type="number" class="form-control" id="endingNumber" placeholder="Enter a number" />

        Step

          <input type="number" class="form-control" id="step" placeholder="Enter a number" />

      <button type="submit" id="submitButton" class="btn btn-
    default">Display Evens</button>
      <button type="reset" id="resetButton" class="btn">Reset</button>
    </form>

          Even numbers between  and
             by
          Result


问:
Undefined: App with mux
So I just started learning Go yesterday and I have been following a fairly simple tutorial on creating a restful api. I can run the tests and everything but when I try to run the app and have it listen on a part it gives me undefined: App.

I cannot seem to find the error in this as Initialize and run should be sufficient enough to start the server. The tutorial also has it exactly like this and I followed it carefully.

UPDATE:

As clarification I attempt to run the program with go run main.go and that's what prompts the error.

I also attempted to follow the advice of an answer and ran go run main.go app.go and I get undefined: getUsers and it points to the line where it says users, err := getUsers(a.DB, start, count). I have added them to my app.go code below.

main.go

```<code>package main

func main() {
    a := App{}

    a.Initialize("root", "password", "user")

    a.Run(":8080")
}
</code>```

app.go

```<code>package main

import (
    "fmt"
    "log"
    "strconv"
    "encoding/json"
    "net/http"
    "github.com/gorilla/mux"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

type App struct {
    Router *mux.Router
    DB     *sql.DB
}

func (a *App) Initialize(user, password, dbname string) {
    connectionString := fmt.Sprintf("%s:%s@/%s", user, password, dbname)

    var err error

    a.DB, err = sql.Open("mysql", connectionString)

    if err != nil {
        log.Fatal(err)
    }

    a.Router = mux.NewRouter()
    a.initializeRoutes()
}

func (a *App) initializeRoutes() {
    a.Router.HandleFunc("/users", a.getUsers).Methods("GET")
}

func (a *App) Run(addr string) {
    log.Fatal(http.ListenAndServe(addr, a.Router))
}

func (a *App) getUsers(w http.ResponseWriter, r *http.Request) {
    count, _ := strconv.Atoi(r.FormValue("count"))
    start, _ := strconv.Atoi(r.FormValue("start"))

    if count > 10 || count < 1 {
        count = 10
    }

    if start < 0 {
        start = 0
    }

    users, err := getUsers(a.DB, start, count)

    if err != nil {
        respondWithError(w, http.StatusInternalServerError, err.Error())

        return
    }

    respondWithJSON(w, http.StatusOK, users);
}
</code>```

答:
How do you run it? If with go run try to pass it all the files:

```<code>go run main.go app.go
</code>```

Or even with asterisk to catch them all:

```<code>go run *.go
</code>```

Another option: build application then run it:

```<code>go build -o app && ./app
</code>```

Title: Undefined: App with mux

Body:
So I just started learning Go yesterday and I have been following a fairly simple tutorial on creating a restful api. I can run the tests and everything but when I try to run the app and have it listen on a part it gives me undefined: App.

I cannot seem to find the error in this as Initialize and run should be sufficient enough to start the server. The tutorial also has it exactly like this and I followed it carefully.

UPDATE:

As clarification I attempt to run the program with go run main.go and that's what prompts the error.

I also attempted to follow the advice of an answer and ran go run main.go app.go and I get undefined: getUsers and it points to the line where it says users, err := getUsers(a.DB, start, count). I have added them to my app.go code below.

main.go

package main

func main() {
    a := App{}

    a.Initialize("root", "password", "user")

    a.Run(":8080")
}

app.go

package main

import (
    "fmt"
    "log"
    "strconv"
    "encoding/json"
    "net/http"
    "github.com/gorilla/mux"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

type App struct {
    Router *mux.Router
    DB     *sql.DB
}

func (a *App) Initialize(user, password, dbname string) {
    connectionString := fmt.Sprintf("%s:%s@/%s", user, password, dbname)

    var err error

    a.DB, err = sql.Open("mysql", connectionString)

    if err != nil {
        log.Fatal(err)
    }

    a.Router = mux.NewRouter()
    a.initializeRoutes()
}

func (a *App) initializeRoutes() {
    a.Router.HandleFunc("/users", a.getUsers).Methods("GET")
}

func (a *App) Run(addr string) {
    log.Fatal(http.ListenAndServe(addr, a.Router))
}

func (a *App) getUsers(w http.ResponseWriter, r *http.Request) {
    count, _ := strconv.Atoi(r.FormValue("count"))
    start, _ := strconv.Atoi(r.FormValue("start"))

    if count > 10 || count < 1 {
        count = 10
    }

    if start < 0 {
        start = 0
    }

    users, err := getUsers(a.DB, start, count)

    if err != nil {
        respondWithError(w, http.StatusInternalServerError, err.Error())

        return
    }

    respondWithJSON(w, http.StatusOK, users);
}

Body:
How do you run it? If with go run try to pass it all the files:

go run main.go app.go

Or even with asterisk to catch them all:

go run *.go

Another option: build application then run it:

go build -o app && ./app