问:
Maven build throws java.lang.ClassNotFoundException during tests performing
I have spring-boot project with integration tests. I'm trying to move to JDK 9. After some changes in pom I'm able to build (with tests skipped) and run project on java 9. But when I try to perform integration tests, I get an exception:

mvn clean install:

```<code>[ERROR] Please refer to pathToProject\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream.
[ERROR] There was an error in the forked process
[ERROR] java.lang.ClassNotFoundException: org.apache.maven.surefire.junit4.JUnit4Provider
[ERROR] org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process
[ERROR] java.lang.ClassNotFoundException: org.apache.maven.surefire.junit4.JUnit4Provider
[ERROR]         at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:673)
[ERROR]         at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:535)
[ERROR]         at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:280)
[ERROR]         at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:245)
[ERROR]         at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1124)
[ERROR]         at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:
[ERROR]         at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:832)
[ERROR]         at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
[ERROR]         at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
[ERROR]         at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
[ERROR]         at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
[ERROR]         at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
[ERROR]         at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
[ERROR]         at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java
[ERROR]         at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
[ERROR]         at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
[ERROR]         at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
[ERROR]         at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
[ERROR]         at org.apache.maven.cli.MavenCli.execute(MavenCli.java:955)
[ERROR]         at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:290)
[ERROR]         at org.apache.maven.cli.MavenCli.main(MavenCli.java:194)
[ERROR]         at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[ERROR]         at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[ERROR]         at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[ERROR]         at java.base/java.lang.reflect.Method.invoke(Method.java:564)
[ERROR]         at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
[ERROR]         at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
[ERROR]         at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
[ERROR]         at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
</code>```

My pom.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>myProject</artifactId>
    <version>0.1.4</version>
    <packaging>jar</packaging>
    <groupId>com.myProject</groupId>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.9</java.version>

        <!-- Dependency versions -->
        <logback.version>1.1.7</logback.version>
        <lombok.version>1.16.18</lombok.version>

        <!-- Plugin versions-->
        <maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
        <maven-surefire-plugin.version>2.20.1</maven-surefire-plugin.version>
        <maven-failsafe-plugin.version>2.20.1</maven-failsafe-plugin.version>
        <docker-maven-plugin.version>1.0.0</docker-maven-plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>

        <!-- tests -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <jdkToolchain>
                        <version>9</version>
                    </jdkToolchain>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>${maven-failsafe-plugin.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <argLine>--add-modules java.se.ee</argLine>
                    <argLine>--add-modules java.xml.bind</argLine>
                    <argLine>--add-modules java.xml.ws.annotation</argLine>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

Maven version: 3.5.2

All integration tests have the same configuration:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations="classpath:application.properties")
public class SomeTest {
</code>```

答: The problem was in maven-surefire-plugin version 2.20.1. It is not working for me even on JDK 8. After decreasing version to 2.18.1, it started to work fine.

Body:
I have spring-boot project with integration tests. I'm trying to move to JDK 9. After some changes in pom I'm able to build (with tests skipped) and run project on java 9. But when I try to perform integration tests, I get an exception:

mvn clean install:

[ERROR] Please refer to pathToProject\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream.
[ERROR] There was an error in the forked process
[ERROR] java.lang.ClassNotFoundException: org.apache.maven.surefire.junit4.JUnit4Provider
[ERROR] org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process
[ERROR] java.lang.ClassNotFoundException: org.apache.maven.surefire.junit4.JUnit4Provider
[ERROR]         at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:673)
[ERROR]         at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:535)
[ERROR]         at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:280)
[ERROR]         at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:245)
[ERROR]         at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1124)
[ERROR]         at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:
[ERROR]         at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:832)
[ERROR]         at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
[ERROR]         at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
[ERROR]         at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
[ERROR]         at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
[ERROR]         at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
[ERROR]         at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
[ERROR]         at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java
[ERROR]         at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
[ERROR]         at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
[ERROR]         at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
[ERROR]         at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
[ERROR]         at org.apache.maven.cli.MavenCli.execute(MavenCli.java:955)
[ERROR]         at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:290)
[ERROR]         at org.apache.maven.cli.MavenCli.main(MavenCli.java:194)
[ERROR]         at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[ERROR]         at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[ERROR]         at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[ERROR]         at java.base/java.lang.reflect.Method.invoke(Method.java:564)
[ERROR]         at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
[ERROR]         at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
[ERROR]         at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
[ERROR]         at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)

My pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>myProject</artifactId>
    <version>0.1.4</version>
    <packaging>jar</packaging>
    <groupId>com.myProject</groupId>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.9</java.version>

        <logback.version>1.1.7</logback.version>
        <lombok.version>1.16.18</lombok.version>

        <maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
        <maven-surefire-plugin.version>2.20.1</maven-surefire-plugin.version>
        <maven-failsafe-plugin.version>2.20.1</maven-failsafe-plugin.version>
        <docker-maven-plugin.version>1.0.0</docker-maven-plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <jdkToolchain>
                        <version>9</version>
                    </jdkToolchain>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>${maven-failsafe-plugin.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <argLine>--add-modules java.se.ee</argLine>
                    <argLine>--add-modules java.xml.bind</argLine>
                    <argLine>--add-modules java.xml.ws.annotation</argLine>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
            </plugin>
        </plugins>
    </build>
</project>

Maven version: 3.5.2

All integration tests have the same configuration:

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations="classpath:application.properties")
public class SomeTest {


来源: stackexchange

问:
MySQL #1140 - Mixing of GROUP columns
Hi wondering if perhaps someone could shed some light on the below error. The sql works fine locally but i get the the  below error remotely.

SQL query:

```<code>   SELECT COUNT(node.nid),
          node.nid AS nid,
          node_data_field_update_date.field_update_date_value AS node_data_field_update_date_field_update_date_value
     FROM node node
LEFT JOIN content_type_update node_data_field_update_date ON node.vid = node_data_field_update_date.vid
    WHERE node.type IN ('update')
ORDER BY node_data_field_update_date_field_update_date_value DESC
</code>```

MySQL said:

#1140 - Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no
  GROUP columns is illegal if there is
  no GROUP BY clause`

答: In Laravel Framework, setting 'strict' => false, in database file in the config folder will fix this.

ContentLicense: CC BY-SA 2.5

Title: MySQL #1140 - Mixing of GROUP columns

Body:
Hi wondering if perhaps someone could shed some light on the below error. The sql works fine locally but i get the the  below error remotely.

SQL query:

   SELECT COUNT(node.nid),
          node.nid AS nid,
          node_data_field_update_date.field_update_date_value AS node_data_field_update_date_field_update_date_value
     FROM node node
LEFT JOIN content_type_update node_data_field_update_date ON node.vid = node_data_field_update_date.vid
    WHERE node.type IN ('update')
ORDER BY node_data_field_update_date_field_update_date_value DESC

MySQL said:

#1140 - Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no
  GROUP columns is illegal if there is
  no GROUP BY clause`

ContentLicense: CC BY-SA 3.0


问:
Consequences of Java 32bit on Win(any) 64bit?
I am trying to install JAI (Java Advanced Imaging) 1.1.3 in my Vista 64 and it says that in order for it to be installed JDK 1.3 and up must be installed. The problem is that I have already installed the latest JDK for Win64 and it seems that it is not willing to work with it.

I would like to know if there are any severe consequences if I install JDK 32bit instead of the 64bit in Vista 64.

Thanks in advance for any advice on the subject!

John

答:
I think the 64 bit Java version for Vista actually has some disadvantages, like no browser plugin (so applets will not work). It seems that the 64 bit Java only makes sense if you really need the 64 bit capability, for normal users the intended version is still the 32 bit one.

Edit: Sun has now released 64 bit versions of the browser plugin and webstart.

OwnerDisplayName: imoschak

OwnerDisplayName: nikow

LastEditorDisplayName: nikow


问:
Spawn image at random position in canvas
I have a canvas and inside it a panel. I want to spawn different image UI object at random position inside my panel (on screen). I took x and y min and max  limits of the panel in order to generate a random position (withing these limts) but the problem is object are not instantiating at desired position. This is my code.

```<code>public class ImageSpawnerScreen : MonoBehaviour {
    public float waitTime = 2;
    public float cubeSpawnTotal = 10;
    public List<GameObject> cubePrefabList;

    float xPosMinLimit = -347;
    float xPosMaxLimit = 340;
    float yPosMinLimit = -458f;
    float yPosMaxLimit = 450f;

    public GameObject panel;
    void Start()
    {
        StartCoroutine(SpawnCube());
    }

    IEnumerator SpawnCube()
    {
        for (int i = 0; i < cubeSpawnTotal; i++)
        {
            GameObject prefabToSpawn = cubePrefabList[Random.Range(0, cubePrefabList.Count - 1)];
            //Vector3 spawnPosition = Camera.main.ScreenToViewportPoint(new Vector3(Random.Range(0,Screen.width),0,Random.Range(0,Screen.height)));  //Random.Range(xPosMinLimit, xPosMaxLimit);

            float xPos = Random.Range(xPosMinLimit, xPosMaxLimit);
            float yPos = Random.Range(yPosMinLimit, yPosMaxLimit);
            Vector3 spawnPosition = new Vector3(xPos, yPos, 0f);
            GameObject spwanObj = Instantiate(prefabToSpawn, spawnPosition, Quaternion.identity) as GameObject;
            spwanObj.transform.parent = panel.transform;
            spwanObj.transform.position = spawnPosition;
            yield return new WaitForSeconds(waitTime);
        }
    }
}
</code>```

I checked instantiated object positions are far away from the given random range position. What I am doing wrong? I think it is Rect Transform so i have to set its position differently.

答:
Indeed, you need to use RectTransform inside a Canvas.
You also don't need the -1 for you List.Count. Check the link in the comment below.

I think the following script will do what you are looking for:

```<code>public class ImageSpawnerScreen : MonoBehaviour
{
    public float waitTime = 2;
    public float cubeSpawnTotal = 10;
    public List<GameObject> imagesList;

    public RectTransform panel;

    void Start()
    {
        StartCoroutine(SpawnImage());
    }

    IEnumerator SpawnImage()
    {
        for (int i = 0; i < cubeSpawnTotal; i++)
        {
            GameObject imageToSpawn = imagesList[Random.Range(0, imagesList.Count)]; // Remove -1 after count since is exclusive for int (https://docs.unity3d.com/ScriptReference/Random.Range.html)

            Vector3 spawnPosition = GetBottomLeftCorner(panel) - new Vector3(Random.Range(0, panel.rect.x), Random.Range(0, panel.rect.y), 0);

            print("Spawn image at position: " + spawnPosition);

            GameObject spwanObj = Instantiate(imageToSpawn, spawnPosition, Quaternion.identity, panel);
            yield return new WaitForSeconds(waitTime);
        }
    }

    Vector3 GetBottomLeftCorner(RectTransform rt)
    {
        Vector3[] v = new Vector3[4];
        rt.GetWorldCorners(v);
        return v[0];
    }
}
</code>```

Let me know if you need more explanations.

Body:
I have a canvas and inside it a panel. I want to spawn different image UI object at random position inside my panel (on screen). I took x and y min and max  limits of the panel in order to generate a random position (withing these limts) but the problem is object are not instantiating at desired position. This is my code.

public class ImageSpawnerScreen : MonoBehaviour {
    public float waitTime = 2;
    public float cubeSpawnTotal = 10;
    public List<GameObject> cubePrefabList;

    float xPosMinLimit = -347;
    float xPosMaxLimit = 340;
    float yPosMinLimit = -458f;
    float yPosMaxLimit = 450f;

    public GameObject panel;
    void Start()
    {
        StartCoroutine(SpawnCube());
    }

    IEnumerator SpawnCube()
    {
        for (int i = 0; i < cubeSpawnTotal; i++)
        {
            GameObject prefabToSpawn = cubePrefabList[Random.Range(0, cubePrefabList.Count - 1)];
            //Vector3 spawnPosition = Camera.main.ScreenToViewportPoint(new Vector3(Random.Range(0,Screen.width),0,Random.Range(0,Screen.height)));  //Random.Range(xPosMinLimit, xPosMaxLimit);

            float xPos = Random.Range(xPosMinLimit, xPosMaxLimit);
            float yPos = Random.Range(yPosMinLimit, yPosMaxLimit);
            Vector3 spawnPosition = new Vector3(xPos, yPos, 0f);
            GameObject spwanObj = Instantiate(prefabToSpawn, spawnPosition, Quaternion.identity) as GameObject;
            spwanObj.transform.parent = panel.transform;
            spwanObj.transform.position = spawnPosition;
            yield return new WaitForSeconds(waitTime);
        }
    }
}

I checked instantiated object positions are far away from the given random range position. What I am doing wrong? I think it is Rect Transform so i have to set its position differently.

Body:
Indeed, you need to use RectTransform inside a Canvas.
You also don't need the -1 for you List.Count. Check the link in the comment below.

I think the following script will do what you are looking for:

public class ImageSpawnerScreen : MonoBehaviour
{
    public float waitTime = 2;
    public float cubeSpawnTotal = 10;
    public List<GameObject> imagesList;

    public RectTransform panel;

    void Start()
    {
        StartCoroutine(SpawnImage());
    }

    IEnumerator SpawnImage()
    {
        for (int i = 0; i < cubeSpawnTotal; i++)
        {
            GameObject imageToSpawn = imagesList[Random.Range(0, imagesList.Count)]; // Remove -1 after count since is exclusive for int (https://docs.unity3d.com/ScriptReference/Random.Range.html)

            Vector3 spawnPosition = GetBottomLeftCorner(panel) - new Vector3(Random.Range(0, panel.rect.x), Random.Range(0, panel.rect.y), 0);

            print("Spawn image at position: " + spawnPosition);

            GameObject spwanObj = Instantiate(imageToSpawn, spawnPosition, Quaternion.identity, panel);
            yield return new WaitForSeconds(waitTime);
        }
    }

    Vector3 GetBottomLeftCorner(RectTransform rt)
    {
        Vector3[] v = new Vector3[4];
        rt.GetWorldCorners(v);
        return v[0];
    }
}

Let me know if you need more explanations.


问:
Android Studio Rendering fragment issue
I am, at the moment, trying to make a google maps app using android studio.

Right now, everything is fine, except for one thing, when i go to the "Design" Tab, in the XML file i have this Redering message:

Rendering Problems A tag  allows a layout file to
  dynamically include different layouts at runtime. At layout editing
  time the specific layout to be used is not known. You can choose which
  layout you would like previewed while editing the layout...

And the main problem is that I cannot use any of the gui components in my layout, I searched about my problem and i understood that with this error, people couldn't see their map but they could put on textfields, widgets, layouts, etc.
But for me, my preview is completly frozen and i can't do any modification.

Picture of my android studio page.

答:
Yes I solved this easily..Simply ignore the message and click line that is showing below of the rendering messages.
Actually fragment contains layout inner and if its not include its showing warning that it must contains you can simply ignore this message below the warning then this rendering issue will be resolved.</p>

Title: Android Studio Rendering fragment issue


问:
Get the indexpath from custom button in accessoryView of a UITableViewCell
I have a UISearchController with a separate UITableViewController as its searchResultsController.

```<code>class SearchResultsViewController: UITableViewController {

    var fruits: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }

    @objc func addFruit(_ sender: UIButton) {
        let point = tableView.convert(sender.bounds.origin, to: sender)
        let indexPath = tableView.indexPathForRow(at: point)
        print(indexPath?.row)
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = fruits[indexPath.row]
        cell.selectionStyle = .none

        let addButton = UIButton(type: .custom)
        addButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        addButton.setImage(UIImage(named: "add"), for: .normal)
        addButton.contentMode = .scaleAspectFit
        addButton.addTarget(self, action: #selector(addFruit(_:)), for: .touchUpInside)
        addButton.sizeToFit()
        cell.accessoryView =  addButton

        return cell
    }

}
</code>```

I need to show a custom button in cells that search results are shown. So I added a UIButton as the cells' accessoryView. And it looks and works fine.

Now I need to get the cell's indexPath when the user taps on this button.

I'm trying to get it like shown below.

```<code>@objc func addFruit(_ sender: UIButton) {
    let point = tableView.convert(sender.bounds.origin, to: sender)
    let indexPath = tableView.indexPathForRow(at: point)
}
</code>```

But it keeps returning nil for every cell.

Is there any other way to get the indexPath from a custom button tap? I added a demo project here as well.

答:
I would suggest using this light solution: add indexPath.row to button tag:

```<code>let addButton = UIButton(type: .custom)
addButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
addButton.tag = indexPath.row
</code>```

And in button action:

```<code>@objc func addFruit(_ sender: UIButton) {
    print(sender.tag)
}
</code>```

Body:
I have a UISearchController with a separate UITableViewController as its searchResultsController.

class SearchResultsViewController: UITableViewController {

    var fruits: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }

    @objc func addFruit(_ sender: UIButton) {
        let point = tableView.convert(sender.bounds.origin, to: sender)
        let indexPath = tableView.indexPathForRow(at: point)
        print(indexPath?.row)
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = fruits[indexPath.row]
        cell.selectionStyle = .none

        let addButton = UIButton(type: .custom)
        addButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        addButton.setImage(UIImage(named: "add"), for: .normal)
        addButton.contentMode = .scaleAspectFit
        addButton.addTarget(self, action: #selector(addFruit(_:)), for: .touchUpInside)
        addButton.sizeToFit()
        cell.accessoryView =  addButton

        return cell
    }

}

I need to show a custom button in cells that search results are shown. So I added a UIButton as the cells' accessoryView. And it looks and works fine.

Now I need to get the cell's indexPath when the user taps on this button.

I'm trying to get it like shown below.

@objc func addFruit(_ sender: UIButton) {
    let point = tableView.convert(sender.bounds.origin, to: sender)
    let indexPath = tableView.indexPathForRow(at: point)
}

But it keeps returning nil for every cell.

Is there any other way to get the indexPath from a custom button tap? I added a demo project here as well.

Body:
I would suggest using this light solution: add indexPath.row to button tag:

let addButton = UIButton(type: .custom)
addButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
addButton.tag = indexPath.row

And in button action:

@objc func addFruit(_ sender: UIButton) {
    print(sender.tag)
}


问:
Get opposite structure field in C++
Let us suppose I have the following structs:

```<code>struct Point
{double _x, _y;};
struct Segment
{Point _p1, _p2;};
typedef Point Segment::* const SegmentEnd;
</code>```

And now I would like to introduce the function which would scale the segment with relation to the SegmentEnd provided. That means change coordinates of the opposite to the provided SegmentEnd. How can I do it?

Here is the code I made to change the provided SegmentEnd, but I need to change the opposite one:

```<code>void scale(Segment& segment, SegmentEnd end, const double& scaleVal)
{
    Point& p(segment.*end);
    p._x = scaleVal*p._x;
    p._y = scaleVal*p._y;
}
</code>```

答:
Couldn't you simply do something like:

```<code>void scale(Segment& segment, bool inverted, const double& scaleVal)
{
    if (!inverted) {
        // scale segment._p1 with respect to segment._p2
    } else {
        // scale segment._p2 with respect to segment._p1
    }
}
</code>```

Then you do not even need to fiddle with the pointers to members.

The param could be an enum ("direction") as well, etc.

You could argue that with the pointer to member you expect to save the branch, but in your case it is not really the case, because you still need to check the addresses to determine which point has been sent.

You could save the branch by providing both points, the scaled one and the other as reference:

```<code>void scale(Segment& segment, SegmentEnd scaled, SegmentEnd reference, const double& scaleVal)
{
    // scale segment.*scaled with reflect to segment.*reference
}
</code>```

and call appropriately:

```<code>scale(segment, Segment::_p1, Segment::_p2, value);
scale(segment, Segment::_p2, Segment::_p1, value);
</code>```

(or to pass the points directly in that case)

Title: Get opposite structure field in C++

Body:
Let us suppose I have the following structs:

struct Point
{double _x, _y;};
struct Segment
{Point _p1, _p2;};
typedef Point Segment::* const SegmentEnd;

And now I would like to introduce the function which would scale the segment with relation to the SegmentEnd provided. That means change coordinates of the opposite to the provided SegmentEnd. How can I do it?

Here is the code I made to change the provided SegmentEnd, but I need to change the opposite one:

void scale(Segment& segment, SegmentEnd end, const double& scaleVal)
{
    Point& p(segment.*end);
    p._x = scaleVal*p._x;
    p._y = scaleVal*p._y;
}

Body:
Couldn't you simply do something like:

void scale(Segment& segment, bool inverted, const double& scaleVal)
{
    if (!inverted) {
        // scale segment._p1 with respect to segment._p2
    } else {
        // scale segment._p2 with respect to segment._p1
    }
}

Then you do not even need to fiddle with the pointers to members.

The param could be an enum ("direction") as well, etc.

You could argue that with the pointer to member you expect to save the branch, but in your case it is not really the case, because you still need to check the addresses to determine which point has been sent.

You could save the branch by providing both points, the scaled one and the other as reference:

void scale(Segment& segment, SegmentEnd scaled, SegmentEnd reference, const double& scaleVal)
{
    // scale segment.*scaled with reflect to segment.*reference
}

and call appropriately:

scale(segment, Segment::_p1, Segment::_p2, value);
scale(segment, Segment::_p2, Segment::_p1, value);

(or to pass the points directly in that case)


问:
how to get every instance of a word( i.e alphanumeric) from a string and change it?
I have a string such as:

```<code>{
    props: {
        options: {
            type: Array
        }
    }
}
</code>```

Now i want to change props into "props" and option into "option" and similarly every word which this whole string might have.

I am doing this because in the original format JSON.parse() is throwing error as this is not in JSON string which should look like this:

```<code>{
    "props": {
        "options": {
            "type": "Array"
        }
    }
}
</code>```

If you have any suggestion don't hesitate to share. Thank you.

答:
Try Below Code :</p>

```<code>var obj = {
            props: {
                options: {
                    type: "name"
                }
            }
        };

    JSON.parse(JSON.stringify(obj));
</code>```

Body:
I have a string such as:

{
    props: {
        options: {
            type: Array
        }
    }
}

Now i want to change props into "props" and option into "option" and similarly every word which this whole string might have.

I am doing this because in the original format JSON.parse() is throwing error as this is not in JSON string which should look like this:

{
    "props": {
        "options": {
            "type": "Array"
        }
    }
}

If you have any suggestion don't hesitate to share. Thank you.

Body:
Try Below Code :

var obj = {
            props: {
                options: {
                    type: "name"
                }
            }
        };

    JSON.parse(JSON.stringify(obj));


问:
Playing sound files one after another in flex AIR code
I have a set of sound clips to be played one after another in a sequence with couple of time interval inbetween.
In my case, its a question - followed by the set of four options.

When I write the below code, all the audop files start together at same time. How can I had time delay inbetween, so that the second clip plays only after the first one is over, and the third one starts playing, only when the second option is over.

I am with Flex AIR AS 3. See code below. Thanks in advance.

```<code>    private function playCoundClips(): void
    {
            //set audio clips

            var questionClipSource : String = "assets/quiz_voiceovers/" + questionCode + "Q.mp3";

            var optionAClipSource : String = "assets/quiz_voiceovers/" + questionCode + "a.mp3";
            var optionBClipSource : String = "assets/quiz_voiceovers/" + questionCode + "b.mp3";
            var optionCClipSource : String = "assets/quiz_voiceovers/" + questionCode + "c.mp3";
            var optionDClipSource : String = "assets/quiz_voiceovers/" + questionCode + "d.mp3";

            playThisClip(questionClipSource);

            playThisClip(optionAClipSource);
            playThisClip(optionBClipSource);

            playThisClip(optionCClipSource);
            playThisClip(optionDClipSource);

    }

    private function playThisClip(clipPath : String) : void
    {
        try
        {
            clipPlayingNow = true;
            var soundReq:URLRequest = new URLRequest(clipPath);
            var sound:Sound = new Sound();
            var soundControl:SoundChannel = new SoundChannel();

            sound.load(soundReq);
            soundControl = sound.play(0, 0);
        }
        catch(err: Error)
        {
            Alert.show(err.getStackTrace());
        }
    }
</code>```

Thanks
Sumit

答:
This helped me
http://livedocs.adobe.com/flex/3/html/help.html?content=Working_with_Sound_09.html

One need to write code for:

```<code>sound.addEventListener(Event.ENTER_FRAME, onEnterFrame);
soundControl.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);

private function onEnterFrame(event:Event):void
{
var estimatedLength:int =
    Math.ceil(sound.length / (sound.bytesLoaded / sound.bytesTotal));

var playbackPercent:uint =
    Math.round(100 * (soundControl.position / estimatedLength));

}

private function onPlaybackComplete(event:Event):void
{
    Alert.show("Hello!");
}
</code>```

Body:
I have a set of sound clips to be played one after another in a sequence with couple of time interval inbetween.
In my case, its a question - followed by the set of four options.

When I write the below code, all the audop files start together at same time. How can I had time delay inbetween, so that the second clip plays only after the first one is over, and the third one starts playing, only when the second option is over.

I am with Flex AIR AS 3. See code below. Thanks in advance.

    private function playCoundClips(): void
    {
            //set audio clips

            var questionClipSource : String = "assets/quiz_voiceovers/" + questionCode + "Q.mp3";

            var optionAClipSource : String = "assets/quiz_voiceovers/" + questionCode + "a.mp3";
            var optionBClipSource : String = "assets/quiz_voiceovers/" + questionCode + "b.mp3";
            var optionCClipSource : String = "assets/quiz_voiceovers/" + questionCode + "c.mp3";
            var optionDClipSource : String = "assets/quiz_voiceovers/" + questionCode + "d.mp3";

            playThisClip(questionClipSource);

            playThisClip(optionAClipSource);
            playThisClip(optionBClipSource);

            playThisClip(optionCClipSource);
            playThisClip(optionDClipSource);

    }

    private function playThisClip(clipPath : String) : void
    {
        try
        {
            clipPlayingNow = true;
            var soundReq:URLRequest = new URLRequest(clipPath);
            var sound:Sound = new Sound();
            var soundControl:SoundChannel = new SoundChannel();

            sound.load(soundReq);
            soundControl = sound.play(0, 0);
        }
        catch(err: Error)
        {
            Alert.show(err.getStackTrace());
        }
    }

Thanks
Sumit

Body:
This helped me
http://livedocs.adobe.com/flex/3/html/help.html?content=Working_with_Sound_09.html

One need to write code for:

sound.addEventListener(Event.ENTER_FRAME, onEnterFrame);
soundControl.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);

private function onEnterFrame(event:Event):void
{
var estimatedLength:int =
    Math.ceil(sound.length / (sound.bytesLoaded / sound.bytesTotal));

var playbackPercent:uint =
    Math.round(100 * (soundControl.position / estimatedLength));

}

private function onPlaybackComplete(event:Event):void
{
    Alert.show("Hello!");
}


问:
Extract a string value from code
I am trying to extract the string : "Plan B Warranty & Breakdown Recovery"

from the following block of code. I am having problems locating it via xpath and get text. I would be grateful for some pointers.

```<code><!DOCTYPE html>
<html class="ng-scope" ng-app="dan">
<head>
<body class="u-scroll-y ng-scope" ng-controller="CoreController as cc">
<div class="c-animate c-animate--show u-pos-f-t ng-hide" ng-show="global.alerts.length">
<div class="o-grid-fluid u-h-100 u-pl-0">
<div class="o-grid__row u-ml-0 u-h-100">
<div class="c-loader ng-hide" ng-show="loadingHome" style="">
<nav class="o-grid__col-xl-2 o-grid__col-lg-3 o-grid__col-xs-4 u-p-0 c-card__block u-h-100 u-shadowed u-pos-f-t ng-scope" ng-if="global.loggedIn">
<div class="u-p-0 u-h-100 o-grid__col-xl-10 o-grid__col-lg-9 o-grid__col-xs-8 u-pull-right" ng-class="{ 'o-grid__col-xl-10 o-grid__col-lg-9 o-grid__col-xs-8 u-pull-right' : global.loggedIn }">
<header class="o-layout-table__row u-bg-primary u-shadowed u-clearfix u-px ng-scope" ng-if="global.loggedIn">
<main class="o-view-container">
<div class="o-grid-fluid u-py-md">
<div class="o-grid__row">
<div class="c-animate c-animate--view-slide-in-right c-animate--view-slide-out-right ng-scope" ng-view="" style="">
<div class="o-grid__col-md-10 o-grid__col-xl-8 o-grid__col-xl-offset-2 o-grid__col-md-offset-1 ng-scope">
<div class="u-mb-lg u-text-center">
<h1 class="u-text-bold">Recommendations</h1>
</div>
<form class="ng-pristine ng-valid ng-valid-min ng-valid-max ng-valid-required" name="recommend" ng-submit="recommend.$valid">
<div class="o-media c-card c-card__block u-shadowed u-mb-lg ng-scope" ng-if="rc.WarrantyEligible && !rc.prevWarranty()">
<label class="c-form-control-label u-px u-py-sm u-w-100">Warranty Options:</label>
<div class="c-form-group u-p-0 u-mb-sm u-clearfix">
<div class="o-grid__col-md-8">
<label class="c-form-control-label u-text-normal">Product Recommendations (Years):</label>
</div>
<div class="o-grid__col-md-4">
<input class="c-form-control ng-pristine ng-untouched ng-valid ng-valid-min ng-valid-max ng-valid-required" required="" placeholder="Years" ng-model="rc.recommend.year" min="1" max="3" type="number">
</div>
</div>
<div class="c-form-group ng-scope" ng-if="!data.answer_taxi">
<label class="c-option c-option--right u-px u-py-sm u-clearfix ng-scope" ng-if="!rc.planA && !rc.prestige" ng-click="cc.utils.audit('recommendation_warranty_plan_b')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.warrantyPlan" value="planB" name="warrantyPlan" type="radio">
<i class="c-option__radio"></i>
Plan B Warranty & Breakdown Recovery
</label>
</div>
</div>
<div class="o-media c-card c-card__block u-shadowed u-mb-lg u-text-body u-bg-success" ng-if="!rc.prevVap() && rc.VapEligible ">
<div class="c-form-group">
<label class="c-form-control-label u-px u-py-sm u-w-100">Vehicle Asset Protection Options:</label>
<label class="c-option c-option--right u-px u-py-sm u-clearfix" ng-click="cc.utils.audit('recommend_vap')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapPlan.plan" value="standard" name="vapPlan" type="radio">
<i class="c-option__radio"></i>
Vehicle Asset Protection - Standard Cover
</label>
<label class="c-option c-option--right u-px u-py-sm u-clearfix" ng-click="cc.utils.audit('vap_key_facts_checked')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapCheck" name="vapCheck" type="checkbox">
<i class="c-option__checkbox"></i>
You confirm that you have received the VAP key facts leaflet?
</label>
</div>
</div>
</form>
<div class="c-form-group">
<input class="c-btn c-btn--primary c-btn--block u-pull-right" value="Complete and Preview" ng-click="rc.complete(recommend.$valid); cc.utils.audit('recommend_complete')" ng-disabled="recommend.$invalid" type="submit">
</div>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js">
<script src="./build/app.js?v=2.13" defer="">
<script src="/build/standalone/jspdf.js" defer="">
<script src="/build/standalone/sigWebTablet.js" defer="">
</body>
</html>
</code>```

ignore this ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

答:
The following xpath worked for me:

```<code>//input[@ng-model='rc.recommend.warrantyPlan']/following-sibling::i[1]
</code>```

It's finding the associated input element, then grabbing the first i element after it.

Title: Extract a string value from code

Body:
I am trying to extract the string : "Plan B Warranty & Breakdown Recovery"

from the following block of code. I am having problems locating it via xpath and get text. I would be grateful for some pointers.

<!DOCTYPE html>

Recommendations

<form class="ng-pristine ng-valid ng-valid-min ng-valid-max ng-valid-required" name="recommend" ng-submit="recommend.$valid">

Warranty Options:

Product Recommendations (Years):

<input class="c-form-control ng-pristine ng-untouched ng-valid ng-valid-min ng-valid-max ng-valid-required" required="" placeholder="Years" ng-model="rc.recommend.year" min="1" max="3" type="number">

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.warrantyPlan" value="planB" name="warrantyPlan" type="radio">

Plan B Warranty & Breakdown Recovery

Vehicle Asset Protection Options:

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapPlan.plan" value="standard" name="vapPlan" type="radio">

Vehicle Asset Protection - Standard Cover

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapCheck" name="vapCheck" type="checkbox">

You confirm that you have received the VAP key facts leaflet?

</form>

<input class="c-btn c-btn--primary c-btn--block u-pull-right" value="Complete and Preview" ng-click="rc.complete(recommend.$valid); cc.utils.audit('recommend_complete')" ng-disabled="recommend.$invalid" type="submit">

Body:
The following xpath worked for me:

//input[@ng-model='rc.recommend.warrantyPlan']/following-sibling::i[1]

It's finding the associated input element, then grabbing the first i element after it.


答:
Please update your code. you pass the UIButton sender in convert function , please pass the tableView into them

```<code>func getIndexPathByCgPoint(_ sender: UIButton) -> IndexPath? {
    let point = sender.convert(sender.bounds.origin, to: tableview)
    guard let indexPath = tableview.indexPathForRow(at: point) else {
        return nil
    }
    return indexPath
}
</code>```

But in case of section header it return nil.

Title: Get the indexpath from custom button in accessoryView of a UITableViewCell

Body:
Please update your code. you pass the UIButton sender in convert function , please pass the tableView into them

func getIndexPathByCgPoint(_ sender: UIButton) -> IndexPath? {
    let point = sender.convert(sender.bounds.origin, to: tableview)
    guard let indexPath = tableview.indexPathForRow(at: point) else {
        return nil
    }
    return indexPath
}

But in case of section header it return nil.


问:
How to force hibernate not to load subentities
I have A and B entities where A can have more Bs

```<code>@Entity
@Table(name = "A")
public class A {

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "b_id", nullable = false, insertable = true, updatable = false)
private Set<B> bs;

}
</code>```

what I need is to say jpa somehow not to load set of Bs in special situations.

I tried it other way around, I defined fetch = FetchType.Lazy and then I say hibernate when i want to load B. Problem is however, that when i do a.getBs(), hibernate loads the bs even when i dont want this behaviour ( I wanted only check if B is loaded or not). It means I need to force hibernate with jpa not to load subentities later (a.getBs()) with lazy load mode OR to force not to load entities with eager load mode.

In jpa there is method Root.fetch(). I would need Root.unfetch()

答:
One way I can think of is to move a out of the method that creates the transaction, and then call a.getBs(). If you have it lazy loaded, it won't be able to fetch it outside of the transaction.

For example:

```<code>@Entity
@Table(name = "A")
public class A {

    // this must be LAZY for this to work
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "b_id", nullable = false, insertable = true, updatable = false)
    private Set<B> bs;

}

...

public void outsideTransaction() {
    A a = getA();

    // a.getBs() will return null if it was never called inside method getA()
    if(a.getBs() == null) {
        // do stuff
    } else {
        // do other stuff
    }
}

public A getA() {
    // transaction starts in this method, however you are handling transactions
    A a = // query for record from table A;

    // do stuff that may or may not involve calling a.getBs()

    return a;
    // transaction ends
}
</code>```

Body:
I have A and B entities where A can have more Bs

@Entity
@Table(name = "A")
public class A {

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "b_id", nullable = false, insertable = true, updatable = false)
private Set bs;

}

what I need is to say jpa somehow not to load set of Bs in special situations.

I tried it other way around, I defined fetch = FetchType.Lazy and then I say hibernate when i want to load B. Problem is however, that when i do a.getBs(), hibernate loads the bs even when i dont want this behaviour ( I wanted only check if B is loaded or not). It means I need to force hibernate with jpa not to load subentities later (a.getBs()) with lazy load mode OR to force not to load entities with eager load mode.

In jpa there is method Root.fetch(). I would need Root.unfetch()

Body:
One way I can think of is to move a out of the method that creates the transaction, and then call a.getBs(). If you have it lazy loaded, it won't be able to fetch it outside of the transaction.

For example:

@Entity
@Table(name = "A")
public class A {

    // this must be LAZY for this to work
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "b_id", nullable = false, insertable = true, updatable = false)
    private Set<B> bs;

}

...

public void outsideTransaction() {
    A a = getA();

    // a.getBs() will return null if it was never called inside method getA()
    if(a.getBs() == null) {
        // do stuff
    } else {
        // do other stuff
    }
}

public A getA() {
    // transaction starts in this method, however you are handling transactions
    A a = // query for record from table A;

    // do stuff that may or may not involve calling a.getBs()

    return a;
    // transaction ends
}


问:
Relative layout params in kotlin
I am trying to set relative layout params programmatically. I can set params using java but not know how to accomplish using kotlin. So what I have tried is as follows :

MainActivity class

```<code>    class MainActivity : AppCompatActivity() {

    lateinit var context : Context
    override fun onCreate(savedInstanceState: android.os.Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context=this
        asdasd.text="finaly done";
   var  param:RelativeLayout.LayoutParams =//don't know what to do here
            val i:Int=1
            var temp :TextView = TextView(this);
            temp.id=i
            temp.layoutParams = param ;
            temp.text= "TextView"+i
            Log.e(ContentValues.TAG, "onCreate: " + i)

    }
}
</code>```

Any help is appreciated!

答:
It work for me::

```<code>    var  param: RelativeLayout.LayoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,100);
    param.setMargins(500,12,0,0)
    val i:Int=1
    var temp : TextView = TextView(this);
    temp.id=i
    temp.layoutParams = param ;
    temp.text= "TextView\nadfadsfasdfadsfasdf\nadfadsfasdfa\nadfadsfasdf"+i
    Log.e(ContentValues.TAG, "onCreate: " + i)
</code>```

See here ouput Generated by it:

Thanks and let me know if you need more.

Title: Relative layout params in kotlin

Body:
I am trying to set relative layout params programmatically. I can set params using java but not know how to accomplish using kotlin. So what I have tried is as follows :

MainActivity class

    class MainActivity : AppCompatActivity() {

    lateinit var context : Context
    override fun onCreate(savedInstanceState: android.os.Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context=this
        asdasd.text="finaly done";
   var  param:RelativeLayout.LayoutParams =//don't know what to do here
            val i:Int=1
            var temp :TextView = TextView(this);
            temp.id=i
            temp.layoutParams = param ;
            temp.text= "TextView"+i
            Log.e(ContentValues.TAG, "onCreate: " + i)

    }
}

Any help is appreciated!

Body:
It work for me::

    var  param: RelativeLayout.LayoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,100);
    param.setMargins(500,12,0,0)
    val i:Int=1
    var temp : TextView = TextView(this);
    temp.id=i
    temp.layoutParams = param ;
    temp.text= "TextView\nadfadsfasdfadsfasdf\nadfadsfasdfa\nadfadsfasdf"+i
    Log.e(ContentValues.TAG, "onCreate: " + i)

See here ouput Generated by it:

Thanks and let me know if you need more.


问:
Which action(s) can I use to create a folder in SharePoint Online via Azure Logic App?
As question title states, I am looking for a proper action in Logic Apps to create a folder. This action will be executed several times -- once per directory as per business rule. There will be no files created in these folders because the intent of the Logic App is to prepare a template folder structure for the users' needs.

In the official documentation I see that there are create file, create item, and list folder actions. They suggest that there might be an action to create a folder too (which I can't find).

If such action does not exist, I may need to use some SharePoint Online API, but that will be a last resort solution.

答:
Correct, so far the SharePoint Connector does not support Folder management tasks.

So, your best option currently is to use the SharePoint API or client libraries in an API or Function App.


问:
Create chat message layout
I have a problem with my chat message Layout in Android.

I have 3 custom textview, but the Time of textView should be set on Bottom and Right align.

Here is my screenshot:

And here is my code:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="60dp"
    android:background="@drawable/msg_in"
    android:orientation="vertical">

    <com.fearefull.chatstory.Widgets.MyTextView
        android:id="@+id/nickname_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="none"
        android:layout_alignParentLeft="true"
        android:paddingBottom="7dp"
        android:paddingLeft="16dp"
        android:paddingRight="12dp"
        android:paddingTop="5dp"
        android:text="adawd awdaw"
        android:textStyle="bold"
        android:textColor="@android:color/holo_green_light"
        android:textSize="18sp"
        tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:autoLink="none"
            android:paddingBottom="7dp"
            android:paddingLeft="16dp"
            android:paddingRight="12dp"
            android:paddingTop="5dp"
            android:text="dlsadfafawfafawawfawf a fawfawfafafkawmflaknfalfntigtggt"
            android:textColor="@android:color/black"
            android:textSize="17sp"
            tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="11:15 PM"
            android:textColor="#a6abad"
            android:textSize="12sp"
            android:layout_alignBottom="@id/textview_message"
            android:layout_alignParentRight="true"
            android:padding="5dp"
            tools:ignore="RtlHardcoded" />
    </RelativeLayout>

</LinearLayout>
```

I used any Alignment for my Time of textView, but it didn't work.

答:
Try this one </p>

```<code> <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="60dp"
        android:background="@drawable/msg_in"
        android:orientation="vertical">

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/nickname_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:autoLink="none"
            android:layout_alignParentLeft="true"
            android:paddingBottom="7dp"
            android:paddingLeft="16dp"
            android:paddingRight="12dp"
            android:paddingTop="5dp"
            android:text="adawd awdaw"
            android:textStyle="bold"
            android:textColor="@android:color/holo_green_light"
            android:textSize="18sp"
            tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <com.fearefull.chatstory.Widgets.MyTextView
                android:id="@+id/textview_message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autoLink="none"
                android:paddingBottom="7dp"
                android:paddingLeft="16dp"
                android:paddingRight="12dp"
                android:paddingTop="5dp"
                android:layout_toLeftOf="@+id/textview_time"
                android:text="dlsadfafawfafawawfawf a fawfawfafafkawmflaknfalfntigtggt"
                android:textColor="@android:color/black"
                android:textSize="17sp"
                tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

            <com.fearefull.chatstory.Widgets.MyTextView
                android:id="@+id/textview_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="11:15 PM"
                android:textColor="#a6abad"
                android:textSize="12sp"
                android:layout_alignBottom="@id/textview_message"
                android:layout_alignParentRight="true"
                android:padding="5dp"
                tools:ignore="RtlHardcoded" />
        </RelativeLayout>

    </LinearLayout>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Create chat message layout

Body:
I have a problem with my chat message Layout in Android.

I have 3 custom textview, but the Time of textView should be set on Bottom and Right align.

Here is my screenshot:

And here is my code:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="60dp"
    android:background="@drawable/msg_in"
    android:orientation="vertical">

    <com.fearefull.chatstory.Widgets.MyTextView
        android:id="@+id/nickname_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="none"
        android:layout_alignParentLeft="true"
        android:paddingBottom="7dp"
        android:paddingLeft="16dp"
        android:paddingRight="12dp"
        android:paddingTop="5dp"
        android:text="adawd awdaw"
        android:textStyle="bold"
        android:textColor="@android:color/holo_green_light"
        android:textSize="18sp"
        tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:autoLink="none"
            android:paddingBottom="7dp"
            android:paddingLeft="16dp"
            android:paddingRight="12dp"
            android:paddingTop="5dp"
            android:text="dlsadfafawfafawawfawf a fawfawfafafkawmflaknfalfntigtggt"
            android:textColor="@android:color/black"
            android:textSize="17sp"
            tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="11:15 PM"
            android:textColor="#a6abad"
            android:textSize="12sp"
            android:layout_alignBottom="@id/textview_message"
            android:layout_alignParentRight="true"
            android:padding="5dp"
            tools:ignore="RtlHardcoded" />
    </RelativeLayout>

</LinearLayout>

I used any Alignment for my Time of textView, but it didn't work.

Body:
Try this one

 <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="60dp"
        android:background="@drawable/msg_in"
        android:orientation="vertical">

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/nickname_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:autoLink="none"
            android:layout_alignParentLeft="true"
            android:paddingBottom="7dp"
            android:paddingLeft="16dp"
            android:paddingRight="12dp"
            android:paddingTop="5dp"
            android:text="adawd awdaw"
            android:textStyle="bold"
            android:textColor="@android:color/holo_green_light"
            android:textSize="18sp"
            tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <com.fearefull.chatstory.Widgets.MyTextView
                android:id="@+id/textview_message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autoLink="none"
                android:paddingBottom="7dp"
                android:paddingLeft="16dp"
                android:paddingRight="12dp"
                android:paddingTop="5dp"
                android:layout_toLeftOf="@+id/textview_time"
                android:text="dlsadfafawfafawawfawf a fawfawfafafkawmflaknfalfntigtggt"
                android:textColor="@android:color/black"
                android:textSize="17sp"
                tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

            <com.fearefull.chatstory.Widgets.MyTextView
                android:id="@+id/textview_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="11:15 PM"
                android:textColor="#a6abad"
                android:textSize="12sp"
                android:layout_alignBottom="@id/textview_message"
                android:layout_alignParentRight="true"
                android:padding="5dp"
                tools:ignore="RtlHardcoded" />
        </RelativeLayout>

    </LinearLayout>


问:
How to have Mysql query (with multiple join) faster and more efficient
I have a big problem with the execution of a MySql query that is very slow.. too slow... unusable!

To read 1000 products with their prices it takes more than 20 seconds!!!

```<code>$dati = mysqli_query($mysqli_connect, "
SELECT      *
FROM        $tb_products
LEFT JOIN   $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN   $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN   $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master

LEFT JOIN   $tb_prices ON (
            $tb_products.product_brand = $tb_prices.price_brand
            AND $tb_products.product_code = $tb_prices.price_code
            AND $tb_prices.price_validity = (
                SELECT  MAX($tb_prices.price_validity)
                FROM    $tb_prices
                WHERE   $tb_prices.price_validity<=DATE_ADD(CURDATE(), INTERVAL +0 DAY)
                        AND $tb_products.product_code = $tb_prices.price_code
            )
        )

WHERE       $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY    $tb_products.product_code
ORDER BY    $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");
</code>```

EDIT:

I've changed, as suggested from Mr.Alvaro, the SELECT * with a more efficient SELECT [list of values] and the execution time dropped from 20 seconds to 14 seconds. Still too slow...

END EDIT

Each product can have different prices, so I use the (select max...) to take the most recent (but not future) price.
Maybe is this function that slow down everything? Are there better solutions in your opinion?

Consider that the same query without the join with the prices it takes only 0.2 seconds.
So I'm convinced that the problem is all in that part of the code.

```<code>$dati = mysqli_query($mysqli_connect, "
SELECT      *
FROM        $tb_products
LEFT JOIN   $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN   $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN   $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master

WHERE       $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY    $tb_products.product_code
ORDER BY    $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");
</code>```

I also considered the fact that it could depend on the power of the server but I would tend to exclude it because the second query (without prices) is quite acceptable as speed.

The prices table is as following

```<code>+----------------+-------------+
| price_id       | int(3)      |
| price_brand    | varchar(5)  |
| price_code     | varchar(50) |
| price_value    | float(10,2) |
| price_validity | date        |
| price_language | varchar(2)  |
+----------------+-------------+
</code>```

答:
SOLVED

The problem was in the last JOIN with the prices table.
Following the suggestions I managed to execute the SELECT MAX (...) separately and it tooks 0.1 seconds to execute.

So I decide to run the main query without the prices and then, in the WHILE cicle to fetch the array, I run a second query to take the price for every single product!
This work perfectly and my page has dropped down from 20 seconds to a few tenths of a second.

So, the code become something like this:

```<code>$dati = mysqli_query($mysqli_connect, "
SELECT      *
FROM        $tb_products
LEFT JOIN   $tb_categories ON $tb_products.product_category =     $tb_categories.category_id_master
LEFT JOIN   $tb_subcategories ON $tb_products.product_subcategory =     $tb_subcategories.subcategory_id_master
LEFT JOIN   $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master

WHERE       $tb_products.product_language='$activeLanguage' AND     $tb_products.product_category!=0
GROUP BY    $tb_products.product_code
ORDER BY    $tb_products.product_brand, $tb_categories.category_rank,     $tb_subcategories.subcategory_rank, $tb_products.product_subcategory,     $tb_products.product_rank
");
</code>```

and then..

```<code>while ($array = mysqli_fetch_array($dati)) {

    $code = $array['product_code'];

    $dati_prices = mysqli_query($mysqli_connect, "
    SELECT  *
    FROM    $tb_prices
    WHERE   $tb_prices.price_brand = '$brand' AND $tb_prices.price_code = '$code' AND $tb_prices.price_validity = (
            SELECT  MAX($tb_prices.price_validity)
            FROM    $tb_prices
            WHERE   $tb_prices.price_validity<=DATE_ADD(CURDATE(), INTERVAL +0 DAY) AND $tb_prices.price_code = '$code'
    )
    GROUP BY    $tb_prices.price_code
    ") ;

}
</code>```

Probably is not the best and elegant solution but for me works pretty well!

Body:
I have a big problem with the execution of a MySql query that is very slow.. too slow... unusable!

To read 1000 products with their prices it takes more than 20 seconds!!!

$dati = mysqli_query($mysqli_connect, "
SELECT      *
FROM        $tb_products
LEFT JOIN   $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN   $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN   $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master

LEFT JOIN   $tb_prices ON (
            $tb_products.product_brand = $tb_prices.price_brand
            AND $tb_products.product_code = $tb_prices.price_code
            AND $tb_prices.price_validity = (
                SELECT  MAX($tb_prices.price_validity)
                FROM    $tb_prices
                WHERE   $tb_prices.price_validity<=DATE_ADD(CURDATE(), INTERVAL +0 DAY)
                        AND $tb_products.product_code = $tb_prices.price_code
            )
        )

WHERE       $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY    $tb_products.product_code
ORDER BY    $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");

EDIT:

I've changed, as suggested from Mr.Alvaro, the SELECT * with a more efficient SELECT [list of values] and the execution time dropped from 20 seconds to 14 seconds. Still too slow...

END EDIT

Each product can have different prices, so I use the (select max...) to take the most recent (but not future) price.
Maybe is this function that slow down everything? Are there better solutions in your opinion?

Consider that the same query without the join with the prices it takes only 0.2 seconds.
So I'm convinced that the problem is all in that part of the code.

$dati = mysqli_query($mysqli_connect, "
SELECT      *
FROM        $tb_products
LEFT JOIN   $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN   $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN   $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master

WHERE       $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY    $tb_products.product_code
ORDER BY    $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");

I also considered the fact that it could depend on the power of the server but I would tend to exclude it because the second query (without prices) is quite acceptable as speed.

The prices table is as following

+----------------+-------------+
| price_id       | int(3)      |
| price_brand    | varchar(5)  |
| price_code     | varchar(50) |
| price_value    | float(10,2) |
| price_validity | date        |
| price_language | varchar(2)  |
+----------------+-------------+

Body:
SOLVED

The problem was in the last JOIN with the prices table.
Following the suggestions I managed to execute the SELECT MAX (...) separately and it tooks 0.1 seconds to execute.

So I decide to run the main query without the prices and then, in the WHILE cicle to fetch the array, I run a second query to take the price for every single product!
This work perfectly and my page has dropped down from 20 seconds to a few tenths of a second.

So, the code become something like this:

$dati = mysqli_query($mysqli_connect, "
SELECT      *
FROM        $tb_products
LEFT JOIN   $tb_categories ON $tb_products.product_category =     $tb_categories.category_id_master
LEFT JOIN   $tb_subcategories ON $tb_products.product_subcategory =     $tb_subcategories.subcategory_id_master
LEFT JOIN   $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master

WHERE       $tb_products.product_language='$activeLanguage' AND     $tb_products.product_category!=0
GROUP BY    $tb_products.product_code
ORDER BY    $tb_products.product_brand, $tb_categories.category_rank,     $tb_subcategories.subcategory_rank, $tb_products.product_subcategory,     $tb_products.product_rank
");

and then..

while ($array = mysqli_fetch_array($dati)) {

    $code = $array['product_code'];

    $dati_prices = mysqli_query($mysqli_connect, "
    SELECT  *
    FROM    $tb_prices
    WHERE   $tb_prices.price_brand = '$brand' AND $tb_prices.price_code = '$code' AND $tb_prices.price_validity = (
            SELECT  MAX($tb_prices.price_validity)
            FROM    $tb_prices
            WHERE   $tb_prices.price_validity<=DATE_ADD(CURDATE(), INTERVAL +0 DAY) AND $tb_prices.price_code = '$code'
    )
    GROUP BY    $tb_prices.price_code
    ") ;

}

Probably is not the best and elegant solution but for me works pretty well!


问:
delete csv's in different folders
I have a lot of files in different folders that I need to delete.

Generally I have been using:

```<code>  try:
        for file in ['C:\\14\\13.csv', 'C:\\54\\13.csv', 'C:\\64\\14.csv', 'C:\\44\\55.csv']
                os.remove(file)
    except OSError as e:
        pass
</code>```

However, if it can't find a file it just moves on to the next part of the script which means it is not a good solution.   I need to delete all the files.  Any idea how this can be achieved?  Perhaps using a different try, except?

Thanks.

答:
Move the try block inside the loop like this:

```<code>for file in [r'C:\14\13.csv', r'C:\54\13.csv', r'C:\64\14.csv', r'C:\44\55.csv']:
    try:
        os.remove(file)
    except Exception as e: # catch all exceptions
        pass
</code>```

Title: delete csv's in different folders

Body:
I have a lot of files in different folders that I need to delete.

Generally I have been using:

  try:
        for file in ['C:\\14\\13.csv', 'C:\\54\\13.csv', 'C:\\64\\14.csv', 'C:\\44\\55.csv']
                os.remove(file)
    except OSError as e:
        pass

However, if it can't find a file it just moves on to the next part of the script which means it is not a good solution.   I need to delete all the files.  Any idea how this can be achieved?  Perhaps using a different try, except?

Thanks.

Body:
Move the try block inside the loop like this:

for file in [r'C:\14\13.csv', r'C:\54\13.csv', r'C:\64\14.csv', r'C:\44\55.csv']:
    try:
        os.remove(file)
    except Exception as e: # catch all exceptions
        pass


答:
Using the simple regex (\w+): along with the JavaScript string prototype replace function, you're able to replace all instances of the key to be enclosed in single quotes.

Here's an example:

let str = `{
    props: {
        options: {
            type: Array
        }
    }
}`;
str = str.replace(/(\w+):/g, (match, key) => {
 return "'"+key+"':";
});
console.log(str);```
</div>
</div>
</p>

<p>And to convert it to a JavaScript object:</p>

```let obj = JSON.parse(str);
```

Title: how to get every instance of a word( i.e alphanumeric) from a string and change it?

Body:
I have a string such as:

{
    props: {
        options: {
            type: Array
        }
    }
}

Now i want to change props into "props" and option into "option" and similarly every word which this whole string might have.

I am doing this because in the original format JSON.parse() is throwing error as this is not in JSON string which should look like this:

{
    "props": {
        "options": {
            "type": "Array"
        }
    }
}

If you have any suggestion don't hesitate to share. Thank you.

Body:
Using the simple regex (\w+): along with the JavaScript string prototype replace function, you're able to replace all instances of the key to be enclosed in single quotes.

Here's an example:

let str = `{
    props: {
        options: {
            type: Array
        }
    }
}`;
str = str.replace(/(\w+):/g, (match, key) => {
 return "'"+key+"':";
});
console.log(str);

And to convert it to a JavaScript object:

let obj = JSON.parse(str);


问:
How to provide table name from textbox to Linq
I want to give table name from textbox to Linq :

```<code>      StudentDatabaseEntities empl = new StudentDatabaseEntities();

        var query = from g in empl.Teachers
                    where g.id == 1
                    select new
                    {
                        Teacher_Id = g.tech_id,
                        Teacher_Name = g.username,
                        Teach_password = g.password,
                        Teacher_contact = g.contact,
                        Teacher_secret = g.secret,

                        //Administrator_Id = g.Administrator.id,

                        Administrator_Name = g.Administrator.username,
                        Administrator_password=g.Administrator.password,
                        Administrator_contact=g.Administrator.contact,
                        Administrator_secret=g.Administrator.secret
                        //etc...
                    };
        dataGridView1.DataSource = query.ToList();
</code>```

In this example I want to give table name from textbox instead of Teacher .
Is it possible ?

答:
You can't/it doesn't make sense to violate type safety in this way:

```<code>from g in myTextbox.Text
where g.id == 1
</code>```

What are you going to write in the textbox? "empl.Teachers"?

What if I wrote "empl.Students", or "go away". What will your program do then?

If you have multiple collections of Teachers, you could do something like this:

```<code>var teachers = new Dictionary<string, (type of your teacher collection)>();
teachers["empl"] = empl.Teachers;
teachers["empl2"] = empl2.Teachers;

from g in teachers[myTextbox.Text]
where g.id == 1
</code>```

And then you can write "empl" or "empl2" in your textbox.. But that doesn't really gel with your expectation of "writing the database table name in the textbox"

Body:
I want to give table name from textbox to Linq :

      StudentDatabaseEntities empl = new StudentDatabaseEntities();

        var query = from g in empl.Teachers
                    where g.id == 1
                    select new
                    {
                        Teacher_Id = g.tech_id,
                        Teacher_Name = g.username,
                        Teach_password = g.password,
                        Teacher_contact = g.contact,
                        Teacher_secret = g.secret,

                        //Administrator_Id = g.Administrator.id,

                        Administrator_Name = g.Administrator.username,
                        Administrator_password=g.Administrator.password,
                        Administrator_contact=g.Administrator.contact,
                        Administrator_secret=g.Administrator.secret
                        //etc...
                    };
        dataGridView1.DataSource = query.ToList();

In this example I want to give table name from textbox instead of Teacher .
Is it possible ?

Body:
You can't/it doesn't make sense to violate type safety in this way:

from g in myTextbox.Text
where g.id == 1

What are you going to write in the textbox? "empl.Teachers"?

What if I wrote "empl.Students", or "go away". What will your program do then?

If you have multiple collections of Teachers, you could do something like this:

var teachers = new Dictionary<string, (type of your teacher collection)>();
teachers["empl"] = empl.Teachers;
teachers["empl2"] = empl2.Teachers;

from g in teachers[myTextbox.Text]
where g.id == 1

And then you can write "empl" or "empl2" in your textbox.. But that doesn't really gel with your expectation of "writing the database table name in the textbox"


问:
Java portlet: how to redirect (server side) to serveResource?
(disclaimer: I'm new to portlet development)

I created portlet (in liferay) to serve files. But user first need to fill small form (name, etc.) and then after clicking "save" I put data do database and should serve the file for download.

I do know how to serve file with:

```<code>@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
</code>```

and save data with action:

```<code>@ProcessAction(name = "save")
public void save(ActionRequest actionRequest, ActionResponse actionResponse)
</code>```

But don't know how to server.transfer from one to another. I can't just call:

```<code>serveResource(actionRequest, actionResponse);
</code>```

because parameters are not compatible.

Also on error I should do:

```<code>PortalUtil.copyRequestParameters(actionRequest, actionResponse);
actionResponse.setRenderParameter("mvcPath", "/myForm.jsp");
</code>```

which is not available for resourceRequest/resourceResponse...

What is proper/elegant way for this kind of redirections in portlets?

答:
For saving forms instead of using processAction, you can directly call the serveResource and save form and serve file from serve method itself.

You can also take help of Ajax request to submit form.

```<code><form action="<portlet:resourceURL/>" method="POST">
...
</form>
</code>```

```<code>@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse){

//Save_form

  if(success){
      //serveFile
      String documentPath = document.getDocumentPath();

      File file = getFile(documentPath);

      String contentType = MimeTypesUtil.getContentType(file);

      long contentLength = file.length();

      is = new FileInputStream(file);

      ServletResponseUtil.sendFile(
          request, response, document.getDocumentName(), is, contentLength, contentType,
          HttpHeaders.CONTENT_DISPOSITION_INLINE);

  }else{

      response.getOutputStream("Error submitting form");
      response.getOutputStream().flush();
  }

}
</code>```

Body:
(disclaimer: I'm new to portlet development)

I created portlet (in liferay) to serve files. But user first need to fill small form (name, etc.) and then after clicking "save" I put data do database and should serve the file for download.

I do know how to serve file with:

@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)

and save data with action:

@ProcessAction(name = "save")
public void save(ActionRequest actionRequest, ActionResponse actionResponse)

But don't know how to server.transfer from one to another. I can't just call:

serveResource(actionRequest, actionResponse);

because parameters are not compatible.

Also on error I should do:

PortalUtil.copyRequestParameters(actionRequest, actionResponse);
actionResponse.setRenderParameter("mvcPath", "/myForm.jsp");

which is not available for resourceRequest/resourceResponse...

What is proper/elegant way for this kind of redirections in portlets?

Body:
For saving forms instead of using processAction, you can directly call the serveResource and save form and serve file from serve method itself.

You can also take help of Ajax request to submit form.

<form action="<portlet:resourceURL/>" method="POST">
...
</form>

@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse){

//Save_form

  if(success){
      //serveFile
      String documentPath = document.getDocumentPath();

      File file = getFile(documentPath);

      String contentType = MimeTypesUtil.getContentType(file);

      long contentLength = file.length();

      is = new FileInputStream(file);

      ServletResponseUtil.sendFile(
          request, response, document.getDocumentName(), is, contentLength, contentType,
          HttpHeaders.CONTENT_DISPOSITION_INLINE);

  }else{

      response.getOutputStream("Error submitting form");
      response.getOutputStream().flush();
  }

}


答:
```<code>var view: RelativeLayout =RelativeLayout(this)
view.layoutParams= RelativeLayout.LayoutParams(25,25)
</code>```

<p>Try This one ... </p>

Title: Relative layout params in kotlin

Body:
var view: RelativeLayout =RelativeLayout(this)
view.layoutParams= RelativeLayout.LayoutParams(25,25)

Try This one ...


问:
Dynamic table design (common lookup table), need a nice query to get the values
sql2005

This is my simplified example:
(in reality there are 40+ tables in here, I only showed 2)

I got a table called tb_modules, with 3 columns (id, description, tablename as varchar):

```<code> 1, UserType, tb_usertype
 2, Religion, tb_religion
</code>```

(Last column is actually the name of a different table)

I got an other table that looks like this:
tb_value (columns:id, tb_modules_ID, usertype_OR_religion_ID)
values:

```<code> 1111, 1, 45
 1112, 1, 55
 1113, 2, 123
 1114, 2, 234
</code>```

so, I mean 45, 55, 123, 234 are usertype OR religion ID's
(45, 55 usertype, 123, 234 religion ID`s)

Don't judge, I didn't design the database

Question
How can I make a select, showing * from tb_value, plus one column
That one column would be TITLE from the tb_usertype or RELIGIONNAME from the tb_religion table

I would like to make a general thing.
Was thinking initially about maybe a SQL function that returns a string, but I think I would need dynamic SQL, which is not ok in a function.

Anyone a better idea ?

答:
To do this dynamically you need to be able to create a sql statement that looks like this

```<code>select tb_value.*, tb_usertype.title as Descr
from tb_value
    inner join tb_usertype
        on tb_value.extid = tb_usertype.id
where tb_value.tb_module_id = 1
union all
select tb_value.*, tb_religion.religionname as Descr
from tb_value
    inner join tb_religion
        on tb_value.extid = tb_religion.id
where tb_value.tb_module_id = 2
-- union 40 other tables
</code>```

Currently you can not do that because you do not have any information in the db telling you which column to use from tb_religion and tb_usertype etc. You can add that as a new field in tb_module.

If you have fieldname to use in tb_module you can build a view that does what you want.
And you could add a trigger to table tb_modules that alters the view whenever tb_modules is modified. That way you do not need to use dynamic sql from the client when doing queries. The only thing you need to worry about is that the table needs to be created in the db before you add a new row to tb_modules

Edit 1
Of course the code in the trigger needs to dynamically build the alter view statement.

Edit 2 You also need to have a field with information about what column in tb_usertype and tb_religion etc. to join against tb_value.extid (usertype_OR_religion_ID). Or you can assume that the field will always be called id

Edit 3 Here is how you could build the trigger on tb_module that alters the view v_values. I have added fieldname as a column in tb_modules and I assume that the id field in the related tables is called id.

```<code>create trigger tb_modules_change on tb_modules after insert, delete, update
as

declare @sql nvarchar(max)
declare @moduleid int
declare @tablename varchar(50)
declare @fieldname varchar(50)

set @sql = 'alter view v_value as '

declare mcur cursor for
  select id, tablename, fieldname
  from tb_modules

open mcur
fetch next from mcur into @moduleid, @tablename, @fieldname
while @@FETCH_STATUS = 0
begin
    set @sql = @sql + 'select tb_value.*, '+@tablename+'.'+@fieldname+' '+
                      'from tb_value '+
                      'inner join '+@tablename+' '+
                        'on tb_value.extid = '+@tablename+'.id '+
                      'where tb_value.tb_module_id = '+cast(@moduleid as varchar(10))
  fetch next from mcur into @moduleid, @tablename, @fieldname

  if @@FETCH_STATUS = 0
  begin
    set @sql = @sql + ' union all '
  end
end
close mcur
deallocate mcur

exec sp_executesql @sql
</code>```

Body:
sql2005

This is my simplified example:
(in reality there are 40+ tables in here, I only showed 2)

I got a table called tb_modules, with 3 columns (id, description, tablename as varchar):

 1, UserType, tb_usertype
 2, Religion, tb_religion

(Last column is actually the name of a different table)

I got an other table that looks like this:
tb_value (columns:id, tb_modules_ID, usertype_OR_religion_ID)
values:

 1111, 1, 45
 1112, 1, 55
 1113, 2, 123
 1114, 2, 234

so, I mean 45, 55, 123, 234 are usertype OR religion ID's
(45, 55 usertype, 123, 234 religion ID`s)

Don't judge, I didn't design the database

Question
How can I make a select, showing * from tb_value, plus one column
That one column would be TITLE from the tb_usertype or RELIGIONNAME from the tb_religion table

I would like to make a general thing.
Was thinking initially about maybe a SQL function that returns a string, but I think I would need dynamic SQL, which is not ok in a function.

Anyone a better idea ?

Body:
To do this dynamically you need to be able to create a sql statement that looks like this

select tb_value.*, tb_usertype.title as Descr
from tb_value
    inner join tb_usertype
        on tb_value.extid = tb_usertype.id
where tb_value.tb_module_id = 1
union all
select tb_value.*, tb_religion.religionname as Descr
from tb_value
    inner join tb_religion
        on tb_value.extid = tb_religion.id
where tb_value.tb_module_id = 2
-- union 40 other tables

Currently you can not do that because you do not have any information in the db telling you which column to use from tb_religion and tb_usertype etc. You can add that as a new field in tb_module.

If you have fieldname to use in tb_module you can build a view that does what you want.
And you could add a trigger to table tb_modules that alters the view whenever tb_modules is modified. That way you do not need to use dynamic sql from the client when doing queries. The only thing you need to worry about is that the table needs to be created in the db before you add a new row to tb_modules

Edit 1
Of course the code in the trigger needs to dynamically build the alter view statement.

Edit 2 You also need to have a field with information about what column in tb_usertype and tb_religion etc. to join against tb_value.extid (usertype_OR_religion_ID). Or you can assume that the field will always be called id

Edit 3 Here is how you could build the trigger on tb_module that alters the view v_values. I have added fieldname as a column in tb_modules and I assume that the id field in the related tables is called id.

create trigger tb_modules_change on tb_modules after insert, delete, update
as

declare @sql nvarchar(max)
declare @moduleid int
declare @tablename varchar(50)
declare @fieldname varchar(50)

set @sql = 'alter view v_value as '

declare mcur cursor for
  select id, tablename, fieldname
  from tb_modules

open mcur
fetch next from mcur into @moduleid, @tablename, @fieldname
while @@FETCH_STATUS = 0
begin
    set @sql = @sql + 'select tb_value.*, '+@tablename+'.'+@fieldname+' '+
                      'from tb_value '+
                      'inner join '+@tablename+' '+
                        'on tb_value.extid = '+@tablename+'.id '+
                      'where tb_value.tb_module_id = '+cast(@moduleid as varchar(10))
  fetch next from mcur into @moduleid, @tablename, @fieldname

  if @@FETCH_STATUS = 0
  begin
    set @sql = @sql + ' union all '
  end
end
close mcur
deallocate mcur

exec sp_executesql @sql


问:
Random number generator two digit
```<code>package com.nusecond.Code;
import java.util.*;

public class Code {

    public static void main(String args[]){

        Random random=new Random();
        for(int j=10;j<=99;j++){
           int num=random.nextInt(100) ;
           //ssLong i=System.currentTimeMillis();
           //String result = String.format("%04d", i % 10000);
           System.out.println("Code generated:"  +num);
        }
    }
}
</code>```

I want to print two digit random numbers between 10 and 99.

Note : I want only one number every time I run the program.

答:
Random random = new Random();

// generate a random integer from 10 to 90 i.e 2 digit random no.

```<code>int abc =  10+random.nextInt(90);
</code>```

Title: Random number generator two digit

Body:
package com.nusecond.Code;
import java.util.*;

public class Code {

    public static void main(String args[]){

        Random random=new Random();
        for(int j=10;j<=99;j++){
           int num=random.nextInt(100) ;
           //ssLong i=System.currentTimeMillis();
           //String result = String.format("%04d", i % 10000);
           System.out.println("Code generated:"  +num);
        }
    }
}

I want to print two digit random numbers between 10 and 99.

Note : I want only one number every time I run the program.

Body:
Random random = new Random();

// generate a random integer from 10 to 90 i.e 2 digit random no.

int abc =  10+random.nextInt(90);


问:
Cannot logout and login as a different Facebook user in ionic 3?
I implemented social media logins like Facebook,google,twitter  using fire-base and ionic 3 with the following link reference.

https://firebase.google.com/docs/auth/web/cordova.

first time i successfully log in with my Facebook account credentials and when i logged out using firebase.auth().signOut() and try to login with different Facebook account, instead of showing login screen in the browser it automatically logged in with previous Facebook account details that I just logged out.

same issue for the all the social media logins. I want the browser to show the login page every time for Facebook instead of automatic login.
Please help me out to solve the problem.

答:
You may implement "logout" option

```<code>firebase.auth().signOut().then(function() {
  // Sign-out successful.
}, function(error) {
  // An error happened.
});
</code>```

https://firebase.google.com/docs/auth/web/password-auth#next_steps

Body:
You may implement "logout" option

firebase.auth().signOut().then(function() {
  // Sign-out successful.
}, function(error) {
  // An error happened.
});

https://firebase.google.com/docs/auth/web/password-auth#next_steps


问:
What does the "Changed Files" pane of the VCS "Log Tab" of WebStorm show for merged commit in Git
The documentation for the "Changed Files" pane of log tab states that:

The Changed Files pane is located on the right of the tool window and
  shows the list of files that were modified within the selected commit.

I'm wondering however what it shows for the merge commit?

For example, I have the following history:

and when the  merge branch 'l' is selected the "changed files" pane is empty.

The diff for merge branch 'l' with i2 shows one modified file a.txt, and the diff for merge branch 'l' with l1 shows one modified file a.txt and one added file c.txt. So the `Change Files" pane doesn't show these differences.

I've done some experiments and it seems that the pane shows files that conflicted during the merge and were not resolved using content from either of the conflicting sides but rather were resolved with custom content different from any of the branch commits involved in the merge. Is it so?

答:
Until 2017.3, for the merge commits it showed the diff introduced inside this merge commit (just like git show).

In 2017.3 a new feature was added to show differences compared to each parent https://youtrack.jetbrains.com/issue/IDEA-148143


问:
How to avoid server call using javascript URL routing without large framework?
Is it possible to somehow create a browser history urlpath, so that I can make my javascript create and reuse browsercache WITHOUT having to route to the server first ?

Link to /about = clientside creates the page and use that one, without server ever knowing about it.

If it is possible, can anyone please write a simple example that works ?
With no framework..

Thanks in advance

答: if you are looking for a plugin give Navigo a try.</p>