问:
C++ Enum equivalent in Kotlin
The problem I am trying to solve:

I have a list of elements. The list can be large and there can be many of them. I would like to access them by index. For those indexes I would like to use words instead of numbers. I would also like this words to be strongly typed, so I cannot mix numbers with them.

I believe Kotlin enum is not good for this, since every enumeration is an object instance itself. I can use Int constants, but then I lose the type safety.

In c++ this problem is solved by an Enum. Enumerations can be casted to their underlying type (in compile time) to be used as indexes. At the same type the Enum is a type and if a function takes it as a parameter, the compiler won't allow passing integers in. The enumerations themselves are not objects themselves, so you can have as many as you like without any performance hit.

C++ code example to show what I am looking for:

```<code>string someArray[] = {"element 0", "element 1"};

enum class Index
{
    first = 0,
    second = 1,
};

string getElement(Index i)
{
    return someArray[(int)i];
}

void foo()
{
    auto element0 = getElement(Index::first);
    auto element1 = getElement(1);  // compile time error - parameter type mismatch
}
</code>```

答:
You have a comma behind second =1,

Remove that to this:

```<code>enum class Index
{
  first = 0,
  second = 1
};
</code>```

Title: C++ Enum equivalent in Kotlin

Body:
The problem I am trying to solve:

I have a list of elements. The list can be large and there can be many of them. I would like to access them by index. For those indexes I would like to use words instead of numbers. I would also like this words to be strongly typed, so I cannot mix numbers with them.

I believe Kotlin enum is not good for this, since every enumeration is an object instance itself. I can use Int constants, but then I lose the type safety.

In c++ this problem is solved by an Enum. Enumerations can be casted to their underlying type (in compile time) to be used as indexes. At the same type the Enum is a type and if a function takes it as a parameter, the compiler won't allow passing integers in. The enumerations themselves are not objects themselves, so you can have as many as you like without any performance hit.

C++ code example to show what I am looking for:

string someArray[] = {"element 0", "element 1"};

enum class Index
{
    first = 0,
    second = 1,
};

string getElement(Index i)
{
    return someArray[(int)i];
}

void foo()
{
    auto element0 = getElement(Index::first);
    auto element1 = getElement(1);  // compile time error - parameter type mismatch
}

Body:
You have a comma behind second =1,

Remove that to this:

enum class Index
{
  first = 0,
  second = 1
};


来源: stackexchange

问:
"Expected initializer before ':' token" with range-based for
```<code>#include <iostream>
#include <array>
using namespace std;

typedef int type;
typedef array <type,6> Liste;
bool appartient(type element, Liste liste);

int main()
{
    Liste maliste = {4,5,-3,12,7,-33};

    cout << appartient(13, maliste) << endl;
    cout << appartient(12, maliste) << endl;
    return 0;
}

bool appartient(type x, Liste liste)
{
    for (auto element: liste) {  //////this line!!!!!!!
        if (x == element) return true;
    }
    return false;
}
</code>```

I am working on this exercise of table in c++. Here I am writing a fonction "appartient" that verify the appartenance of an element on a list. But I have some errors in this fonction:

1/ error: expected initializer before ':' token

2/ error: expected primary-expression before 'return'

3/ error: expected ';' before 'return'

4/ error: expected primary-expression before 'return'

5/ error: expected ')' before 'return'

Why?

答:
Apparently your compiler does not support range-based for-loops, at least not with the options you are using.

Range-based for is supported since GCC v4.6, Clang v3.0, MSVC v17.0, eccp v4.5, Intel C++ v13.0, IBM XLC++ v13.1.2, Sun/Oracle C++ 5.13, Cray v8.4, PGI 2015, and HP aCC A.06.28.

Check your compiler is up to date, and check its manual on how to activate C++11 support.

ContentLicense: CC BY-SA 3.0

Body:
#include <iostream>
#include <array>
using namespace std;

typedef int type;
typedef array <type,6> Liste;
bool appartient(type element, Liste liste);

int main()
{
    Liste maliste = {4,5,-3,12,7,-33};

    cout << appartient(13, maliste) << endl;
    cout << appartient(12, maliste) << endl;
    return 0;
}

bool appartient(type x, Liste liste)
{
    for (auto element: liste) {  //////this line!!!!!!!
        if (x == element) return true;
    }
    return false;
}

I am working on this exercise of table in c++. Here I am writing a fonction "appartient" that verify the appartenance of an element on a list. But I have some errors in this fonction:

1/ error: expected initializer before ':' token

2/ error: expected primary-expression before 'return'

3/ error: expected ';' before 'return'

4/ error: expected primary-expression before 'return'

5/ error: expected ')' before 'return'

Why?


问:
PgAdmin fatal error. The appllication server could not be contacted
A couple of days before I have installed on my PC with Windows 7 Professional new version of PgAdmin (version 4). It worked fine, but today it loads slowly and then information window appears with text: "PgAdmin fatal error. The appllication server could not be contacted.". I restarted windows, but it doesn't help. Is there any solution of this problem? Thanks.</p>

答: I had the same issue. Try right clicking the PgAdmin icon and clicking "Run as administrator". Worked for me.</p>


问:
SQLException: "The table is full" during SonarQube 6.7 LTS upgrade
We've been using SonarQube for a long time, upgraded over many versions and now executed the long awaited LTS upgrade from version 5.6.6 to 6.7. Unfortunately, the database migration failed due to an SQLException "The table 'project_measures' is full".

Are there any guidelines about what do in such a case?

Is it not okay to upgrade directly from version 5.6.6 to 6.7? Should I first upgrade to some other intermediate version? I thought LTS-to-LTS upgrades should work out fine...

```<code>2017.11.15 00:49:38 INFO  web[][DbMigrations] #1218 'Delete orphan measures without component': success | time=16143ms
2017.11.15 00:49:38 INFO  web[][DbMigrations] #1219 'Make column PROJECT_MEASURES.COMPONENT_UUID not nullable'...
2017.11.15 00:51:04 ERROR web[][DbMigrations] #1219 'Make column PROJECT_MEASURES.COMPONENT_UUID not nullable': failure | time=85651ms
2017.11.15 00:51:04 ERROR web[][DbMigrations] Executed DB migrations: failure | time=1502042ms
2017.11.15 00:51:04 ERROR web[][o.s.s.p.d.m.DatabaseMigrationImpl] DB migration failed | time=1502119ms
2017.11.15 00:51:04 ERROR web[][o.s.s.p.d.m.DatabaseMigrationImpl] DB migration ended with an exception
org.sonar.server.platform.db.migration.step.MigrationStepExecutionException: Execution of migration step #1219 'Make column PROJECT_MEASURES.COMPONENT_UUID not nullable' failed
    at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:79)
    at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:67)
    at java.util.Iterator.forEachRemaining(Iterator.java:116)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.util.stream.ReferencePipeline$Head.forEachOrdered(ReferencePipeline.java:590)
    at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:52)
    at org.sonar.server.platform.db.migration.engine.MigrationEngineImpl.execute(MigrationEngineImpl.java:50)
    at org.sonar.server.platform.db.migration.DatabaseMigrationImpl.doUpgradeDb(DatabaseMigrationImpl.java:105)
    at org.sonar.server.platform.db.migration.DatabaseMigrationImpl.doDatabaseMigration(DatabaseMigrationImpl.java:80)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Fail to execute ALTER TABLE project_measures MODIFY COLUMN component_uuid VARCHAR (50) NOT NULL
    at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:97)
    at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:77)
    at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:117)
    at org.sonar.server.platform.db.migration.version.v60.MakeComponentUuidNotNullOnMeasures.execute(MakeComponentUuidNotNullOnMeasures.java:40)
    at org.sonar.server.platform.db.migration.step.DdlChange.execute(DdlChange.java:45)
    at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:75)
    ... 11 common frames omitted
Caused by: java.sql.SQLException: The table 'project_measures' is full
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2444)
    at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:845)
    at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:745)
    at org.apache.commons.dbcp.DelegatingStatement.execute(DelegatingStatement.java:264)
    at org.apache.commons.dbcp.DelegatingStatement.execute(DelegatingStatement.java:264)
    at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:82)
    ... 16 common frames omitted
</code>```

SonarQube is installed on a RHEL7 host using MySQL (rh-mysql57-mysql-server). The database location is /var/opt/rh/rh-mysql57/lib/mysql/sonar and there is free disk space available (but maybe not enough?):

```<code>/dev/mapper/vg0-var_opt   20G   17G  3.1G  85% /var/opt
</code>```

答:
Upgrade 5.6.6 to 6.7 is supported. According to your stack trace you are using MySQL server.

Can you have a look at server log files and the free space available on MySQL (maybe there is no enough space on your MySQL server for the migration) ?

Body:
We've been using SonarQube for a long time, upgraded over many versions and now executed the long awaited LTS upgrade from version 5.6.6 to 6.7. Unfortunately, the database migration failed due to an SQLException "The table 'project_measures' is full".

Are there any guidelines about what do in such a case?

Is it not okay to upgrade directly from version 5.6.6 to 6.7? Should I first upgrade to some other intermediate version? I thought LTS-to-LTS upgrades should work out fine...

2017.11.15 00:49:38 INFO  web[][DbMigrations] #1218 'Delete orphan measures without component': success | time=16143ms
2017.11.15 00:49:38 INFO  web[][DbMigrations] #1219 'Make column PROJECT_MEASURES.COMPONENT_UUID not nullable'...
2017.11.15 00:51:04 ERROR web[][DbMigrations] #1219 'Make column PROJECT_MEASURES.COMPONENT_UUID not nullable': failure | time=85651ms
2017.11.15 00:51:04 ERROR web[][DbMigrations] Executed DB migrations: failure | time=1502042ms
2017.11.15 00:51:04 ERROR web[][o.s.s.p.d.m.DatabaseMigrationImpl] DB migration failed | time=1502119ms
2017.11.15 00:51:04 ERROR web[][o.s.s.p.d.m.DatabaseMigrationImpl] DB migration ended with an exception
org.sonar.server.platform.db.migration.step.MigrationStepExecutionException: Execution of migration step #1219 'Make column PROJECT_MEASURES.COMPONENT_UUID not nullable' failed
    at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:79)
    at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:67)
    at java.util.Iterator.forEachRemaining(Iterator.java:116)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.util.stream.ReferencePipeline$Head.forEachOrdered(ReferencePipeline.java:590)
    at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:52)
    at org.sonar.server.platform.db.migration.engine.MigrationEngineImpl.execute(MigrationEngineImpl.java:50)
    at org.sonar.server.platform.db.migration.DatabaseMigrationImpl.doUpgradeDb(DatabaseMigrationImpl.java:105)
    at org.sonar.server.platform.db.migration.DatabaseMigrationImpl.doDatabaseMigration(DatabaseMigrationImpl.java:80)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Fail to execute ALTER TABLE project_measures MODIFY COLUMN component_uuid VARCHAR (50) NOT NULL
    at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:97)
    at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:77)
    at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:117)
    at org.sonar.server.platform.db.migration.version.v60.MakeComponentUuidNotNullOnMeasures.execute(MakeComponentUuidNotNullOnMeasures.java:40)
    at org.sonar.server.platform.db.migration.step.DdlChange.execute(DdlChange.java:45)
    at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:75)
    ... 11 common frames omitted
Caused by: java.sql.SQLException: The table 'project_measures' is full
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2444)
    at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:845)
    at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:745)
    at org.apache.commons.dbcp.DelegatingStatement.execute(DelegatingStatement.java:264)
    at org.apache.commons.dbcp.DelegatingStatement.execute(DelegatingStatement.java:264)
    at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:82)
    ... 16 common frames omitted

SonarQube is installed on a RHEL7 host using MySQL (rh-mysql57-mysql-server). The database location is /var/opt/rh/rh-mysql57/lib/mysql/sonar and there is free disk space available (but maybe not enough?):

/dev/mapper/vg0-var_opt   20G   17G  3.1G  85% /var/opt


问:
Escaping literal s and ' while using sed
I'm using sed in Gitbash for Windows to run through a body of XML texts marking up certain strings.

One of the strings concerned is:

```<code>S. Margaret's
</code>```

which needs to be enclosed in an element like so:

```<code><orgName id="16">S.Margaret's</orgName>
</code>```

And so my script reads:

```<code>sed -e 's/S. Margaret's/<orgName id="16">S. Margaret's<\/orgName>/g'
</code>```

Where I have escaped the forward slash in the  tag that I need to insert.

This throws an error "orgName: No such file or directory"

I suppose the issue is to do with the 's/ after Margaret, which is interpreted as the beginning of a new command, but how do I escape it? I've tried various combinations of backslashes but without success.

答:
' cannot be escaped inside a string in simple quotes. The shell sees your command as

```<code>sed -e 's/S. Margaret's/<orgName id="16">S. Margaret's<\/orgName>/g'
        ^^^^^^^^^^^^^
        string in single quotes
                        ^ redirection operator
                         ^^^^^^^ file name to read input from
</code>```

The usual construct is '...'\''...'.

Body:
I'm using sed in Gitbash for Windows to run through a body of XML texts marking up certain strings.

One of the strings concerned is:

S. Margaret's

which needs to be enclosed in an element like so:

<orgName id="16">S.Margaret's</orgName>

And so my script reads:

sed -e 's/S. Margaret's/<orgName id="16">S. Margaret's<\/orgName>/g'

Where I have escaped the forward slash in the  tag that I need to insert.

This throws an error "orgName: No such file or directory"

I suppose the issue is to do with the 's/ after Margaret, which is interpreted as the beginning of a new command, but how do I escape it? I've tried various combinations of backslashes but without success.

Body:
' cannot be escaped inside a string in simple quotes. The shell sees your command as

sed -e 's/S. Margaret's/<orgName id="16">S. Margaret's<\/orgName>/g'
        ^^^^^^^^^^^^^
        string in single quotes
                        ^ redirection operator
                         ^^^^^^^ file name to read input from

The usual construct is '...'\''...'.


问:
Tomcat & Eclipse integration
I'm developing on a Ubuntu 8.04 machine using Eclipse Ganymede. I installed Tomcat 5.5 using sudo apt-get install tomcat5.5 tomcat5.5-admin and using an Ant script I deploy my WAR file by copying it to $CATALINA_HOME/webapps.

I then created an Eclipse project and I have it output compiled source in a similar but separate directory structure under $PROJECT_ROOT/target/. I still deploy the WAR file by right clicking on the build.xml and choosing my deploy-war task.

As Tomcat is running as a deamon, automatically started up on booting, I'm not instructing it when to start or exit.

My problems with this setup are:

Using this approach I do not get any output to the Eclipse console, as Tomcat is running under the tomcat55 user and I have a different login and no access to Stdout of tomcat55.

The logging which occurs is also directed to Stdout at the moment, which I find pretty nice during development. But it's not nice when I can't see it. :-)

I don't have any servers under the Server tab and no Run configurations. This makes it impossible for me to use the Debug mode of Eclipse, which otherwise is quite convenient.

What do you think I should do to integrate them and in turn make my development environment much better?

答:
I'd say forget the pre-packaged Tomcat. Grab the apache-tomcat-x.y.z.zip from the site, unzip it somewhere in your $HOME and add a Server to your eclipse workspace, pointing to your local installation of tomcat. Of course you need the j2ee/wtp Eclipse bundle. Works fine on Windows, can't see a reason for it not working on Linux.

Edit: You may have to fiddle with server ports if you have two tomcat installs.

ContentLicense: CC BY-SA 2.5

Title: Tomcat & Eclipse integration

OwnerDisplayName: agnul


问:
How can I fix "Design editor is unavailable until a successful build" error?
I started to learn Android Studio. I try to echo out simple "Hello World":

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</RelativeLayout>
</code>```

but when I clicked "design" view, this error is showing?

Design editor is unavailable until a successful build

How can I fix this error.

I just noticed that my xml code is causing error. Is that why this may be not working?

答: Edit you xml file in Notepad++ and build it again. It's work for me</p>

ContentLicense: CC BY-SA 4.0

Body:
I started to learn Android Studio. I try to echo out simple "Hello World":

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</RelativeLayout>

but when I clicked "design" view, this error is showing?

Design editor is unavailable until a successful build

How can I fix this error.

I just noticed that my xml code is causing error. Is that why this may be not working?


问:
How do I give external or local html doc link to bootstrap nav-pills?
I need to link my another webpage to my pictures nav menu.
Ex: if I click my pictures menu , it opens google.com.

Framework: bootstrap 4

```<code>div class="row row2">
        <div class="col-md-12">
            <ul class="nav nav-pills justify-content-center nav-justified" role="tablist">
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">About me</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My pictures</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My music</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My files</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My videos</a>
                </li>
            </ul>
        </div>
    </div>
</code>```

答:
This is the correct code for my question. i solve this with your help. thankyou

Html

```<code><div class="row row2">
        <div class="col-md-12">
            <ul class="nav nav-pills justify-content-center nav-justified" role="tablist">
                <li class="nav-item">
                    <a class="nav-link" href="about_me.html">About me</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="my_pictures.html">My pictures</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="my_music.html">My music</a>
                </li>
                <li class="nav-item active">
                    <a class="nav-link" href="my_files.html">My files</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="my_videos.html">My videos</a>
                </li>
            </ul>
        </div>
    </div>
</code>```

CSS

```<code>    .active {
    background-color: #39a0c9 !important;
    color: #fff !important;
}
</code>```

Body:
I need to link my another webpage to my pictures nav menu.
Ex: if I click my pictures menu , it opens google.com.

Framework: bootstrap 4

div class="row row2">

                    About me

                    My pictures

                    My music

                    My files

                    My videos

Body:
This is the correct code for my question. i solve this with your help. thankyou

Html

<div class="row row2">
        <div class="col-md-12">
            <ul class="nav nav-pills justify-content-center nav-justified" role="tablist">
                <li class="nav-item">
                    <a class="nav-link" href="about_me.html">About me</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="my_pictures.html">My pictures</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="my_music.html">My music</a>
                </li>
                <li class="nav-item active">
                    <a class="nav-link" href="my_files.html">My files</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="my_videos.html">My videos</a>
                </li>
            </ul>
        </div>
    </div>

CSS

    .active {
    background-color: #39a0c9 !important;
    color: #fff !important;
}


问:
ORDER BY with different WHERE condition
Here is illustrated scenario for my problem.

```<code>SELECT field
FROM myTable
WHERE field1 = 'abc' AND filed2 = 'xyz' AND field3 = 'pqr'
ORDER BY field4 ASC
</code>```

This query give me result as:

```<code>result1
result2
result3
</code>```

Now if I run following query, then

```<code>SELECT field
FROM myTable
WHERE field1 = 'xxx' AND field2 = 'xyz'
ORDER BY field4 ASC

result2
result3
result1
</code>```

So, basically both query give same results but with different order. But I want result from first query with second query's ORDER BY. See both have different condition on field1. Everything else is same.

答:
There is nothing wrong with this.

2 query return different rows (the first with field1 = 'abc', the second with 'xxx'), so why should these 2 result sets correlate?

Here is an example:

```<code>declare @myTable table (field varchar(100),
                        field1 varchar(100),
                        field2 varchar(100),
                        field3 varchar(100),
                        field4 int);

insert into @myTable (field, field1, field2, field3, field4)
values  ('result1', 'abc', 'xyz', 'pqr',1),
('result2', 'abc', 'xyz', 'pqr',2),
('result3', 'abc', 'xyz', 'pqr',3);

insert into @myTable (field, field1, field2, field4)
values
('result2', 'xxx', 'xyz',1),
('result3', 'xxx', 'xyz',2),
('result1', 'xxx', 'xyz',3);

SELECT field
FROM @myTable
WHERE field1 = 'abc' AND field2 = 'xyz' AND field3 = 'pqr'
ORDER BY field4 ASC

--result1
--result2
--result3

SELECT field
FROM @myTable
WHERE field1 = 'xxx' AND field2 = 'xyz'
ORDER BY field4 ASC

--result2
--result3
--result1
</code>```

Title: ORDER BY with different WHERE condition

Body:
Here is illustrated scenario for my problem.

SELECT field
FROM myTable
WHERE field1 = 'abc' AND filed2 = 'xyz' AND field3 = 'pqr'
ORDER BY field4 ASC

This query give me result as:

result1
result2
result3

Now if I run following query, then

SELECT field
FROM myTable
WHERE field1 = 'xxx' AND field2 = 'xyz'
ORDER BY field4 ASC

result2
result3
result1

So, basically both query give same results but with different order. But I want result from first query with second query's ORDER BY. See both have different condition on field1. Everything else is same.

Body:
There is nothing wrong with this.

2 query return different rows (the first with field1 = 'abc', the second with 'xxx'), so why should these 2 result sets correlate?

Here is an example:

declare @myTable table (field varchar(100),
                        field1 varchar(100),
                        field2 varchar(100),
                        field3 varchar(100),
                        field4 int);

insert into @myTable (field, field1, field2, field3, field4)
values  ('result1', 'abc', 'xyz', 'pqr',1),
('result2', 'abc', 'xyz', 'pqr',2),
('result3', 'abc', 'xyz', 'pqr',3);

insert into @myTable (field, field1, field2, field4)
values
('result2', 'xxx', 'xyz',1),
('result3', 'xxx', 'xyz',2),
('result1', 'xxx', 'xyz',3);

SELECT field
FROM @myTable
WHERE field1 = 'abc' AND field2 = 'xyz' AND field3 = 'pqr'
ORDER BY field4 ASC

--result1
--result2
--result3

SELECT field
FROM @myTable
WHERE field1 = 'xxx' AND field2 = 'xyz'
ORDER BY field4 ASC

--result2
--result3
--result1


问:
Count entries of specific object property name within current index
How would I efficiently go about counting the .length of a specific object property within a current object index?

Would I need to iterate through each content.item index and then iterate through content.item.itemSettings.item.monsters and on the way do a "manual" countup?

In the below im trying to count a specific property for each
content.item where the property im trying to count is "monsters":

```<code>content.item.itemSettings.item.monsters
</code>```

The first (index) count [0] of content.item would be expected to be = 4

The second (index) count [1] of content.item would be expected to be = 3

var content = {
  item: [{
      mainId: 50,

      itemSettings: {
        item: [{
            level: 1,

            monsters: [{
                name: 'monster 1',

                item: [{
                  innerLabel: 'blue',
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: 'monster 2',

                item: [{
                  innerLabel: 'pink',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 1,

            monsters: [{
                name: 'monster 3',

                item: [{
                  innerLabel: 'gray',
                  year: [{
                      yearVal: 2016,
                      yearStat: 50,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 55,
                    }
                  ]
                }]
              },
              {
                name: 'monster 4',

                item: [{
                  innerLabel: 'red',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 100,
                    }
                  ]
                }]
              },
            ]
          },
        ] //mainId
      }, //itemSettings
    }, //content.item

    //NEW
    {
      mainId: 60,

      itemSettings: {
        item: [{
            level: 2,

            monsters: [{
                name: 'monster 2-1',

                item: [{
                  innerLabel: 'blue',
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: 'monster 2-2',

                item: [{
                  innerLabel: 'pink',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 2,

            monsters: [{
              name: 'monster 2-3',

              item: [{
                innerLabel: 'gray',
                year: [{
                    yearVal: 2016,
                    yearStat: 50,
                  },
                  {
                    yearVal: 2012,
                    yearStat: 55,
                  }
                ]
              }]
            }, ]
          },
        ] //mainId
      }, //itemSettings
    }, //content.item

  ]
}; //content
```

答:
You can use reduce for this. (If you don't understand anything in the code, please ask)

var length = content.item.reduce((sum, value) => {
  return sum + Object.values(value.itemSettings.item).reduce((isum, ivalue) => {
    return isum + ivalue.monsters.length;
  }, 0);
}, 0);
```

<p><strong>Working code:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var content = {
  item: [
    {
      mainId: 50,
      itemSettings: {
        item: [{
            level: 1,

            monsters: [{
                name: "monster 1",

                item: [{
                  innerLabel: "blue",
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: "monster 2",

                item: [{
                  innerLabel: "pink",
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 1,

            monsters: [{
                name: "monster 3",

                item: [{
                  innerLabel: "gray",
                  year: [{
                      yearVal: 2016,
                      yearStat: 50,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 55,
                    }
                  ]
                }]
              },
              {
                name: "monster 4",

                item: [{
                  innerLabel: "red",
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 100,
                    }
                  ]
                }]
              },
            ]
          },
        ]
      },
    },
   {
      mainId: 60,

      itemSettings: {
        item: [{
            level: 2,

            monsters: [{
                name: "monster 2-1",

                item: [{
                  innerLabel: "blue",
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: "monster 2-2",

                item: [{
                  innerLabel: "pink",
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 2,

            monsters: [{
              name: "monster 2-3",

              item: [{
                innerLabel: "gray",
                year: [{
                    yearVal: 2016,
                    yearStat: 50,
                  },
                  {
                    yearVal: 2012,
                    yearStat: 55,
                  }
                ]
              }]
            }, ]
          },
        ]
      },
    }
  ]
};

var length = content.item.reduce((sum, value) => {
    return sum + Object.values(value.itemSettings.item).reduce((isum, ivalue) => {
      return isum + ivalue.monsters.length;
    }, 0);
}, 0);

console.log(length);</code>```

Body:
How would I efficiently go about counting the .length of a specific object property within a current object index?

Would I need to iterate through each content.item index and then iterate through content.item.itemSettings.item.monsters and on the way do a "manual" countup?

In the below im trying to count a specific property for each
content.item where the property im trying to count is "monsters":

content.item.itemSettings.item.monsters

The first (index) count [0] of content.item would be expected to be = 4

The second (index) count [1] of content.item would be expected to be = 3

var content = {
  item: [{
      mainId: 50,

      itemSettings: {
        item: [{
            level: 1,

            monsters: [{
                name: 'monster 1',

                item: [{
                  innerLabel: 'blue',
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: 'monster 2',

                item: [{
                  innerLabel: 'pink',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 1,

            monsters: [{
                name: 'monster 3',

                item: [{
                  innerLabel: 'gray',
                  year: [{
                      yearVal: 2016,
                      yearStat: 50,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 55,
                    }
                  ]
                }]
              },
              {
                name: 'monster 4',

                item: [{
                  innerLabel: 'red',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 100,
                    }
                  ]
                }]
              },
            ]
          },
        ] //mainId
      }, //itemSettings
    }, //content.item

    //NEW
    {
      mainId: 60,

      itemSettings: {
        item: [{
            level: 2,

            monsters: [{
                name: 'monster 2-1',

                item: [{
                  innerLabel: 'blue',
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: 'monster 2-2',

                item: [{
                  innerLabel: 'pink',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 2,

            monsters: [{
              name: 'monster 2-3',

              item: [{
                innerLabel: 'gray',
                year: [{
                    yearVal: 2016,
                    yearStat: 50,
                  },
                  {
                    yearVal: 2012,
                    yearStat: 55,
                  }
                ]
              }]
            }, ]
          },
        ] //mainId
      }, //itemSettings
    }, //content.item

  ]
}; //content

Body:
You can use reduce for this. (If you don't understand anything in the code, please ask)

var length = content.item.reduce((sum, value) => {
  return sum + Object.values(value.itemSettings.item).reduce((isum, ivalue) => {
    return isum + ivalue.monsters.length;
  }, 0);
}, 0);

Working code:

var content = {
  item: [
    {
      mainId: 50,
      itemSettings: {
        item: [{
            level: 1,

            monsters: [{
                name: "monster 1",

                item: [{
                  innerLabel: "blue",
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: "monster 2",

                item: [{
                  innerLabel: "pink",
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 1,

            monsters: [{
                name: "monster 3",

                item: [{
                  innerLabel: "gray",
                  year: [{
                      yearVal: 2016,
                      yearStat: 50,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 55,
                    }
                  ]
                }]
              },
              {
                name: "monster 4",

                item: [{
                  innerLabel: "red",
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 100,
                    }
                  ]
                }]
              },
            ]
          },
        ]
      },
    },
   {
      mainId: 60,

      itemSettings: {
        item: [{
            level: 2,

            monsters: [{
                name: "monster 2-1",

                item: [{
                  innerLabel: "blue",
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: "monster 2-2",

                item: [{
                  innerLabel: "pink",
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 2,

            monsters: [{
              name: "monster 2-3",

              item: [{
                innerLabel: "gray",
                year: [{
                    yearVal: 2016,
                    yearStat: 50,
                  },
                  {
                    yearVal: 2012,
                    yearStat: 55,
                  }
                ]
              }]
            }, ]
          },
        ]
      },
    }
  ]
};

var length = content.item.reduce((sum, value) => {
    return sum + Object.values(value.itemSettings.item).reduce((isum, ivalue) => {
      return isum + ivalue.monsters.length;
    }, 0);
}, 0);

console.log(length);


问:
Change title in App Bar when user navigates to a different component in React
I have a React app with a bunch of components and have it structured in the following way

```<code>class App extends Component {
  render() {
    return (
      <Router>
        <ResponsiveDrawer>
          <div className="App">
              <div>
                <Route exact path="/" component={Administrator} />
                <Route path="/admin" component={Administrator} />
                <Route exact path="/jobs" component={Jobs} />
                <Route path="/jobs/:id" render={({match}) => <ViewJob id={match.params.id} />} />
                <Route path="/entries/:jobId/:entryId" render={({match}) => <Entry jobId={match.params.jobId} entryId={match.params.entryId} />} />
                <Route exact path="/reports" component={Reports} />
                <Route path="/reports/:jobId" render={({match}) => <JobReport id={match.params.jobId} />} />
                <Route path="/reports/activity" component={ActivityReport} />
              </div>
          </div>
         </ResponsiveDrawer>
     </Router>

    );
  }
}

export default App;
</code>```

Part of the ResponsiveDrawer contains a title that I want to change based on which component the user is currently in. Is there any way that I can pass props up to a parent like that?

答: if you're not using redux, you can add a switch-case statement in the componentDidMount of the ResponsiveDrawer component based on location.pathname.</p>

Body:
I have a React app with a bunch of components and have it structured in the following way

class App extends Component {
  render() {
    return (
      <Router>
        <ResponsiveDrawer>

                <Route exact path="/" component={Administrator} />
                <Route path="/admin" component={Administrator} />
                <Route exact path="/jobs" component={Jobs} />
                <Route path="/jobs/:id" render={({match}) => <ViewJob id={match.params.id} />} />
                <Route path="/entries/:jobId/:entryId" render={({match}) => <Entry jobId={match.params.jobId} entryId={match.params.entryId} />} />
                <Route exact path="/reports" component={Reports} />
                <Route path="/reports/:jobId" render={({match}) => <JobReport id={match.params.jobId} />} />
                <Route path="/reports/activity" component={ActivityReport} />

         </ResponsiveDrawer>
     </Router>

    );
  }
}

export default App;

Part of the ResponsiveDrawer contains a title that I want to change based on which component the user is currently in. Is there any way that I can pass props up to a parent like that?


问:
how to make content occupy whole page regardless of the screen size?
I am designing a web page for the mobile first time. I have given 100% width and height so that content will render at the full page regardless of mobile screen size. but still, as you can see from the screenshot, there is empty space below and on the right side. Also even one of my checkbox content is even crossing the width of the page. I have tried putting that content in a span tag and defining a class and putting something like max-width: 20 px or something but it is not having any effect whatsoever. below my code snippet of HTML and css

/* style.css */
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

body {
 margin: 0;
height: 100%;
width: 100%;
}

/* this page css */

mat-card{
width: 100%;
}

img{
padding: 2%;
text-align: center;
width:5%;
height: 5%;
}

.logo {
  margin: 10%;
 text-align: center;

}

.confirm-text {
max-width: 30px;
   display: block;
}

.example-container {
  display: flex;
  flex-direction: column;
}

.example-container>* {
  width: 100%;
}

.example-right-align {
  text-align: right;
}

input.example-right-align::-webkit-outer-spin-button,
input.example-right-align::-webkit-inner-spin-button {
  display: none;
}

.example-radio-group {
  display: inline-flex;
  flex-direction: column;
}
.checkbox {
display: block;
flex-direction: column;
padding-left:4%;
}

strong {
padding-left: 4%;
}
p {
  padding-left: 4%;
}

.example-radio-button {
  margin: 3%;
}

.example-selected-value {
  margin: 15px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><mat-card><div class="logo">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRE3x0vsDn1R5O0v7QKVvJNMJK2txXUv8IIsY-2t4R8ore5AjMk0g" alt="image">
  <br>
  <br>
  <p>your return request has been confirmed. please tell us a convenient time to schedule the pick up</p>
</div></mat-card>
<mat-card class="login-form">
<form class="example-container" (ngSubmit)="onSubmit(f)" #f="ngForm">
  <strong>Pick up your preferred date</strong>
  <mat-radio-group class="example-radio-group" name="selectedDate" [(ngModel)]="selectedDate" required>
  <mat-radio-button class="example-radio-button"
     *ngFor="let date of dateOptions" [value]="date" ngDefaultControl>
    {{date}}
  </mat-radio-button>
</mat-radio-group>
<br><br>
<strong>Select a preferred time</strong>
<mat-radio-group
 class="example-radio-group" name="selectedTime" [(ngModel)]="selectedTime" required>
  <mat-radio-button class="example-radio-button"
    *ngFor="let time of timeOptions" [value]="time" ngDefaultControl>
    {{time}}
  </mat-radio-button>
</mat-radio-group>
<hr>
<mat-checkbox class="checkbox" name="confirmation" [(ngModel)]="confirmation" required>
  <span class="confirm-text">I confirm the above selected date and time as the preferred slot for return pick up.</span>
</mat-checkbox>
<hr>
<button mat-raised-button color="accent"  type="submit"  [disabled]="!f.valid">Submit</button>
</form>
</mat-card></code>```

edit: this is index.html

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Myntra</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://storage.googleapis.com/code.getmdl.io/1.1.0/material.indigo-pink.min.css" rel="stylesheet" /
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

</head>
<body>
  <app-root></app-root>
</body>
</html>
</code>```

答:
You could also link to a CSS stylesheet like Normalize.css to remove some of the default CSS of the browser and make your page look more consistent across different browsers.  Just make sure to link to your main CSS stylesheet AFTER Normalize.css.

https://necolas.github.io/normalize.css/

Body:
I am designing a web page for the mobile first time. I have given 100% width and height so that content will render at the full page regardless of mobile screen size. but still, as you can see from the screenshot, there is empty space below and on the right side. Also even one of my checkbox content is even crossing the width of the page. I have tried putting that content in a span tag and defining a class and putting something like max-width: 20 px or something but it is not having any effect whatsoever. below my code snippet of HTML and css

/* style.css */
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

body {
 margin: 0;
height: 100%;
width: 100%;
}

/* this page css */

mat-card{
width: 100%;
}

img{
padding: 2%;
text-align: center;
width:5%;
height: 5%;
}

.logo {
  margin: 10%;
 text-align: center;

}

.confirm-text {
max-width: 30px;
   display: block;
}

.example-container {
  display: flex;
  flex-direction: column;
}

.example-container>* {
  width: 100%;
}

.example-right-align {
  text-align: right;
}

input.example-right-align::-webkit-outer-spin-button,
input.example-right-align::-webkit-inner-spin-button {
  display: none;
}

.example-radio-group {
  display: inline-flex;
  flex-direction: column;
}
.checkbox {
display: block;
flex-direction: column;
padding-left:4%;
}

strong {
padding-left: 4%;
}
p {
  padding-left: 4%;
}

.example-radio-button {
  margin: 3%;
}

.example-selected-value {
  margin: 15px 0;
}

<mat-card>

your return request has been confirmed. please tell us a convenient time to schedule the pick up

</mat-card>
<mat-card class="login-form">
<form class="example-container" (ngSubmit)="onSubmit(f)" #f="ngForm">
  Pick up your preferred date
  <mat-radio-group class="example-radio-group" name="selectedDate" [(ngModel)]="selectedDate" required>
  <mat-radio-button class="example-radio-button"
     *ngFor="let date of dateOptions" [value]="date" ngDefaultControl>
    {{date}}
  </mat-radio-button>
</mat-radio-group>

Select a preferred time
<mat-radio-group
 class="example-radio-group" name="selectedTime" [(ngModel)]="selectedTime" required>
  <mat-radio-button class="example-radio-button"
    *ngFor="let time of timeOptions" [value]="time" ngDefaultControl>
    {{time}}
  </mat-radio-button>
</mat-radio-group>

<mat-checkbox class="checkbox" name="confirmation" [(ngModel)]="confirmation" required>
  I confirm the above selected date and time as the preferred slot for return pick up.
</mat-checkbox>

<button mat-raised-button color="accent"  type="submit"  [disabled]="!f.valid">Submit</button>
</form>
</mat-card>

edit: this is index.html

<!doctype html>

  <meta charset="utf-8">
  <title>Myntra</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://storage.googleapis.com/code.getmdl.io/1.1.0/material.indigo-pink.min.css" rel="stylesheet" /
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <app-root></app-root>


问:
hibernate named queries
In hibernate, when we do, session.getNamedQuery(QUERY_NAME), we do not need to pass in the name of the hbm.xml file where the named query is stored. The name of the hbm.xml is mentioned in the cfg file.

The question is, if there are 5 hbm.xml files for named queries, and there is a name conflict with respect to the query name(i.e. same QUERY_NAME in all 5 files), how hibernate will resolve it?

Intuitively, it appears before doing session.getNamedQuery(QUERY_NAME), one should need to explicitly load the particular hbm.xml file where the query is written.

答: Though this doesn't directly address the question, it's common practice to give your queries names that reflect the package and entity they deal with to avoid naming collisions. Instead of "findUser" you might have something like "com.myproject.domain.User.findByUsernameAndPassword"</p>

Title: hibernate named queries


问:
Unity3d - Audio rough sound when transition between play and pause
I have a Unity script that will play audio (foot step) while the player is moving. The script is working, but there is one more problem, the audio seems too rough (and maybe can harm my speaker hehe) when transition between play and pause.

This is my script

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerController : MonoBehaviour {
    Rigidbody playerRigid;
    private Vector3 pindah;
    public AudioSource audioSource;
    public AudioClip audioClip;
    public float lowPitchRange = .95f;
    public float hiPitchRange = 1.05f;

    void Awake () {
        audioSource = GetComponent<AudioSource> ();
        audioSource.clip = audioClip;
        float randomPitch = Random.Range (lowPitchRange, hiPitchRange);
        audioSource.pitch = randomPitch;
    }

    // Use this for initialization
    void Start () {
        //mengambil komponen rigidbody player
        playerRigid = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void Update () {
        //untuk mendapatkan input dari virtual joystick button
        float h = CrossPlatformInputManager.GetAxisRaw ("Horizontal");
        float v = CrossPlatformInputManager.GetAxisRaw ("Vertical");

        if ((h != 0f || v != 0f) && !audioSource.isPlaying) {
            audioSource.Play ();
        } else {
            audioSource.Pause ();
        }
        //memindah posisi player sesuai input yang didapat
        pindah = new Vector3 (h, 0.0f, v);
        playerRigid.velocity = pindah;
    }
}
</code>```

答:
I guess you need to change the code like this:</p>

```<code>if (h != 0f || v != 0f) {
     if (!audioSource.isPlaying) audioSource.Play ();
} else {
     audioSource.Pause ();
}
</code>```

Body:
I have a Unity script that will play audio (foot step) while the player is moving. The script is working, but there is one more problem, the audio seems too rough (and maybe can harm my speaker hehe) when transition between play and pause.

This is my script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerController : MonoBehaviour {
    Rigidbody playerRigid;
    private Vector3 pindah;
    public AudioSource audioSource;
    public AudioClip audioClip;
    public float lowPitchRange = .95f;
    public float hiPitchRange = 1.05f;

    void Awake () {
        audioSource = GetComponent<AudioSource> ();
        audioSource.clip = audioClip;
        float randomPitch = Random.Range (lowPitchRange, hiPitchRange);
        audioSource.pitch = randomPitch;
    }

    // Use this for initialization
    void Start () {
        //mengambil komponen rigidbody player
        playerRigid = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void Update () {
        //untuk mendapatkan input dari virtual joystick button
        float h = CrossPlatformInputManager.GetAxisRaw ("Horizontal");
        float v = CrossPlatformInputManager.GetAxisRaw ("Vertical");

        if ((h != 0f || v != 0f) && !audioSource.isPlaying) {
            audioSource.Play ();
        } else {
            audioSource.Pause ();
        }
        //memindah posisi player sesuai input yang didapat
        pindah = new Vector3 (h, 0.0f, v);
        playerRigid.velocity = pindah;
    }
}

Body:
I guess you need to change the code like this:

if (h != 0f || v != 0f) {
     if (!audioSource.isPlaying) audioSource.Play ();
} else {
     audioSource.Pause ();
}


问:
Bind class to a slot in Vue.js 2
I'm trying to create a reusable component for iterating over items, filtering them, and adding some classes to the slot (if the item is even, odd, first, last etc..)

Here's my reusable component:

```<code><template>
  <ul :class="classes">
    <slot
      v-for="(item, index) in filteredItems"
      :item="item"
      :class="{
        'first': index == 0,
        'odd': !(index % 2),
        'even': index % 2,
        'last': index == (filteredItems.length - 1)
      }"
    >
    </slot>
  </ul>
</template>

<script>
export default {
  props: ['items', 'classes'],
  data() {
    return {
      filteredItems: this.items.filter(item => item.active)
    };
  }
};
</script>
</code>```

And here's how I use it:

```<code><component-list :classes="'some-class'" :items="category.products">
  <template scope="props">
    <product :product="props.item"></product>
  </template>
<component-list>
</code>```

Everything works as expected, but it doesn't add classes to the element put inside .

Am I doing anything wrong? Is it even technically possible in Vue.js 2 to do something like this?

Thanks for any help or suggestion!

答:
I have another way can get your aim, but not use render, still use slot.

The reusable component:

```<code><template>
  <ul :class="classes">
    <slot
      v-for="(item, index) in filteredItems"
      :item="item"
      :_class="{
        'first': index == 0,
        'odd': !(index % 2),
        'even': index % 2,
        'last': index == (filteredItems.length - 1)
      }"
    >
    </slot>
  </ul>
</template>

<script>
export default {
  props: ['items', 'classes'],
  data() {
    return {
      filteredItems: this.items.filter(item => item.active)
    };
  }
};
</script>
</code>```

use _class to class keyword, so Vue.js will let _class as the common property.

Then in your use:

```<code><component-list :classes="'some-class'" :items="category.products">
  <template scope="{ item, _class }">
    <product :product="item" :class="_class"></product>
  </template>
<component-list>
</code>```

By the scope property, your can still get _class from slot.

After all, use render may be more conciseness. :)

Title: Bind class to a slot in Vue.js 2

Body:
I'm trying to create a reusable component for iterating over items, filtering them, and adding some classes to the slot (if the item is even, odd, first, last etc..)

Here's my reusable component:

<template>

    <slot
      v-for="(item, index) in filteredItems"
      :item="item"
      :class="{
        'first': index == 0,
        'odd': !(index % 2),
        'even': index % 2,
        'last': index == (filteredItems.length - 1)
      }"
    >
    </slot>

</template>

And here's how I use it:

<component-list :classes="'some-class'" :items="category.products">
  <template scope="props">
    <product :product="props.item"></product>
  </template>
<component-list>

Everything works as expected, but it doesn't add classes to the element put inside .

Am I doing anything wrong? Is it even technically possible in Vue.js 2 to do something like this?

Thanks for any help or suggestion!

Body:
I have another way can get your aim, but not use render, still use slot.

The reusable component:

<template>
  <ul :class="classes">
    <slot
      v-for="(item, index) in filteredItems"
      :item="item"
      :_class="{
        'first': index == 0,
        'odd': !(index % 2),
        'even': index % 2,
        'last': index == (filteredItems.length - 1)
      }"
    >
    </slot>
  </ul>
</template>

<script>
export default {
  props: ['items', 'classes'],
  data() {
    return {
      filteredItems: this.items.filter(item => item.active)
    };
  }
};
</script>

use _class to class keyword, so Vue.js will let _class as the common property.

Then in your use:

<component-list :classes="'some-class'" :items="category.products">
  <template scope="{ item, _class }">
    <product :product="item" :class="_class"></product>
  </template>
<component-list>

By the scope property, your can still get _class from slot.

After all, use render may be more conciseness. :)


问:
posting multiple parameters in jsonobjectrequest volley
I need to post multiple parameters in postbody in Jsonobject postbody here.I searched all over stack but cudnt find out.please help me

```<code>public void startArchive(String sessionId) {
    JSONObject postBody = null;
    try {
        postBody = new JSONObject("{\"sessionId\": \"" + sessionId + "\"}");
    } catch (JSONException e){
        Log.e(LOG_TAG, "Parsing json body failed");
        e.getStackTrace();
    }

    this.reqQueue.add(new JsonObjectRequest(Request.Method.POST, OpenTokConfig.ARCHIVE_START_ENDPOINT,
            postBody,
            new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.i(LOG_TAG, "archive started");
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            delegate.onWebServiceCoordinatorError(error);
        }
    }));
}
</code>```

my parameters

```<code>{
"sessionId" : "session_id",
"hasAudio" : true,
"hasVideo" : true,
"name" : "archive_name"
"outputMode" : "composed",
</code>```

}

I need to include this as well

```<code>  Content-Type:application/json
</code>```

postman gives this response

答:
You can send JsonObject Request with using Volley library. See below code , Hope this will help you .

```<code>     try {
                JSONObject jsonObject = new JSONObject("{" +
                        "\"sessionId\":\"" + sessionId + "\"," +
                        "\"hasAudio\":\"" + hasAudio + "\"," +
                        "\"hasVideo\":\"" + hasVideo + "\"," +
                        "\"outputMode\":\"" + outputMode + "\"}");

                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(YOUR_URL , jsonObject, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Utils.hideProgressDialog();
                        try{
                            if(response!=null){
                                // do something with the response
                            }
                        }catch (JSONException ex){
                            ex.printStackTrace();
                            Toast.makeText(getActivity(), "Ops, Something wrong. Try again later. ", Toast.LENGTH_SHORT).show();
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                      // Handle Error .
                    }
                })
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("Content-Type", "application/json");
                    return params;
                } ;

                AppController.getInstance().addToRequestQueue(jsonObjectRequest, "json_object");
            } catch (Exception ex) {
                ex.printStackTrace();
                Toast.makeText(getContext(), "Ops, Something wrong. Try again later. ", Toast.LENGTH_SHORT).show();
            }
</code>```

Add The AppController Class As Below :

```<code>public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;

    }
    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

}
</code>```

Add AppContoller in your Manifest.xml file in <application> tag .

```<code> <application
        android:name=".AppController">  ...... </application>
</code>```

Body:
I need to post multiple parameters in postbody in Jsonobject postbody here.I searched all over stack but cudnt find out.please help me

public void startArchive(String sessionId) {
    JSONObject postBody = null;
    try {
        postBody = new JSONObject("{\"sessionId\": \"" + sessionId + "\"}");
    } catch (JSONException e){
        Log.e(LOG_TAG, "Parsing json body failed");
        e.getStackTrace();
    }

    this.reqQueue.add(new JsonObjectRequest(Request.Method.POST, OpenTokConfig.ARCHIVE_START_ENDPOINT,
            postBody,
            new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.i(LOG_TAG, "archive started");
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            delegate.onWebServiceCoordinatorError(error);
        }
    }));
}

my parameters

{
"sessionId" : "session_id",
"hasAudio" : true,
"hasVideo" : true,
"name" : "archive_name"
"outputMode" : "composed",

}

I need to include this as well

  Content-Type:application/json

postman gives this response

Body:
You can send JsonObject Request with using Volley library. See below code , Hope this will help you .

     try {
                JSONObject jsonObject = new JSONObject("{" +
                        "\"sessionId\":\"" + sessionId + "\"," +
                        "\"hasAudio\":\"" + hasAudio + "\"," +
                        "\"hasVideo\":\"" + hasVideo + "\"," +
                        "\"outputMode\":\"" + outputMode + "\"}");

                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(YOUR_URL , jsonObject, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Utils.hideProgressDialog();
                        try{
                            if(response!=null){
                                // do something with the response
                            }
                        }catch (JSONException ex){
                            ex.printStackTrace();
                            Toast.makeText(getActivity(), "Ops, Something wrong. Try again later. ", Toast.LENGTH_SHORT).show();
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                      // Handle Error .
                    }
                })
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("Content-Type", "application/json");
                    return params;
                } ;

                AppController.getInstance().addToRequestQueue(jsonObjectRequest, "json_object");
            } catch (Exception ex) {
                ex.printStackTrace();
                Toast.makeText(getContext(), "Ops, Something wrong. Try again later. ", Toast.LENGTH_SHORT).show();
            }

Add The AppController Class As Below :

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;

    }
    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

}

Add AppContoller in your Manifest.xml file in <application> tag .

 <application
        android:name=".AppController">  ...... </application>


问:
After successful authentication token is not authenticated
I'm new in Symfony 3.2. I need to implement form authentication. User fetches from database. After post to /login onAuthenticationSuccess event fires, but token is still unauthenticate:

What i am doing wrong?

security.yml

```<code>security:

    encoders:
        AppBundle\Entity\User:
            algorithm: bcrypt
            iterations: 10

    role_hierarchy:
        ROLE_ADMIN: ROLE_USER
        ROLE_DEVELOPER: ROLE_ADMIN

    providers:
        in_memory:
            memory: ~
        dvm_db_provider:
            entity:
               class: AppBundle:User

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        anonymous: true
        pattern: ^/
        guard:
            authenticators: [dvm.authenticator]

        form_login:
            login_path: login
            check_path: login
            csrf_token_generator: security.csrf.token_manager

        logout: ~
        provider: dvm_db_provider

access_control:
</code>```

User.php

```<code><?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * User
 *
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 */
class User implements AdvancedUserInterface, \Serializable, EquatableInterface {

    /**
     * @var string
     *
     * @ORM\Column(name="id", type="guid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="surname", type="string", length=255)
     */
    private $surname;
    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;
    /**
     * @var string
     *
     * @ORM\Column(name="patronymic", type="string", length=255, nullable=true)
     */
    private $patronymic;
    /**
     * @var \DateTime
     *
     * @ORM\Column(name="birthday", type="date")
     */
    private $birthday;

    /**
     * @var string
     *
     * @ORM\Column(name="gender", type="string", length=1)
     */
    private $gender;
    /**
     * @var string
     *
     * @ORM\Column(name="avatar", type="string", length=255, unique=true)
     */
    private $avatar;
    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     */
    private $email;
    /**
     * @var string
     */
    private $plainPass;
    /**
     * @var string
     *
     * @ORM\Column(name="pass_hash", type="string", length=255)
     */
    private $passHash;
    /**
     * @var bool
     *
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    /**
     * @var PersistentCollection
     *
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Role")
     * @ORM\JoinTable(name="users_roles", joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *   inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")})
     */
    private $roles;

    /**
     * @return string
     */
    public function getPlainPass() {
        return $this->plainPass;
    }

    /**
     * @param string $plainPass
     */
    public function setPlainPass($plainPass) {
        $this->plainPass = $plainPass;
        $this->passHash = password_hash($this->plainPass, PASSWORD_BCRYPT);
    }

    public function eraseCredentials() {
        $this->setPlainPass('');
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Get surname
     *
     * @return string
     */
    public function getSurname() {
        return $this->surname;
    }

    /**
     * Set surname
     *
     * @param string $surname
     *
     * @return User
     */
    public function setSurname($surname) {
        $this->surname = $surname;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName() {
        return $this->name;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return User
     */
    public function setName($name) {
        $this->name = $name;

        return $this;
    }

    /**
     * Get patronymic
     *
     * @return string
     */
    public function getPatronymic() {
        return $this->patronymic;
    }

    /**
     * Set patronymic
     *
     * @param string $patronymic
     *
     * @return User
     */
    public function setPatronymic($patronymic) {
        $this->patronymic = $patronymic;

        return $this;
    }

    /**
     * Get birthday
     *
     * @return \DateTime
     */
    public function getBirthday() {
        return $this->birthday;
    }

    /**
     * Set birthday
     *
     * @param \DateTime $birthday
     *
     * @return User
     */
    public function setBirthday($birthday) {
        $this->birthday = $birthday;

        return $this;
    }

    /**
     * Get gender
     *
     * @return string
     */
    public function getGender() {
        return $this->gender;
    }

    /**
     * Set gender
     *
     * @param string $gender
     *
     * @return User
     */
    public function setGender($gender) {
        $this->gender = $gender;

        return $this;
    }

    /**
     * Get avatar
     *
     * @return string
     */
    public function getAvatar() {
        return $this->avatar;
    }

    /**
     * Set avatar
     *
     * @param string $avatar
     *
     * @return User
     */
    public function setAvatar($avatar) {
        $this->avatar = $avatar;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail() {
        return $this->email;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return User
     */
    public function setEmail($email) {
        $this->email = $email;

        return $this;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     *
     * @return User
     */
    public function setIsBlocked($isActive) {
        $this->isActive = $isActive;

        return $this;
    }

    public function serialize() {
        return serialize([$this->id, $this->name, $this->surname, $this->patronymic, $this->getPassword(), $this->isActive, $this->email]);
    }

    public function getPassword() {
        return $this->getPassHash();
    }

    /**
     * @return string
     */
    public function getPassHash() {
        return $this->passHash;
    }

    public function getSalt() {
        return null;
    }

    public function unserialize($serialized) {
        list($this->id, $this->name, $this->surname, $this->patronymic, $this->passHash, $this->isActive, $this->email)
                = unserialize($serialized);
    }

    public function isAccountNonExpired() {
        return true;
    }

    public function isAccountNonLocked() {
        return true;
    }

    public function isCredentialsNonExpired() {
        return true;
    }

    public function isEqualTo(UserInterface $user) {
        return $this->getUsername() === $user->getUsername()
                && $this->getPassword() === $user->getPassword();
    }

    public function getUsername() {
        return $this->email;
    }

    /**
     * @return array
     */
    public function getRoles() {
        $rolesArray = [];
        /* @var $role Role */
        foreach ($this->roles->toArray() as $role) $rolesArray[] = $role->getName();
        return $rolesArray;
    }

    /**
     * @param array $roles
     */
    public function setRoles($roles) {
        $this->roles = $roles;
    }

    public function isEnabled() {
        return $this->getIsActive();
    }

    /**
     * Get isActive
     *
     * @return bool
     */
    public function getIsActive() {
        return $this->isActive;
    }

    public function setPassword($pass) {
        $this->setPlainPass($pass);
    }
}
</code>```

Authenticator.php

```<code>class Authenticator extends AbstractGuardAuthenticator {

    public function getCredentials(Request $request) {
        if ($request->getPathInfo() != '/login' || !$request->isMethod('POST')) return null;
        return ['u' => $request->get('_username'), 'p' => $request->get('_password')];
    }

    public function getUser($credentials, UserProviderInterface $userProvider) {
        if (!$credentials['u']) return null;
        return $userProvider->loadUserByUsername($credentials['u']);
    }

    public function checkCredentials($credentials, UserInterface $user) {
        if (!password_verify($credentials['p'], $user->getPassword())) {
            dump([$credentials['p'], $user->getPassword()], password_verify($credentials['p'], $user->getPassword()));
            die;
        }
        if (!$credentials['p']) return null;
        return password_verify($credentials['p'], $user->getPassword());
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
        dump(__FUNCTION__);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) {
        dump(__FUNCTION__);
        $token->setAuthenticated(true);
    }

    public function supportsRememberMe() {
        return false;
    }

    public function start(Request $request, AuthenticationException $authException = null) {
        return new RedirectResponse('/login');
    }

}
</code>```

Security_log

```<code>[2017-05-26 09:38:03] security.DEBUG: Read existing security token from the session. {"key":"_security_main"} []
[2017-05-26 09:38:03] security.DEBUG: User was reloaded from a user provider. {"username":"...@mail.ru","provider":"Symfony\\Bridge\\Doctrine\\Security\\User\\EntityUserProvider"} []
[2017-05-26 09:38:03] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":1} []
[2017-05-26 09:38:03] security.DEBUG: Calling getCredentials() on guard configurator. {"firewall_key":"main","authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.DEBUG: Passing guard token information to the GuardAuthenticationProvider {"firewall_key":"main","authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.INFO: Guard authentication successful! {"token":"[object] (Symfony\\Component\\Security\\Guard\\Token\\PostAuthenticationGuardToken: PostAuthenticationGuardToken(user=\"....@mail.ru\", authenticated=true, roles=\"ROLE_DEVELOPER\"))","authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.DEBUG: Guard authenticator set success response. {"response":"[object] (Symfony\\Component\\HttpFoundation\\RedirectResponse: HTTP/1.0 302 Found\r\nCache-Control: no-cache, private\r\nDate:          Thu, 25 May 2017 23:38:03 GMT\r\nLocation:      /\r\n\r\n<!DOCTYPE html>\n<html>\n    <head>\n        <meta charset=\"UTF-8\" />\n        <meta http-equiv=\"refresh\" content=\"1;url=/\" />\n\n        <title>Redirecting to /</title>\n    </head>\n    <body>\n        Redirecting to <a href=\"/\">/</a>.\n    </body>\n</html>)","authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.DEBUG: Remember me skipped: it is not configured for the firewall. {"authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.DEBUG: The "AppBundle\Security\DvmAuthenticator" authenticator set the response. Any later authenticator will not be called {"authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.DEBUG: Stored the security token in the session. {"key":"_security_main"} []
[2017-05-26 09:38:04] security.DEBUG: Read existing security token from the session. {"key":"_security_main"} []
[2017-05-26 09:38:04] security.DEBUG: User was reloaded from a user provider. {"username":"...@mail.ru","provider":"Symfony\\Bridge\\Doctrine\\Security\\User\\EntityUserProvider"} []
[2017-05-26 09:38:04] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":1} []
[2017-05-26 09:38:04] security.DEBUG: Calling getCredentials() on guard configurator. {"firewall_key":"main","authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:04] security.DEBUG: Stored the security token in the session. {"key":"_security_main"} []
[2017-05-26 09:41:56] security.DEBUG: Read existing security token from the session. {"key":"_security_main"} []
</code>```

答:
I guess this function is making the problem with authentication because returns false in your case.

```<code>public function isEqualTo(UserInterface $user) {
    return $this->getUsername() === $user->getUsername()
            && $this->getPassword() === $user->getPassword();
}
</code>```

Please try to just compare the id.

```<code>public function isEqualTo(UserInterface $user)
{
    return $this->id === $user->getId();
}
</code>```

Body:
I'm new in Symfony 3.2. I need to implement form authentication. User fetches from database. After post to /login onAuthenticationSuccess event fires, but token is still unauthenticate:

What i am doing wrong?

security.yml

security:

    encoders:
        AppBundle\Entity\User:
            algorithm: bcrypt
            iterations: 10

    role_hierarchy:
        ROLE_ADMIN: ROLE_USER
        ROLE_DEVELOPER: ROLE_ADMIN

    providers:
        in_memory:
            memory: ~
        dvm_db_provider:
            entity:
               class: AppBundle:User

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        anonymous: true
        pattern: ^/
        guard:
            authenticators: [dvm.authenticator]

        form_login:
            login_path: login
            check_path: login
            csrf_token_generator: security.csrf.token_manager

        logout: ~
        provider: dvm_db_provider

access_control:

User.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * User
 *
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 */
class User implements AdvancedUserInterface, \Serializable, EquatableInterface {

    /**
     * @var string
     *
     * @ORM\Column(name="id", type="guid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="surname", type="string", length=255)
     */
    private $surname;
    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;
    /**
     * @var string
     *
     * @ORM\Column(name="patronymic", type="string", length=255, nullable=true)
     */
    private $patronymic;
    /**
     * @var \DateTime
     *
     * @ORM\Column(name="birthday", type="date")
     */
    private $birthday;

    /**
     * @var string
     *
     * @ORM\Column(name="gender", type="string", length=1)
     */
    private $gender;
    /**
     * @var string
     *
     * @ORM\Column(name="avatar", type="string", length=255, unique=true)
     */
    private $avatar;
    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     */
    private $email;
    /**
     * @var string
     */
    private $plainPass;
    /**
     * @var string
     *
     * @ORM\Column(name="pass_hash", type="string", length=255)
     */
    private $passHash;
    /**
     * @var bool
     *
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    /**
     * @var PersistentCollection
     *
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Role")
     * @ORM\JoinTable(name="users_roles", joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *   inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")})
     */
    private $roles;

    /**
     * @return string
     */
    public function getPlainPass() {
        return $this->plainPass;
    }

    /**
     * @param string $plainPass
     */
    public function setPlainPass($plainPass) {
        $this->plainPass = $plainPass;
        $this->passHash = password_hash($this->plainPass, PASSWORD_BCRYPT);
    }

    public function eraseCredentials() {
        $this->setPlainPass('');
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Get surname
     *
     * @return string
     */
    public function getSurname() {
        return $this->surname;
    }

    /**
     * Set surname
     *
     * @param string $surname
     *
     * @return User
     */
    public function setSurname($surname) {
        $this->surname = $surname;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName() {
        return $this->name;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return User
     */
    public function setName($name) {
        $this->name = $name;

        return $this;
    }

    /**
     * Get patronymic
     *
     * @return string
     */
    public function getPatronymic() {
        return $this->patronymic;
    }

    /**
     * Set patronymic
     *
     * @param string $patronymic
     *
     * @return User
     */
    public function setPatronymic($patronymic) {
        $this->patronymic = $patronymic;

        return $this;
    }

    /**
     * Get birthday
     *
     * @return \DateTime
     */
    public function getBirthday() {
        return $this->birthday;
    }

    /**
     * Set birthday
     *
     * @param \DateTime $birthday
     *
     * @return User
     */
    public function setBirthday($birthday) {
        $this->birthday = $birthday;

        return $this;
    }

    /**
     * Get gender
     *
     * @return string
     */
    public function getGender() {
        return $this->gender;
    }

    /**
     * Set gender
     *
     * @param string $gender
     *
     * @return User
     */
    public function setGender($gender) {
        $this->gender = $gender;

        return $this;
    }

    /**
     * Get avatar
     *
     * @return string
     */
    public function getAvatar() {
        return $this->avatar;
    }

    /**
     * Set avatar
     *
     * @param string $avatar
     *
     * @return User
     */
    public function setAvatar($avatar) {
        $this->avatar = $avatar;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail() {
        return $this->email;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return User
     */
    public function setEmail($email) {
        $this->email = $email;

        return $this;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     *
     * @return User
     */
    public function setIsBlocked($isActive) {
        $this->isActive = $isActive;

        return $this;
    }

    public function serialize() {
        return serialize([$this->id, $this->name, $this->surname, $this->patronymic, $this->getPassword(), $this->isActive, $this->email]);
    }

    public function getPassword() {
        return $this->getPassHash();
    }

    /**
     * @return string
     */
    public function getPassHash() {
        return $this->passHash;
    }

    public function getSalt() {
        return null;
    }

    public function unserialize($serialized) {
        list($this->id, $this->name, $this->surname, $this->patronymic, $this->passHash, $this->isActive, $this->email)
                = unserialize($serialized);
    }

    public function isAccountNonExpired() {
        return true;
    }

    public function isAccountNonLocked() {
        return true;
    }

    public function isCredentialsNonExpired() {
        return true;
    }

    public function isEqualTo(UserInterface $user) {
        return $this->getUsername() === $user->getUsername()
                && $this->getPassword() === $user->getPassword();
    }

    public function getUsername() {
        return $this->email;
    }

    /**
     * @return array
     */
    public function getRoles() {
        $rolesArray = [];
        /* @var $role Role */
        foreach ($this->roles->toArray() as $role) $rolesArray[] = $role->getName();
        return $rolesArray;
    }

    /**
     * @param array $roles
     */
    public function setRoles($roles) {
        $this->roles = $roles;
    }

    public function isEnabled() {
        return $this->getIsActive();
    }

    /**
     * Get isActive
     *
     * @return bool
     */
    public function getIsActive() {
        return $this->isActive;
    }

    public function setPassword($pass) {
        $this->setPlainPass($pass);
    }
}

Authenticator.php

class Authenticator extends AbstractGuardAuthenticator {

    public function getCredentials(Request $request) {
        if ($request->getPathInfo() != '/login' || !$request->isMethod('POST')) return null;
        return ['u' => $request->get('_username'), 'p' => $request->get('_password')];
    }

    public function getUser($credentials, UserProviderInterface $userProvider) {
        if (!$credentials['u']) return null;
        return $userProvider->loadUserByUsername($credentials['u']);
    }

    public function checkCredentials($credentials, UserInterface $user) {
        if (!password_verify($credentials['p'], $user->getPassword())) {
            dump([$credentials['p'], $user->getPassword()], password_verify($credentials['p'], $user->getPassword()));
            die;
        }
        if (!$credentials['p']) return null;
        return password_verify($credentials['p'], $user->getPassword());
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
        dump(__FUNCTION__);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) {
        dump(__FUNCTION__);
        $token->setAuthenticated(true);
    }

    public function supportsRememberMe() {
        return false;
    }

    public function start(Request $request, AuthenticationException $authException = null) {
        return new RedirectResponse('/login');
    }

}

Security_log

[2017-05-26 09:38:03] security.DEBUG: Read existing security token from the session. {"key":"_security_main"} []
[2017-05-26 09:38:03] security.DEBUG: User was reloaded from a user provider. {"username":"...@mail.ru","provider":"Symfony\\Bridge\\Doctrine\\Security\\User\\EntityUserProvider"} []
[2017-05-26 09:38:03] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":1} []
[2017-05-26 09:38:03] security.DEBUG: Calling getCredentials() on guard configurator. {"firewall_key":"main","authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.DEBUG: Passing guard token information to the GuardAuthenticationProvider {"firewall_key":"main","authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.INFO: Guard authentication successful! {"token":"[object] (Symfony\\Component\\Security\\Guard\\Token\\PostAuthenticationGuardToken: PostAuthenticationGuardToken(user=\"....@mail.ru\", authenticated=true, roles=\"ROLE_DEVELOPER\"))","authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.DEBUG: Guard authenticator set success response. {"response":"[object] (Symfony\\Component\\HttpFoundation\\RedirectResponse: HTTP/1.0 302 Found\r\nCache-Control: no-cache, private\r\nDate:          Thu, 25 May 2017 23:38:03 GMT\r\nLocation:      /\r\n\r\n<!DOCTYPE html>\n\n    \n        <meta charset=\"UTF-8\" />\n        <meta http-equiv=\"refresh\" content=\"1;url=/\" />\n\n        <title>Redirecting to /</title>\n    \n    \n        Redirecting to /.\n    \n)","authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.DEBUG: Remember me skipped: it is not configured for the firewall. {"authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.DEBUG: The "AppBundle\Security\DvmAuthenticator" authenticator set the response. Any later authenticator will not be called {"authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:03] security.DEBUG: Stored the security token in the session. {"key":"_security_main"} []
[2017-05-26 09:38:04] security.DEBUG: Read existing security token from the session. {"key":"_security_main"} []
[2017-05-26 09:38:04] security.DEBUG: User was reloaded from a user provider. {"username":"...@mail.ru","provider":"Symfony\\Bridge\\Doctrine\\Security\\User\\EntityUserProvider"} []
[2017-05-26 09:38:04] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":1} []
[2017-05-26 09:38:04] security.DEBUG: Calling getCredentials() on guard configurator. {"firewall_key":"main","authenticator":"AppBundle\\Security\\DvmAuthenticator"} []
[2017-05-26 09:38:04] security.DEBUG: Stored the security token in the session. {"key":"_security_main"} []
[2017-05-26 09:41:56] security.DEBUG: Read existing security token from the session. {"key":"_security_main"} []

Body:
I guess this function is making the problem with authentication because returns false in your case.

public function isEqualTo(UserInterface $user) {
    return $this->getUsername() === $user->getUsername()
            && $this->getPassword() === $user->getPassword();
}

Please try to just compare the id.

public function isEqualTo(UserInterface $user)
{
    return $this->id === $user->getId();
}