问:
scala slick does not persist data
I have the following code which does not work ... not work means in this case it does not persis in database....

DTO / DAO

```<code>  def createChangelogEntry(changeLog: ChangelogModel): Future[ChangelogModel] = {
    println("..........................................")
    println(changeLog)

    val entry =
      (changelogs returning changelogs.map(_.id)
        into ((log,id) => log.copy(id=Some(id)))
        ) += ChangelogModel(None, changeLog.createdat, changeLog.text)

    db.run(entry)
  }
</code>```

what could be the problem in this case? match on the model works fine ...

UUpdate:

SQL:

```<code>CREATE TABLE Changelog (
  id BIGINT(255) NOT NULL,
  createdat DATETIME NOT NULL,
  text text NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

My Model:

```<code>package models

import java.sql.Date

import play.api.libs.json.{JsValue, Json, Writes}

/**
  * Created by Felix Hohlwegler on 08.06.2017.
  */
case class ChangelogModel(
                           id: Option[Int] = None,
                           createdat: String,
                           text: String
                         )

object ChangelogModel {
  implicit val changelogFormat = Json.format[ChangelogModel]
}
</code>```

Controller Function:

```<code>package controllers

import javax.inject.{Inject, Singleton}

import dto.changelogDTO
import models.{ChangelogModel, ProcessTemplatesModel}
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc.{Action, AnyContent, Controller, Request}

import scala.concurrent.Future

/**
  * Created by Felix Hohlwegler on 08.06.2017.
  */
@Singleton
class Changelogs @Inject()(changelogDTO: changelogDTO) extends Controller {

  def createChangelogEntry = Action { implicit request =>
    request.body.asJson.map(_.validate[ChangelogModel] match {
      case JsSuccess(process, _) =>
        changelogDTO.createChangelogEntry(process)
      case err@JsError(_) => BadRequest("TEST")
      case _ => BadRequest("fail to create Counter")
    }).getOrElse(BadRequest("Failure tu create Counter"))
    Ok("s")
  }
}
</code>```

答:
One problem is that you are not waiting for your insert to complete from your controller:

```<code>// Problem
case JsSuccess(process, _) => changelogDTO.createChangelogEntry(process)
</code>```

You should be mapping on the future and returning its result asynchronously like this:

```<code>// Do this
case JsSuccess(process, _) => changelogDTO.createChangelogEntry(process).map(model => Ok(Json.toJson(model))
</code>```

However this will mean that you will need all of the other cases to return futures too, and you will have to change the resulting action to by async.  This is how I would do it:

```<code>def createChangelogEntry = Action.async(parse.json) { implicit request =>
  request.body.validate[ChangelogModel].fold(
    errors => Future(BadRequest(JsError.toJson(errors))),
    changelogModel => changelogDTO.createChangelogEntry(changelogModel).map(model => Ok(Json.toJson(model))
  )
}
</code>```

In the meantime you might find it easier to debug by just wrapping your current insert in an Await.result like this:

```<code>import scala.concurrent.duration._

case JsSuccess(process, _) =>
  val model = Await.result(changelogDTO.createChangelogEntry(process), 5 seconds)
  Ok("We inserted the thing")
</code>```

Title: scala slick does not persist data

Body:
I have the following code which does not work ... not work means in this case it does not persis in database....

DTO / DAO

  def createChangelogEntry(changeLog: ChangelogModel): Future[ChangelogModel] = {
    println("..........................................")
    println(changeLog)

    val entry =
      (changelogs returning changelogs.map(_.id)
        into ((log,id) => log.copy(id=Some(id)))
        ) += ChangelogModel(None, changeLog.createdat, changeLog.text)

    db.run(entry)
  }

what could be the problem in this case? match on the model works fine ...

UUpdate:

SQL:

CREATE TABLE Changelog (
  id BIGINT(255) NOT NULL,
  createdat DATETIME NOT NULL,
  text text NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

My Model:

package models

import java.sql.Date

import play.api.libs.json.{JsValue, Json, Writes}

/**
  * Created by Felix Hohlwegler on 08.06.2017.
  */
case class ChangelogModel(
                           id: Option[Int] = None,
                           createdat: String,
                           text: String
                         )

object ChangelogModel {
  implicit val changelogFormat = Json.format[ChangelogModel]
}

Controller Function:

package controllers

import javax.inject.{Inject, Singleton}

import dto.changelogDTO
import models.{ChangelogModel, ProcessTemplatesModel}
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc.{Action, AnyContent, Controller, Request}

import scala.concurrent.Future

/**
  * Created by Felix Hohlwegler on 08.06.2017.
  */
@Singleton
class Changelogs @Inject()(changelogDTO: changelogDTO) extends Controller {

  def createChangelogEntry = Action { implicit request =>
    request.body.asJson.map(_.validate[ChangelogModel] match {
      case JsSuccess(process, _) =>
        changelogDTO.createChangelogEntry(process)
      case err@JsError(_) => BadRequest("TEST")
      case _ => BadRequest("fail to create Counter")
    }).getOrElse(BadRequest("Failure tu create Counter"))
    Ok("s")
  }
}

Body:
One problem is that you are not waiting for your insert to complete from your controller:

// Problem
case JsSuccess(process, _) => changelogDTO.createChangelogEntry(process)

You should be mapping on the future and returning its result asynchronously like this:

// Do this
case JsSuccess(process, _) => changelogDTO.createChangelogEntry(process).map(model => Ok(Json.toJson(model))

However this will mean that you will need all of the other cases to return futures too, and you will have to change the resulting action to by async.  This is how I would do it:

def createChangelogEntry = Action.async(parse.json) { implicit request =>
  request.body.validate[ChangelogModel].fold(
    errors => Future(BadRequest(JsError.toJson(errors))),
    changelogModel => changelogDTO.createChangelogEntry(changelogModel).map(model => Ok(Json.toJson(model))
  )
}

In the meantime you might find it easier to debug by just wrapping your current insert in an Await.result like this:

import scala.concurrent.duration._

case JsSuccess(process, _) =>
  val model = Await.result(changelogDTO.createChangelogEntry(process), 5 seconds)
  Ok("We inserted the thing")


来源: stackexchange

问:
Unexpected token u in JSON
I have an Ajax function that sends and retrieves a string. Once the Ajax receives the string, it calls a function called drawChart. drawChart then converts that string into an array using JSON.parse I am also using Google Charts to create a chart using the data that was passed in. Everything is working correctly. The chart is being made and it looks all fine, however; I am getting this error in the console:

Uncaught (in promise) SyntaxError: Unexpected token u in JSON at
  position 0
      at JSON.parse ()
      at drawChart (index.js?c1496931740:24)
      at anonymous

I did research this error and it happens when the data type that is being passed in JSON.parse is undefined. I tried to use console.log(typeof(data)) to check if it really is undefined, but it outputs 2 things. First it outputs string, then outputs undefined. Afterwards, it displays the error, but the chart gets displayed successfully. Here's my code:

```<code>function aggregator(field, size) {
    /*Build jSON query string*/
    var jString = '{"aggs": { "group_by_date": { "terms": { "field": "' + field + '", "size" : ' + size + '} } } }';

    google.charts.setOnLoadCallback(drawChart);   /*Load Chart*/

    /*Sending and retrieving data using Ajax*/
    $.ajax({
        url: 'index.php',
        type: 'post',
        datatype: 'json',
        data: {
            qSet: jString,
            size: size
        },
        success: drawChart
    });
}

var drawChart = function(data)
{
    console.log(typeof(data));
    data = JSON.parse(data);  /*Convert the data back into an array*/

    var chartData = new google.visualization.DataTable();  /*Set up the chart*/

    chartData.addColumn('string', 'year');
    chartData.addColumn('number', 'Records');

    /*For loop to add rows*/
    for (var i = 0; i < data.length; ++i){
        chartData.addRow(data[i]);
    }

    var options = {
        title: 'Arrival Data'
    };

    var chart = new google.visualization.BarChart(document.getElementById('chartContainer'));
    chart.draw(chartData, options);
};
</code>```

What is the reason for this error? Why do I receive 2 outputs (string and then undefined) when I do console.log(typeof(data))? How can I fix it?

答:
Why do I receive 2 outputs (string and then undefined) when I do console.log(typeof(data))?

Because you are calling the function twice.

google.charts.setOnLoadCallback(drawChart);

success: drawChart

Only call it when you get the data.

google.charts.setOnLoadCallback lets you specify a function to run when the API is available.

Create a new function which makes your Ajax request and call that when the API has loaded.

```<code>google.charts.setOnLoadCallback(sendAjaxRequest); /*Load Chart*/

function sendAjaxRequest() {

  $.ajax({
    url: 'index.php',
    type: 'post',
    datatype: 'json',
    data: {
      qSet: jString,
      size: size
    },
    success: drawChart
  });
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Unexpected token u in JSON

Body:
I have an Ajax function that sends and retrieves a string. Once the Ajax receives the string, it calls a function called drawChart. drawChart then converts that string into an array using JSON.parse I am also using Google Charts to create a chart using the data that was passed in. Everything is working correctly. The chart is being made and it looks all fine, however; I am getting this error in the console:

Uncaught (in promise) SyntaxError: Unexpected token u in JSON at
  position 0
      at JSON.parse ()
      at drawChart (index.js?c1496931740:24)
      at anonymous

I did research this error and it happens when the data type that is being passed in JSON.parse is undefined. I tried to use console.log(typeof(data)) to check if it really is undefined, but it outputs 2 things. First it outputs string, then outputs undefined. Afterwards, it displays the error, but the chart gets displayed successfully. Here's my code:

function aggregator(field, size) {
    /*Build jSON query string*/
    var jString = '{"aggs": { "group_by_date": { "terms": { "field": "' + field + '", "size" : ' + size + '} } } }';

    google.charts.setOnLoadCallback(drawChart);   /*Load Chart*/

    /*Sending and retrieving data using Ajax*/
    $.ajax({
        url: 'index.php',
        type: 'post',
        datatype: 'json',
        data: {
            qSet: jString,
            size: size
        },
        success: drawChart
    });
}

var drawChart = function(data)
{
    console.log(typeof(data));
    data = JSON.parse(data);  /*Convert the data back into an array*/

    var chartData = new google.visualization.DataTable();  /*Set up the chart*/

    chartData.addColumn('string', 'year');
    chartData.addColumn('number', 'Records');

    /*For loop to add rows*/
    for (var i = 0; i < data.length; ++i){
        chartData.addRow(data[i]);
    }

    var options = {
        title: 'Arrival Data'
    };

    var chart = new google.visualization.BarChart(document.getElementById('chartContainer'));
    chart.draw(chartData, options);
};

What is the reason for this error? Why do I receive 2 outputs (string and then undefined) when I do console.log(typeof(data))? How can I fix it?

Body:
Why do I receive 2 outputs (string and then undefined) when I do console.log(typeof(data))?

Because you are calling the function twice.

google.charts.setOnLoadCallback(drawChart);

success: drawChart

Only call it when you get the data.

google.charts.setOnLoadCallback lets you specify a function to run when the API is available.

Create a new function which makes your Ajax request and call that when the API has loaded.

google.charts.setOnLoadCallback(sendAjaxRequest); /*Load Chart*/

function sendAjaxRequest() {

  $.ajax({
    url: 'index.php',
    type: 'post',
    datatype: 'json',
    data: {
      qSet: jString,
      size: size
    },
    success: drawChart
  });
}


问:
Flyway migration fails even though script runs ok in DB client (MySQL)
I'm working on a flyway migration that will write the contents of one table as JSON string in a field of another table. I'm trying to get rid of about 50 of these tables and replace them with fields containing JSON strings.

The problem I'm having is that the query runs fine when I run it in MySQL Workbench, but it fails when I run the flyway migration. I've tried modifying the query. Running a very simple stored procedure works. Running a select on INFORMATION_SCHEMA.COLUMNS also works ok. I've tried writing the query using SET @qry := () and it makes no difference. I'd appreciate any idea about how to solve this.

```<code>MySQLSyntaxErrorException: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near 'PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
--    =========' at line 13
</code>```

This is the query

```<code>SET GLOBAL group_concat_max_len = (10*1024);
SET GLOBAL max_allowed_packet = (50*1024*1024);
SET @schema = 'db';

SET @table = 'InterfaceTable';
SET @className = 'TestInterfaceConfing';
SET @interfaceType = 'Test';

SELECT CONCAT(
  'UPDATE TestTable as tt SET interfaceConfig=(SELECT CONCAT(TRIM(TRAILING ', QUOTE(','),
  ' FROM CONCAT(', QUOTE('{"@class":"'), ',', QUOTE(@className), ',', QUOTE('",'), ',',
  GROUP_CONCAT(QUOTE('"'), ',', QUOTE(COLUMN_NAME), ',', QUOTE('"'), ',', QUOTE(':'), ',',
  IF(type like '%CHAR', '\'"\',', ''), 'IF(', COLUMN_NAME, ' is null,', IF(type like '%CHAR', '\'\'', QUOTE('null')) , ',', COLUMN_NAME, ')', IF(type like '%CHAR', ',\'"\'', ''), ',', QUOTE(',')),
  ')), ''}'') FROM ', @table, ' as interface WHERE tt.id=interface.id) where tt.interfaceType=', QUOTE(@interfaceType), ';'
)
INTO @qry
FROM
  (SELECT COLUMN_NAME, DATA_TYPE as type FROM INFORMATION_SCHEMA.COLUMNS c
  WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table) t;

PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

答: This is almost certainly due to our parser tripping over the many combinations of quotes. Please file an issue in the issue tracker and include the simplest form of the query that breaks.</p>

Body:
I'm working on a flyway migration that will write the contents of one table as JSON string in a field of another table. I'm trying to get rid of about 50 of these tables and replace them with fields containing JSON strings.

The problem I'm having is that the query runs fine when I run it in MySQL Workbench, but it fails when I run the flyway migration. I've tried modifying the query. Running a very simple stored procedure works. Running a select on INFORMATION_SCHEMA.COLUMNS also works ok. I've tried writing the query using SET @qry := () and it makes no difference. I'd appreciate any idea about how to solve this.

MySQLSyntaxErrorException: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near 'PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
--    =========' at line 13

This is the query

SET GLOBAL group_concat_max_len = (10*1024);
SET GLOBAL max_allowed_packet = (50*1024*1024);
SET @schema = 'db';

SET @table = 'InterfaceTable';
SET @className = 'TestInterfaceConfing';
SET @interfaceType = 'Test';

SELECT CONCAT(
  'UPDATE TestTable as tt SET interfaceConfig=(SELECT CONCAT(TRIM(TRAILING ', QUOTE(','),
  ' FROM CONCAT(', QUOTE('{"@class":"'), ',', QUOTE(@className), ',', QUOTE('",'), ',',
  GROUP_CONCAT(QUOTE('"'), ',', QUOTE(COLUMN_NAME), ',', QUOTE('"'), ',', QUOTE(':'), ',',
  IF(type like '%CHAR', '\'"\',', ''), 'IF(', COLUMN_NAME, ' is null,', IF(type like '%CHAR', '\'\'', QUOTE('null')) , ',', COLUMN_NAME, ')', IF(type like '%CHAR', ',\'"\'', ''), ',', QUOTE(',')),
  ')), ''}'') FROM ', @table, ' as interface WHERE tt.id=interface.id) where tt.interfaceType=', QUOTE(@interfaceType), ';'
)
INTO @qry
FROM
  (SELECT COLUMN_NAME, DATA_TYPE as type FROM INFORMATION_SCHEMA.COLUMNS c
  WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table) t;

PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


问:
Cookie expiration date not working C#
I'm setting a cookie like so:

```<code>protected void SetCookie(bool value, int expiration)
{
    var cookie = Response.Cookies[COOKIE_NAME] ?? new HttpCookie(COOKIE_NAME);
    cookie.Value = value.ToString();
    cookie.Expires = DateTime.UtcNow.AddDays(expiration);
    Response.Cookies.Set(cookie);
}
</code>```

In the SetCookie function, when I inspect the cookie on the last line, the Expiration is set to tomorrow's date.

However, when I retrieve this cookie on the next page load:

```<code>var cookie = Request.Cookies[COOKIE_NAME];
</code>```

the cookie exists, but the expiration date is the default date value of 1/1/0001 12:00:00 AM

答:
I believe the expiration is a client-side thing. The browser should send any not-expired cookies, but does not send the expiration date (only name and value). I think you should re-set and refresh the expiration on each request.

This was the first format reference I found: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie

If for whatever reason you need to retrieve the expiration data server side, I would include it in the cookie contents or set a secondary cookie to contain that information.

Title: Cookie expiration date not working C#

Body:
I'm setting a cookie like so:

protected void SetCookie(bool value, int expiration)
{
    var cookie = Response.Cookies[COOKIE_NAME] ?? new HttpCookie(COOKIE_NAME);
    cookie.Value = value.ToString();
    cookie.Expires = DateTime.UtcNow.AddDays(expiration);
    Response.Cookies.Set(cookie);
}

In the SetCookie function, when I inspect the cookie on the last line, the Expiration is set to tomorrow's date.

However, when I retrieve this cookie on the next page load:

var cookie = Request.Cookies[COOKIE_NAME];

the cookie exists, but the expiration date is the default date value of 1/1/0001 12:00:00 AM


问:
a very simple query is not working PHP
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

```<code>  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>
</code>```

答:
Try this instead:

```<code>$query = "select * From user where email='" . $email . "' and password='" . $password . "';
</code>```

Then immediately change that to this instead:

```<code>$query = "select * From user where email='" . mysql_real_escape_string($email) . "' and password='" . mysql_real_escape_string($password) . "';
</code>```

ContentLicense: CC BY-SA 2.5

Title: a very simple query is not working PHP

Body:
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>

Body:
Try this instead:

$query = "select * From user where email='" . $email . "' and password='" . $password . "';

Then immediately change that to this instead:

$query = "select * From user where email='" . mysql_real_escape_string($email) . "' and password='" . mysql_real_escape_string($password) . "';


问:
Could not load Spatialite extension in qSqlite ( QT 5.9)
I am trying to load Spatialite as extension in qSqlite ( Qt 5.9), I have done that before with Qt4.8, but I failed with the QT5.9.
I changed the sqlite.pri by removing "SQLITE_OMIT_LOAD_EXTENSION", and I did some change on the sqlite.c by removing the "#define SQLITE_OMIT_LOAD_EXTENSION 1", and adding "#define SQLITE_ENABLE_LOAD_EXTENSION 1".
I also add the following lines to openDatabase(....)

```<code>#if defined(SQLITE_ENABLE_LOAD_EXTENSION)
| SQLITE_LoadExtension|SQLITE_LoadExtFunc
#endif
</code>```

Now the "requet.setQuery("SELECT load_extension('spatialite')", dbProject);" function is recognized, but I got this message:
error "The specified procedure could not be found.\r\nUnable to fetch row"
If I take a look on my debug output in MSVC14, I can see that the spatialite.dll and all its dependencies have been loaded.

Notice: I tested this with my Spatialite and also the mod_spatialite that I download form their website.

Any ideas about this problem?
Thanks in advance.

答:
Thanks for eyllanesc, I found the solution thanks to your explanations and suggestions.

The problem was with my compiled library (still i don't know why?), and also with the mod_spatialite that I downloaded. This last one when we use it with the visual studio need a replacement for the libstdc++_64-6.dll because it will cause crash.

My problem was here, the one that I used was not the good one, and was causing the The specified procedure could not be found, so I downloaded the x86_64-5.3.0-release-win32-seh-rt_v4-rev0 and I used the libstdc++-6.dll (I changed the name to libstdc++_64-6.dll) with the libgcc_s_seh-1.dll. I also changed the libxml2-2.dll with another one that I compiled before.

Then I used one of the following solutions:

Solution 1:
I used the code before with modification because the ret = sqlite3_exec (db_handle, sql, NULL, NULL, &err_msg); was causing crash, and also I sent the db via parameters because it does not work like it was in the previous code.

so my working code now is:

```<code>#include <QtCore/QCoreApplication>
#include <QtSql/QtSql>
#include "sqlite3.h"

int enable_spatialite(QSqlDatabase db) {
    QVariant v = db.driver()->handle();
    if (v.isValid() && qstrcmp(v.typeName(), "sqlite3*") == 0)
    {
        sqlite3_initialize();
        sqlite3 *db_handle = *static_cast<sqlite3 **>(v.data());

        if (db_handle != 0) {

            sqlite3_enable_load_extension(db_handle, 1);

            QSqlQueryModel sql;
            sql.setQuery("SELECT load_extension('mod_spatialite')", db);
            if (sql.lastError().isValid())
            {
                qDebug() << "Error: cannot load the Spatialite extension (" << sql.lastError().text()<<")";
                return 0;
            }
            else    return 1;
        }
    }
    return 0;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "Project");
    db.setDatabaseName("dbTest.db");
    if (!db.open())
    {
        qDebug()<<"Critical"<< "Impossible to intialize the database !\n" + db.lastError().text();
        return 0;
    }
    qDebug()<<enable_spatialite(db);

    //just a test
    QSqlQueryModel sql;
    sql.setQuery("SELECT HEX(GeomFromText('POINT(10 20)'));", db);
    qDebug() << sql.index(0, 0).data().toString();

    return a.exec();
}
</code>```

one important things also, is that I recompiled the qsqlite driver to remove the SQLITE_OMIT_LOAD_EXTENSION

Solution 2: (Direct solution)

open the "Qt5.9.0\5.9\Src\qtbase\src\3rdparty\sqlite\" folder and change the sqlite3.c as following:

comment or remove the #define SQLITE_OMIT_LOAD_EXTENSION 1

add:

```<code>#ifndef SQLITE_ENABLE_LOAD_EXTENSION
#define SQLITE_ENABLE_LOAD_EXTENSION 1
#endif
</code>```

go the static int openDatabase(  const char *zFilename,sqlite3 **ppDb,  unsigned int flags, const char *zVfs) function and add | SQLITE_LoadExtFunc to SQLITE_ENABLE_LOAD_EXTENSION as following:

```<code>#ifdef SQLITE_ENABLE_LOAD_EXTENSION
                 | SQLITE_LoadExtension | SQLITE_LoadExtFunc
#endif
</code>```

compile your plugin again using your compiler ( nmake in my case) in Qt5.9.0\5.9\Src\qtbase\src\plugins\sqldrivers\sqlite\sqlite.pro

call the following code to load your spatialite:

```<code>QSqlQueryModel sql;
sql.setQuery("SELECT load_extension('mod_spatialite')", db);
</code>```

Body:
I am trying to load Spatialite as extension in qSqlite ( Qt 5.9), I have done that before with Qt4.8, but I failed with the QT5.9.
I changed the sqlite.pri by removing "SQLITE_OMIT_LOAD_EXTENSION", and I did some change on the sqlite.c by removing the "#define SQLITE_OMIT_LOAD_EXTENSION 1", and adding "#define SQLITE_ENABLE_LOAD_EXTENSION 1".
I also add the following lines to openDatabase(....)

#if defined(SQLITE_ENABLE_LOAD_EXTENSION)
| SQLITE_LoadExtension|SQLITE_LoadExtFunc
#endif

Now the "requet.setQuery("SELECT load_extension('spatialite')", dbProject);" function is recognized, but I got this message:
error "The specified procedure could not be found.\r\nUnable to fetch row"
If I take a look on my debug output in MSVC14, I can see that the spatialite.dll and all its dependencies have been loaded.

Notice: I tested this with my Spatialite and also the mod_spatialite that I download form their website.

Any ideas about this problem?
Thanks in advance.

Body:
Thanks for eyllanesc, I found the solution thanks to your explanations and suggestions.

The problem was with my compiled library (still i don't know why?), and also with the mod_spatialite that I downloaded. This last one when we use it with the visual studio need a replacement for the libstdc++_64-6.dll because it will cause crash.

My problem was here, the one that I used was not the good one, and was causing the The specified procedure could not be found, so I downloaded the x86_64-5.3.0-release-win32-seh-rt_v4-rev0 and I used the libstdc++-6.dll (I changed the name to libstdc++_64-6.dll) with the libgcc_s_seh-1.dll. I also changed the libxml2-2.dll with another one that I compiled before.

Then I used one of the following solutions:

Solution 1:
I used the code before with modification because the ret = sqlite3_exec (db_handle, sql, NULL, NULL, &err_msg); was causing crash, and also I sent the db via parameters because it does not work like it was in the previous code.

so my working code now is:

#include <QtCore/QCoreApplication>
#include <QtSql/QtSql>
#include "sqlite3.h"

int enable_spatialite(QSqlDatabase db) {
    QVariant v = db.driver()->handle();
    if (v.isValid() && qstrcmp(v.typeName(), "sqlite3*") == 0)
    {
        sqlite3_initialize();
        sqlite3 *db_handle = *static_cast<sqlite3 **>(v.data());

        if (db_handle != 0) {

            sqlite3_enable_load_extension(db_handle, 1);

            QSqlQueryModel sql;
            sql.setQuery("SELECT load_extension('mod_spatialite')", db);
            if (sql.lastError().isValid())
            {
                qDebug() << "Error: cannot load the Spatialite extension (" << sql.lastError().text()<<")";
                return 0;
            }
            else    return 1;
        }
    }
    return 0;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "Project");
    db.setDatabaseName("dbTest.db");
    if (!db.open())
    {
        qDebug()<<"Critical"<< "Impossible to intialize the database !\n" + db.lastError().text();
        return 0;
    }
    qDebug()<<enable_spatialite(db);

    //just a test
    QSqlQueryModel sql;
    sql.setQuery("SELECT HEX(GeomFromText('POINT(10 20)'));", db);
    qDebug() << sql.index(0, 0).data().toString();

    return a.exec();
}

one important things also, is that I recompiled the qsqlite driver to remove the SQLITE_OMIT_LOAD_EXTENSION

Solution 2: (Direct solution)

open the "Qt5.9.0\5.9\Src\qtbase\src\3rdparty\sqlite\" folder and change the sqlite3.c as following:

comment or remove the #define SQLITE_OMIT_LOAD_EXTENSION 1

add:

#ifndef SQLITE_ENABLE_LOAD_EXTENSION
#define SQLITE_ENABLE_LOAD_EXTENSION 1
#endif

go the static int openDatabase(  const char *zFilename,sqlite3 **ppDb,  unsigned int flags, const char *zVfs) function and add | SQLITE_LoadExtFunc to SQLITE_ENABLE_LOAD_EXTENSION as following:

#ifdef SQLITE_ENABLE_LOAD_EXTENSION
                 | SQLITE_LoadExtension | SQLITE_LoadExtFunc
#endif

compile your plugin again using your compiler ( nmake in my case) in Qt5.9.0\5.9\Src\qtbase\src\plugins\sqldrivers\sqlite\sqlite.pro

call the following code to load your spatialite:

QSqlQueryModel sql;
sql.setQuery("SELECT load_extension('mod_spatialite')", db);


问:
Browser shows plain text instead of HTML in mac
I want to write an html document like this :

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

<h1>My First Heading</h1>

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

I wrote it and saved it in my desktop with the name hello.html , but when I open this file with firefox or safari, the browser shows the whole text (including  and all of the texts) instead of only showing my first heading!
what's the problem?

答: I've had the same issue in TextEdit. The resolution is - go to "Format", then "Make plain text". Save the document and open it again in browser. It had worked in my case. Hope it will work for you too.</p>

Body:
I want to write an html document like this :

My First Heading

I wrote it and saved it in my desktop with the name hello.html , but when I open this file with firefox or safari, the browser shows the whole text (including  and all of the texts) instead of only showing my first heading!
what's the problem?


问:
$_POST data is empty after submit
I'm having a contact form by html below:

```<code><form id="contactForm" action="http://voicemarketing.cmctelecom.vn/php/contact-form.php" method="POST">
<div class="row">
    <div class="form-group">
        <div class="col-md-6">
            <label>Your Name *</label>
            <input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>
        </div>
        <div class="col-md-6">
            <label>Your Company Name *</label>
            <input type="text" value="" data-msg-required="Please enter your company name." maxlength="100" class="form-control" name="companyname" id="companyname" required>
        </div>
    </div>
</div>
<div class="row">
    <div class="form-group">
        <div class="col-md-6">
            <label>Your phone number *</label>
            <input type="number" value="" data-msg-required="Please enter your phone number." maxlength="12" class="form-control" name="phonenumber" id="phonenumber" required>
        </div>
        <div class="col-md-6">
            <label>Your email address *</label>
            <input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>
        </div>
    </div>
</div>
<div class="row">
    <div class="form-group">
        <div class="col-md-12">
            <label>Message *</label>
            <textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message" required></textarea>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-12">
        <input type="submit" value="Send Message" class="btn btn-primary btn-lg mb-xlg" data-loading-text="Loading...">
    </div>
</div>
</code>```

I tried to get the value by $_POST

```<code>$fields = array(
0 => array(
    'text' => 'Name',
    'val' => $_POST['name']
),
1 => array(
    'text' => 'Email address',
    'val' => $_POST['email']

),
2 => array(
    'text' => 'Message',
    'val' => $_POST['message']

),
3 => array(
    'text' => 'Company',
    'val' => $_POST['companyname']
),
4 => array(
    'text' => 'Phone Number',
    'val' => $_POST['phonenumber']
));
</code>```

Like usual, I put $_POST['name of form']
but only name, email, message are working
and companyname, phonenumber return nothing.
I really can't figure what is the problem is

答:
Close the  in the html part of the code and set the type of phone number to text.</p>

```<code><form>.....</form>
</code>```

Title: $_POST data is empty after submit

Body:
I'm having a contact form by html below:

<form id="contactForm" action="http://voicemarketing.cmctelecom.vn/php/contact-form.php" method="POST">

            Your Name *
            <input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>

            Your Company Name *
            <input type="text" value="" data-msg-required="Please enter your company name." maxlength="100" class="form-control" name="companyname" id="companyname" required>

            Your phone number *
            <input type="number" value="" data-msg-required="Please enter your phone number." maxlength="12" class="form-control" name="phonenumber" id="phonenumber" required>

            Your email address *
            <input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>

            Message *
            <textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message" required></textarea>

        <input type="submit" value="Send Message" class="btn btn-primary btn-lg mb-xlg" data-loading-text="Loading...">

I tried to get the value by $_POST

$fields = array(
0 => array(
    'text' => 'Name',
    'val' => $_POST['name']
),
1 => array(
    'text' => 'Email address',
    'val' => $_POST['email']

),
2 => array(
    'text' => 'Message',
    'val' => $_POST['message']

),
3 => array(
    'text' => 'Company',
    'val' => $_POST['companyname']
),
4 => array(
    'text' => 'Phone Number',
    'val' => $_POST['phonenumber']
));

Like usual, I put $_POST['name of form']
but only name, email, message are working
and companyname, phonenumber return nothing.
I really can't figure what is the problem is

Body:
Close the  in the html part of the code and set the type of phone number to text.

<form>.....</form>


问:
find command error in shell script
I have a file "log_data.txt" which contains various log files and the mtime next to the names with a space. Contents of the file are as shown below,

```<code>Log1 2
Log2 6
Log3 5
Log4 7
Log5 3
</code>```

The intent here is my script shown below has to assign itself the log filename and delete the files as per the mtime next to it.

```<code>IFS=''
while read line
do
find /opt/tmp/log/ -name `$line | awk '{print $1}'`*.log -mtime `$line | awk '{print $2}'` -exec rm -rf {} \;
echo ---------
done < log_data.txt
</code>```

If I assign an integer next to mtime in the script, it works fine, but, it throws the below error, if I put "$line | awk '{print $2}'" in the find command.

```<code>---------
./log_clear_script.sh: line 4: Log1      2: not found
./log_clear_script.sh: line 4: Log1      2: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log2     6: not found
./log_clear_script.sh: line 4: Log2     6: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log3       5: not found
./log_clear_script.sh: line 4: Log3       5: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log4  7: not found
./log_clear_script.sh: line 4: Log4  7: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log5        3: not found
./log_clear_script.sh: line 4: Log5        3: not found
find: invalid argument `-exec' to `-mtime'
</code>```

Please help me resolve it. All responses are much appreciated. - Thank you.

答:
change </p>

```<code> `$line | awk '{print $2}'`
</code>```

<p>To </p>

```<code>`echo $line | awk '{print $2}'`
</code>```

Title: find command error in shell script

Body:
I have a file "log_data.txt" which contains various log files and the mtime next to the names with a space. Contents of the file are as shown below,

Log1 2
Log2 6
Log3 5
Log4 7
Log5 3

The intent here is my script shown below has to assign itself the log filename and delete the files as per the mtime next to it.

IFS=''
while read line
do
find /opt/tmp/log/ -name `$line | awk '{print $1}'`*.log -mtime `$line | awk '{print $2}'` -exec rm -rf {} \;
echo ---------
done < log_data.txt

If I assign an integer next to mtime in the script, it works fine, but, it throws the below error, if I put "$line | awk '{print $2}'" in the find command.

---------
./log_clear_script.sh: line 4: Log1      2: not found
./log_clear_script.sh: line 4: Log1      2: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log2     6: not found
./log_clear_script.sh: line 4: Log2     6: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log3       5: not found
./log_clear_script.sh: line 4: Log3       5: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log4  7: not found
./log_clear_script.sh: line 4: Log4  7: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log5        3: not found
./log_clear_script.sh: line 4: Log5        3: not found
find: invalid argument `-exec' to `-mtime'

Please help me resolve it. All responses are much appreciated. - Thank you.

Body:
change

 `$line | awk '{print $2}'`

To

`echo $line | awk '{print $2}'`


问:
MVAPICH 2.3 configure for multiple devices
While mvapich from version 2.3 deprecated the Nemesis interface, is there any way now to configure it at once for Infiniband support with fallback to TCP when failed? Or do I have to have two compilations for different network setups in my grid?</p>

答:
I'll answer my question with the information from MVAPICH developers:

At this point, the default MVAPICH channel cannot use TCP as a fallback if IB fails. We will see if such a support can be enabled in the future.


问:
How to customize Jackson ObjectMapper with Spring application.properties?
I want to enable the following jackson mapper feature:
MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES

According to https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html:

Could be configured in application.properties as follows:
spring.jackson.mapper.accept_case_insensitive_properties=true

But:

```<code>@RestController
public class MyServlet {
    @RequestMapping("/test")
    public void test(@Valid TestReq req) {

    }
}

public class TestReq {
    @NotBlank
    private String name;
}
</code>```

Usage:

```<code>localhost:8080/test?name=test //works
localhost:8080/test?Name=test //fails with 'name may not be blank'
</code>```

So, the case insensitive property is not taken into account. But why?

By the way: even using Jackson2ObjectMapperBuilderCustomizer explicit does not work:

```<code>@Bean
public Jackson2ObjectMapperBuilderCustomizer initJackson() {
    Jackson2ObjectMapperBuilderCustomizer c = new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.featuresToEnable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
        }
    };

    return c;
}
</code>```

spring-boot-1.5.3.RELEASE

答:
Simple answer: it is not possible.

The Jackson2ObjectMapperBuilderCustomizer affects the JSON POST requests only. It has no effect on the get query binding.

Body:
I want to enable the following jackson mapper feature:
MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES

According to https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html:

Could be configured in application.properties as follows:
spring.jackson.mapper.accept_case_insensitive_properties=true

But:

@RestController
public class MyServlet {
    @RequestMapping("/test")
    public void test(@Valid TestReq req) {

    }
}

public class TestReq {
    @NotBlank
    private String name;
}

Usage:

localhost:8080/test?name=test //works
localhost:8080/test?Name=test //fails with 'name may not be blank'

So, the case insensitive property is not taken into account. But why?

By the way: even using Jackson2ObjectMapperBuilderCustomizer explicit does not work:

@Bean
public Jackson2ObjectMapperBuilderCustomizer initJackson() {
    Jackson2ObjectMapperBuilderCustomizer c = new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.featuresToEnable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
        }
    };

    return c;
}

spring-boot-1.5.3.RELEASE


问:
force gcc to compile when stack-overflow is detected
How can i force gcc to compile a program in which i declare an array of unsigned integers that is bigger than my ram - without getting the warning warning: "integer overflow in expression"?

eg. i have 8gb of ram and i want do declare an array of 8.5gb.

edit:

thanks everybody, i figured out that the problem wasnt with the datatype but with some preprocessor stuff. it took me quite a while though. :)
i wrote

```<code>#define GIBI 1073741824
#define ARRAYSIZE 2*GIBI
</code>```

and obviously the compiler didnt like that.

答: I'm fairly sure that "integer overflow in expression"? does not mean that you are overflowing the stack but rather you are doing some math that may potentially overflow a signed integer which is Undefined Behavior. It would help if you paste the line the warning is referring to.

Body:
How can i force gcc to compile a program in which i declare an array of unsigned integers that is bigger than my ram - without getting the warning warning: "integer overflow in expression"?

eg. i have 8gb of ram and i want do declare an array of 8.5gb.

edit:

thanks everybody, i figured out that the problem wasnt with the datatype but with some preprocessor stuff. it took me quite a while though. :)
i wrote

#define GIBI 1073741824
#define ARRAYSIZE 2*GIBI

and obviously the compiler didnt like that.


问:
Way to securely give a password to R application from the terminal?
Does R have a function that allows a user to provide a password securely, such as Python's getpass module?

(see http://docs.python.org/library/getpass.html for an example of what I mean)

答:
Here is a login pop-up, based on ?modalDialog.</p>

```<code>library("shiny")

shinyApp(
  ui <- basicPage(
    actionButton("login", "Login"),
    verbatimTextOutput("secrets")
  ),

  server <- function(input, output, session) {
    vals <- reactiveValues(authenticated=FALSE)

    passwordModal <- function(message=NULL) {
      modalDialog(
        textInput("username", "Username", input$username),
        passwordInput("password", "Password", input$password),

        if (!is.null(message)) div(tags$b(message, style="color: red;")),

        footer = tagList(
          modalButton("Cancel"),
          actionButton("authenticate", "OK")
        )
      )
    }

    observeEvent(input$login, {
      showModal(passwordModal())
    })

    observeEvent(input$authenticate, {
      vals$authenticated <- FALSE
      if (!is.null(input$username) && nzchar(input$username) &&
          !is.null(input$password) && nzchar(input$password)) {
        removeModal()

        if (input$password == "letmein") {
          vals$authenticated <- TRUE
        } else {
          showModal(passwordModal(message="Incorrect password!"))
        }

      } else {
        showModal(passwordModal(message="Please fill in your username and password"))
      }
    })

    output$secrets <- renderText({
      if (vals$authenticated) {
        paste("Don't tell anyone, ", input$username, ", but...", sep="")
      } else {
        "I can't tell you that!"
      }
    })
  }
)
</code>```

Body:
Here is a login pop-up, based on ?modalDialog.

library("shiny")

shinyApp(
  ui <- basicPage(
    actionButton("login", "Login"),
    verbatimTextOutput("secrets")
  ),

  server <- function(input, output, session) {
    vals <- reactiveValues(authenticated=FALSE)

    passwordModal <- function(message=NULL) {
      modalDialog(
        textInput("username", "Username", input$username),
        passwordInput("password", "Password", input$password),

        if (!is.null(message)) div(tags$b(message, style="color: red;")),

        footer = tagList(
          modalButton("Cancel"),
          actionButton("authenticate", "OK")
        )
      )
    }

    observeEvent(input$login, {
      showModal(passwordModal())
    })

    observeEvent(input$authenticate, {
      vals$authenticated <- FALSE
      if (!is.null(input$username) && nzchar(input$username) &&
          !is.null(input$password) && nzchar(input$password)) {
        removeModal()

        if (input$password == "letmein") {
          vals$authenticated <- TRUE
        } else {
          showModal(passwordModal(message="Incorrect password!"))
        }

      } else {
        showModal(passwordModal(message="Please fill in your username and password"))
      }
    })

    output$secrets <- renderText({
      if (vals$authenticated) {
        paste("Don't tell anyone, ", input$username, ", but...", sep="")
      } else {
        "I can't tell you that!"
      }
    })
  }
)


问:
Jest: How should I mock a class function?
Good evening!

I'm trying to get my head around mocking in general, and this seems like a good case for it.

I have a class that handles image loading and keeps track of said images using an alias (e.g., this._imgLoaded[path] = image)

```<code>export default class Loader {

    // Constructor and what not

    _loadImage(path) {
        return new Promise((resolve, reject) => {
          let image = new Image();
          image.src = path;
          image.onload = () => resolve(image);
          image.onerror = () =>
            reject(new Error("Image is not defined. Unable to load it."));
        });
      }

      async loadImage(path, alias) {
        const newPath = this._enrichRelativePath(path);
        let image;
        try {
          image = await this._loadImage(newPath);
        } catch (error) {
          // log and rethrow
          console.error(error);
          throw error;
        }

        // cache the loaded image:
        this._imgLoaded[newPath] = image;

        if (alias) {
          this._imgAlias[alias] = newPath;
        }
      }
    }
</code>```

I think that in order to unit test this, I have to create a mock function for _loadImage and make it return something.

What would be the best way to do so, while keeping the other functions intact?

As a side note, I'm using ES6.

Thanks!

答:
It seems to work with prototype (__mocks__/loader.js):

```<code>let Loader = require.requireActual("../src/loader.js");

Loader.prototype._loadImage = function() {
  return "test";
};

module.exports = Loader;
</code>```

And then, in the test file (__tests__/loader.test.js):

```<code>import Loader from "loader";
jest.setMock("loader", require("../__mocks__/loader"));

test("Something", () => {
  expect.assertions(1);

  const loader = new Loader();

  expect(loader._loadImage()).toBe("test");
});
</code>```

Body:
Good evening!

I'm trying to get my head around mocking in general, and this seems like a good case for it.

I have a class that handles image loading and keeps track of said images using an alias (e.g., this._imgLoaded[path] = image)

export default class Loader {

    // Constructor and what not

    _loadImage(path) {
        return new Promise((resolve, reject) => {
          let image = new Image();
          image.src = path;
          image.onload = () => resolve(image);
          image.onerror = () =>
            reject(new Error("Image is not defined. Unable to load it."));
        });
      }

      async loadImage(path, alias) {
        const newPath = this._enrichRelativePath(path);
        let image;
        try {
          image = await this._loadImage(newPath);
        } catch (error) {
          // log and rethrow
          console.error(error);
          throw error;
        }

        // cache the loaded image:
        this._imgLoaded[newPath] = image;

        if (alias) {
          this._imgAlias[alias] = newPath;
        }
      }
    }

I think that in order to unit test this, I have to create a mock function for _loadImage and make it return something.

What would be the best way to do so, while keeping the other functions intact?

As a side note, I'm using ES6.

Thanks!

Body:
It seems to work with prototype (__mocks__/loader.js):

let Loader = require.requireActual("../src/loader.js");

Loader.prototype._loadImage = function() {
  return "test";
};

module.exports = Loader;

And then, in the test file (__tests__/loader.test.js):

import Loader from "loader";
jest.setMock("loader", require("../__mocks__/loader"));

test("Something", () => {
  expect.assertions(1);

  const loader = new Loader();

  expect(loader._loadImage()).toBe("test");
});


问:
Karaf how to exclude specified bundle from log
I would  like to exclude my bundle from root  karaf log. The JSON sended by this bundle is too large, and the log is no more readeable.

I suppose that I should change osgi:*  in line :

```<code>rootLogger=INFO,out,osgi:*
</code>```

Which value I should put there ?

Edit, the problem is more complicated that I thought.

The JSON sont injected in logs by  org.apache.cxf.cxf-rt-features-logging.  It is used also by other bundle. I vould like remove only JSON sending and receiving by my bundle.

How can I do this ?

答:
If you want to exclude a specific bundle from logging, just turn off logging for the bundle within the pax logging config.

```<code>log4j.logger.mybundle = OFF
</code>```

If you want to fine tune CXF message logging please check http://cxf.apache.org/docs/message-logging.html.

Some things to note:

The logger name is .. karaf by default only cuts it to just the type.
      A lot of the details are in the MDC values
      You need to change your pax logging config to make these visible.

You can use the logger name to fine tune which services you want to log this way. For example set the debug level to WARN for noisy
  services to avoid that they are logged or log some services to another
  file.

Body:
I would  like to exclude my bundle from root  karaf log. The JSON sended by this bundle is too large, and the log is no more readeable.

I suppose that I should change osgi:*  in line :

rootLogger=INFO,out,osgi:*

Which value I should put there ?

Edit, the problem is more complicated that I thought.

The JSON sont injected in logs by  org.apache.cxf.cxf-rt-features-logging.  It is used also by other bundle. I vould like remove only JSON sending and receiving by my bundle.

How can I do this ?

Body:
If you want to exclude a specific bundle from logging, just turn off logging for the bundle within the pax logging config.

log4j.logger.mybundle = OFF

If you want to fine tune CXF message logging please check http://cxf.apache.org/docs/message-logging.html.

Some things to note:

The logger name is .. karaf by default only cuts it to just the type.
      A lot of the details are in the MDC values
      You need to change your pax logging config to make these visible.

You can use the logger name to fine tune which services you want to log this way. For example set the debug level to WARN for noisy
  services to avoid that they are logged or log some services to another
  file.


问:
Java static method vs function
What is difference between this codes in java 8 :

This  :

```<code>public class Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}
</code>```

and this :

```<code>public interface Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}
</code>```

This is main class :

```<code>public class MainClass {
    public static void main(String[] args) {
            Hello.sayHello(); //for function
            Hello.sayHello(); //for class
    }
}
</code>```

答:
I think we have two difference :

1) interfaces can only have one function .

2) important : interface is not class , so have not block static :

view this code :

```<code>public class Hello {
    static {
        System.out.println("Ok");
    }
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}
</code>```

this block run when you call class .

you can not do this on function interfaces . (intefaces have not this block)

sorry for bad english language

Title: Java static method vs function

Body:
What is difference between this codes in java 8 :

This  :

public class Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}

and this :

public interface Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}

This is main class :

public class MainClass {
    public static void main(String[] args) {
            Hello.sayHello(); //for function
            Hello.sayHello(); //for class
    }
}

Body:
I think we have two difference :

1) interfaces can only have one function .

2) important : interface is not class , so have not block static :

view this code :

public class Hello {
    static {
        System.out.println("Ok");
    }
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}

this block run when you call class .

you can not do this on function interfaces . (intefaces have not this block)

sorry for bad english language


问:
group by operation in pandas
I am reading groupby function in pandas in book Data analysis using python. Here author mentioned as below.

```<code>In [13]: df = DataFrame({'key1' : ['a', 'a', 'b', 'b', 'a'],
....: 'key2' : ['one', 'two', 'one', 'two', 'one'],
....: 'data1' : np.random.randn(5),
....: 'data2' : np.random.randn(5)})

In [14]: df
Out[14]:
    data1       data2   key1 key2
0   -0.204708 1.393406  a    one
1   0.478943  0.092908  a    two
2   -0.519439 0.281746  b    one
3   -0.555730 0.769023  b    two
4   1.965781  1.246435  a    one

In [21]: states = np.array(['Ohio', 'California', 'California', 'Ohio', 'Ohio'])
In [22]: years = np.array([2005, 2005, 2006, 2005, 2006])

In [23]: df['data1'].groupby([states, years]).mean()
Out[23]:
California 2005 0.478943
           2006 -0.519439
Ohio       2005 -0.380219
           2006 1.965781
</code>```

My question is how df['data1'] is groupbed as df is no where linked to states and years. I am not geeting how output is produced. Kindly explain

答:
When performing a groupby you can pass

by : mapping, function, str, or iterable

Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If an ndarray is passed, the values are used as-is determine the groups. A str or list of strs may be passed to group by the columns in self

iterable

In this case you passed an iterable or an array.  When you use an array, you had better have the same length as the dataframe itself.  Otherwise:

```<code># Doesn't throw an error because the length of `df` is 5
df.groupby(list(range(5)))

# This does throw an error
df.groupby(list(range(6)))

KeyError: 0
</code>```

pd.Series

Consider the series s where we specify the length to be the same as df as well as the index to be the same.

```<code>s = pd.Series(list(range(len(df))), df.index)
</code>```

Then when we do a groupby the indices are aligned

```<code>df.groupby(s)
</code>```

With a pd.Series we don't have to be concerned with the length, because, pandas will do the alignment for us

```<code># also works
df.groupby(s.append(pd.Series(1, [len(df)])))
</code>```

str

In the case of a string being passed to the gropuby, pandas will look for a column with that name to groupby.

function

In the case of a function being passed, pandas will map that function on the index of df and use the resulting iterable to groupby.

Title: group by operation in pandas

Body:
I am reading groupby function in pandas in book Data analysis using python. Here author mentioned as below.

In [13]: df = DataFrame({'key1' : ['a', 'a', 'b', 'b', 'a'],
....: 'key2' : ['one', 'two', 'one', 'two', 'one'],
....: 'data1' : np.random.randn(5),
....: 'data2' : np.random.randn(5)})

In [14]: df
Out[14]:
    data1       data2   key1 key2
0   -0.204708 1.393406  a    one
1   0.478943  0.092908  a    two
2   -0.519439 0.281746  b    one
3   -0.555730 0.769023  b    two
4   1.965781  1.246435  a    one

In [21]: states = np.array(['Ohio', 'California', 'California', 'Ohio', 'Ohio'])
In [22]: years = np.array([2005, 2005, 2006, 2005, 2006])

In [23]: df['data1'].groupby([states, years]).mean()
Out[23]:
California 2005 0.478943
           2006 -0.519439
Ohio       2005 -0.380219
           2006 1.965781

My question is how df['data1'] is groupbed as df is no where linked to states and years. I am not geeting how output is produced. Kindly explain

Body:
When performing a groupby you can pass

by : mapping, function, str, or iterable

Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If an ndarray is passed, the values are used as-is determine the groups. A str or list of strs may be passed to group by the columns in self

iterable

In this case you passed an iterable or an array.  When you use an array, you had better have the same length as the dataframe itself.  Otherwise:

# Doesn't throw an error because the length of `df` is 5
df.groupby(list(range(5)))

# This does throw an error
df.groupby(list(range(6)))

KeyError: 0

pd.Series

Consider the series s where we specify the length to be the same as df as well as the index to be the same.

s = pd.Series(list(range(len(df))), df.index)

Then when we do a groupby the indices are aligned

df.groupby(s)

With a pd.Series we don't have to be concerned with the length, because, pandas will do the alignment for us

# also works
df.groupby(s.append(pd.Series(1, [len(df)])))

str

In the case of a string being passed to the gropuby, pandas will look for a column with that name to groupby.

function

In the case of a function being passed, pandas will map that function on the index of df and use the resulting iterable to groupby.


问:
knitr executing R code chunks in HTML-style comments
Using Rstudio to edit an Rmarkdown file, I use HTML comments mark out large blocks that I don't want to have processed or in the output. This works just fine in Rstudio, which ignores everything in the comments. However, when I ask Rstudio to knit the document, knitr is executing the R code blocks in the comments.

Here's an MWE .Rmd file:

```<code># Important stuff I want to see
This is what I want to see:
```{r}
pi # I like pi
```
<!---
**This section commented out, as not ready to be knit yet**
This is what I do not want to see:
```{r}
cake # I also like cake, but it's undefined
```
-->
</code>```

This causes knitr to fail with Error in eval(expr, envir, enclos) : object 'cake' not found ... Execution halted

Is there an easy way to comment out whole swathes of an Rmarkdown file which prevents knitr from executing the R code chunks in the comments?

I have looked at global comment option for R markdown in knitr and Comments in Markdown, as well as https://yihui.name/knitr/, but didn't find a solution.

答:
Taking jburkhardt's idea of using eval=F, this works as a way of doing block comments where knitr does not execute the R code blocks:

```<code>Stuff I want to see...
```{r}
pi
```

<!--
This is added at the beginning of the comment:
```{r, include=FALSE}
knitr::opts_chunk$set(eval= FALSE)
```

Stuff I have commented out:

```{r}
cake
```

This is added to the end of the comment:
```{r, include=FALSE, eval=TRUE}
knitr::opts_chunk$set(eval= TRUE)
```
-->

More stuff I want to see:
```{r}
2*pi
```
</code>```

It's a bit clunky, and it's certainly not bulletproof (for example, knitr will still run any code blocks it finds with explicit eval=true), but it works in my case.

Body:
Using Rstudio to edit an Rmarkdown file, I use HTML comments mark out large blocks that I don't want to have processed or in the output. This works just fine in Rstudio, which ignores everything in the comments. However, when I ask Rstudio to knit the document, knitr is executing the R code blocks in the comments.

Here's an MWE .Rmd file:

# Important stuff I want to see
This is what I want to see:
```{r}
pi # I like pi
```

This causes knitr to fail with Error in eval(expr, envir, enclos) : object 'cake' not found ... Execution halted

Is there an easy way to comment out whole swathes of an Rmarkdown file which prevents knitr from executing the R code chunks in the comments?

I have looked at global comment option for R markdown in knitr and Comments in Markdown, as well as https://yihui.name/knitr/, but didn't find a solution.

Body:
Taking jburkhardt's idea of using eval=F, this works as a way of doing block comments where knitr does not execute the R code blocks:

Stuff I want to see...
```{r}
pi
```

<!--
This is added at the beginning of the comment:
```{r, include=FALSE}
knitr::opts_chunk$set(eval= FALSE)
```

Stuff I have commented out:

```{r}
cake
```

This is added to the end of the comment:
```{r, include=FALSE, eval=TRUE}
knitr::opts_chunk$set(eval= TRUE)
```
-->

More stuff I want to see:
```{r}
2*pi
```

It's a bit clunky, and it's certainly not bulletproof (for example, knitr will still run any code blocks it finds with explicit eval=true), but it works in my case.


答:
Try</p>

```<code>$query = "SELECT * FROM user WHERE email = '".$email."' AND password = '".$password."'";
</code>```

Title: a very simple query is not working PHP

Body:
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>

Body:
Try

$query = "SELECT * FROM user WHERE email = '".$email."' AND password = '".$password."'";


问:
Permission denied (publickey) when SSH Access to Amazon EC2 instance
I want to use my Amazon ec2 instance but faced the following error:

```<code>Permission denied (publickey).
</code>```

I have created my key pair and downloaded .pem file.

Given:

```<code>chmod  600 pem file.
</code>```

Then, this command

```<code>ssh -i /home/kashif/serverkey.pem  ubuntu@ec2-54-227-242-179.compute-1.amazonaws.com
</code>```

But have this error:

```<code>Permission denied (publickey)
</code>```

Also, how can I connect with filezilla to upload/download files?

答:
It's a basic thing, but always confirm which user you are trying to do the login. Im my case was just a distraction. I was trying using a root user:

```<code>ssh -i ~/keys/<key_name> root@111.111.111.111
</code>```

But was another user:

```<code>ssh -i ~/keys/<key_name> dedeco@111.111.111.111
</code>```

Body:
I want to use my Amazon ec2 instance but faced the following error:

Permission denied (publickey).

I have created my key pair and downloaded .pem file.

Given:

chmod  600 pem file.

Then, this command

ssh -i /home/kashif/serverkey.pem  ubuntu@ec2-54-227-242-179.compute-1.amazonaws.com

But have this error:

Permission denied (publickey)

Also, how can I connect with filezilla to upload/download files?

Body:
It's a basic thing, but always confirm which user you are trying to do the login. Im my case was just a distraction. I was trying using a root user:

ssh -i ~/keys/<key_name> root@111.111.111.111

But was another user:

ssh -i ~/keys/<key_name> dedeco@111.111.111.111


问:
Read JSON file data on client side with pure javascript
I have a JSON file on my local computer and I want to read its contents and display it on the web browser by using pure javascript. Anything which refers to the server side will not work for me. It is required to be done purely on the Client Side. What are the possible solutions ?
Note: ajax and anything related to that should not be used.

答:
```<code>function readFile(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4) {
            if(rawFile.status === 200 || rawFile.status == 0) {
                var allText = rawFile.responseText;
                var value = JSON.stringify;
                // now display on browser :)
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///C:/your/path/to/file.txt");
</code>```


问:
IDownloaderClient onServiceConnected Not Being Called
I'm trying to get my app to download expansion files when it starts up. I followed the guide from Android and for a while it would start to download, then stop at 98% telling me that it couldn't verify the file, but the file was actually there. Today, I haven't changed any code, and it's not even trying to download. I've put breakpoints all over the class and it never gets to the onServiceConnected method that comes from IDownloaderClient.

At the end of onCreate I have

```<code>initializeDownloadUI();

if (!expansionFilesDelivered()) {
    try {
        final Intent launchIntent = MainActivity.this.getIntent();
        final Intent intentToLaunchThisActivityFromNotification = new Intent(MainActivity.this, MainActivity.this.getClass());

        intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());

        if (launchIntent.getCategories() != null) {
            for (String category : launchIntent.getCategories())
                intentToLaunchThisActivityFromNotification.addCategory(category);
        }

        // Build PendingIntent used to open this activity from Notification.
        final PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intentToLaunchThisActivityFromNotification, PendingIntent.FLAG_UPDATE_CURRENT);

        // Request to start the download.
        final int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this, pendingIntent, DownloaderServiceHelper.class);

        if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
            initializeDownloadUI();
            return;
        }
    } catch (PackageManager.NameNotFoundException exc) {
        Log.wtf("MainActivity", "Cannot find own package.");
        exc.printStackTrace();
    }
} else validateXAPKZipFiles();
</code>```

And my initializeDownloadUI() is

```<code>mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, DownloaderService.class);
setContentView(R.layout.main);

mPB = (ProgressBar) findViewById(R.id.progressBar);
mStatusText = (TextView) findViewById(R.id.statusText);
mProgressFraction = (TextView) findViewById(R.id.progressAsFraction);
mProgressPercent = (TextView) findViewById(R.id.progressAsPercentage);
mAverageSpeed = (TextView) findViewById(R.id.progressAverageSpeed);
mTimeRemaining = (TextView) findViewById(R.id.progressTimeRemaining);
mDashboard = findViewById(R.id.downloaderDashboard);
mCellMessage = findViewById(R.id.approveCellular);
mPauseButton = (Button) findViewById(R.id.pauseButton);
mWiFiSettingButton = (Button) findViewById(R.id.wifiSettingsButton);

mPauseButton.setOnClickListener(this);
mWiFiSettingButton.setOnClickListener(this);
(findViewById(R.id.resumeOverCellular)).setOnClickListener(this);
</code>```

Also, my onResume is

```<code>if (null != mDownloaderClientStub) {
    mDownloaderClientStub.connect(this);
}

super.onResume();
</code>```

It steps through the onCreate as expected, but for some reason it doesn't connect the service. Like I said, this was working a few days ago and I didn't change anything, but now it doesn't work.

Any help?

答:
Seems like your Service class name is DownloaderServiceHelper
So you need to change the code in initializeDownloadUi method

from

mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, DownloaderService.class);

to

mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, DownloaderServiceHelper.class);

Body:
I'm trying to get my app to download expansion files when it starts up. I followed the guide from Android and for a while it would start to download, then stop at 98% telling me that it couldn't verify the file, but the file was actually there. Today, I haven't changed any code, and it's not even trying to download. I've put breakpoints all over the class and it never gets to the onServiceConnected method that comes from IDownloaderClient.

At the end of onCreate I have

initializeDownloadUI();

if (!expansionFilesDelivered()) {
    try {
        final Intent launchIntent = MainActivity.this.getIntent();
        final Intent intentToLaunchThisActivityFromNotification = new Intent(MainActivity.this, MainActivity.this.getClass());

        intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());

        if (launchIntent.getCategories() != null) {
            for (String category : launchIntent.getCategories())
                intentToLaunchThisActivityFromNotification.addCategory(category);
        }

        // Build PendingIntent used to open this activity from Notification.
        final PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intentToLaunchThisActivityFromNotification, PendingIntent.FLAG_UPDATE_CURRENT);

        // Request to start the download.
        final int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this, pendingIntent, DownloaderServiceHelper.class);

        if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
            initializeDownloadUI();
            return;
        }
    } catch (PackageManager.NameNotFoundException exc) {
        Log.wtf("MainActivity", "Cannot find own package.");
        exc.printStackTrace();
    }
} else validateXAPKZipFiles();

And my initializeDownloadUI() is

mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, DownloaderService.class);
setContentView(R.layout.main);

mPB = (ProgressBar) findViewById(R.id.progressBar);
mStatusText = (TextView) findViewById(R.id.statusText);
mProgressFraction = (TextView) findViewById(R.id.progressAsFraction);
mProgressPercent = (TextView) findViewById(R.id.progressAsPercentage);
mAverageSpeed = (TextView) findViewById(R.id.progressAverageSpeed);
mTimeRemaining = (TextView) findViewById(R.id.progressTimeRemaining);
mDashboard = findViewById(R.id.downloaderDashboard);
mCellMessage = findViewById(R.id.approveCellular);
mPauseButton = (Button) findViewById(R.id.pauseButton);
mWiFiSettingButton = (Button) findViewById(R.id.wifiSettingsButton);

mPauseButton.setOnClickListener(this);
mWiFiSettingButton.setOnClickListener(this);
(findViewById(R.id.resumeOverCellular)).setOnClickListener(this);

Also, my onResume is

if (null != mDownloaderClientStub) {
    mDownloaderClientStub.connect(this);
}

super.onResume();

It steps through the onCreate as expected, but for some reason it doesn't connect the service. Like I said, this was working a few days ago and I didn't change anything, but now it doesn't work.

Any help?


问:
What does sed -i '/$$wf_cdc=/c\$$wf_cdc='"$1"'' mean?
I have this script with just one line, but I could not understand what it really does:

```<code>sed -i '/$$wf_cdc=/c\$$wf_cdc='"$1"'' /Infa_sharedBDE/PARAMS/pf_CREDITO_CDC.cfg
</code>```

It should replace creating a copy of the pf_CREDITI_CDC.cfg file, but
what does this command do?

```<code>'/$$wf_cdc=/c\$$wf_cdc='"$1"''
</code>```

What is $$?

答:
$$ is used literally here. The command does the following:

'/$$wf_cdc=/ is a line address: if a line contains the string $$wf_cdc=, then ...

c\$$wf_cdc='"$1"'' could also be written c $$wf_cdc='"$1"'' (at least in GNU sed): it replaces the pattern space (the current line) with \$$wf_cdc='"$1"''. Personally, I'd escape $ both times to make sure it's not interpreted as end-of-line anchor, but sometimes you get away without it.

'"$1"'' is the first positional parameter properly quoted: end single quote of the sed command, then insert $1 in double quotes, then finish rest of single quoted string (empty, in this case, and could be dropped in my opinion).

All in all, this will be called in a function or script, find the line containing $$wf_cdc= and replace it with $$wf_cdc=<parameter>, where <parameter> is supplied to the script or function as its first argument.

The -i flag replaces the file being edited "in place", i.e., makes and modifies a temporary copy and then renames that copy to the name of the original file.

Body:
I have this script with just one line, but I could not understand what it really does:

sed -i '/$$wf_cdc=/c\$$wf_cdc='"$1"'' /Infa_sharedBDE/PARAMS/pf_CREDITO_CDC.cfg

It should replace creating a copy of the pf_CREDITI_CDC.cfg file, but
what does this command do?

'/$$wf_cdc=/c\$$wf_cdc='"$1"''

What is $$?


问:
Codeigniter : array to string conversion error
Here is my model:

```<code>public function count_diabetic(){
    $query = $this->db->query("Select count(diabetic) as count_diabetic from member where diabetic is not NULL");

    return $query->result_array();
}

public function count_hypertensive(){
    $query = $this->db->query("Select count(hypertensive) as count_hypertensive from member where hypertensive is not NULL");

    return $query->result();
}
</code>```

here is my controller:

```<code>public function home(){
             $this->load->model('Jsv_model');
             $data = array(

                'count_diabetic' => $this->Jsv_model->count_diabetic(),
                'count_hypertensive' => $this->Jsv_model->count_hypertensive()

             );

             $this->session->set_userdata($data);

            $this->load->view('home');
    }
</code>```

Here is my view with in php tag:

```<code> echo $this->session->userdata('count_diabetic');
</code>```

But Here it shows error that array to string conversion error..
please help me

答:
Inside count_diabetic() you should change $query->result_array()

into

$query->row()->count_diabetic,

it would return number of count only not array.

Do it to count_hypertensive() too.

Body:
Here is my model:

public function count_diabetic(){
    $query = $this->db->query("Select count(diabetic) as count_diabetic from member where diabetic is not NULL");

    return $query->result_array();
}

public function count_hypertensive(){
    $query = $this->db->query("Select count(hypertensive) as count_hypertensive from member where hypertensive is not NULL");

    return $query->result();
}

here is my controller:

public function home(){
             $this->load->model('Jsv_model');
             $data = array(

                'count_diabetic' => $this->Jsv_model->count_diabetic(),
                'count_hypertensive' => $this->Jsv_model->count_hypertensive()

             );

             $this->session->set_userdata($data);

            $this->load->view('home');
    }

Here is my view with in php tag:

 echo $this->session->userdata('count_diabetic');

But Here it shows error that array to string conversion error..
please help me


问:
Where is the error in this? ( access query)
```<code>SELECT [02d1_NTS_Report_Structure].Nation, [02d1_NTS_Report_Structure].Region,
    [02d1_NTS_Report_Structure].Territory, [02d1_NTS_Report_Structure].Zone,
    iif ([02d1_NTS_Report_Structure].Zone="-",
        iff ([02d1_NTS_Report_Structure].Territory="-",
            iff ([02d1_NTS_Report_Structure].Region="-",
                [02d1_NTS_Report_Structure].Nation,
                [02d1_NTS_Report_Structure].Region),
        [02d1_NTS_Report_Structure].Territory),
    [02d1_NTS_Report_Structure].Zone)
FROM 02d1_NTS_Report_Structure;
</code>```

答:
Looks like you're using "IFF" instead of "IIF" in a couple places.

Try this:

```<code>SELECT [02d1_NTS_Report_Structure].Nation, [02d1_NTS_Report_Structure].Region,
    [02d1_NTS_Report_Structure].Territory, [02d1_NTS_Report_Structure].Zone,
    iif ([02d1_NTS_Report_Structure].Zone="-",
        iif ([02d1_NTS_Report_Structure].Territory="-",
            iif ([02d1_NTS_Report_Structure].Region="-",
                [02d1_NTS_Report_Structure].Nation,
                [02d1_NTS_Report_Structure].Region),
        [02d1_NTS_Report_Structure].Territory),
    [02d1_NTS_Report_Structure].Zone)
FROM 02d1_NTS_Report_Structure;
</code>```

Body:
Looks like you're using "IFF" instead of "IIF" in a couple places.

Try this:

SELECT [02d1_NTS_Report_Structure].Nation, [02d1_NTS_Report_Structure].Region,
    [02d1_NTS_Report_Structure].Territory, [02d1_NTS_Report_Structure].Zone,
    iif ([02d1_NTS_Report_Structure].Zone="-",
        iif ([02d1_NTS_Report_Structure].Territory="-",
            iif ([02d1_NTS_Report_Structure].Region="-",
                [02d1_NTS_Report_Structure].Nation,
                [02d1_NTS_Report_Structure].Region),
        [02d1_NTS_Report_Structure].Territory),
    [02d1_NTS_Report_Structure].Zone)
FROM 02d1_NTS_Report_Structure;


问:
Map markers are not shown when ammap.js and amchart.js is used on same page
I am trying to create dashboard using AmChart, as they are easy to work and are more interactive. I've found almost everything via example or multiple forms. I stuck at one place which is quite unusual and unable to find any particular clue why this thing happen, due to that i need opinion so here is my problem, looking forward for the quick answer from you people. Thanks in advance.

I am using Map (with markers) and Bar chart on same page due to that i need to use ammap.js (used for map) and amchart.js (user for rest of the charts) on the same page. Unfortunately when both javascripts are used map markers are not shown although rest of the things are working fine. I've try to remove only amchart.js after that markers are easily visible but bar chart is gone. Why this problem occurs, i need to make markers clickable and on the bar chart will update itself. Kindly help me out to achieve this particular task.

Thanks

答:
Including ammap.js and amcharts.js together will cause the libraries to conflict with each other as the underlying classes contain the same methods and one will override the other. You need to include ammap_amcharts_extension.js instead of ammap.js, which will safely extend amcharts.js to support map functionality.

```<code><script type="text/javascript" src="path/to/amcharts.js"></script>
<script type="text/javascript" src="path/to/ammap_amcharts_extension.js"></script>
</code>```

Body:
Including ammap.js and amcharts.js together will cause the libraries to conflict with each other as the underlying classes contain the same methods and one will override the other. You need to include ammap_amcharts_extension.js instead of ammap.js, which will safely extend amcharts.js to support map functionality.

<script type="text/javascript" src="path/to/amcharts.js"></script>
<script type="text/javascript" src="path/to/ammap_amcharts_extension.js"></script>


问:
gwt appengine - user service return page
I have an entire gwt home page, it has a sign in button (rpc).

This is the service implementation (just like the example):

```<code>UserService userService = UserServiceFactory.getUserService();
        HttpServletRequest request = this.getThreadLocalRequest();
    String message = "";
    String thisURL = request.getRequestURI();

    Principal principal = request.getUserPrincipal();
    if(principal == null){
        message = "<p>Please <a href=\"" + userService.createLoginURL(thisURL) + "\">sign in</a>.</p>";
    }
    else{
        message = "Hola " + principal.getName() + ". Puedes <a href=\"" +
                    userService.createLogoutURL(thisURL)+ "\">sign out</a>.</p>";
    }
    return message;
</code>```

I let the doGet method empty.

Then, when I sign in/sign out it redirects me to a blank page (to myApp/myServlet), but I want to back to the page I was (my gwt home or wherever I was).

答:
Point A: request.getRequestURI(); method. This method would always return the URL of the servlet where the current request is being processed.

Point B: In userService.createLoginURL(thisURL) , the thisURL is actually the URL where the user should be redirected to after successful login. In your case, thisURL point to your current the servlet path and not where you want the user to be redirected to (refer point A)

That is, if your page where you want to redirect user after successful login is www.yourapp.com/home, what you actually need to do is something like this:

```<code>UserService userService = UserServiceFactory.getUserService();
        HttpServletRequest request = this.getThreadLocalRequest();
    String message = "";
    String thisURL = "http://www.yourapp.com/home";

    Principal principal = request.getUserPrincipal();
    if(principal == null){
        message = "<p>Please <a href=\"" + userService.createLoginURL(thisURL) + "\">sign in</a>.</p>";
    }
    else{
        message = "Hola " + principal.getName() + ". Puedes <a href=\"" +
                    userService.createLogoutURL(thisURL)+ "\">sign out</a>.</p>";
    }
    return message;
</code>```

^Note the value being set for thisURL.

Body:
I have an entire gwt home page, it has a sign in button (rpc).

This is the service implementation (just like the example):

UserService userService = UserServiceFactory.getUserService();
        HttpServletRequest request = this.getThreadLocalRequest();
    String message = "";
    String thisURL = request.getRequestURI();

    Principal principal = request.getUserPrincipal();
    if(principal == null){
        message = "
Please sign in.
";
    }
    else{
        message = "Hola " + principal.getName() + ". Puedes sign out.
";
    }
    return message;

I let the doGet method empty.

Then, when I sign in/sign out it redirects me to a blank page (to myApp/myServlet), but I want to back to the page I was (my gwt home or wherever I was).

Body:
Point A: request.getRequestURI(); method. This method would always return the URL of the servlet where the current request is being processed.

Point B: In userService.createLoginURL(thisURL) , the thisURL is actually the URL where the user should be redirected to after successful login. In your case, thisURL point to your current the servlet path and not where you want the user to be redirected to (refer point A)

That is, if your page where you want to redirect user after successful login is www.yourapp.com/home, what you actually need to do is something like this:

UserService userService = UserServiceFactory.getUserService();
        HttpServletRequest request = this.getThreadLocalRequest();
    String message = "";
    String thisURL = "http://www.yourapp.com/home";

    Principal principal = request.getUserPrincipal();
    if(principal == null){
        message = "<p>Please <a href=\"" + userService.createLoginURL(thisURL) + "\">sign in</a>.</p>";
    }
    else{
        message = "Hola " + principal.getName() + ". Puedes <a href=\"" +
                    userService.createLogoutURL(thisURL)+ "\">sign out</a>.</p>";
    }
    return message;

^Note the value being set for thisURL.


问:
Moving highlight works on one page but not the other
I am using this moving highlight as reference on my website: https://css-tricks.com/examples/MovingHighlight/

```<code><script>
var originalBG = '',
    lightColor = 'fff',
    gradientSize = 500;

$('.navigation .flex, .navigation a, .black')
.mousemove(function(e) {
    originalBG = $(".navigation .flex, .black").css("background-color");
    x  = e.pageX - this.offsetLeft;
    y  = e.pageY - this.offsetTop;
    xy = x + " " + y;

    bgWebKit = "-webkit-gradient(radial, " + xy + ", 0, " + xy + ", 400, from(rgba(255,255,255,0.2)), to(rgba(255,255,255,0.0))), " + originalBG;
    bgMoz    = "-moz-radial-gradient(" + x + "px " + y + "px 45deg, circle, " + lightColor + " 0%, " + originalBG + " " + gradientSize + "px)";

    $(this)
      .css({ background: bgWebKit })
      .css({ background: bgMoz });

}).mouseleave(function() {
        $(this).css({ background: originalBG });
});
</script>
</code>```

I've tried removing various scripts etc but nothing seems to be working. Any ideas why I'm not seeing the gradient on the home page?

答: removing the parent elements position:relative; solved the problem.

Body:
I am using this moving highlight as reference on my website: https://css-tricks.com/examples/MovingHighlight/

I've tried removing various scripts etc but nothing seems to be working. Any ideas why I'm not seeing the gradient on the home page?


问:
associate a specific index to a vector
Can I associate an index to a vector that is maintained and that I can retrieve by a second vector?

```<code>V1<-c("a", "b", "c", "d", "e", "f")
</code>```

I want to associate an index something similar to:

```<code>"a" "b" "c" "d" "e" "f"
 1   2   3   4   5   6
</code>```

Then by a second vector

```<code>V2<-c("b", "c", "f")
</code>```

I should get integers 2, 3, 6

I know I can create a data frame with two columns ID=V1 and ixd= 1:length(V1)and subset by V2

I am wondering if there is a faster way

答:
I wanted to provide an alternative way:

V1 <- 1:6
names(V1) <- letters[1:6]   # Attach names to your list
V2 <- letters[seq(2,6,2)]   # c("b","d","f")
V1[V2]

This gives me

```<code>b d f
2 4 6
</code>```

Title: associate a specific index to a vector

Body:
Can I associate an index to a vector that is maintained and that I can retrieve by a second vector?

V1<-c("a", "b", "c", "d", "e", "f")

I want to associate an index something similar to:

"a" "b" "c" "d" "e" "f"
 1   2   3   4   5   6

Then by a second vector

V2<-c("b", "c", "f")

I should get integers 2, 3, 6

I know I can create a data frame with two columns ID=V1 and ixd= 1:length(V1)and subset by V2

I am wondering if there is a faster way

Body:
I wanted to provide an alternative way:

V1 <- 1:6
names(V1) <- letters[1:6]   # Attach names to your list
V2 <- letters[seq(2,6,2)]   # c("b","d","f")
V1[V2]

This gives me

b d f
2 4 6