问:
Ajax issue with Flask
For the past few days I have been attempting to get an ajax call to work with Flask. No matter what I try nothing is working. So I will jump right into my code:

Python Code:

```<code> @app.route("/num")
 def num():
     return render_template('num.html')

 @app.route('/add_num', methods=['POST'])
 def add_num():
    a = request.form['a']
    b = request.form['b']
    a = int(a)
    b = int(b)
    print(a)
    if a and b:
      c = a + b
      return jsonify(result = c)
    return jsonify({'error' : 'Missing Data'})
</code>```

HTML Code

```<code>  <form>
     <input id='a' type="text" size="5" name="a"/> +
     <input id='b' type="text" size="5" name="b"/> =
     <br>
     <br>
     <button>Add It!</button>
  </form>

  <h1 id='result'>Result</h1>
</code>```

Ajax Code:

```<code>     <script type="text/javascript">
       $(document).ready(function(){
          $('form').bind('submit', function(event){
            $.ajax({
               data: {
                  a: $('#a').val(),
                  b: $('#b').val()
               },
               type: 'POST',
               url: '/add_num',
               dataType: 'json',
               data: JSON.stringify(json),
               contentType: 'application/json;charset=UTF-8'
           })
            .done(function(data){
              if (data.error){
                $('#result').text(data.error).show();
              }else{
                $('#result').text(data.result).show();
              }
           });
        event.preventDefault();
        });
       });
      </script>
</code>```

When I hit the submit button nothing happens. I will see this in the URL:
           http://127.0.0.1:5000/num?a=2&b=3
Also, at one point I was getting the numbers added but taken to a separate page that showed JSON information. To have that happen my top line of my form was this:

```<code>    <form action='add_num' method="post" role='form'>
</code>```

Now I have tried to use a different format of ajax which works perfectly fine in my code. However, I want to try this method because I like it much better. I am fairly certain that the solution is something simple but I cannot track it down. Any help would be great!

This is what finally got it working for me:

```<code>`  $(document).ready(function(){
     $('form').bind('submit', function(event){
        event.preventDefault();
           $.ajax({
               data: {
                  a: $('#a').val(),
                  b: $('#b').val()
           },
            type: 'POST',
            url: '/add_num',
            success: function(data){
            $('#result').text(data.result).show();
        }
     });
   });
  });`
</code>```

答:
Move event.preventDefault() above your ajax call. If you saw a and b in the parameter string, that means the form is performing its default action.

EDIT: It could be that you two data keys in the object you're passing to $.ajax and that on the second data key you're calling JSON.stringify with a variable that doesn't seem to exist as a parameter.

Title: Ajax issue with Flask

Body:
For the past few days I have been attempting to get an ajax call to work with Flask. No matter what I try nothing is working. So I will jump right into my code:

Python Code:

 @app.route("/num")
 def num():
     return render_template('num.html')

 @app.route('/add_num', methods=['POST'])
 def add_num():
    a = request.form['a']
    b = request.form['b']
    a = int(a)
    b = int(b)
    print(a)
    if a and b:
      c = a + b
      return jsonify(result = c)
    return jsonify({'error' : 'Missing Data'})

HTML Code

  <form>
     <input id='a' type="text" size="5" name="a"/> +
     <input id='b' type="text" size="5" name="b"/> =

     <button>Add It!</button>
  </form>

Result

Ajax Code:

When I hit the submit button nothing happens. I will see this in the URL:
           http://127.0.0.1:5000/num?a=2&b=3
Also, at one point I was getting the numbers added but taken to a separate page that showed JSON information. To have that happen my top line of my form was this:

    <form action='add_num' method="post" role='form'>

Now I have tried to use a different format of ajax which works perfectly fine in my code. However, I want to try this method because I like it much better. I am fairly certain that the solution is something simple but I cannot track it down. Any help would be great!

This is what finally got it working for me:

`  $(document).ready(function(){
     $('form').bind('submit', function(event){
        event.preventDefault();
           $.ajax({
               data: {
                  a: $('#a').val(),
                  b: $('#b').val()
           },
            type: 'POST',
            url: '/add_num',
            success: function(data){
            $('#result').text(data.result).show();
        }
     });
   });
  });`


来源: stackexchange

问:
SQL Server Update statement to change year and month of a datetime column
I want to update the TimeOccurred column in all tables in a database (also fine with doing 1 table at a time if that is necessary). This is what the current values in this column look like:

```<code>2017-06-12 14:34:00
</code>```

I would like to replace that value in all tables in the column TimeOccurred by changing just the year to the current year and the month to the previous month.

So 2012-03-14 14:34:00 becomes 2017-05-14 14:34:00.

It would also help if I could check the day and if it was 29,30,or 31 change it to 25.

Update:

It's -1 month based on the current right now month. We want to change the days in case the month ends up being February, we can't have an event happening on February 31st for example. So all events should be days 1-28 to be safe.

More sample data:

```<code>2014-07-28 13:03:00
2012-07-28 13:03:00
2015-07-28 13:03:00
2014-07-28 13:03:00
2015-07-28 13:03:00
2016-07-29 11:02:00
2013-07-29 11:07:00
2005-07-29 11:12:00
2010-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
</code>```

答:
Try this:

```<code>DATEADD(mm, DATEDIFF(mm, TimeOccurred, current_timestamp)-1, TimeOccurred)
</code>```

See this to prove it works, including a demo for what will happen at the end of March rolling into February:

http://rextester.com/TIATZ28074

ContentLicense: CC BY-SA 3.0

Body:
I want to update the TimeOccurred column in all tables in a database (also fine with doing 1 table at a time if that is necessary). This is what the current values in this column look like:

2017-06-12 14:34:00

I would like to replace that value in all tables in the column TimeOccurred by changing just the year to the current year and the month to the previous month.

So 2012-03-14 14:34:00 becomes 2017-05-14 14:34:00.

It would also help if I could check the day and if it was 29,30,or 31 change it to 25.

Update:

It's -1 month based on the current right now month. We want to change the days in case the month ends up being February, we can't have an event happening on February 31st for example. So all events should be days 1-28 to be safe.

More sample data:

2014-07-28 13:03:00
2012-07-28 13:03:00
2015-07-28 13:03:00
2014-07-28 13:03:00
2015-07-28 13:03:00
2016-07-29 11:02:00
2013-07-29 11:07:00
2005-07-29 11:12:00
2010-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00

Body:
Try this:

DATEADD(mm, DATEDIFF(mm, TimeOccurred, current_timestamp)-1, TimeOccurred)

See this to prove it works, including a demo for what will happen at the end of March rolling into February:

http://rextester.com/TIATZ28074


问:
CGAffineTransformMakeRotation() is resizing image on iPad?
I'm my application I have a UIImage view that is set up with an image in my view's nib file. In the view did load method of my view controller I rotate the image using the following line,

```<code>self.myImage.transform = CGAffineTransformMakeRotation(-126 * M_PI / 180);
</code>```

Now on the iPhone version of my app my image is getting rotated by -126° just fine. However I've just recently started working on an iPad version of my app and when I use the above line of code to rotate the image it also gets resized?

As far as my eyes can tell it seems as though the width and height are being swapped?

Is there something I missed?

NOTE: If it helps i'm also setting the anchor point using,

```<code>[myImage.layer setAnchorPoint:CGPointMake( 0.5, 0.857142857 )];
</code>```

And i'm running the code in he iPad 4.2 simulator

答:
Well I've figured out my problem. First of all the only orientation that I'm supporting on the iPad is landscape mode, versus portrait mode on the iPhone version. By changing the orientation of the device the position of my image is also changing.

To fix the problem I had to adjust the Autosizing property of my UIImage in interface Builder, I enabled all the outer "bars" and disabled all the inner "bars" and that seemed to fix the problem.

ContentLicense: CC BY-SA 2.5

Body:
I'm my application I have a UIImage view that is set up with an image in my view's nib file. In the view did load method of my view controller I rotate the image using the following line,

self.myImage.transform = CGAffineTransformMakeRotation(-126 * M_PI / 180);

Now on the iPhone version of my app my image is getting rotated by -126° just fine. However I've just recently started working on an iPad version of my app and when I use the above line of code to rotate the image it also gets resized?

As far as my eyes can tell it seems as though the width and height are being swapped?

Is there something I missed?

NOTE: If it helps i'm also setting the anchor point using,

[myImage.layer setAnchorPoint:CGPointMake( 0.5, 0.857142857 )];

And i'm running the code in he iPad 4.2 simulator


问:
Cronjobs in node.js
Is there a possibility to periodically call functions at a specific time of the day in node.js? My first implementation was

```<code>setInterval(functionName(),(24*60*60*1000));
</code>```

This is suboptimal, because it will restart every time I restart node. Are there better possibilities to implement this?

答:
It's an old question, but in addition to the accepted answer a library  with examples is worth mentioning.

cron is a lightweight package which runs the specified function at given interval, using only system's time and no db persistence.

```<code>const CronJob = require('cron').CronJob;
const jobFiveMinutes = require("./job.five-minutes");
const jobMondayMorning = require("./job.monday-morning");

var jobs = [
    new CronJob({
        cronTime: "00 */5 * * * *", //every five minutes
        onTick: function() {
            jobFiveMinutes();
        },
        start: false, //don't start immediately
        timeZone: 'America/Los_Angeles'
    }),
    new CronJob({
        cronTime: "00 00 9 * * 1", //9 am Monday morning
        onTick: function() {
            jobMondayMorning();
        },
        start: false,
        timeZone: 'America/Los_Angeles'
    }),
];

jobs.forEach(function(job) {
    job.start(); //start the jobs
});
</code>```

Above, we required two files and call them inside of two cronjobs, set at different intervals. The files simply export the functions:

```<code>//job.five-minutes.js
module.exports = function(){
    console.log("runs every five minutes")
};

//job.monday-morning.js
module.exports = function(){
    console.log("runs every monday morning at 9 am, Los Angeles time")
};
</code>```

Whether you run it locally or on remote server in any region, it will run according to the passed timezone (which is optional though, and does not matter in case of minutes).

Also, restarting the server/script will have no affect on its working as it's synced with system time. A "00 */5 * * * *" job will run on each multiple of 5 i.e. 5, 10, 15, 20 and so on. So, even if you restart the script at 24, it will run at 25 not 29.

Lastly, the package has extended the cron syntax to include seconds on the left most. Therefore, you can even tell at what exact second of the minute you want to run the job.

Title: Cronjobs in node.js

Body:
Is there a possibility to periodically call functions at a specific time of the day in node.js? My first implementation was

setInterval(functionName(),(24*60*60*1000));

This is suboptimal, because it will restart every time I restart node. Are there better possibilities to implement this?

Body:
It's an old question, but in addition to the accepted answer a library  with examples is worth mentioning.

cron is a lightweight package which runs the specified function at given interval, using only system's time and no db persistence.

const CronJob = require('cron').CronJob;
const jobFiveMinutes = require("./job.five-minutes");
const jobMondayMorning = require("./job.monday-morning");

var jobs = [
    new CronJob({
        cronTime: "00 */5 * * * *", //every five minutes
        onTick: function() {
            jobFiveMinutes();
        },
        start: false, //don't start immediately
        timeZone: 'America/Los_Angeles'
    }),
    new CronJob({
        cronTime: "00 00 9 * * 1", //9 am Monday morning
        onTick: function() {
            jobMondayMorning();
        },
        start: false,
        timeZone: 'America/Los_Angeles'
    }),
];

jobs.forEach(function(job) {
    job.start(); //start the jobs
});

Above, we required two files and call them inside of two cronjobs, set at different intervals. The files simply export the functions:

//job.five-minutes.js
module.exports = function(){
    console.log("runs every five minutes")
};

//job.monday-morning.js
module.exports = function(){
    console.log("runs every monday morning at 9 am, Los Angeles time")
};

Whether you run it locally or on remote server in any region, it will run according to the passed timezone (which is optional though, and does not matter in case of minutes).

Also, restarting the server/script will have no affect on its working as it's synced with system time. A "00 */5 * * * *" job will run on each multiple of 5 i.e. 5, 10, 15, 20 and so on. So, even if you restart the script at 24, it will run at 25 not 29.

Lastly, the package has extended the cron syntax to include seconds on the left most. Therefore, you can even tell at what exact second of the minute you want to run the job.


问:
Difference between single and double quotes in awk
I have this awk statement:

```<code>glb_library="my_library"
awk "
        /^Direct Dependers of/ { next }
        /^---/                 { next }
        /^$glb_library:/       { ver=\$0; next }
                               { gsub(/[[:space:]]/, '', \$0); print ver':'\$0 }
      " file
</code>```

Basically, I have enclosed the awk code in double quotes so that the shell variable glb_library is expanded.  I have made sure to escape the $ character to prevent the shell from expanding $0. Followed the guidance from here.

awk gives me this error:

```<code>awk: syntax error at source line 5
 context is
                                   { gsub(/[[:space:]]/, >>>  ' <<<
</code>```

I want to understand:

Is it legal to use single quotes inside awk? Why is '' not a null string like "" is?

Does awk treat single and double quotes differently?

My code worked after I escaped the single quotes with backslashes and used \"\" to represent the null string instead of ''.

答:
Never enclose any script in double quotes or you're sentencing yourself to backslash-hell. This is the syntax for what you're trying to do:</p>

```<code>glb_library="my_library"
awk -v glb_library="$glb_library" '
        /^Direct Dependers of/ { next }
        /^---/                 { next }
        $0 ~ "^"glb_library":" { ver=$0; next }
                               { gsub(/[[:space:]]/, ""); print ver":"$0 }
      ' file
</code>```

Body:
I have this awk statement:

glb_library="my_library"
awk "
        /^Direct Dependers of/ { next }
        /^---/                 { next }
        /^$glb_library:/       { ver=\$0; next }
                               { gsub(/[[:space:]]/, '', \$0); print ver':'\$0 }
      " file

Basically, I have enclosed the awk code in double quotes so that the shell variable glb_library is expanded.  I have made sure to escape the $ character to prevent the shell from expanding $0. Followed the guidance from here.

awk gives me this error:

awk: syntax error at source line 5
 context is
                                   { gsub(/[[:space:]]/, >>>  ' <<<

I want to understand:

Is it legal to use single quotes inside awk? Why is '' not a null string like "" is?

Does awk treat single and double quotes differently?

My code worked after I escaped the single quotes with backslashes and used \"\" to represent the null string instead of ''.

Body:
Never enclose any script in double quotes or you're sentencing yourself to backslash-hell. This is the syntax for what you're trying to do:

glb_library="my_library"
awk -v glb_library="$glb_library" '
        /^Direct Dependers of/ { next }
        /^---/                 { next }
        $0 ~ "^"glb_library":" { ver=$0; next }
                               { gsub(/[[:space:]]/, ""); print ver":"$0 }
      ' file


问:
sudo: command not found when I ssh into server
I am a newbie with server handling and Linux. I am trying to install composer on my server so that i can host my Laravel project onto it as mentioned in the tutorial in Ultimate Guide: Deploy Laravel 5.3 App on LEMP Stack. I ssh into the server and after installation of composer when I run sudo mv composer.phar /usr/local/bin/composer I am getting a message in the terminal:

```<code>-bash: sudo: command not found
</code>```

I desperately need some deliberate help

答:
Sudo is probably not installed or not in your path

check to see if you are root in this case sudo is not needed unless you are trying to impersonate another user. just run your command without sudo mv composer.phar /usr/local/bin/composer

See if sudo is your path by running which sudo or echo $PATH. If sudo is not in your path, your path variable might be broken. You can try testing this by executing a common location for sudo /usr/bin/sudo or running locate sudo | grep bin to attempt to find its location.

If you know that sudo was installed, or your path looks broken, try fixing your path. Check your distribution's env file (/etc/environment in ubuntu) to make sure that it is formatted correctly (script commands are illegal in this file)

If you are not root and you want to run a command with root prvileges then you must install sudo. But if you don't have sudo and you are not root then you can't install it. In this case I recommend switching to the root user with su

If you do not have the root password and you own the machine, you can reset the root password with a tutorial such as https://askubuntu.com/questions/24006/how-do-i-reset-a-lost-administrative-password

After you manage to login as root install sudo with apt-get update; apt-get install sudosince you are using Ubuntu.

Verify the the name of your sudoers group with visudo and modify your sudoers file if you need to. https://www.digitalocean.com/community/tutorials/how-to-edit-the-sudoers-file-on-ubuntu-and-centos

if you have an existing sudoers group or you create one you can add yourself to the group. For example if your sudoers group is called sudo run usermod -aG sudo myuser. The sudoers group by default in Ubuntu based Linux is sudo. A sudoers group entry looks like this: %sudo ALL=(ALL:ALL) ALL

If you are trying to impersonate another user and cannot install sudo, you can still use su if it is installed and you have permission / password for the other user.

e.g. su someuser

ContentLicense: CC BY-SA 4.0

Body:
I am a newbie with server handling and Linux. I am trying to install composer on my server so that i can host my Laravel project onto it as mentioned in the tutorial in Ultimate Guide: Deploy Laravel 5.3 App on LEMP Stack. I ssh into the server and after installation of composer when I run sudo mv composer.phar /usr/local/bin/composer I am getting a message in the terminal:

-bash: sudo: command not found

I desperately need some deliberate help


问:
Worth Upgrading from Intellij Idea7 to Idea8?
I use Intellij Idea 7 for Java dev.  My dev is 'limited' to all J2SE features plus light JSP, Servlets, and super light usage of JPA.  No J2EE, no massive use of random frameworks, etc.

Is it worth upgrading to ver 8? "Worth it" to me means better "core functionality" in terms of speed (ESPECIALLY startup speed), memory utilization (seems like it starts having serious problems with four or more projects open), and auto bug-finding.
More frameworks supported and more languages supported (other than perhaps Haskell and C++), and more refactorings don't interest me at this time.

A while back, I installed a preview version of 8 and it seemed -exactly- the same as 7, as far as my needs were concerned.

Anyone loving the upgrade to 8, and if so, why?

Thanks

答: I am working on the Diana-EAP build - but 8 has git integration built in.  The EAP has better git integration than the 8.0.1 release - it looks like that is something they are really focusing on.  </p>

OwnerDisplayName: Brian

OwnerDisplayName: harmanjd


问:
Flyway regularly hangs (MariaDB connector, RDS)
I've been seeing frequent hangs on deployment, at the migration step. Java/Scala application packaged in WAR for Tomcat. Database is RDS Aurora using MariaDB connector (https://downloads.mariadb.org/connector-java/).

Probably has nothing to do with Flyway but is a generic problem getting a connection.

Migration is run from shell in container:

```<code>java -cp `echo WEB-INF/lib/*|tr ' ' :` foo.Migrate
</code>```

Migration code looks like:

```<code>def main(args: Array[String]): Unit = {
  Environment.dbFlywayPassword.foreach { pass =>
    val flyway = new Flyway
    flyway.setDataSource(Environment.jdbcUrl, "flyway", pass)
    flyway.migrate
  }
}
</code>```

Connection string:

```<code>jdbc:mysql:aurora://%RDS_HOST%/xxx?serverSslCert=/rds-ca-2015-root.pem&useSSL=true&connectTimeout=10000
</code>```

I've tried increasing logging level in Flyway, but nothing is logged after this line:

```<code>15:57:35.115 [main] INFO  o.f.c.internal.util.VersionPrinter - Flyway 4.2.0 by Boxfuse
</code>```

So I got a thread dump, that looks like this:

```<code>15:57:35.115 [main] INFO  o.f.c.internal.util.VersionPrinter - Flyway 4.2.0 by Boxfuse
2017-06-08 15:57:56
Full thread dump OpenJDK 64-Bit Server VM (25.121-b13 mixed mode):

"MariaDb-failover-1" #8 daemon prio=5 os_prio=0 tid=0x00005555f80ae000 nid=0x14 waiting on condition [0x00007fc330b8f000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x00000000f5c59b10> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

"Service Thread" #7 daemon prio=9 os_prio=0 tid=0x00005555f70bf000 nid=0x12 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C1 CompilerThread1" #6 daemon prio=9 os_prio=0 tid=0x00005555f7063000 nid=0x11 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #5 daemon prio=9 os_prio=0 tid=0x00005555f7060800 nid=0x10 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00005555f705e800 nid=0xf waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00005555f702f000 nid=0xe in Object.wait() [0x00007fc331616000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x00000000f5a30c58> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
    - locked <0x00000000f5a30c58> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00005555f702c000 nid=0xd in Object.wait() [0x00007fc331717000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x00000000f5a30e10> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:502)
    at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
    - locked <0x00000000f5a30e10> (a java.lang.ref.Reference$Lock)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

"main" #1 prio=5 os_prio=0 tid=0x00005555f6f85000 nid=0xb runnable [0x00007fc34341d000]
   java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    at java.net.SocketInputStream.read(SocketInputStream.java:171)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
    at sun.security.ssl.InputRecord.read(InputRecord.java:503)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
    - locked <0x00000000f0a66090> (a java.lang.Object)
    at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:930)
    at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
    - locked <0x00000000f0a81eb0> (a sun.security.ssl.AppInputStream)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
    - locked <0x00000000f06b5118> (a java.io.BufferedInputStream)
    at org.mariadb.jdbc.internal.io.input.StandardPacketInputStream.getPacketArray(StandardPacketInputStream.java:125)
    at org.mariadb.jdbc.internal.io.input.StandardPacketInputStream.getPacket(StandardPacketInputStream.java:95)
    at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readPacket(AbstractQueryProtocol.java:1002)
    at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.getResult(AbstractQueryProtocol.java:982)
    at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.readRequestSessionVariables(AbstractConnectProtocol.java:498)
    at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.readPipelineAdditionalData(AbstractConnectProtocol.java:544)
    at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connect(AbstractConnectProtocol.java:410)
    at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connect(AbstractConnectProtocol.java:357)
    at org.mariadb.jdbc.internal.protocol.AuroraProtocol.loop(AuroraProtocol.java:149)
    at org.mariadb.jdbc.internal.failover.impl.AuroraListener.reconnectFailedConnection(AuroraListener.java:179)
    at org.mariadb.jdbc.internal.failover.impl.MastersSlavesListener.initializeConnection(MastersSlavesListener.java:154)
    at org.mariadb.jdbc.internal.failover.FailoverProxy.<init>(FailoverProxy.java:94)
    at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:464)
    at org.mariadb.jdbc.Driver.connect(Driver.java:103)
    at org.flywaydb.core.internal.util.jdbc.DriverDataSource.getConnectionFromDriver(DriverDataSource.java:416)
    at org.flywaydb.core.internal.util.jdbc.DriverDataSource.getConnection(DriverDataSource.java:381)
    at org.flywaydb.core.internal.util.jdbc.JdbcUtils.openConnection(JdbcUtils.java:51)
    at org.flywaydb.core.Flyway.execute(Flyway.java:1418)
    at org.flywaydb.core.Flyway.migrate(Flyway.java:971)
    at tgam.service.data.Migrate$.$anonfun$main$1(Migrate.scala:11)
    at foo.Migrate$.$anonfun$main$1$adapted(Migrate.scala:8)
    at foo.Migrate$$$Lambda$4/458209687.apply(Unknown Source)
    at scala.Option.foreach(Option.scala:257)
    at foo.Migrate$.main(Migrate.scala:8)
    at foo.Migrate.main(Migrate.scala)

"VM Thread" os_prio=0 tid=0x00005555f7022000 nid=0xc runnable

"VM Periodic Task Thread" os_prio=0 tid=0x00005555f70da800 nid=0x13 waiting on condition

JNI global references: 232

Heap
 def new generation   total 4928K, used 1611K [0x00000000f0600000, 0x00000000f0b50000, 0x00000000f5950000)
  eden space 4416K,  24% used [0x00000000f0600000, 0x00000000f0712c10, 0x00000000f0a50000)
  from space 512K, 100% used [0x00000000f0a50000, 0x00000000f0ad0000, 0x00000000f0ad0000)
  to   space 512K,   0% used [0x00000000f0ad0000, 0x00000000f0ad0000, 0x00000000f0b50000)
 tenured generation   total 10944K, used 4187K [0x00000000f5950000, 0x00000000f6400000, 0x0000000100000000)
   the space 10944K,  38% used [0x00000000f5950000, 0x00000000f5d66e78, 0x00000000f5d67000, 0x00000000f6400000)
 Metaspace       used 13061K, capacity 13306K, committed 13568K, reserved 1060864K
  class space    used 1381K, capacity 1449K, committed 1536K, reserved 1048576K
</code>```

Looks like an I/O hang in org.mariadb.jdbc.Driver.connect, but I do have a connectTimeout set (10 seconds). This timeout doesn't seem to be effective (would I need a socketTimeout per https://github.com/brettwooldridge/HikariCP/issues/754 ?)

This has been happening for a while. The same thing happened when I was using Tomcat's contextInitialized hook to do migrations. I decided to refactor out into a separate invocation before starting Tomcat, which looks like a better idea in general, but it hasn't affected this behaviour.

What will typically happen is that the code will hang, after 2-3 minutes ECS will timeout, and trigger a redeploy. After some number of these retries (e.g. up to 10), Flyway will run successfully and the service will start.

答:
OK, seems this is a known bug in RDS Aurora - and it's alluded to in the MariaDB Connector doc (surely it should be a runtime warning, though!)

https://mariadb.com/kb/en/mariadb/about-mariadb-connector-j/#infrequently-used

usePipelineAuth   Not compatible with aurora During connection,
  different queries are executed. When option is active those queries
  are send using pipeline (all queries are send, then only all results
  are reads), permitting faster connection creation. Default: true.
  Since 1.6.0

Also kudos to wlad_ in Freenode #maria who pointed me in the right direction.

Body:
I've been seeing frequent hangs on deployment, at the migration step. Java/Scala application packaged in WAR for Tomcat. Database is RDS Aurora using MariaDB connector (https://downloads.mariadb.org/connector-java/).

Probably has nothing to do with Flyway but is a generic problem getting a connection.

Migration is run from shell in container:

java -cp `echo WEB-INF/lib/*|tr ' ' :` foo.Migrate

Migration code looks like:

def main(args: Array[String]): Unit = {
  Environment.dbFlywayPassword.foreach { pass =>
    val flyway = new Flyway
    flyway.setDataSource(Environment.jdbcUrl, "flyway", pass)
    flyway.migrate
  }
}

Connection string:

jdbc:mysql:aurora://%RDS_HOST%/xxx?serverSslCert=/rds-ca-2015-root.pem&useSSL=true&connectTimeout=10000

I've tried increasing logging level in Flyway, but nothing is logged after this line:

15:57:35.115 [main] INFO  o.f.c.internal.util.VersionPrinter - Flyway 4.2.0 by Boxfuse

So I got a thread dump, that looks like this:

15:57:35.115 [main] INFO  o.f.c.internal.util.VersionPrinter - Flyway 4.2.0 by Boxfuse
2017-06-08 15:57:56
Full thread dump OpenJDK 64-Bit Server VM (25.121-b13 mixed mode):

"MariaDb-failover-1" #8 daemon prio=5 os_prio=0 tid=0x00005555f80ae000 nid=0x14 waiting on condition [0x00007fc330b8f000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x00000000f5c59b10> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

"Service Thread" #7 daemon prio=9 os_prio=0 tid=0x00005555f70bf000 nid=0x12 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C1 CompilerThread1" #6 daemon prio=9 os_prio=0 tid=0x00005555f7063000 nid=0x11 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #5 daemon prio=9 os_prio=0 tid=0x00005555f7060800 nid=0x10 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00005555f705e800 nid=0xf waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00005555f702f000 nid=0xe in Object.wait() [0x00007fc331616000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x00000000f5a30c58> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
    - locked <0x00000000f5a30c58> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00005555f702c000 nid=0xd in Object.wait() [0x00007fc331717000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x00000000f5a30e10> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:502)
    at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
    - locked <0x00000000f5a30e10> (a java.lang.ref.Reference$Lock)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

"main" #1 prio=5 os_prio=0 tid=0x00005555f6f85000 nid=0xb runnable [0x00007fc34341d000]
   java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    at java.net.SocketInputStream.read(SocketInputStream.java:171)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
    at sun.security.ssl.InputRecord.read(InputRecord.java:503)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
    - locked <0x00000000f0a66090> (a java.lang.Object)
    at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:930)
    at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
    - locked <0x00000000f0a81eb0> (a sun.security.ssl.AppInputStream)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
    - locked <0x00000000f06b5118> (a java.io.BufferedInputStream)
    at org.mariadb.jdbc.internal.io.input.StandardPacketInputStream.getPacketArray(StandardPacketInputStream.java:125)
    at org.mariadb.jdbc.internal.io.input.StandardPacketInputStream.getPacket(StandardPacketInputStream.java:95)
    at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readPacket(AbstractQueryProtocol.java:1002)
    at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.getResult(AbstractQueryProtocol.java:982)
    at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.readRequestSessionVariables(AbstractConnectProtocol.java:498)
    at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.readPipelineAdditionalData(AbstractConnectProtocol.java:544)
    at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connect(AbstractConnectProtocol.java:410)
    at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connect(AbstractConnectProtocol.java:357)
    at org.mariadb.jdbc.internal.protocol.AuroraProtocol.loop(AuroraProtocol.java:149)
    at org.mariadb.jdbc.internal.failover.impl.AuroraListener.reconnectFailedConnection(AuroraListener.java:179)
    at org.mariadb.jdbc.internal.failover.impl.MastersSlavesListener.initializeConnection(MastersSlavesListener.java:154)
    at org.mariadb.jdbc.internal.failover.FailoverProxy.<init>(FailoverProxy.java:94)
    at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:464)
    at org.mariadb.jdbc.Driver.connect(Driver.java:103)
    at org.flywaydb.core.internal.util.jdbc.DriverDataSource.getConnectionFromDriver(DriverDataSource.java:416)
    at org.flywaydb.core.internal.util.jdbc.DriverDataSource.getConnection(DriverDataSource.java:381)
    at org.flywaydb.core.internal.util.jdbc.JdbcUtils.openConnection(JdbcUtils.java:51)
    at org.flywaydb.core.Flyway.execute(Flyway.java:1418)
    at org.flywaydb.core.Flyway.migrate(Flyway.java:971)
    at tgam.service.data.Migrate$.$anonfun$main$1(Migrate.scala:11)
    at foo.Migrate$.$anonfun$main$1$adapted(Migrate.scala:8)
    at foo.Migrate$$$Lambda$4/458209687.apply(Unknown Source)
    at scala.Option.foreach(Option.scala:257)
    at foo.Migrate$.main(Migrate.scala:8)
    at foo.Migrate.main(Migrate.scala)

"VM Thread" os_prio=0 tid=0x00005555f7022000 nid=0xc runnable

"VM Periodic Task Thread" os_prio=0 tid=0x00005555f70da800 nid=0x13 waiting on condition

JNI global references: 232

Heap
 def new generation   total 4928K, used 1611K [0x00000000f0600000, 0x00000000f0b50000, 0x00000000f5950000)
  eden space 4416K,  24% used [0x00000000f0600000, 0x00000000f0712c10, 0x00000000f0a50000)
  from space 512K, 100% used [0x00000000f0a50000, 0x00000000f0ad0000, 0x00000000f0ad0000)
  to   space 512K,   0% used [0x00000000f0ad0000, 0x00000000f0ad0000, 0x00000000f0b50000)
 tenured generation   total 10944K, used 4187K [0x00000000f5950000, 0x00000000f6400000, 0x0000000100000000)
   the space 10944K,  38% used [0x00000000f5950000, 0x00000000f5d66e78, 0x00000000f5d67000, 0x00000000f6400000)
 Metaspace       used 13061K, capacity 13306K, committed 13568K, reserved 1060864K
  class space    used 1381K, capacity 1449K, committed 1536K, reserved 1048576K

Looks like an I/O hang in org.mariadb.jdbc.Driver.connect, but I do have a connectTimeout set (10 seconds). This timeout doesn't seem to be effective (would I need a socketTimeout per https://github.com/brettwooldridge/HikariCP/issues/754 ?)

This has been happening for a while. The same thing happened when I was using Tomcat's contextInitialized hook to do migrations. I decided to refactor out into a separate invocation before starting Tomcat, which looks like a better idea in general, but it hasn't affected this behaviour.

What will typically happen is that the code will hang, after 2-3 minutes ECS will timeout, and trigger a redeploy. After some number of these retries (e.g. up to 10), Flyway will run successfully and the service will start.


问:
POSTing data with one to many relationship using Thymeleaf
When Posting data with one to many relationship using Thymeleaf, I want to save form site with dropdown list (nomclient) from table produit

Entity Model

```<code> @Entity

 public class Produit implements Serializable {
    ...
    @OneToMany(fetch = FetchType.LAZY,mappedBy="produit")
    private List<Site> listSites=new ArrayList<Site>();
    ...
</code>```

Entity Model - Produit

```<code>public class Site implements Serializable {
  ...
  @JoinColumn(name = "refProduit")
  @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
  private Produit produit;
  ...
</code>```

Controller site

```<code>@Controller
public class SiteController {

  private SiteRepository siteRepository;

  @RequestMapping(value="/save2",method=RequestMethod.POST)
  public String save2(Model model, @Valid @ModelAttribute("site") Site site, BindingResult result) {
     if(result.hasErrors()){
            return "formProduit";
       }  else{
            siteRepository.save(site);               //line55

      return "confirmationsite";
      }}

...
</code>```

ERROR

```<code>java.lang.NullPointerException: null
at com.example.web.SiteController.save2(SiteController.java:53) ~[classes/:na]
</code>```

答:
You are missing to inject the Repository into the controller. Add @Inject on top of the siteRepository.

```<code>@Controller
public class SiteController {

  @Inject
  private SiteRepository siteRepository;
</code>```

Body:
When Posting data with one to many relationship using Thymeleaf, I want to save form site with dropdown list (nomclient) from table produit

Entity Model

 @Entity

 public class Produit implements Serializable {
    ...
    @OneToMany(fetch = FetchType.LAZY,mappedBy="produit")
    private List<Site> listSites=new ArrayList<Site>();
    ...

Entity Model - Produit

public class Site implements Serializable {
  ...
  @JoinColumn(name = "refProduit")
  @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
  private Produit produit;
  ...

Controller site

@Controller
public class SiteController {

  private SiteRepository siteRepository;

  @RequestMapping(value="/save2",method=RequestMethod.POST)
  public String save2(Model model, @Valid @ModelAttribute("site") Site site, BindingResult result) {
     if(result.hasErrors()){
            return "formProduit";
       }  else{
            siteRepository.save(site);               //line55

      return "confirmationsite";
      }}

...

ERROR

java.lang.NullPointerException: null
at com.example.web.SiteController.save2(SiteController.java:53) ~[classes/:na]

Body:
You are missing to inject the Repository into the controller. Add @Inject on top of the siteRepository.

@Controller
public class SiteController {

  @Inject
  private SiteRepository siteRepository;


问:
python how to get name of the enum
I have an enum like this

```<code>class testEnum(Enum):
   Code_1 = "successful response"
   Code_2 = "failure response"
</code>```

Then I have a method that takes the enum key name Code_1 and enum key value successful response as inputs.

If I send testEnum.Code_1 then that resolves to successful response and not Code_1.

I checked some documentation online that suggests to use testEnum.Code_1.name but that throws an error saing that 'name' doesn't exist for the enum item.

Does anyone know how to get the name of the enum key ?

答:
dir(testEnum) will give you the dictionary keys.

e.g.

```<code>dir(testEnum)
</code>```

returns:

['Code_1',
 'Code_2',
 'class',
 'delattr',
 'dict',
 'dir',
 'doc',
 'eq',
 'format',
 'ge',
 'getattribute',
 'gt',
 'hash',
 'init',
 'init_subclass',
 'le',
 'lt',
 'module',
 'ne',
 'new',
 'reduce',
 'reduce_ex',
 'repr',
 'setattr',
 'sizeof',
 'str',
 'subclasshook',
 'weakref']

Title: python how to get name of the enum

Body:
I have an enum like this

class testEnum(Enum):
   Code_1 = "successful response"
   Code_2 = "failure response"

Then I have a method that takes the enum key name Code_1 and enum key value successful response as inputs.

If I send testEnum.Code_1 then that resolves to successful response and not Code_1.

I checked some documentation online that suggests to use testEnum.Code_1.name but that throws an error saing that 'name' doesn't exist for the enum item.

Does anyone know how to get the name of the enum key ?

Body:
dir(testEnum) will give you the dictionary keys.

e.g.

dir(testEnum)

returns:

['Code_1',
 'Code_2',
 'class',
 'delattr',
 'dict',
 'dir',
 'doc',
 'eq',
 'format',
 'ge',
 'getattribute',
 'gt',
 'hash',
 'init',
 'init_subclass',
 'le',
 'lt',
 'module',
 'ne',
 'new',
 'reduce',
 'reduce_ex',
 'repr',
 'setattr',
 'sizeof',
 'str',
 'subclasshook',
 'weakref']


问:
string.format not returning correct string when used with SQLite
desired output: Can you relate [chore one] to one of your values (such as [value one], [value two] and [ value three])? If so, how is the activity related to your value(s)?

actual output: Can you relate [null] to one of your values (such as [value one], [value two] and [ value three])? If so, how is the activity related to your value(s)? Can you relate [chore one] to one of your values (such as [null], [null] and [ null])? If so, how is the activity related to your value(s)?

query method:

```<code>   public String getChoreOneWValues() {
    SQLiteDatabase db = helper.getWritableDatabase();
    //Select
    String[] columns= {StressQuizSQLiteHelper.CHORE_ONE,StressQuizSQLiteHelper.VALUE_ONE,
            StressQuizSQLiteHelper.VALUE_TWO, StressQuizSQLiteHelper.VALUE_THREE};
    Cursor cursor=db.query(StressQuizSQLiteHelper.REC_CHOICE_TABLE_NAME, columns, null, null, null, null, null);
    StringBuilder buffer=new StringBuilder();
    while(cursor.moveToNext())
    {
        int index1=cursor.getColumnIndex(StressQuizSQLiteHelper.CHORE_ONE);
        int index2=cursor.getColumnIndex(StressQuizSQLiteHelper.VALUE_ONE);
        int index3=cursor.getColumnIndex(StressQuizSQLiteHelper.VALUE_TWO);
        int index4=cursor.getColumnIndex(StressQuizSQLiteHelper.VALUE_THREE);
        String choreOne=cursor.getString((index1));
        String value1=cursor.getString((index2));
        String value2=cursor.getString((index3));
        String value3=cursor.getString((index4));
        buffer.append(String.format("Can you relate \"%s\" to one of your values (such as %s, %s and %s)?" +
                " If so, how is the activity related to your value(s)? ", choreOne, value1,value2, value3));
    }
    cursor.close();
    return buffer.toString();

}
</code>```

create table string:

```<code>private static final String CREATE__REC_CHOICE_TABLE = "create table "
            + REC_CHOICE_TABLE_NAME + " ("
            + REC_CHOICE_TABLE_NAME_UID
            + " integer primary key autoincrement not null,"
            + VALUE_ONE
            + " text,"
            + VALUE_TWO
            + " text,"
            + VALUE_THREE
            + " text,"
            + CHORE_ONE
            + " text,"
            + CHORE_TWO
            + " text,"
            + CHORE_THREE
            + " text,"
            + CHORE_FOUR
            + " text,"
            + CHORE_FIVE
            + " text,"
            + VALUE_JOURNAL_ENTRY_ONE
            + " text,"
            + VALUE_JOURNAL_ENTRY_TWO
            + " text,"
            + VALUE_JOURNAL_ENTRY_THREE
            + " text,"
            + VALUE_JOURNAL_ENTRY_FOUR
            + " text,"
            + VALUE_JOURNAL_ENTRY_FIVE
            + " text"
            + ");";
</code>```

insert methods:

```<code>public long insertPersonalValues(String one, String two, String three){
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(StressQuizSQLiteHelper.VALUE_ONE, one);
    contentValues.put(StressQuizSQLiteHelper.VALUE_TWO, two);
    contentValues.put(StressQuizSQLiteHelper.VALUE_THREE, three);

    long id = db.insert(StressQuizSQLiteHelper.REC_CHOICE_TABLE_NAME, null, contentValues);
    return id;

}

public long insertChores(String one, String two, String three, String four, String five){
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(StressQuizSQLiteHelper.CHORE_ONE, one);
    contentValues.put(StressQuizSQLiteHelper.CHORE_TWO, two);
    contentValues.put(StressQuizSQLiteHelper.CHORE_THREE, three);
    contentValues.put(StressQuizSQLiteHelper.CHORE_FOUR, four);
    contentValues.put(StressQuizSQLiteHelper.CHORE_FIVE, five);

    long id = db.insert(StressQuizSQLiteHelper.REC_CHOICE_TABLE_NAME, null, contentValues);
    return id;
}
</code>```

答: I used an update statement to update the null values to the desired values. </p>

Body:
desired output: Can you relate [chore one] to one of your values (such as [value one], [value two] and [ value three])? If so, how is the activity related to your value(s)?

actual output: Can you relate [null] to one of your values (such as [value one], [value two] and [ value three])? If so, how is the activity related to your value(s)? Can you relate [chore one] to one of your values (such as [null], [null] and [ null])? If so, how is the activity related to your value(s)?

query method:

   public String getChoreOneWValues() {
    SQLiteDatabase db = helper.getWritableDatabase();
    //Select
    String[] columns= {StressQuizSQLiteHelper.CHORE_ONE,StressQuizSQLiteHelper.VALUE_ONE,
            StressQuizSQLiteHelper.VALUE_TWO, StressQuizSQLiteHelper.VALUE_THREE};
    Cursor cursor=db.query(StressQuizSQLiteHelper.REC_CHOICE_TABLE_NAME, columns, null, null, null, null, null);
    StringBuilder buffer=new StringBuilder();
    while(cursor.moveToNext())
    {
        int index1=cursor.getColumnIndex(StressQuizSQLiteHelper.CHORE_ONE);
        int index2=cursor.getColumnIndex(StressQuizSQLiteHelper.VALUE_ONE);
        int index3=cursor.getColumnIndex(StressQuizSQLiteHelper.VALUE_TWO);
        int index4=cursor.getColumnIndex(StressQuizSQLiteHelper.VALUE_THREE);
        String choreOne=cursor.getString((index1));
        String value1=cursor.getString((index2));
        String value2=cursor.getString((index3));
        String value3=cursor.getString((index4));
        buffer.append(String.format("Can you relate \"%s\" to one of your values (such as %s, %s and %s)?" +
                " If so, how is the activity related to your value(s)? ", choreOne, value1,value2, value3));
    }
    cursor.close();
    return buffer.toString();

}

create table string:

private static final String CREATE__REC_CHOICE_TABLE = "create table "
            + REC_CHOICE_TABLE_NAME + " ("
            + REC_CHOICE_TABLE_NAME_UID
            + " integer primary key autoincrement not null,"
            + VALUE_ONE
            + " text,"
            + VALUE_TWO
            + " text,"
            + VALUE_THREE
            + " text,"
            + CHORE_ONE
            + " text,"
            + CHORE_TWO
            + " text,"
            + CHORE_THREE
            + " text,"
            + CHORE_FOUR
            + " text,"
            + CHORE_FIVE
            + " text,"
            + VALUE_JOURNAL_ENTRY_ONE
            + " text,"
            + VALUE_JOURNAL_ENTRY_TWO
            + " text,"
            + VALUE_JOURNAL_ENTRY_THREE
            + " text,"
            + VALUE_JOURNAL_ENTRY_FOUR
            + " text,"
            + VALUE_JOURNAL_ENTRY_FIVE
            + " text"
            + ");";

insert methods:

public long insertPersonalValues(String one, String two, String three){
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(StressQuizSQLiteHelper.VALUE_ONE, one);
    contentValues.put(StressQuizSQLiteHelper.VALUE_TWO, two);
    contentValues.put(StressQuizSQLiteHelper.VALUE_THREE, three);

    long id = db.insert(StressQuizSQLiteHelper.REC_CHOICE_TABLE_NAME, null, contentValues);
    return id;

}

public long insertChores(String one, String two, String three, String four, String five){
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(StressQuizSQLiteHelper.CHORE_ONE, one);
    contentValues.put(StressQuizSQLiteHelper.CHORE_TWO, two);
    contentValues.put(StressQuizSQLiteHelper.CHORE_THREE, three);
    contentValues.put(StressQuizSQLiteHelper.CHORE_FOUR, four);
    contentValues.put(StressQuizSQLiteHelper.CHORE_FIVE, five);

    long id = db.insert(StressQuizSQLiteHelper.REC_CHOICE_TABLE_NAME, null, contentValues);
    return id;
}


问:
Tableau Excluded Data - Calculated Fields and Overlapping Time Periods
I want to plot revenue for two time periods "Last 30 Days" and "Last 60 Days" on the same diagram. The problem is that for "Last 60 Days" all the data that already is in "Last 30 Days" will not be included.

This is due to my IF clause which looks like this:

```<code>IF [Auftragsdatum] >= DATEADD('day', -30, NOW()) AND [Auftragsdatum] <= DATEADD('day', 0, NOW()) THEN 'Last 30 Days'
ELSEIF [Auftragsdatum] >= DATEADD('day', -60, NOW()) AND [Auftragsdatum] <= DATEADD('day', 0, NOW()) THEN 'Last 60 Days'
END
</code>```

Does anybody know how to work around this?

答:
Create a calculated field called revenue_last_30_days defined as

IF  DATEDIFF('day', [Auftragsdatum], TODAY()) <= 30 AND
    [Auftragsdatum] <= TODAY() THEN [Revenue] END

Create a second calculated field called revenue_last_60_days defined as

IF  DATEDIFF('day', [Auftragsdatum], TODAY()) <= 60 AND
    [Auftragsdatum] <= TODAY() THEN [Revenue] END

Plot both measures as desired, probably using the pseudo fields Measure Names and Measure Values to specify your viz.

If you don't ever have future revenue in your data, you can drop the test checking to be no later than today -- since that will always be true.

Body:
I want to plot revenue for two time periods "Last 30 Days" and "Last 60 Days" on the same diagram. The problem is that for "Last 60 Days" all the data that already is in "Last 30 Days" will not be included.

This is due to my IF clause which looks like this:

IF [Auftragsdatum] >= DATEADD('day', -30, NOW()) AND [Auftragsdatum] <= DATEADD('day', 0, NOW()) THEN 'Last 30 Days'
ELSEIF [Auftragsdatum] >= DATEADD('day', -60, NOW()) AND [Auftragsdatum] <= DATEADD('day', 0, NOW()) THEN 'Last 60 Days'
END

Does anybody know how to work around this?


问:
fosuserbundle No route found for "GET /login/"
I recently updated symfony2 using composer, and now I can't login. Here are the relevant files. Let me know if more data is needed.

app/config/routing.yml

```<code>app_admin:
resource: "@AppAdminBundle/Resources/config/routing.yml"
prefix:   /admin
host: dashboard.muchomonitor.com

app_website:
resource: "@AppWebsiteBundle/Resources/config/routing.yml"
prefix:   /
host: www.muchomonitor.com

app_monitor:
resource: "@AppMonitorBundle/Resources/config/routing.yml"
prefix:   /
host: dashboard.muchomonitor.com

fos_user_security:
resource: "@FOSUserBundle/Resources/config/routing/security.xml"
host: dashboard.muchomonitor.com

fos_user_security_reset:
resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
prefix: /login
host: dashboard.muchomonitor.com
</code>```

app/config/security.yml

```<code>security:
encoders:
    FOS\UserBundle\Model\UserInterface: sha512

role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN

providers:
    fos_userbundle:
        id: fos_user.user_provider.username
    user:
        entity: { class: App\MonitorBundle\Entity\User, property: username }

firewalls:
    main:
        pattern: ^/
        provider: user
        form_login:
            provider: fos_userbundle
            csrf_provider: form.csrf_provider
            login_path: fos_user_security_login
            check_path: fos_user_security_check
            default_target_path: /
        logout:       true
        anonymous:    true
        logout:
            path:   /logout
            target: /login

access_control:
    - { path: ^/admin, role: ROLE_SUPER_ADMIN, host: dashboard.muchomonitor.com }
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, host: dashboard.muchomonitor.com }
    - { path: ^/_, role: ROLE_ADMIN } # Development mode
    - { path: ^/public-status, role: IS_AUTHENTICATED_ANONYMOUSLY, host: dashboard.muchomonitor.com }
    - { path: ^/ipn, role: IS_AUTHENTICATED_ANONYMOUSLY, host: dashboard.muchomonitor.com }
    - { path: ^/invoice, role: IS_AUTHENTICATED_ANONYMOUSLY, host: dashboard.muchomonitor.com }
    - { path: ^/, role: ROLE_USER, host: dashboard.muchomonitor.com }
</code>```

vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Resources/config/routing/security.xml

```<code><?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="fos_user_security_login" pattern="/login">
        <default key="_controller">FOSUserBundle:Security:login</default>
    </route>

    <route id="fos_user_security_check" pattern="/login_check">
        <default key="_controller">FOSUserBundle:Security:check</default>
        <requirement key="_method">POST</requirement>
    </route>

    <route id="fos_user_security_logout" pattern="/logout">
        <default key="_controller">FOSUserBundle:Security:logout</default>
    </route>

</routes>
</code>```

vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Resources/config/routing/resetting.xml

```<code><?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="fos_user_resetting_request" pattern="/request">
        <default key="_controller">FOSUserBundle:Resetting:request</default>
        <requirement key="_method">GET</requirement>
    </route>

    <route id="fos_user_resetting_send_email" pattern="/send-email">
        <default key="_controller">FOSUserBundle:Resetting:sendEmail</default>
        <requirement key="_method">POST</requirement>
    </route>

    <route id="fos_user_resetting_check_email" pattern="/check-email">
        <default key="_controller">FOSUserBundle:Resetting:checkEmail</default>
        <requirement key="_method">GET</requirement>
    </route>

    <route id="fos_user_resetting_reset" pattern="/reset/{token}">
        <default key="_controller">FOSUserBundle:Resetting:reset</default>
        <requirement key="_method">GET|POST</requirement>
    </route>

</routes>
</code>```

php app/console route:debug

```<code>Name                           Method   Scheme Host                       Path
app_admin_users                ANY      ANY    dashboard.muchomonitor.com /admin
app_admin_add_user             ANY      ANY    dashboard.muchomonitor.com /admin
app_admin_edit_user            ANY      ANY    dashboard.muchomonitor.com /admin
app_admin_delete_user          ANY      ANY    dashboard.muchomonitor.com                                    /admin/user/{id}/delete
app_admin_login_user           ANY      ANY    dashboard.muchomonitor.com  /admin/user/{id}/login
app_admin_plans                ANY      ANY    dashboard.muchomonitor.com /admin/plans
app_admin_delete_plan          ANY      ANY    dashboard.muchomonitor.com /admin/plans/{id}/delete
app_admin_edit_plan            ANY      ANY    dashboard.muchomonitor.com /admin/plans/{id}/edit
app_admin_add_plan             ANY      ANY    dashboard.muchomonitor.com /admin/plans/add
app_admin_invoices             ANY      ANY    dashboard.muchomonitor.com /admin/invoices
app_admin_delete_invoice       ANY      ANY    dashboard.muchomonitor.com /admin/invoices/{id}/delete
app_admin_edit_invoice         ANY      ANY    dashboard.muchomonitor.com /admin/invoices/{id}/edit
app_admin_add_invoice          ANY      ANY    dashboard.muchomonitor.com /admin/invoices/add
app_website_index              ANY      ANY    www.muchomonitor.com       /
app_website_pricing            ANY      ANY    www.muchomonitor.com       /pricing
app_website_privacy_policy     ANY      ANY    www.muchomonitor.com       /legal/privacypolicy
app_website_signup             ANY      ANY    www.muchomonitor.com       /signup
app_website_tos                ANY      ANY    www.muchomonitor.com       /legal/termsofservice
app_website_contact_us         ANY      ANY    www.muchomonitor.com       /contactus
app_monitor_dashboard          ANY      ANY    dashboard.muchomonitor.com /
app_monitor_dashboard_search   ANY      ANY    dashboard.muchomonitor.com /dashboard/search/{filter}
app_monitor_dashboard_toggle   ANY      ANY    dashboard.muchomonitor.com /dashboard/toggle/{monitor}
app_monitor_dashboard_delete   ANY      ANY    dashboard.muchomonitor.com /dashboard/delete
app_monitor_dashboard_test     ANY      ANY    dashboard.muchomonitor.com /dashboard/test
app_monitor_monitors           ANY      ANY    dashboard.muchomonitor.com /monitors
app_monitor_monitors_edit      ANY      ANY    dashboard.muchomonitor.com /monitors/edit/{monitor}
app_monitor_monitors_new       ANY      ANY    dashboard.muchomonitor.com /monitors/new
app_monitor_monitors_toggle    ANY      ANY    dashboard.muchomonitor.com /monitors/toggle/{monitor}
app_monitor_monitors_delete    ANY      ANY    dashboard.muchomonitor.com /monitors/delete
app_monitor_monitors_test      ANY      ANY    dashboard.muchomonitor.com /monitors/test
app_monitor_report             ANY      ANY    dashboard.muchomonitor.com /report
app_monitor_reports            ANY      ANY    dashboard.muchomonitor.com /report
app_monitor_report_specific    ANY      ANY    dashboard.muchomonitor.com /report/{monitor}
app_monitor_accounts           ANY      ANY    dashboard.muchomonitor.com /accounts
app_monitor_accounts_edit      ANY      ANY    dashboard.muchomonitor.com /accounts/edit/{id}
app_monitor_accounts_new       ANY      ANY    dashboard.muchomonitor.com /accounts/new
app_monitor_accounts_delete    ANY      ANY    dashboard.muchomonitor.com /accounts/delete
app_monitor_billing            ANY      ANY    dashboard.muchomonitor.com /billing
app_monitor_billing_all        ANY      ANY    dashboard.muchomonitor.com /billing/all
app_monitor_billing_invoice    ANY      ANY    dashboard.muchomonitor.com /invoice/{key}/{id}
app_monitor_notifications      ANY      ANY    dashboard.muchomonitor.com /notifications
app_monitor_ipn                ANY      ANY    dashboard.muchomonitor.com /ipn
app_monitor_ipn_stripe         ANY      ANY    dashboard.muchomonitor.com /ipn-stripe
fos_user_security_login        ANY      ANY    dashboard.muchomonitor.com /login
fos_user_security_check        POST     ANY    dashboard.muchomonitor.com /login_check
fos_user_security_logout       ANY      ANY    dashboard.muchomonitor.com /logout
fos_user_resetting_request     GET      ANY    dashboard.muchomonitor.com /login/request
fos_user_resetting_send_email  POST     ANY    dashboard.muchomonitor.com /login/send-email
fos_user_resetting_check_email GET      ANY    dashboard.muchomonitor.com /login/check-email
fos_user_resetting_reset       GET|POST ANY    dashboard.muchomonitor.com /login/reset/{token}
</code>```

going onto dashboard.muchomonitor.com/login shows it doesn't work, despite what the above command said.

EDIT:
I have solved the problem. In routing.yml

```<code>fos_user_security_login:
pattern:  /login/
defaults: { _controller: FOSUserBundle:Security:login }

fos_user_security_check:
pattern:  /login_check
defaults: { _controller: FOSUserBundle:Security:check }

fos_user_security_logout:
pattern:  /logout
defaults: { _controller: FOSUserBundle:Security:logout }
</code>```

答:
I got the similar problem, although I resolved differently (using Symfony 3.1, but perhaps it is the same work around).

When I executed in the console the command bin/console debug:router, I could see that the routes for the authentication provided by the FoS User bundle were correct, and they displayed properly.

Now, the problem is that in the console, the default environment was DEV, whereas from the broser, it was PROD.

I executed the same command above, but explicitely passing the environment, as follows:

bin/console debug:router --env=dev, and I got the same results as earlier.

But when executing bin/console debug:router --env=prod, I got an error in the console, saying that the routing.yml file could not be found.

That was correct. I had changed the structure of the app/config directory, and created a folder for each environment, with the relevant files in each folder (much neater configuration, IMHO).

But it looks like the path for routing.yml for the PROD environment is hardcoded in some vendors (example, in vendor/sensio/generator-bundle/Command), and because of that, the location of that file can't be changed.

After re-arranging the configuration folder, everything worked (but I had to clear the cache of the PROD environment, as follows: bin/console cache:clear --no-warmup --env=prod .

Body:
I recently updated symfony2 using composer, and now I can't login. Here are the relevant files. Let me know if more data is needed.

app/config/routing.yml

app_admin:
resource: "@AppAdminBundle/Resources/config/routing.yml"
prefix:   /admin
host: dashboard.muchomonitor.com

app_website:
resource: "@AppWebsiteBundle/Resources/config/routing.yml"
prefix:   /
host: www.muchomonitor.com

app_monitor:
resource: "@AppMonitorBundle/Resources/config/routing.yml"
prefix:   /
host: dashboard.muchomonitor.com

fos_user_security:
resource: "@FOSUserBundle/Resources/config/routing/security.xml"
host: dashboard.muchomonitor.com

fos_user_security_reset:
resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
prefix: /login
host: dashboard.muchomonitor.com

app/config/security.yml

security:
encoders:
    FOS\UserBundle\Model\UserInterface: sha512

role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN

providers:
    fos_userbundle:
        id: fos_user.user_provider.username
    user:
        entity: { class: App\MonitorBundle\Entity\User, property: username }

firewalls:
    main:
        pattern: ^/
        provider: user
        form_login:
            provider: fos_userbundle
            csrf_provider: form.csrf_provider
            login_path: fos_user_security_login
            check_path: fos_user_security_check
            default_target_path: /
        logout:       true
        anonymous:    true
        logout:
            path:   /logout
            target: /login

access_control:
    - { path: ^/admin, role: ROLE_SUPER_ADMIN, host: dashboard.muchomonitor.com }
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, host: dashboard.muchomonitor.com }
    - { path: ^/_, role: ROLE_ADMIN } # Development mode
    - { path: ^/public-status, role: IS_AUTHENTICATED_ANONYMOUSLY, host: dashboard.muchomonitor.com }
    - { path: ^/ipn, role: IS_AUTHENTICATED_ANONYMOUSLY, host: dashboard.muchomonitor.com }
    - { path: ^/invoice, role: IS_AUTHENTICATED_ANONYMOUSLY, host: dashboard.muchomonitor.com }
    - { path: ^/, role: ROLE_USER, host: dashboard.muchomonitor.com }

vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Resources/config/routing/security.xml

<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="fos_user_security_login" pattern="/login">
        <default key="_controller">FOSUserBundle:Security:login</default>
    </route>

    <route id="fos_user_security_check" pattern="/login_check">
        <default key="_controller">FOSUserBundle:Security:check</default>
        <requirement key="_method">POST</requirement>
    </route>

    <route id="fos_user_security_logout" pattern="/logout">
        <default key="_controller">FOSUserBundle:Security:logout</default>
    </route>

</routes>

vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Resources/config/routing/resetting.xml

<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="fos_user_resetting_request" pattern="/request">
        <default key="_controller">FOSUserBundle:Resetting:request</default>
        <requirement key="_method">GET</requirement>
    </route>

    <route id="fos_user_resetting_send_email" pattern="/send-email">
        <default key="_controller">FOSUserBundle:Resetting:sendEmail</default>
        <requirement key="_method">POST</requirement>
    </route>

    <route id="fos_user_resetting_check_email" pattern="/check-email">
        <default key="_controller">FOSUserBundle:Resetting:checkEmail</default>
        <requirement key="_method">GET</requirement>
    </route>

    <route id="fos_user_resetting_reset" pattern="/reset/{token}">
        <default key="_controller">FOSUserBundle:Resetting:reset</default>
        <requirement key="_method">GET|POST</requirement>
    </route>

</routes>

php app/console route:debug

Name                           Method   Scheme Host                       Path
app_admin_users                ANY      ANY    dashboard.muchomonitor.com /admin
app_admin_add_user             ANY      ANY    dashboard.muchomonitor.com /admin
app_admin_edit_user            ANY      ANY    dashboard.muchomonitor.com /admin
app_admin_delete_user          ANY      ANY    dashboard.muchomonitor.com                                    /admin/user/{id}/delete
app_admin_login_user           ANY      ANY    dashboard.muchomonitor.com  /admin/user/{id}/login
app_admin_plans                ANY      ANY    dashboard.muchomonitor.com /admin/plans
app_admin_delete_plan          ANY      ANY    dashboard.muchomonitor.com /admin/plans/{id}/delete
app_admin_edit_plan            ANY      ANY    dashboard.muchomonitor.com /admin/plans/{id}/edit
app_admin_add_plan             ANY      ANY    dashboard.muchomonitor.com /admin/plans/add
app_admin_invoices             ANY      ANY    dashboard.muchomonitor.com /admin/invoices
app_admin_delete_invoice       ANY      ANY    dashboard.muchomonitor.com /admin/invoices/{id}/delete
app_admin_edit_invoice         ANY      ANY    dashboard.muchomonitor.com /admin/invoices/{id}/edit
app_admin_add_invoice          ANY      ANY    dashboard.muchomonitor.com /admin/invoices/add
app_website_index              ANY      ANY    www.muchomonitor.com       /
app_website_pricing            ANY      ANY    www.muchomonitor.com       /pricing
app_website_privacy_policy     ANY      ANY    www.muchomonitor.com       /legal/privacypolicy
app_website_signup             ANY      ANY    www.muchomonitor.com       /signup
app_website_tos                ANY      ANY    www.muchomonitor.com       /legal/termsofservice
app_website_contact_us         ANY      ANY    www.muchomonitor.com       /contactus
app_monitor_dashboard          ANY      ANY    dashboard.muchomonitor.com /
app_monitor_dashboard_search   ANY      ANY    dashboard.muchomonitor.com /dashboard/search/{filter}
app_monitor_dashboard_toggle   ANY      ANY    dashboard.muchomonitor.com /dashboard/toggle/{monitor}
app_monitor_dashboard_delete   ANY      ANY    dashboard.muchomonitor.com /dashboard/delete
app_monitor_dashboard_test     ANY      ANY    dashboard.muchomonitor.com /dashboard/test
app_monitor_monitors           ANY      ANY    dashboard.muchomonitor.com /monitors
app_monitor_monitors_edit      ANY      ANY    dashboard.muchomonitor.com /monitors/edit/{monitor}
app_monitor_monitors_new       ANY      ANY    dashboard.muchomonitor.com /monitors/new
app_monitor_monitors_toggle    ANY      ANY    dashboard.muchomonitor.com /monitors/toggle/{monitor}
app_monitor_monitors_delete    ANY      ANY    dashboard.muchomonitor.com /monitors/delete
app_monitor_monitors_test      ANY      ANY    dashboard.muchomonitor.com /monitors/test
app_monitor_report             ANY      ANY    dashboard.muchomonitor.com /report
app_monitor_reports            ANY      ANY    dashboard.muchomonitor.com /report
app_monitor_report_specific    ANY      ANY    dashboard.muchomonitor.com /report/{monitor}
app_monitor_accounts           ANY      ANY    dashboard.muchomonitor.com /accounts
app_monitor_accounts_edit      ANY      ANY    dashboard.muchomonitor.com /accounts/edit/{id}
app_monitor_accounts_new       ANY      ANY    dashboard.muchomonitor.com /accounts/new
app_monitor_accounts_delete    ANY      ANY    dashboard.muchomonitor.com /accounts/delete
app_monitor_billing            ANY      ANY    dashboard.muchomonitor.com /billing
app_monitor_billing_all        ANY      ANY    dashboard.muchomonitor.com /billing/all
app_monitor_billing_invoice    ANY      ANY    dashboard.muchomonitor.com /invoice/{key}/{id}
app_monitor_notifications      ANY      ANY    dashboard.muchomonitor.com /notifications
app_monitor_ipn                ANY      ANY    dashboard.muchomonitor.com /ipn
app_monitor_ipn_stripe         ANY      ANY    dashboard.muchomonitor.com /ipn-stripe
fos_user_security_login        ANY      ANY    dashboard.muchomonitor.com /login
fos_user_security_check        POST     ANY    dashboard.muchomonitor.com /login_check
fos_user_security_logout       ANY      ANY    dashboard.muchomonitor.com /logout
fos_user_resetting_request     GET      ANY    dashboard.muchomonitor.com /login/request
fos_user_resetting_send_email  POST     ANY    dashboard.muchomonitor.com /login/send-email
fos_user_resetting_check_email GET      ANY    dashboard.muchomonitor.com /login/check-email
fos_user_resetting_reset       GET|POST ANY    dashboard.muchomonitor.com /login/reset/{token}

going onto dashboard.muchomonitor.com/login shows it doesn't work, despite what the above command said.

EDIT:
I have solved the problem. In routing.yml

fos_user_security_login:
pattern:  /login/
defaults: { _controller: FOSUserBundle:Security:login }

fos_user_security_check:
pattern:  /login_check
defaults: { _controller: FOSUserBundle:Security:check }

fos_user_security_logout:
pattern:  /logout
defaults: { _controller: FOSUserBundle:Security:logout }


问:
Angular Google Maps ui-gmap-google-map doesn't load the map
I have simple scenario but still, doesn't work..:

index.html

```<code><!DOCTYPE html>
<html lang="en" ng-app="myapp">
<head>
    <meta charset="utf-8">
    <title>app</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    <!-- Custom-->
    <link rel="stylesheet" href="/css/style.css">
    <script type="text/javascript" src="/js/lodash.js"></script>
    <script type="text/javascript" src="/js/angular.js"></script>
    <script type="text/javascript" src="/js/angular-simple-logger.js"></script>
    <script type="text/javascript" src="/js/angular-google-maps.js"></script>
    <script type="text/javascript" src="/js/angular-google-maps-street-view.js"></script>

    <script type="text/javascript" src="/js/app/app.js"></script>

    <!-- Controllers -->
    <script type="text/javascript" src="/js/app/controllers/MainController.js"></script>

</head>
<body ng-controller="MainController">

<ui-gmap-google-map center='map.center' zoom='map.zoom'></ui-gmap-google-map>

</body>
</html>
</code>```

app.js

```<code>var myapp = angular.module('myapp', ['uiGmapgoogle-maps']);

myapp.config(function (uiGmapGoogleMapApiProvider) {
    uiGmapGoogleMapApiProvider.configure({
        key: 'MY_API_KEY',
        // v: '3.28',
        libraries: 'weather,geometry,visualization'
    });
});
</code>```

MainController.js

```<code>myapp.controller("MainController",function ($scope,uiGmapGoogleMapApi) {

    uiGmapGoogleMapApi.then(function (maps) {
        $scope.maps = maps;
        $scope.map = { center: { latitude: 45, longitude: -73 }, zoom: 10 };
    });

});
</code>```

style.css

```<code>ui-gmap-google-map{
    border: 1px dashed darkred;
    width: 500px;
    height: 300px;
    display: inline-block;
}

.angular-google-map-container {
    width: 400px;
    height: 400px;
}
</code>```

No errors in the console. The css is applying ok, the promise in the controller is working ok but no map is displayed.

The fact that the DOM is staying like that is bothering me :

```<code><ui-gmap-google-map center="map.center" zoom="map.zoom"></ui-gmap-google-map>
</code>```

because on the example site I saw that angular is changing it like that :

```<code><ui-gmap-google-map center="map.center" zoom="map.zoom" class="ng-isolate-scope"><div class="angular-google-map"><div class="angular-google-map-container">
</div><div ng-transclude="" style="display: none"></div></div></ui-gmap-google-map>
</code>```

(or something like that)

Any idea what am I doing wrong ?

答:
Since your map is loading inside a promise, try using ng-if to render it conditionally (as specified here):

```<code><ui-gmap-google-map ng-if='map.center'
                   center='map.center'
                   zoom='map.zoom'>
</ui-gmap-google-map>
</code>```

Working demo here.

Body:
I have simple scenario but still, doesn't work..:

index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>app</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    <link rel="stylesheet" href="/css/style.css">

<ui-gmap-google-map center='map.center' zoom='map.zoom'></ui-gmap-google-map>

app.js

var myapp = angular.module('myapp', ['uiGmapgoogle-maps']);

myapp.config(function (uiGmapGoogleMapApiProvider) {
    uiGmapGoogleMapApiProvider.configure({
        key: 'MY_API_KEY',
        // v: '3.28',
        libraries: 'weather,geometry,visualization'
    });
});

MainController.js

myapp.controller("MainController",function ($scope,uiGmapGoogleMapApi) {

    uiGmapGoogleMapApi.then(function (maps) {
        $scope.maps = maps;
        $scope.map = { center: { latitude: 45, longitude: -73 }, zoom: 10 };
    });

});

style.css

ui-gmap-google-map{
    border: 1px dashed darkred;
    width: 500px;
    height: 300px;
    display: inline-block;
}

.angular-google-map-container {
    width: 400px;
    height: 400px;
}

No errors in the console. The css is applying ok, the promise in the controller is working ok but no map is displayed.

The fact that the DOM is staying like that is bothering me :

<ui-gmap-google-map center="map.center" zoom="map.zoom"></ui-gmap-google-map>

because on the example site I saw that angular is changing it like that :

<ui-gmap-google-map center="map.center" zoom="map.zoom" class="ng-isolate-scope">

</ui-gmap-google-map>

(or something like that)

Any idea what am I doing wrong ?

Body:
Since your map is loading inside a promise, try using ng-if to render it conditionally (as specified here):

<ui-gmap-google-map ng-if='map.center'
                   center='map.center'
                   zoom='map.zoom'>
</ui-gmap-google-map>

Working demo here.


问:
How to load specific div or id ajax and laravel
i have a comment system on my app in laravel and i can edit my comments with ajax but once edited it doesn't load automatically the edited comment. To see the edited comment i need to reload the page manually. I will put some of the code here.

This is the JS:

        var commentId = 0;
        var divcomment = null;

        $('.edit-comment').click(function(event){
          event.preventDefault();
          /* Accedemos al Div Que contiene el Panel*/
          var divcomment = this.parentNode.parentNode;
          /* Buscamos el Contenido con Id display-text  */
          commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
          var commentBody = $(divcomment).find('#display-comment').text();
          $('#comment').val(commentBody);
          $('#edit-comment').modal();
           /* Asignas a tu modal */
        });

        $('#modal-save').on('click', function(){
            $.ajax({
                method: 'PUT',
                url: urlEdit,
                data: {
                    comment: $('#comment').val(),
                    commentId: commentId,
                    _token: token,
                    _method: 'PUT',
                    dataType: 'json',
                 }
            })
            .done(function (msg){
                $(divcomment).text(msg['new_comment']);
                $('#edit-comment').modal('hide');
            });
        });
```

<p>This is the Html:</p>

<pre class="lang-html prettyprint-override"><code> <article class="row">
                            <div class="col-md-3 col-sm-3 hidden-xs">
                              <figure class="thumbnail">
                                <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}" />
                                <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
                              </figure>
                            </div>
                            <div class="col-md-8 col-sm-8">
                              <div class="panel panel-default arrow left">
                                <div class="panel-body">
                                  <header class="text-left">
                                    <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}</div>
                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}</time>
                                  </header>
                                  <div id="comment-post" data-commentid="{{ $comment->id }}">
                                      <p id="display-comment">{{ $comment->comment }}</p>
                                  </div>
                                </div>

                                <div class="panel-footer list-inline comment-footer">
                                  @if(Auth::guest())

                                  No puedes responder ningún comentario si no has ingresado.

                                  @else

                                  @if(Auth::user() == $comment->user)
                                    Editar Eliminar
                                  @endif

                                  @if(Auth::user() != $comment->user)
                                    Responder
                                  @endif

                                  @endif
                                </div>

                              </div>
                            </div>
                          </article>
</code>```

2 variables created on the view

```<code>  var token = '{{ Session::token() }}';
  var urlEdit = '{{ url('comments/update') }}';
</code>```

and finally the modal where i edit the comment:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Editar Comentario

        <form>

            Editar comentario
            <textarea class="form-control" name="comment" id="comment"></textarea>

        </form>

        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"> Editar</button>

```

Everything's working but the only thing i need is to load the edited comment back without refresh the whole page, btw i used $('#display-comment').load(document.URL +  ' #display-comment'); and with this line i succesfully load the edited comment but, it load all the comments on the edited one, so i have to refresh the whole page to show just the edited.

答:
Assuming that the data sent to the php side of things is the same data that you then want to update to, the following should work:

```<code>$('#modal-save').on('click', function(){
    var comment = $('#comment').val();
    // shove the edited comment into a variable local to the modal handler
    $.ajax({
        method: 'PUT',
        url: urlEdit,
        data: {
            comment: comment, // reference said variable for ajax data
            commentId: commentId,
            _token: token,
            _method: 'PUT'
         },
         dataType: 'json'
    })
    .done(function (msg){
        //$(divcomment).text(msg['new_comment']);
        // I commented out the above line as it clears the
        // divcomment div's text entirely.
        // Comment out the below 'if check' if it is not needed.
        if (msg.success === true) {
            $(divcomment).find('#display-comment').text(comment);
            // And overwrite the #display-comment div with the new
            // data if the user was successful in editing the comment
        }
        $('#edit-comment').modal('hide');
    });
});
</code>```

In a previous question of yours, you had a controller method on the php side of things that handled the ajax.  Instead of redirecting(since it is ajax, there is no redirect), you should instead return json to indicate whether the action was successful or not.  Here is an example of that:

```<code>public function update(Request $request)
{

    //...

    $comment = Comment::find($request['commentId']);
    if (Auth::user() != $comment->user) {
        return response()->json(['success' => false], 200);
    }

    //...

    return response()->json(['new_comment' => $comment->comment, 'success' => true], 200);
}
</code>```

I referenced the above json in my answer on the javascript side of things; if you are not going to use the json response, then simply comment out the line(as I also noted in the code).

Update:
I missed something in your earlier block of code; you declare divcomment outside of the edit link's handler, but then you re-declare it inside of that handler again.  I missed this in my earlier answer, so simply deleting the var from it, so it uses the outside declaration, fixes your code:

```<code>var commentId = 0;
var divcomment = null; //this is already declared, no reason to declare it
// again

$('.edit-comment').click(function(event){
    event.preventDefault();
    /* Accedemos al Div Que contiene el Panel*/
    divcomment = this.parentNode.parentNode;
 // ^ remove the var, making this use the global variable you already
 // made above
    /* Buscamos el Contenido con Id display-text  */
    commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
    var commentBody = $(divcomment).find('#display-comment').text();
    $('#comment').val(commentBody);
    $('#edit-comment').modal();
    /* Asignas a tu modal */
});
</code>```

Body:
i have a comment system on my app in laravel and i can edit my comments with ajax but once edited it doesn't load automatically the edited comment. To see the edited comment i need to reload the page manually. I will put some of the code here.

This is the JS:

        var commentId = 0;
        var divcomment = null;

        $('.edit-comment').click(function(event){
          event.preventDefault();
          /* Accedemos al Div Que contiene el Panel*/
          var divcomment = this.parentNode.parentNode;
          /* Buscamos el Contenido con Id display-text  */
          commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
          var commentBody = $(divcomment).find('#display-comment').text();
          $('#comment').val(commentBody);
          $('#edit-comment').modal();
           /* Asignas a tu modal */
        });

        $('#modal-save').on('click', function(){
            $.ajax({
                method: 'PUT',
                url: urlEdit,
                data: {
                    comment: $('#comment').val(),
                    commentId: commentId,
                    _token: token,
                    _method: 'PUT',
                    dataType: 'json',
                 }
            })
            .done(function (msg){
                $(divcomment).text(msg['new_comment']);
                $('#edit-comment').modal('hide');
            });
        });

This is the Html:

                                user->profilepic  }}" />

{{ $comment->user->name }}

 {{ $comment->user->name }}

                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"> {{ $comment->created_at->diffForHumans() }}</time>

id }}">

{{ $comment->comment }}

                                  @if(Auth::guest())

                                  No puedes responder ningún comentario si no has ingresado.

                                  @else

                                  @if(Auth::user() == $comment->user)
                                    Editar Eliminar
                                  @endif

                                  @if(Auth::user() != $comment->user)
                                    Responder
                                  @endif

                                  @endif

2 variables created on the view

  var token = '{{ Session::token() }}';
  var urlEdit = '{{ url('comments/update') }}';

and finally the modal where i edit the comment:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Editar Comentario

        <form>

            Editar comentario
            <textarea class="form-control" name="comment" id="comment"></textarea>

        </form>

        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"> Editar</button>

Everything's working but the only thing i need is to load the edited comment back without refresh the whole page, btw i used $('#display-comment').load(document.URL +  ' #display-comment'); and with this line i succesfully load the edited comment but, it load all the comments on the edited one, so i have to refresh the whole page to show just the edited.

Body:
Assuming that the data sent to the php side of things is the same data that you then want to update to, the following should work:

$('#modal-save').on('click', function(){
    var comment = $('#comment').val();
    // shove the edited comment into a variable local to the modal handler
    $.ajax({
        method: 'PUT',
        url: urlEdit,
        data: {
            comment: comment, // reference said variable for ajax data
            commentId: commentId,
            _token: token,
            _method: 'PUT'
         },
         dataType: 'json'
    })
    .done(function (msg){
        //$(divcomment).text(msg['new_comment']);
        // I commented out the above line as it clears the
        // divcomment div's text entirely.
        // Comment out the below 'if check' if it is not needed.
        if (msg.success === true) {
            $(divcomment).find('#display-comment').text(comment);
            // And overwrite the #display-comment div with the new
            // data if the user was successful in editing the comment
        }
        $('#edit-comment').modal('hide');
    });
});

In a previous question of yours, you had a controller method on the php side of things that handled the ajax.  Instead of redirecting(since it is ajax, there is no redirect), you should instead return json to indicate whether the action was successful or not.  Here is an example of that:

public function update(Request $request)
{

    //...

    $comment = Comment::find($request['commentId']);
    if (Auth::user() != $comment->user) {
        return response()->json(['success' => false], 200);
    }

    //...

    return response()->json(['new_comment' => $comment->comment, 'success' => true], 200);
}

I referenced the above json in my answer on the javascript side of things; if you are not going to use the json response, then simply comment out the line(as I also noted in the code).

Update:
I missed something in your earlier block of code; you declare divcomment outside of the edit link's handler, but then you re-declare it inside of that handler again.  I missed this in my earlier answer, so simply deleting the var from it, so it uses the outside declaration, fixes your code:

var commentId = 0;
var divcomment = null; //this is already declared, no reason to declare it
// again

$('.edit-comment').click(function(event){
    event.preventDefault();
    /* Accedemos al Div Que contiene el Panel*/
    divcomment = this.parentNode.parentNode;
 // ^ remove the var, making this use the global variable you already
 // made above
    /* Buscamos el Contenido con Id display-text  */
    commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
    var commentBody = $(divcomment).find('#display-comment').text();
    $('#comment').val(commentBody);
    $('#edit-comment').modal();
    /* Asignas a tu modal */
});


问:
How to get last record of table in CodeIgniter?
How to get last record of table in Codeigniter?

My table name is post I want to get last id or next id of last record in this table!

答:
```<code>$this->db->select("*");
$this->db->from("table name");
$this->db->limit(1);
$this->db->order_by('id',"DESC");
$query = $this->db->get();
$result = $query->result();
</code>```


问:
Parsing csv where the last "header" is followed by a space
I'm trying to parse csv using str_getcsv in the following manner however I'm running into two problems (below).

```<code>$url = 'http://my.events.calendar/api/csv?mycalendarquery';
$response = wp_remote_get($url);
$response_body = $response['body']; // this is a really long string
$parsed_string = str_getcsv($response_body, ',', '"');
$full_events_array = array_chunk($parsed_string, 11);
</code>```

Problem 1 - I can't use explode because one of the fields in the csv is "Description" which contains many/lengthy prose descriptions of events. Naturally these include commas, new lines, returns, etc...

Problem 2 - This is the one I have a question about. The categories (headers?) for the csv file are "Subject", "Date", (more things here...) "Description", "Calendar Address". However the last one doesn't have a comma after it. So, the entries for "Subject" and "Calendar" address are being combined like this -

```<code>array(11) {
  [0] =>
  string(32) "Calendar Address
  "Application Due"" // this pattern happens for every event but with a url instead.
// Yes, I know this looks wrong in the code block, but this is exactly how the data is coming in (complete with the double quotes).
</code>```

How do I parse this so that Calendar Address and Application Due are separated?

For reference, I've also tried str_getcsv($response_body, '"', ','); str_getcsv($response_body, ',', '"', '\n'); and several other combinations. Thanks for the help!

答:
This script will read the CSV file into 251 rows of 12 elements each.</p>

```<code><?php // demo/temp_44414553.php
/**
 * https://stackoverflow.com/questions/44414553/parsing-csv-where-the-last-header-is-followed-by-a-space?noredirect=1#comment75830321_44414553
 */
error_reporting(E_ALL);

// UNABLE TO ACCESS: http://events.uconn.edu/exports-2017-05-31-2017-07-01.csv
// COPY MADE HERE FROM THE DOWNLOAD LINK
$url = 'storage/exports-2017-05-31-2017-07-01.csv';
$csv = file_get_contents($url);
echo $csv;

$fpr = fopen($url, 'r');
if (!$fpr) trigger_error("Unable to open $url", E_USER_ERROR);

$kount = 0;
while (!feof($fpr))
{
    $row = fgetcsv($fpr);
    $kount++;
    if (!$row) break;
    echo PHP_EOL . count($row);
}

echo PHP_EOL . "There are $kount rows in the CSV at $url";
</code>```

Body:
I'm trying to parse csv using str_getcsv in the following manner however I'm running into two problems (below).

$url = 'http://my.events.calendar/api/csv?mycalendarquery';
$response = wp_remote_get($url);
$response_body = $response['body']; // this is a really long string
$parsed_string = str_getcsv($response_body, ',', '"');
$full_events_array = array_chunk($parsed_string, 11);

Problem 1 - I can't use explode because one of the fields in the csv is "Description" which contains many/lengthy prose descriptions of events. Naturally these include commas, new lines, returns, etc...

Problem 2 - This is the one I have a question about. The categories (headers?) for the csv file are "Subject", "Date", (more things here...) "Description", "Calendar Address". However the last one doesn't have a comma after it. So, the entries for "Subject" and "Calendar" address are being combined like this -

array(11) {
  [0] =>
  string(32) "Calendar Address
  "Application Due"" // this pattern happens for every event but with a url instead.
// Yes, I know this looks wrong in the code block, but this is exactly how the data is coming in (complete with the double quotes).

How do I parse this so that Calendar Address and Application Due are separated?

For reference, I've also tried str_getcsv($response_body, '"', ','); str_getcsv($response_body, ',', '"', '\n'); and several other combinations. Thanks for the help!

Body:
This script will read the CSV file into 251 rows of 12 elements each.

<?php // demo/temp_44414553.php
/**
 * https://stackoverflow.com/questions/44414553/parsing-csv-where-the-last-header-is-followed-by-a-space?noredirect=1#comment75830321_44414553
 */
error_reporting(E_ALL);

// UNABLE TO ACCESS: http://events.uconn.edu/exports-2017-05-31-2017-07-01.csv
// COPY MADE HERE FROM THE DOWNLOAD LINK
$url = 'storage/exports-2017-05-31-2017-07-01.csv';
$csv = file_get_contents($url);
echo $csv;

$fpr = fopen($url, 'r');
if (!$fpr) trigger_error("Unable to open $url", E_USER_ERROR);

$kount = 0;
while (!feof($fpr))
{
    $row = fgetcsv($fpr);
    $kount++;
    if (!$row) break;
    echo PHP_EOL . count($row);
}

echo PHP_EOL . "There are $kount rows in the CSV at $url";