问:
@ManyToOne(fetch = FetchType.LAZY) doesn't work on non-primary key referenced column
I'm having some troubles to make a @ManyToOne association to be loaded lazilly. I'm using the fetch=LAZY but it doesn't work when join isn't made by the primary key column.

I know this question was already asked but I think it wasn't properly answered, so I provide detailed information to clarify the issue.

This is my model:

```<code>DummyB -> DummyA
</code>```

These are the tables:

```<code>create table dummyA  (
  id number(18,0), --pk
  name varchar2(20) -- unique field
);

create table dummyB  (
  id number(18,0),
  dummya_id number(18,0),
  dummya_name varchar2(20)
);
</code>```

And these are the entities:

```<code>@Entity
public class DummyA implements Serializable {

    private Long id;
    private String name;

    @Id
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

@Entity
public class DummyB implements Serializable {

    private Long id;
    private DummyA dummyA;

    @Id
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    /* Case 1: mapping DummyB -> DummyA by DummyA NON primary key (field name) */
    // @ManyToOne(fetch = FetchType.LAZY)
    // @JoinColumn(name = "dummya_id")
    // public DummyA getDummyA() {
    // return dummyA;
    // }

    /* Case 2: mapping DummyB -> DummyA by DummyA primary key */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dummya_name", referencedColumnName = "name")
    @LazyToOne(LazyToOneOption.PROXY)
    public DummyA getDummyA() {
        return dummyA;
    }

    public void setDummyA(DummyA dummyA) {
        this.dummyA = dummyA;
    }

}
</code>```

Note getDummyA method in entity DummyB is duplicate to try out two cases to join the entities.

Case 1: mapping DummyB -> DummyA by DummyA primary key

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "dummya_id")

This works fine, just one query is executed to retrieve DummyB objects.

Case 2: mapping DummyB -> DummyA by DummyA NON primary key (field name)

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "dummya_name", referencedColumnName="name")

Same dummyB select is execute, but right after, a dummyA select is executed filtering by name=? to fetch the related A object.

I'm using a really simple jUnit to execute filtering:

```<code>public class DummyTest {

    @Autowired
    HibernateTransactionManager transactionManager;

    @Test
    @Transactional
    public void testFindDummyB() throws DAOException {
        Long idDummyB = 2L;

        Session session = getCurrentHibernateSession();

        List lst = session.createCriteria(DummyB.class)
                .add(Restrictions.eq("id", idDummyB)).list();

        assertTrue(lst.size() > 0);
    }

    private Session getCurrentHibernateSession() {
        return this.transactionManager.getSessionFactory().getCurrentSession();
    }

}
</code>```

My libraries:

org.hibernate:hibernate-core:jar:4.2.17.Final:compile

org.hibernate.common:hibernate-commons-annotations:jar:4.0.2.Final:compile

org.hibernate.javax.persistence:hibernate-jpa-2.0-api:jar:1.0.1.Final:compile

org.hibernate:hibernate-validator:jar:4.3.2.Final:provided

Other things I've already tried:

Adding hiberante's @LazyToOne to getDummyA() method doesn't have any effect.

```<code>@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "dummya_name", referencedColumnName = "name")
@LazyToOne(LazyToOneOption.PROXY)
</code>```

Creating a foreign key from DummyB table to dummyA (and an unique constraint in dummya.name field) has no effect.

Adding @Column(unique = true) on DummyA getName() method didn't make it.

Set optional=true or false as suggested  here has no effect either.

Trying to force the lazy loading using the setFetchMode in the criteria didn't work, DummyA select keeps executing.

```<code>List lst = session.createCriteria(DummyB.class)
.add(Restrictions.eq("id", idDummyB)).
setFetchMode("dummyA", FetchMode.SELECT)
.list();
</code>```

I can't find in Hibernate's docs a point where it refers to this behaviour, so I wonder if there's anything is wrong in my annotations or I came upon a Hibernate bug.

Can anyone tell?

UPDATED by md-dev request:
To set it more clear:

Is this the expected behaviour or is a bug? if this the expected behaviour, where is it documented?

Thank you.

答:
In case someone still has problems with this
We got it to work the following way:

```<code>@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "dummya_name", referencedColumnName = "name", insertable = false, updatable = false),
@LazyToOne(LazyToOneOption.NO_PROXY)
public DummyA getDummyA() {
    if (fieldHandler != null) {
        return (DummyA) fieldHandler.readObject(this, "dummyA", dummyA);
    }
    return dummyA;
}

public void setDummyA(DummyA dummyA) {
    if (fieldHandler != null) {
        this.dummyA = (DummyA ) fieldHandler.writeObject(this, "dummyA", this.dummyA, dummyA);
        return;
    }
    this.dummyA= dummyA;
}

@Override
public void setFieldHandler(FieldHandler fieldHandler) {
    this.fieldHandler = fieldHandler;
}

@Override
public FieldHandler getFieldHandler() {
    return fieldHandler;
}
</code>```

It was explained well in Hibernate lazy loading for reverse one to one workaround - how does this work?

As @alina-petukhova mentioned the DummyB class must implement the FieldHandled interface.

In Spring Boot 2 the FieldHandled interface was replaced by PersistentAttributeInterceptable and the FieldHandler was replaced by PersistentAttributeInterceptor

see https://docs.jboss.org/hibernate/orm/5.3/javadocs/org/hibernate/engine/spi/PersistentAttributeInterceptable.html

Body:
I'm having some troubles to make a @ManyToOne association to be loaded lazilly. I'm using the fetch=LAZY but it doesn't work when join isn't made by the primary key column.

I know this question was already asked but I think it wasn't properly answered, so I provide detailed information to clarify the issue.

This is my model:

DummyB -> DummyA

These are the tables:

create table dummyA  (
  id number(18,0), --pk
  name varchar2(20) -- unique field
);

create table dummyB  (
  id number(18,0),
  dummya_id number(18,0),
  dummya_name varchar2(20)
);

And these are the entities:

@Entity
public class DummyA implements Serializable {

    private Long id;
    private String name;

    @Id
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

@Entity
public class DummyB implements Serializable {

    private Long id;
    private DummyA dummyA;

    @Id
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    /* Case 1: mapping DummyB -> DummyA by DummyA NON primary key (field name) */
    // @ManyToOne(fetch = FetchType.LAZY)
    // @JoinColumn(name = "dummya_id")
    // public DummyA getDummyA() {
    // return dummyA;
    // }

    /* Case 2: mapping DummyB -> DummyA by DummyA primary key */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dummya_name", referencedColumnName = "name")
    @LazyToOne(LazyToOneOption.PROXY)
    public DummyA getDummyA() {
        return dummyA;
    }

    public void setDummyA(DummyA dummyA) {
        this.dummyA = dummyA;
    }

}

Note getDummyA method in entity DummyB is duplicate to try out two cases to join the entities.

Case 1: mapping DummyB -> DummyA by DummyA primary key

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "dummya_id")

This works fine, just one query is executed to retrieve DummyB objects.

Case 2: mapping DummyB -> DummyA by DummyA NON primary key (field name)

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "dummya_name", referencedColumnName="name")

Same dummyB select is execute, but right after, a dummyA select is executed filtering by name=? to fetch the related A object.

I'm using a really simple jUnit to execute filtering:

public class DummyTest {

    @Autowired
    HibernateTransactionManager transactionManager;

    @Test
    @Transactional
    public void testFindDummyB() throws DAOException {
        Long idDummyB = 2L;

        Session session = getCurrentHibernateSession();

        List lst = session.createCriteria(DummyB.class)
                .add(Restrictions.eq("id", idDummyB)).list();

        assertTrue(lst.size() > 0);
    }

    private Session getCurrentHibernateSession() {
        return this.transactionManager.getSessionFactory().getCurrentSession();
    }

}

My libraries:

org.hibernate:hibernate-core:jar:4.2.17.Final:compile

org.hibernate.common:hibernate-commons-annotations:jar:4.0.2.Final:compile

org.hibernate.javax.persistence:hibernate-jpa-2.0-api:jar:1.0.1.Final:compile

org.hibernate:hibernate-validator:jar:4.3.2.Final:provided

Other things I've already tried:

Adding hiberante's @LazyToOne to getDummyA() method doesn't have any effect.

@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "dummya_name", referencedColumnName = "name")
@LazyToOne(LazyToOneOption.PROXY)

Creating a foreign key from DummyB table to dummyA (and an unique constraint in dummya.name field) has no effect.

Adding @Column(unique = true) on DummyA getName() method didn't make it.

Set optional=true or false as suggested  here has no effect either.

Trying to force the lazy loading using the setFetchMode in the criteria didn't work, DummyA select keeps executing.

List lst = session.createCriteria(DummyB.class)
.add(Restrictions.eq("id", idDummyB)).
setFetchMode("dummyA", FetchMode.SELECT)
.list();

I can't find in Hibernate's docs a point where it refers to this behaviour, so I wonder if there's anything is wrong in my annotations or I came upon a Hibernate bug.

Can anyone tell?

UPDATED by md-dev request:
To set it more clear:

Is this the expected behaviour or is a bug? if this the expected behaviour, where is it documented?

Thank you.

Body:
In case someone still has problems with this
We got it to work the following way:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "dummya_name", referencedColumnName = "name", insertable = false, updatable = false),
@LazyToOne(LazyToOneOption.NO_PROXY)
public DummyA getDummyA() {
    if (fieldHandler != null) {
        return (DummyA) fieldHandler.readObject(this, "dummyA", dummyA);
    }
    return dummyA;
}

public void setDummyA(DummyA dummyA) {
    if (fieldHandler != null) {
        this.dummyA = (DummyA ) fieldHandler.writeObject(this, "dummyA", this.dummyA, dummyA);
        return;
    }
    this.dummyA= dummyA;
}

@Override
public void setFieldHandler(FieldHandler fieldHandler) {
    this.fieldHandler = fieldHandler;
}

@Override
public FieldHandler getFieldHandler() {
    return fieldHandler;
}

It was explained well in Hibernate lazy loading for reverse one to one workaround - how does this work?

As @alina-petukhova mentioned the DummyB class must implement the FieldHandled interface.

In Spring Boot 2 the FieldHandled interface was replaced by PersistentAttributeInterceptable and the FieldHandler was replaced by PersistentAttributeInterceptor

see https://docs.jboss.org/hibernate/orm/5.3/javadocs/org/hibernate/engine/spi/PersistentAttributeInterceptable.html


来源: stackexchange

问:
How to display data from database When Selecting Multiple option from Dropdown using PHP Mysqli
Script Page is working nicely. When I select the multiple options in next dashboard page, no records display. Please fix this problem. I think the selected value cannot recognize in dashboard page

Script.php

```<code><?php include("connection.php") ?>
<form id="script" name="script" action="dashboard.php" method="post">
    <strong>Choose Script Name : </strong><select name="script[]" id="select3" multiple=multiple style="margin: 20px;width:300px;">
        <?php
        $result = $conn->query("select script_name from script_details ORDER BY script_name");
        while ($row = $result->fetch_assoc()) {
            unset($script_name);
            $script_name = $row['script_name'];
            echo '<option value="' . $id . '">' . $script_name . '</option>'; // Generated From database
        }
        ?>
    </select>
    <input type="submit" name="submit" id="button" value="View Dashboard" />
</form>
</code>```

Dashboard.php

```<code><table border="1">
    <tr align="center">
        <th>Number </th>      <th>Script Name</th>    <th> Date</th>
    </tr>
    <?php
    include("connection.php");
    $select = $_POST['script'];
    $selects = "SELECT * FROM script_details where script_name='$select'";
    $result = $conn->query($selects);
    echo "<table>";
    while ($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["id"] . "</td><td>" . $row["script_name"] . "</td></tr>" . "</td><td>" . $row["date"] . "</td></tr>";
    }
    echo "</table>";
[This is script page Image. Selecting option from script_details database. Field name : script_name.][1]?>
</code>```

This is Dashboard page. when selecting script2, script3 option. Doesnot show record for selected items.

答:
I would approach it in the following way:

```<code>$scriptsArr = $_POST['script'];
$scriptsStr = implode(',', $scriptsArr);

$selects = "SELECT * FROM script_details where script_name IN ($scriptsStr)";
</code>```

I've split it to few variables so you can understand the process.
Hope I could help!

I hope your understand is not safe at all, I would suggest you will read a bit more about prepared statements:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

ContentLicense: CC BY-SA 3.0

Body:
Script Page is working nicely. When I select the multiple options in next dashboard page, no records display. Please fix this problem. I think the selected value cannot recognize in dashboard page

Script.php

<?php include("connection.php") ?>
<form id="script" name="script" action="dashboard.php" method="post">
    Choose Script Name : <select name="script[]" id="select3" multiple=multiple style="margin: 20px;width:300px;">
        <?php
        $result = $conn->query("select script_name from script_details ORDER BY script_name");
        while ($row = $result->fetch_assoc()) {
            unset($script_name);
            $script_name = $row['script_name'];
            echo '<option value="' . $id . '">' . $script_name . '</option>'; // Generated From database
        }
        ?>
    </select>
    <input type="submit" name="submit" id="button" value="View Dashboard" />
</form>

Dashboard.php

        Number 	      Script Name	     Date

    <?php
    include("connection.php");
    $select = $_POST['script'];
    $selects = "SELECT * FROM script_details where script_name='$select'";
    $result = $conn->query($selects);
    echo "
";
    while ($row = $result->fetch_assoc()) {
        echo "
" . $row["id"] . "	" . $row["script_name"] . "
" . "	" . $row["date"] . "
";
    }
    echo "
";
[This is script page Image. Selecting option from script_details database. Field name : script_name.][1]?>

This is Dashboard page. when selecting script2, script3 option. Doesnot show record for selected items.

Body:
I would approach it in the following way:

$scriptsArr = $_POST['script'];
$scriptsStr = implode(',', $scriptsArr);

$selects = "SELECT * FROM script_details where script_name IN ($scriptsStr)";

I've split it to few variables so you can understand the process.
Hope I could help!

I hope your understand is not safe at all, I would suggest you will read a bit more about prepared statements:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php


问:
How do I run a Gradle project in the IntelliJ
I cloned a repo from Github and I would like to run it in the IntellIJ. The build tool used is Gradle and I have zero experience so far. The build.gradle file is provided below,

```<code>apply plugin: 'java'
//apply plugin: 'eclipse-wtp'
apply plugin: 'maven'
apply plugin: 'spring-boot'

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8

buildscript {
    ext {
        springBootVersion = '1.3.0.RELEASE'
    }
    repositories {
        mavenCentral()
        maven { url "http://repo.spring.io/libs-release" }
        maven { url "http://repo.spring.io/milestone" }
        maven { url "http://repo.spring.io/snapshot" }
    }

    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

repositories {
    mavenCentral()
    maven { url "http://repo.spring.io/libs-release" }
    maven { url "http://repo.spring.io/milestone" }
    maven { url "http://repo.spring.io/snapshot" }
}

ext {
    commonsPoolVersion = '2.4.2'
    nettyVersion = '4.0.33.Final'
    reactorVersion = '2.0.7.RELEASE'
    redisVersion = '0.6'
    springSessionVersion = '1.1.0.M1'
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-security")
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-websocket")
    compile("org.springframework.boot:spring-boot-starter-actuator")
    compile("org.springframework.boot:spring-boot-starter-redis")

    compile("org.springframework.security:spring-security-messaging")
    compile("org.springframework.session:spring-session:$springSessionVersion")
    compile("org.apache.commons:commons-pool2:$commonsPoolVersion")
    compile("com.github.kstyrc:embedded-redis:$redisVersion")
    compile("io.projectreactor:reactor-core:${reactorVersion}")
    compile("io.projectreactor:reactor-net:${reactorVersion}") {
        exclude group: "io.netty", module: "netty-all"
    }
    compile("io.netty:netty-all:$nettyVersion")

    testCompile("org.springframework.boot:spring-boot-starter-test")
}

eclipse {
    classpath {
         containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
         containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
    }
}
</code>```

I have installed the gradle using brew and the installation location is /usr/local/opt/gradle. In the IntelliJ, I have set the GRADLE_HOME as /usr/local/opt/gradle/libexec.

When I run the project with command gradle bootRun --stacktrace, I get the following error message,

```<code>FAILURE: Build failed with an exception.

* Where:
Build file '/Users/Mockyenl/IdeaProjects/spring-websocket-chat/build.gradle' line: 4

* What went wrong:
A problem occurred evaluating root project 'spring-websocket-chat'.
> Failed to apply plugin [class 'io.spring.gradle.dependencymanagement.DependencyManagementPlugin']
   > Could not create task of type 'DependencyManagementReportTask'.

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project 'spring-websocket-chat'.
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:187)
        at org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:77)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:192)
        at org.gradle.configuration.BuildOperationScriptPlugin$1.run(BuildOperationScriptPlugin.java:61)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.configuration.BuildOperationScriptPlugin.apply(BuildOperationScriptPlugin.java:58)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:39)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
        at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:63)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.access$100(LifecycleProjectEvaluator.java:33)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$ConfigureProject.run(LifecycleProjectEvaluator.java:103)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:49)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:654)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:132)
        at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
        at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:60)
        at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:38)
        at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuild.run(DefaultGradleLauncher.java:195)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:157)
        at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:44)
        at org.gradle.initialization.DefaultGradleLauncher$1.run(DefaultGradleLauncher.java:122)
        at org.gradle.internal.work.DefaultWorkerLeaseService$2.execute(DefaultWorkerLeaseService.java:124)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:116)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:99)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:66)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
        at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:44)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:51)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:55)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:42)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:50)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin [class 'io.spring.gradle.dependencymanagement.DependencyManagementPlugin']
        at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:150)
        at org.gradle.api.internal.plugins.DefaultPluginManager.addImperativePlugin(DefaultPluginManager.java:80)
        at org.gradle.api.internal.plugins.DefaultPluginManager.addImperativePlugin(DefaultPluginManager.java:86)
        at org.gradle.api.internal.plugins.DefaultPluginContainer.apply(DefaultPluginContainer.java:60)
        at org.springframework.boot.gradle.dependencymanagement.DependencyManagementPluginFeatures.apply(DependencyManagementPluginFeatures.java:44)
        at org.springframework.boot.gradle.SpringBootPlugin.apply(SpringBootPlugin.java:47)
        at org.springframework.boot.gradle.SpringBootPlugin.apply(SpringBootPlugin.java:38)
        at org.gradle.api.internal.plugins.ImperativeOnlyPluginTarget.applyImperative(ImperativeOnlyPluginTarget.java:41)
        at org.gradle.api.internal.plugins.RuleBasedPluginTarget.applyImperative(RuleBasedPluginTarget.java:49)
        at org.gradle.api.internal.plugins.DefaultPluginManager.addPlugin(DefaultPluginManager.java:165)
        at org.gradle.api.internal.plugins.DefaultPluginManager.access$200(DefaultPluginManager.java:47)
        at org.gradle.api.internal.plugins.DefaultPluginManager$AddPluginBuildOperation.run(DefaultPluginManager.java:252)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:144)
        at org.gradle.api.internal.plugins.DefaultPluginManager.apply(DefaultPluginManager.java:125)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyType(DefaultObjectConfigurationAction.java:113)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:36)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:80)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:136)
        at org.gradle.api.internal.project.AbstractPluginAware.apply(AbstractPluginAware.java:46)
        at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.java:34)
        at org.gradle.api.Script$apply$0.callCurrent(Unknown Source)
        at build_4b35wimvl540y84qjn2xnlyq9.run(/Users/Chaklader/IdeaProjects/spring-websocket-chat/build.gradle:4)
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
        ... 88 more
Caused by: org.gradle.api.tasks.TaskInstantiationException: Could not create task of type 'DependencyManagementReportTask'.
        at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:123)
        at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:118)
        at org.gradle.util.GUtil.uncheckedCall(GUtil.java:402)
        at org.gradle.api.internal.AbstractTask.injectIntoNewInstance(AbstractTask.java:174)
        at org.gradle.api.internal.project.taskfactory.TaskFactory.create(TaskFactory.java:118)
        at org.gradle.api.internal.project.taskfactory.TaskFactory.create(TaskFactory.java:38)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory.create(AnnotationProcessingTaskFactory.java:51)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory.create(AnnotationProcessingTaskFactory.java:32)
        at org.gradle.api.internal.project.taskfactory.DependencyAutoWireTaskFactory.create(DependencyAutoWireTaskFactory.java:44)
        at org.gradle.api.internal.project.taskfactory.DependencyAutoWireTaskFactory.create(DependencyAutoWireTaskFactory.java:27)
        at org.gradle.api.internal.tasks.DefaultTaskContainer$TaskInstantiator.create(DefaultTaskContainer.java:301)
        at org.gradle.api.internal.tasks.DefaultTaskContainer$TaskInstantiator.create(DefaultTaskContainer.java:289)
        at org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:116)
        at org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:147)
        at org.gradle.api.internal.tasks.DefaultTaskContainer_Decorated.create(Unknown Source)
        at org.gradle.api.internal.tasks.DefaultTaskContainer_Decorated$create.call(Unknown Source)
        at io.spring.gradle.dependencymanagement.DependencyManagementPlugin.apply(DependencyManagementPlugin.groovy:57)
        at io.spring.gradle.dependencymanagement.DependencyManagementPlugin.apply(DependencyManagementPlugin.groovy)
        at org.gradle.api.internal.plugins.ImperativeOnlyPluginTarget.applyImperative(ImperativeOnlyPluginTarget.java:41)
        at org.gradle.api.internal.plugins.RuleBasedPluginTarget.applyImperative(RuleBasedPluginTarget.java:49)
        at org.gradle.api.internal.plugins.DefaultPluginManager.addPlugin(DefaultPluginManager.java:165)
        at org.gradle.api.internal.plugins.DefaultPluginManager.access$200(DefaultPluginManager.java:47)
        at org.gradle.api.internal.plugins.DefaultPluginManager$AddPluginBuildOperation.run(DefaultPluginManager.java:252)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:144)
        ... 114 more
Caused by: org.gradle.internal.service.UnknownServiceException: No service of type StyledTextOutputFactory available in ProjectScopeServices.
        at org.gradle.internal.service.DefaultServiceRegistry.getServiceProvider(DefaultServiceRegistry.java:352)
        at org.gradle.internal.service.DefaultServiceRegistry.doGet(DefaultServiceRegistry.java:341)
        at org.gradle.internal.service.DefaultServiceRegistry.get(DefaultServiceRegistry.java:329)
        at org.gradle.api.internal.DependencyInjectingInstantiator.convertParameters(DependencyInjectingInstantiator.java:85)
        at org.gradle.api.internal.DependencyInjectingInstantiator.newInstance(DependencyInjectingInstantiator.java:54)
        at org.gradle.api.internal.ClassGeneratorBackedInstantiator.newInstance(ClassGeneratorBackedInstantiator.java:36)
        at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:121)
        ... 141 more

BUILD FAILED in 0s
</code>```

The gradle info is here,

When I try to synchronize the project, I get the message,

How can I just run the project properly ?

答:
That project you are trying to build builds fine on Travis CI where by default Gradle 2.0 is available if not something else is configured which is not the case for that project.

I think the build is simply not compatible with Gradle 4.0 as in major versions Gradle tends to break backwards compatibility to clean up stuff.

To make the project build for you, you shoudl try using Gradle 2.0.

Additionally you should post an improvement request to that project that they should make use of the Gradle Wrapper.

In my opinion each and every Gradle project, even the tiniest, should use the Gradle Wrapper. Besides that someone who wants to build the project does not have to have Gradle installed as the wrapper cares about downloading and Gradle but only a compatible Java version needs to be installed, in the wrapper you define the Gradle version for which the build is designed and runs fine with to prevent the exact same problem you are having right now.

Body:
I cloned a repo from Github and I would like to run it in the IntellIJ. The build tool used is Gradle and I have zero experience so far. The build.gradle file is provided below,

apply plugin: 'java'
//apply plugin: 'eclipse-wtp'
apply plugin: 'maven'
apply plugin: 'spring-boot'

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8

buildscript {
    ext {
        springBootVersion = '1.3.0.RELEASE'
    }
    repositories {
        mavenCentral()
        maven { url "http://repo.spring.io/libs-release" }
        maven { url "http://repo.spring.io/milestone" }
        maven { url "http://repo.spring.io/snapshot" }
    }

    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

repositories {
    mavenCentral()
    maven { url "http://repo.spring.io/libs-release" }
    maven { url "http://repo.spring.io/milestone" }
    maven { url "http://repo.spring.io/snapshot" }
}

ext {
    commonsPoolVersion = '2.4.2'
    nettyVersion = '4.0.33.Final'
    reactorVersion = '2.0.7.RELEASE'
    redisVersion = '0.6'
    springSessionVersion = '1.1.0.M1'
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-security")
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-websocket")
    compile("org.springframework.boot:spring-boot-starter-actuator")
    compile("org.springframework.boot:spring-boot-starter-redis")

    compile("org.springframework.security:spring-security-messaging")
    compile("org.springframework.session:spring-session:$springSessionVersion")
    compile("org.apache.commons:commons-pool2:$commonsPoolVersion")
    compile("com.github.kstyrc:embedded-redis:$redisVersion")
    compile("io.projectreactor:reactor-core:${reactorVersion}")
    compile("io.projectreactor:reactor-net:${reactorVersion}") {
        exclude group: "io.netty", module: "netty-all"
    }
    compile("io.netty:netty-all:$nettyVersion")

    testCompile("org.springframework.boot:spring-boot-starter-test")
}

eclipse {
    classpath {
         containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
         containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
    }
}

I have installed the gradle using brew and the installation location is /usr/local/opt/gradle. In the IntelliJ, I have set the GRADLE_HOME as /usr/local/opt/gradle/libexec.

When I run the project with command gradle bootRun --stacktrace, I get the following error message,

FAILURE: Build failed with an exception.

* Where:
Build file '/Users/Mockyenl/IdeaProjects/spring-websocket-chat/build.gradle' line: 4

* What went wrong:
A problem occurred evaluating root project 'spring-websocket-chat'.
> Failed to apply plugin [class 'io.spring.gradle.dependencymanagement.DependencyManagementPlugin']
   > Could not create task of type 'DependencyManagementReportTask'.

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project 'spring-websocket-chat'.
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:187)
        at org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:77)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:192)
        at org.gradle.configuration.BuildOperationScriptPlugin$1.run(BuildOperationScriptPlugin.java:61)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.configuration.BuildOperationScriptPlugin.apply(BuildOperationScriptPlugin.java:58)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:39)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
        at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:63)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.access$100(LifecycleProjectEvaluator.java:33)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$ConfigureProject.run(LifecycleProjectEvaluator.java:103)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:49)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:654)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:132)
        at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
        at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:60)
        at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:38)
        at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuild.run(DefaultGradleLauncher.java:195)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:157)
        at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:44)
        at org.gradle.initialization.DefaultGradleLauncher$1.run(DefaultGradleLauncher.java:122)
        at org.gradle.internal.work.DefaultWorkerLeaseService$2.execute(DefaultWorkerLeaseService.java:124)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:116)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:99)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:66)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
        at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:44)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:51)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:55)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:42)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:50)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin [class 'io.spring.gradle.dependencymanagement.DependencyManagementPlugin']
        at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:150)
        at org.gradle.api.internal.plugins.DefaultPluginManager.addImperativePlugin(DefaultPluginManager.java:80)
        at org.gradle.api.internal.plugins.DefaultPluginManager.addImperativePlugin(DefaultPluginManager.java:86)
        at org.gradle.api.internal.plugins.DefaultPluginContainer.apply(DefaultPluginContainer.java:60)
        at org.springframework.boot.gradle.dependencymanagement.DependencyManagementPluginFeatures.apply(DependencyManagementPluginFeatures.java:44)
        at org.springframework.boot.gradle.SpringBootPlugin.apply(SpringBootPlugin.java:47)
        at org.springframework.boot.gradle.SpringBootPlugin.apply(SpringBootPlugin.java:38)
        at org.gradle.api.internal.plugins.ImperativeOnlyPluginTarget.applyImperative(ImperativeOnlyPluginTarget.java:41)
        at org.gradle.api.internal.plugins.RuleBasedPluginTarget.applyImperative(RuleBasedPluginTarget.java:49)
        at org.gradle.api.internal.plugins.DefaultPluginManager.addPlugin(DefaultPluginManager.java:165)
        at org.gradle.api.internal.plugins.DefaultPluginManager.access$200(DefaultPluginManager.java:47)
        at org.gradle.api.internal.plugins.DefaultPluginManager$AddPluginBuildOperation.run(DefaultPluginManager.java:252)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:144)
        at org.gradle.api.internal.plugins.DefaultPluginManager.apply(DefaultPluginManager.java:125)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyType(DefaultObjectConfigurationAction.java:113)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:36)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:80)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:136)
        at org.gradle.api.internal.project.AbstractPluginAware.apply(AbstractPluginAware.java:46)
        at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.java:34)
        at org.gradle.api.Script$apply$0.callCurrent(Unknown Source)
        at build_4b35wimvl540y84qjn2xnlyq9.run(/Users/Chaklader/IdeaProjects/spring-websocket-chat/build.gradle:4)
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
        ... 88 more
Caused by: org.gradle.api.tasks.TaskInstantiationException: Could not create task of type 'DependencyManagementReportTask'.
        at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:123)
        at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:118)
        at org.gradle.util.GUtil.uncheckedCall(GUtil.java:402)
        at org.gradle.api.internal.AbstractTask.injectIntoNewInstance(AbstractTask.java:174)
        at org.gradle.api.internal.project.taskfactory.TaskFactory.create(TaskFactory.java:118)
        at org.gradle.api.internal.project.taskfactory.TaskFactory.create(TaskFactory.java:38)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory.create(AnnotationProcessingTaskFactory.java:51)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory.create(AnnotationProcessingTaskFactory.java:32)
        at org.gradle.api.internal.project.taskfactory.DependencyAutoWireTaskFactory.create(DependencyAutoWireTaskFactory.java:44)
        at org.gradle.api.internal.project.taskfactory.DependencyAutoWireTaskFactory.create(DependencyAutoWireTaskFactory.java:27)
        at org.gradle.api.internal.tasks.DefaultTaskContainer$TaskInstantiator.create(DefaultTaskContainer.java:301)
        at org.gradle.api.internal.tasks.DefaultTaskContainer$TaskInstantiator.create(DefaultTaskContainer.java:289)
        at org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:116)
        at org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:147)
        at org.gradle.api.internal.tasks.DefaultTaskContainer_Decorated.create(Unknown Source)
        at org.gradle.api.internal.tasks.DefaultTaskContainer_Decorated$create.call(Unknown Source)
        at io.spring.gradle.dependencymanagement.DependencyManagementPlugin.apply(DependencyManagementPlugin.groovy:57)
        at io.spring.gradle.dependencymanagement.DependencyManagementPlugin.apply(DependencyManagementPlugin.groovy)
        at org.gradle.api.internal.plugins.ImperativeOnlyPluginTarget.applyImperative(ImperativeOnlyPluginTarget.java:41)
        at org.gradle.api.internal.plugins.RuleBasedPluginTarget.applyImperative(RuleBasedPluginTarget.java:49)
        at org.gradle.api.internal.plugins.DefaultPluginManager.addPlugin(DefaultPluginManager.java:165)
        at org.gradle.api.internal.plugins.DefaultPluginManager.access$200(DefaultPluginManager.java:47)
        at org.gradle.api.internal.plugins.DefaultPluginManager$AddPluginBuildOperation.run(DefaultPluginManager.java:252)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:95)
        at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:144)
        ... 114 more
Caused by: org.gradle.internal.service.UnknownServiceException: No service of type StyledTextOutputFactory available in ProjectScopeServices.
        at org.gradle.internal.service.DefaultServiceRegistry.getServiceProvider(DefaultServiceRegistry.java:352)
        at org.gradle.internal.service.DefaultServiceRegistry.doGet(DefaultServiceRegistry.java:341)
        at org.gradle.internal.service.DefaultServiceRegistry.get(DefaultServiceRegistry.java:329)
        at org.gradle.api.internal.DependencyInjectingInstantiator.convertParameters(DependencyInjectingInstantiator.java:85)
        at org.gradle.api.internal.DependencyInjectingInstantiator.newInstance(DependencyInjectingInstantiator.java:54)
        at org.gradle.api.internal.ClassGeneratorBackedInstantiator.newInstance(ClassGeneratorBackedInstantiator.java:36)
        at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:121)
        ... 141 more

BUILD FAILED in 0s

The gradle info is here,

When I try to synchronize the project, I get the message,

How can I just run the project properly ?


问:
HTML Javascript font size change
```<code><html>
<head>
  <meta charset="utf-8">
  <script>
    function test(){
      var name = document.getElementById('name').value;
      var snumber = document.getElementById('snumber').value;
      document.write("name="+name+"");
      document.write("&snumber="+snumber+"<br />");
    }
  </script>
</head>

<body>
   <h2>Example of sending data using POST</h2>
     Name :
   <input type="text" id="name"><br/>
     Student number:
   <input type="text" id="snumber"><br/><br/>
   <input type="button" value="submit" onclick="test();">
</body>
</html>
</code>```

I want to change the font size of 6th and 7th lines' result to h2 size
I can change in body section by putting

```<code> <h2></h2>
</code>```

however, it's not working in a script section. If I input data in name and snumber section, It connects to a new page that shows inputs like "name=David&snum=21467564" I want this font size to be h2 size!

答:
try this one

function test(){
 var name = document.getElementById('name').value;
 var snumber = document.getElementById('snumber').value;
 document.write("
name="+name+"
");
 document.write("
snumber="+snumber+"

");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Example of sending data using POST</h2>
Name :
<input type="text" id="name"><br/>
Student number:
<input type="text" id="snumber"><br/><br/>
<input type="button" value="submit" onclick="test();"></code>```

Title: HTML Javascript font size change

Body:
  <meta charset="utf-8">

Example of sending data using POST

     Name :
   <input type="text" id="name">

     Student number:
   <input type="text" id="snumber">

   <input type="button" value="submit" onclick="test();">

I want to change the font size of 6th and 7th lines' result to h2 size
I can change in body section by putting

however, it's not working in a script section. If I input data in name and snumber section, It connects to a new page that shows inputs like "name=David&snum=21467564" I want this font size to be h2 size!

Body:
try this one

function test(){
 var name = document.getElementById('name').value;
 var snumber = document.getElementById('snumber').value;
 document.write("<h2>name="+name+"</h2>");
 document.write("<h2>snumber="+snumber+"</h2><br />");
}

<h2>Example of sending data using POST</h2>
Name :
<input type="text" id="name"><br/>
Student number:
<input type="text" id="snumber"><br/><br/>
<input type="button" value="submit" onclick="test();">


问:
Displaying Date and Time separately from a String in localized format in Android
I know there are a lot of similar questions, and so far some of the solutions that I tried, but did not fully answer my question are: this, this, this, this, this, this, this, this, this, this, and a lot more.

I am making an app where I get user's post from server and sort it by date, and also displaying date and time it was created in the post. Right now I have a working solution, and I am doing it by converting string from a server in this format yyyy-MM-dd HH:mm:ss to my custom date and time format.

The problem is: I do not want to hard code a format, but instead I want to display it in the format that user phone has, and do it separately for both date and time. By the local format of the phone I mean - am-pm/24 hour format, and same for the date format - dd-MM-YY, or MM-dd-YYYY, or dd-MM, etc.

So far I have looked through a lot of solutions, most of which have that hardcoded format. I try to avoid, but I think that additional problem is that I want to separate date and time from datetime string. The other problem is that the transformation is not separate for date and time.

In short I want to format 2017-07-04 12:00:00 to 04 Jul 2017 and 12:00 PM, or 07/04/17 and 12:00. ie. Separating date and time into two strings, and displaying them in localized phone format.

My Adapter:

```<code> public class UserPostsAdapter extends RecyclerView.Adapter<UserPostsAdapter.PostsViewHolder> {

     private List<UserPosts> postItems;
     private Context context;
     private static final String TAG = UserPosts.class.getSimpleName();

     class PostsViewHolder extends RecyclerView.ViewHolder {
    TextView userPostsTitle, userPostsDate, userPostsTime, userPost, textViewStars, textViewComments;
         ImageView imageViewDisplayComments, imageViewReply, imageViewCommentStar;
         String pCcontactId, postId;

         PostsViewHolder(View itemView) {
             super(itemView);

             userPostsTitle = (TextView) itemView.findViewById(R.id.userPostsTitle);
             userPostsDate = (TextView) itemView.findViewById(R.id.userPostsDate);
             userPostsTime = (TextView) itemView.findViewById(R.id.userPostsTime);
             userPost = (TextView) itemView.findViewById(R.id.userPost);

             textViewStars = (TextView) itemView.findViewById(R.id.textViewStars);
             textViewComments = (TextView) itemView.findViewById(R.id.textViewComments);

             imageViewCommentStar = (ImageView) itemView.findViewById(R.id.imageViewCommentStar);
             imageViewDisplayComments = (ImageView) itemView.findViewById(R.id.imageViewDisplayComments);
             imageViewReply = (ImageView) itemView.findViewById(R.id.imageViewReply);
         }
     }

     public UserPostsAdapter(List<UserPosts> postsList, Context context) {
         this.postItems = postsList;
         this.context = context;
     }

     @Override
     public UserPostsAdapter.PostsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_user_post, parent, false);

         return new UserPostsAdapter.PostsViewHolder(itemView);
     }

     @Override
     public void onBindViewHolder(final UserPostsAdapter.PostsViewHolder holder, int position) {
         final UserPosts post = postItems.get(position);

         SQLiteHandler db = new SQLiteHandler(context.getApplicationContext());
         HashMap<String, String> user = db.getUserDetails();
         final String currentUserId = user.get("uid");

         if (post.getTitle() != null && !post.getTitle().isEmpty()) {
             holder.userPostsTitle.setText(post.getTitle());
         } else {
             holder.userPostsTitle.setVisibility(View.GONE);
         }
         holder.userPostsDate.setText(convertDate(postItems.get(position).getCreatedDate()));
         holder.userPostsTime.setText(convertTime(postItems.get(position).getCreatedTime()));
         holder.userPost.setText(post.getPostedText());
         if (Integer.parseInt(post.getLikesNumber()) > 0) {
             holder.textViewStars.setText(post.getLikesNumber());
         }
         holder.textViewComments.setText(post.getCommentsNumber());

         holder.pCcontactId = post.getUserId();
         final String postId = holder.postId = post.getId();

         holder.imageViewDisplayComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
     });

     ***TRANSFORMING DATE AND TIME SEPARATELY TO CUSTOM FORMAT***
-----------------------------------------------------------------------------
private String convertDate(String time) {

    SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat dateFormatConverted = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault());
    java.util.Locale.getDefault());

    SimpleDateFormat(datePattern);

      DateFormat.getTimeInstance(DateFormat.SHORT).parse(mTimeDisplay.getText().toString());

    java.util.Date date = null;

    try {
        date = dateFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return dateFormatConverted.format(date);
}

private String convertTime(String time) {

    SimpleDateFormat timeFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat timeFormatConverted = new SimpleDateFormat("HH:mm", Locale.getDefault());

    java.util.Date date = null;

    try {
        date = timeFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return timeFormatConverted.format(date);
}
-----------------------------------------------------------------------------
     @Override
     public int getItemCount() {
         return postItems.size();
     }
 }
</code>```

答:
First I strongly recommend that you save dates as long(1) and not as String It would simplify your code a lot. You can handle dates and display them in the current Locale without having a single formatting string like "yyyy_MM_dd" in your code.

Then to get the Date or Time in current Locale just :

```<code>String dateLocalizedStr = DateFormat.getDateInstance().format(myDate);
String timeLocalizedStr = DateFormat.getTimeInstance().format(myDate);
</code>```

You can change to long or short format passing an argument to getDateInstance() or getTimenstance()

(1) as long or Date because Date internally is a long.

Body:
I know there are a lot of similar questions, and so far some of the solutions that I tried, but did not fully answer my question are: this, this, this, this, this, this, this, this, this, this, and a lot more.

I am making an app where I get user's post from server and sort it by date, and also displaying date and time it was created in the post. Right now I have a working solution, and I am doing it by converting string from a server in this format yyyy-MM-dd HH:mm:ss to my custom date and time format.

The problem is: I do not want to hard code a format, but instead I want to display it in the format that user phone has, and do it separately for both date and time. By the local format of the phone I mean - am-pm/24 hour format, and same for the date format - dd-MM-YY, or MM-dd-YYYY, or dd-MM, etc.

So far I have looked through a lot of solutions, most of which have that hardcoded format. I try to avoid, but I think that additional problem is that I want to separate date and time from datetime string. The other problem is that the transformation is not separate for date and time.

In short I want to format 2017-07-04 12:00:00 to 04 Jul 2017 and 12:00 PM, or 07/04/17 and 12:00. ie. Separating date and time into two strings, and displaying them in localized phone format.

My Adapter:

 public class UserPostsAdapter extends RecyclerView.Adapter<UserPostsAdapter.PostsViewHolder> {

     private List<UserPosts> postItems;
     private Context context;
     private static final String TAG = UserPosts.class.getSimpleName();

     class PostsViewHolder extends RecyclerView.ViewHolder {
    TextView userPostsTitle, userPostsDate, userPostsTime, userPost, textViewStars, textViewComments;
         ImageView imageViewDisplayComments, imageViewReply, imageViewCommentStar;
         String pCcontactId, postId;

         PostsViewHolder(View itemView) {
             super(itemView);

             userPostsTitle = (TextView) itemView.findViewById(R.id.userPostsTitle);
             userPostsDate = (TextView) itemView.findViewById(R.id.userPostsDate);
             userPostsTime = (TextView) itemView.findViewById(R.id.userPostsTime);
             userPost = (TextView) itemView.findViewById(R.id.userPost);

             textViewStars = (TextView) itemView.findViewById(R.id.textViewStars);
             textViewComments = (TextView) itemView.findViewById(R.id.textViewComments);

             imageViewCommentStar = (ImageView) itemView.findViewById(R.id.imageViewCommentStar);
             imageViewDisplayComments = (ImageView) itemView.findViewById(R.id.imageViewDisplayComments);
             imageViewReply = (ImageView) itemView.findViewById(R.id.imageViewReply);
         }
     }

     public UserPostsAdapter(List<UserPosts> postsList, Context context) {
         this.postItems = postsList;
         this.context = context;
     }

     @Override
     public UserPostsAdapter.PostsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_user_post, parent, false);

         return new UserPostsAdapter.PostsViewHolder(itemView);
     }

     @Override
     public void onBindViewHolder(final UserPostsAdapter.PostsViewHolder holder, int position) {
         final UserPosts post = postItems.get(position);

         SQLiteHandler db = new SQLiteHandler(context.getApplicationContext());
         HashMap<String, String> user = db.getUserDetails();
         final String currentUserId = user.get("uid");

         if (post.getTitle() != null && !post.getTitle().isEmpty()) {
             holder.userPostsTitle.setText(post.getTitle());
         } else {
             holder.userPostsTitle.setVisibility(View.GONE);
         }
         holder.userPostsDate.setText(convertDate(postItems.get(position).getCreatedDate()));
         holder.userPostsTime.setText(convertTime(postItems.get(position).getCreatedTime()));
         holder.userPost.setText(post.getPostedText());
         if (Integer.parseInt(post.getLikesNumber()) > 0) {
             holder.textViewStars.setText(post.getLikesNumber());
         }
         holder.textViewComments.setText(post.getCommentsNumber());

         holder.pCcontactId = post.getUserId();
         final String postId = holder.postId = post.getId();

         holder.imageViewDisplayComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
     });

     ***TRANSFORMING DATE AND TIME SEPARATELY TO CUSTOM FORMAT***
-----------------------------------------------------------------------------
private String convertDate(String time) {

    SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat dateFormatConverted = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault());
    java.util.Locale.getDefault());

    SimpleDateFormat(datePattern);

      DateFormat.getTimeInstance(DateFormat.SHORT).parse(mTimeDisplay.getText().toString());

    java.util.Date date = null;

    try {
        date = dateFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return dateFormatConverted.format(date);
}

private String convertTime(String time) {

    SimpleDateFormat timeFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat timeFormatConverted = new SimpleDateFormat("HH:mm", Locale.getDefault());

    java.util.Date date = null;

    try {
        date = timeFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return timeFormatConverted.format(date);
}
-----------------------------------------------------------------------------
     @Override
     public int getItemCount() {
         return postItems.size();
     }
 }

Body:
First I strongly recommend that you save dates as long(1) and not as String It would simplify your code a lot. You can handle dates and display them in the current Locale without having a single formatting string like "yyyy_MM_dd" in your code.

Then to get the Date or Time in current Locale just :

String dateLocalizedStr = DateFormat.getDateInstance().format(myDate);
String timeLocalizedStr = DateFormat.getTimeInstance().format(myDate);

You can change to long or short format passing an argument to getDateInstance() or getTimenstance()

(1) as long or Date because Date internally is a long.


问:
Random HTML Email characters replaced with "=" in Outlook
I've stripped this email down and it's still displaying the problem: certain random characters are being replaced by "=" in Outlook. I'm using PHP/Codeigniter and sparkpost.com as the mailing mechanism.

In outlook.com:

In gmail/other clients tested, it's fine

Email Config:

```<code>$config['protocol']  = 'smtp';
$config['smtp_host'] = "smtp.sparkpostmail.com";
$config['smtp_user'] = "SMTP_Injection";
$config['smtp_pass'] = " ";
$config['smtp_port'] = 587;
$config['wordwrap'] = TRUE;
$config['mailtype']  = 'html';
$config['charset'] = 'utf-8';
$config['newline'] = "\r\n";
</code>```

Stripped down HTML for Email

https://pastebin.com/inBrhEtJ

Any ideas?

答:
In your config add the following line:

```<code>$config['crlf'] = "\r\n";
</code>```

The reason is the following:

According to RFC 2045 for a quoted-printable encoding \r\n must be used.
However Codeigniter breaks this rule because they say some server can't handle this properly, and use therefore \n only.

This is documented in the E-Mail Library under /system/libraries/EMail.php.
You can see that in Line 182 on the official Github Rep.

Body:
I've stripped this email down and it's still displaying the problem: certain random characters are being replaced by "=" in Outlook. I'm using PHP/Codeigniter and sparkpost.com as the mailing mechanism.

In outlook.com:

In gmail/other clients tested, it's fine

Email Config:

$config['protocol']  = 'smtp';
$config['smtp_host'] = "smtp.sparkpostmail.com";
$config['smtp_user'] = "SMTP_Injection";
$config['smtp_pass'] = " ";
$config['smtp_port'] = 587;
$config['wordwrap'] = TRUE;
$config['mailtype']  = 'html';
$config['charset'] = 'utf-8';
$config['newline'] = "\r\n";

Stripped down HTML for Email

https://pastebin.com/inBrhEtJ

Any ideas?

Body:
In your config add the following line:

$config['crlf'] = "\r\n";

The reason is the following:

According to RFC 2045 for a quoted-printable encoding \r\n must be used.
However Codeigniter breaks this rule because they say some server can't handle this properly, and use therefore \n only.

This is documented in the E-Mail Library under /system/libraries/EMail.php.
You can see that in Line 182 on the official Github Rep.


问:
How to frame mongo db query with specific user id and array of subdocument field not equal to null
Consider the following example. From this, I want to frame a query in mongo db which has UserId: "test" and "Orders.PaidDateTime" not equal to null

I should get the following result.

Example:

```<code>{
    "_id" : ObjectId("5953b6873a45f70afc6ce3a2"),
    "CreatedDateTime" : ISODate("2017-06-28T14:00:39.192Z"),
    "UserId" : "test",
    "Orders" : [
        {
            "_id" : ObjectId("59560f2b844faa0ff4933aa6"),
            "CreatedDateTime" : ISODate("2017-06-30T08:43:23.666Z"),
            "PaidDateTime" : null
        },
        {
            "_id" : ObjectId("59564ba3a046041364c24de4"),
            "CreatedDateTime" : ISODate("2017-06-30T13:01:23.290Z"),
            "PaidDateTime" : null
        },
        {
            "_id" : ObjectId("59564f168be0720e1c346857"),
            "CreatedDateTime" : ISODate("2017-06-30T13:16:06.072Z"),
            "PaidDateTime" : ISODate("2017-06-30T13:16:29.000Z")
        }
    ]
},
{
    "_id" : ObjectId("5953b6873a45f70afc6ce3a2"),
    "CreatedDateTime" : ISODate("2017-06-28T14:00:39.192Z"),
    "UserId" : "test",
    "Orders" : [
        {
            "_id" : ObjectId("59560f2b844faa0ff4933aa6"),
            "CreatedDateTime" : ISODate("2017-06-30T08:43:23.666Z"),
            "PaidDateTime" : null
        }
    ]
}
</code>```

Result:

```<code>{
    "_id" : ObjectId("5953b6873a45f70afc6ce3a2"),
    "CreatedDateTime" : ISODate("2017-06-28T14:00:39.192Z"),
    "UserId" : "test",
    "Orders" : [
        {
            "_id" : ObjectId("59564f168be0720e1c346857"),
            "CreatedDateTime" : ISODate("2017-06-30T13:16:06.072Z"),
            "PaidDateTime" : ISODate("2017-06-30T13:16:29.000Z")
        }
    ]
}
</code>```

答:
Use $ne opertaor https://docs.mongodb.com/manual/reference/operator/query/ne/
db.inventory.find( { UserId: "test" , "Orders.PaidDateTime" : { $ne: null } } )

Body:
Consider the following example. From this, I want to frame a query in mongo db which has UserId: "test" and "Orders.PaidDateTime" not equal to null

I should get the following result.

Example:

{
    "_id" : ObjectId("5953b6873a45f70afc6ce3a2"),
    "CreatedDateTime" : ISODate("2017-06-28T14:00:39.192Z"),
    "UserId" : "test",
    "Orders" : [
        {
            "_id" : ObjectId("59560f2b844faa0ff4933aa6"),
            "CreatedDateTime" : ISODate("2017-06-30T08:43:23.666Z"),
            "PaidDateTime" : null
        },
        {
            "_id" : ObjectId("59564ba3a046041364c24de4"),
            "CreatedDateTime" : ISODate("2017-06-30T13:01:23.290Z"),
            "PaidDateTime" : null
        },
        {
            "_id" : ObjectId("59564f168be0720e1c346857"),
            "CreatedDateTime" : ISODate("2017-06-30T13:16:06.072Z"),
            "PaidDateTime" : ISODate("2017-06-30T13:16:29.000Z")
        }
    ]
},
{
    "_id" : ObjectId("5953b6873a45f70afc6ce3a2"),
    "CreatedDateTime" : ISODate("2017-06-28T14:00:39.192Z"),
    "UserId" : "test",
    "Orders" : [
        {
            "_id" : ObjectId("59560f2b844faa0ff4933aa6"),
            "CreatedDateTime" : ISODate("2017-06-30T08:43:23.666Z"),
            "PaidDateTime" : null
        }
    ]
}

Result:

{
    "_id" : ObjectId("5953b6873a45f70afc6ce3a2"),
    "CreatedDateTime" : ISODate("2017-06-28T14:00:39.192Z"),
    "UserId" : "test",
    "Orders" : [
        {
            "_id" : ObjectId("59564f168be0720e1c346857"),
            "CreatedDateTime" : ISODate("2017-06-30T13:16:06.072Z"),
            "PaidDateTime" : ISODate("2017-06-30T13:16:29.000Z")
        }
    ]
}


答:
function test(){
      var name = document.getElementById('name').value;
      var snumber = document.getElementById('snumber').value;

 document.write("
name="+name+"
");
 document.write("
&snumber="+snumber+"

");
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Example of sending data using POST</h2>
     Name :
   <input type="text" id="name"><br/>
     Student number:
   <input type="text" id="snumber"><br/><br/>
   <input type="button" value="submit" onclick="test();"></code>```

Title: HTML Javascript font size change

Body:
function test(){
      var name = document.getElementById('name').value;
      var snumber = document.getElementById('snumber').value;

 document.write("<h2>name="+name+"</h2>");
 document.write("<h2>&snumber="+snumber+"</h2> <br/>");
 }

<h2>Example of sending data using POST</h2>
     Name :
   <input type="text" id="name"><br/>
     Student number:
   <input type="text" id="snumber"><br/><br/>
   <input type="button" value="submit" onclick="test();">


问:
LoadRunner Truclient, need to access elements directly and force events. How to force the .onClick() event?
We have an App Under Test which is using frames, and seems to be ignoring standards. (Image 1-3.)

Problem: I need to force an onClick() event inside the page, because TruClient does the click() event, but the onClick() doesn't fire. We're using a "Navigate" step as a workaround for one, but cannot use that for other steps.

Code of interest viewed in IE 11 is:

    <title>Revenue Management System</title>
    <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
    <meta name="ProgId" content="FrontPage.Editor.Document">

    <frameset rows="43,*" cols="*" frameborder="NO" border="0" framespacing="0">
      <frame src="html/top_pannel.htm" name="top" scrolling="NO" noresize >
      <frameset cols="153,*" frameborder="auto" border="0" framespacing="0">
        <frame src="html/LP_index.htm" name="menu" scrolling="auto" noresize >
        <frame src="html/main.htm" name="maindata">
      </frameset>
    </frameset>
    <noframes>
    </noframes>
    ```
</div>
</div>
</p>

<p>Using Developer tools, we can see (Picture 4, not able to copy & paste from Internet Exploder Dev Tools.)</p>

<p><img src="https://i.stack.imgur.com/PoOiw.png" alt="Picture 4: Code for the menu we're working on as POC"></p>

<p>Also: Seems I cannot use JavaScript to access the main window, burrow into the frames, and use a <code>getObjectByID()</code> on the various links which are not responding correctly. Tried a "Evaluate JavaScript on Object", but that hasn't seemed to work.</p>

<p>Wondering if I can use the technique here -->FrameBreaker to get around it? But that doesn't get me into the main window, as when I check with: </p>

```var x = window.frameElement;
window.alert(x);
```

<p>The alert returns "null". So, top level frame, I believe. </p>

<p>I've been working with jquery (<code>window.alert($("#slideMenu_0").text());</code> failed evaluation in "run step" mode), and </p>

```var x = document.getElementsByTagName("a");
window.alert(x);
```

<p>doesn't want to return anything, and neither will </p>

```var element = document.getElementById('slideMenu_0');
```

<p>or </p>

```var x = document.getElementsByClassName("clA0");
```

Also of note, I have no Admin permissions to the machine, though LoadRunner runs under elevated privileges.

Would appreciate any insight. We have 4 items so far that need a quick fix on this; unfortunately, I'm the best we've got right now.  ;-)

Please advise if images did not upload - behind a firewall by paranoid schizophrenics

答:
Some of the APIs TruClient uses are available only in Standard Mode, so if the website doesn’t render in Standard Mode TruClinet will not support it by definition.
According to your description, this seems to be the case.
Therefor, I recommend using TruClient Firefox or TruClient Chromium instead.
Please note that removing the enforcement will prevent TruClient from recording your actions.

Hope it helped,
Elad.

Body:
We have an App Under Test which is using frames, and seems to be ignoring standards. (Image 1-3.)

Problem: I need to force an onClick() event inside the page, because TruClient does the click() event, but the onClick() doesn't fire. We're using a "Navigate" step as a workaround for one, but cannot use that for other steps.

Code of interest viewed in IE 11 is:

    <title>Revenue Management System</title>
    <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
    <meta name="ProgId" content="FrontPage.Editor.Document">

    <frameset rows="43,*" cols="*" frameborder="NO" border="0" framespacing="0">
      <frame src="html/top_pannel.htm" name="top" scrolling="NO" noresize >
      <frameset cols="153,*" frameborder="auto" border="0" framespacing="0">
        <frame src="html/LP_index.htm" name="menu" scrolling="auto" noresize >
        <frame src="html/main.htm" name="maindata">
      </frameset>
    </frameset>
    <noframes>
    </noframes>

Using Developer tools, we can see (Picture 4, not able to copy & paste from Internet Exploder Dev Tools.)

Also: Seems I cannot use JavaScript to access the main window, burrow into the frames, and use a getObjectByID() on the various links which are not responding correctly. Tried a "Evaluate JavaScript on Object", but that hasn't seemed to work.

Wondering if I can use the technique here -->FrameBreaker to get around it? But that doesn't get me into the main window, as when I check with:

var x = window.frameElement;
window.alert(x);

The alert returns "null". So, top level frame, I believe.

I've been working with jquery (window.alert($("#slideMenu_0").text()); failed evaluation in "run step" mode), and

var x = document.getElementsByTagName("a");
window.alert(x);

doesn't want to return anything, and neither will

var element = document.getElementById('slideMenu_0');

or

var x = document.getElementsByClassName("clA0");

Also of note, I have no Admin permissions to the machine, though LoadRunner runs under elevated privileges.

Would appreciate any insight. We have 4 items so far that need a quick fix on this; unfortunately, I'm the best we've got right now.  ;-)

Please advise if images did not upload - behind a firewall by paranoid schizophrenics


问:
PHP SQL SELECT sum(value) WHERE x LIKE '%$month%' (foreach)
I have a table:

```<code>user_id |       month       | value
    1   | firstname_1_2017  |   5
    1   | secondname_1_2017 |   4
    1   | firstname_2_2017  |   7
    1   | secondname_2_2017 |   8
    1   | firstname_3_2017  |   5
    1   | secondname_3_2017 |   4
    1   | firstname_4_2017  |   7
    1   | secondname_4_2017 |   8
</code>```

I need sum "value" for each month with a foreach.

firstname_1_2017 + secondname_1_2017 = 9

firstname_2_2017 + secondname_2_2017 = 15

I have an array for the months:

```<code>$array_months = array( '1','2','3','4','5','6','7','8','9','10','11','12' );
</code>```

So I wrote (in php):

```<code>SELECT sum(value)
FROM table
WHERE user_id = $user_id
AND month LIKE '%_$array_months_2017%'
</code>```

When I write a foreach, the result is the same sum of all values repeat for each month (Example: Jan 48 points, Feb 48 points, Mar 48 points...).

I'd like this result with a foreach:

You have "9" points in January

You have "15" points in February

etc...

答:
You should think about changing your DB design to separate Month and Year from user's name.

Not a good approach, but a solution will be to extract month year from month string and group it to calculate sum for each month.

```<code>SELECT SUBSTR(month, LOCATE('_', month) + 1) AS month_year, SUM(value)
FROM users
WHERE user_id = 1
GROUP BY month_year;
</code>```

Working Fiddle

Body:
I have a table:

user_id |       month       | value
    1   | firstname_1_2017  |   5
    1   | secondname_1_2017 |   4
    1   | firstname_2_2017  |   7
    1   | secondname_2_2017 |   8
    1   | firstname_3_2017  |   5
    1   | secondname_3_2017 |   4
    1   | firstname_4_2017  |   7
    1   | secondname_4_2017 |   8

I need sum "value" for each month with a foreach.

firstname_1_2017 + secondname_1_2017 = 9

firstname_2_2017 + secondname_2_2017 = 15

I have an array for the months:

$array_months = array( '1','2','3','4','5','6','7','8','9','10','11','12' );

So I wrote (in php):

SELECT sum(value)
FROM table
WHERE user_id = $user_id
AND month LIKE '%_$array_months_2017%'

When I write a foreach, the result is the same sum of all values repeat for each month (Example: Jan 48 points, Feb 48 points, Mar 48 points...).

I'd like this result with a foreach:

You have "9" points in January

You have "15" points in February

etc...

Body:
You should think about changing your DB design to separate Month and Year from user's name.

Not a good approach, but a solution will be to extract month year from month string and group it to calculate sum for each month.

SELECT SUBSTR(month, LOCATE('_', month) + 1) AS month_year, SUM(value)
FROM users
WHERE user_id = 1
GROUP BY month_year;

Working Fiddle