问:
could not find Factory: javax.faces.context.FacesContextFactory
I notice that when trying to setup my JSF 2 webapp running on jetty, i have this error :

java.lang.IllegalStateException: Application was not properly
  initialized at startup, could not find Factory:
  javax.faces.context.FacesContextFactory

which is easily solved by adding this to my web.xml

```<code><listener>
    <listener-class>
        com.sun.faces.config.ConfigureListener
    </listener-class>
</listener>
</code>```

I've tried searching for a detailed explanation but in futile ..

jetty-maven-plugin:8.0.3.v20111011:run + jdk 7 + eclipse indigo

And here's my maven dependency :

```<code><dependencies>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.faces</artifactId>
        <version>2.1.3</version>
        <scope>compile</scope>
    </dependency>
</dependencies>
</code>```

Here's my web.xml :

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <display-name>Basic Setup Web Application</display-name>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
    <listener>
        <listener-class>
            com.sun.faces.config.ConfigureListener
        </listener-class>
    </listener>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
</web-app>
</code>```

and here's the output of the jetty plugin :

```<code>[INFO] <<< jetty-maven-plugin:8.0.3.v20111011:run (default-cli) @ BasicSetup <<<
[INFO]
[INFO] --- jetty-maven-plugin:8.0.3.v20111011:run (default-cli) @ BasicSetup ---
[INFO] Configuring Jetty for project: BasicSetup Maven Webapp
[INFO] webAppSourceDirectory C:\Users\albert\workspace\BasicSetup\src\main\webapp does not exist. Defaulting to C:\Users\albert\workspace\BasicSetup\src\main\webapp
[INFO] Reload Mechanic: automatic
[INFO] Classes = C:\Users\albert\workspace\BasicSetup\target\classes
[INFO] Context path = /basicSetup
[INFO] Tmp directory = C:\Users\albert\workspace\BasicSetup\target\tmp
[INFO] Web defaults = org/eclipse/jetty/webapp/webdefault.xml
[INFO] Web overrides =  none
[INFO] web.xml file = file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/WEB-INF/web.xml
[INFO] Webapp directory = C:\Users\albert\workspace\BasicSetup\src\main\webapp
2011-10-25 14:24:51.091:INFO:oejs.Server:jetty-8.0.3.v20111011
2011-10-25 14:24:51.334:INFO:oejpw.PlusConfiguration:No Transaction manager found - if your webapp requires one, please configure one.
2011-10-25 14:24:52.108:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/basicSetup,[file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/, jar:file:/C:/Users/albert/.m2/repository/org/glassfish/javax.faces/2.1.3/javax.faces-2.1.3.jar!/META-INF/resources/]},file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/
2011-10-25 14:24:52.108:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/basicSetup,[file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/, jar:file:/C:/Users/albert/.m2/repository/org/glassfish/javax.faces/2.1.3/javax.faces-2.1.3.jar!/META-INF/resources/]},file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/
2011-10-25 14:24:52.108:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/basicSetup,[file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/, jar:file:/C:/Users/albert/.m2/repository/org/glassfish/javax.faces/2.1.3/javax.faces-2.1.3.jar!/META-INF/resources/]},file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/
2011-10-25 14:24:52.149:WARN:/basicSetup:unavailable
java.lang.IllegalStateException: Application was not properly initialized at startup, could not find Factory: javax.faces.context.FacesContextFactory
    at javax.faces.FactoryFinder$FactoryManager.getFactory(FactoryFinder.java:967)
    at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:316)
    at javax.faces.webapp.FacesServlet.init(FacesServlet.java:302)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:456)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:276)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:779)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:255)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1212)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:610)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:453)
    at org.mortbay.jetty.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:256)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:224)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:167)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:224)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:89)
    at org.eclipse.jetty.server.Server.doStart(Server.java:262)
    at org.mortbay.jetty.plugin.JettyServer.doStart(JettyServer.java:65)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.mortbay.jetty.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:511)
    at org.mortbay.jetty.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:364)
    at org.mortbay.jetty.plugin.JettyRunMojo.execute(JettyRunMojo.java:514)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:107)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:534)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
[INFO] Started Jetty Server
2011-10-25 14:24:52.165:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:8080 STARTING
[INFO] Starting scanner at interval of 10 seconds.
</code>```

Any thoughts ?

答:
I had this issue on my project, in that included  two jar file to lib folder now my problem salved.Thank You

com.sun.faces:jsf-api:2.2.9
com.sun.faces:jsf-impl:2.2.9

Body:
I notice that when trying to setup my JSF 2 webapp running on jetty, i have this error :

java.lang.IllegalStateException: Application was not properly
  initialized at startup, could not find Factory:
  javax.faces.context.FacesContextFactory

which is easily solved by adding this to my web.xml

<listener>
    <listener-class>
        com.sun.faces.config.ConfigureListener
    </listener-class>
</listener>

I've tried searching for a detailed explanation but in futile ..

jetty-maven-plugin:8.0.3.v20111011:run + jdk 7 + eclipse indigo

And here's my maven dependency :

<dependencies>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.faces</artifactId>
        <version>2.1.3</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

Here's my web.xml :

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <display-name>Basic Setup Web Application</display-name>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
    <listener>
        <listener-class>
            com.sun.faces.config.ConfigureListener
        </listener-class>
    </listener>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
</web-app>

and here's the output of the jetty plugin :

[INFO] <<< jetty-maven-plugin:8.0.3.v20111011:run (default-cli) @ BasicSetup <<<
[INFO]
[INFO] --- jetty-maven-plugin:8.0.3.v20111011:run (default-cli) @ BasicSetup ---
[INFO] Configuring Jetty for project: BasicSetup Maven Webapp
[INFO] webAppSourceDirectory C:\Users\albert\workspace\BasicSetup\src\main\webapp does not exist. Defaulting to C:\Users\albert\workspace\BasicSetup\src\main\webapp
[INFO] Reload Mechanic: automatic
[INFO] Classes = C:\Users\albert\workspace\BasicSetup\target\classes
[INFO] Context path = /basicSetup
[INFO] Tmp directory = C:\Users\albert\workspace\BasicSetup\target\tmp
[INFO] Web defaults = org/eclipse/jetty/webapp/webdefault.xml
[INFO] Web overrides =  none
[INFO] web.xml file = file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/WEB-INF/web.xml
[INFO] Webapp directory = C:\Users\albert\workspace\BasicSetup\src\main\webapp
2011-10-25 14:24:51.091:INFO:oejs.Server:jetty-8.0.3.v20111011
2011-10-25 14:24:51.334:INFO:oejpw.PlusConfiguration:No Transaction manager found - if your webapp requires one, please configure one.
2011-10-25 14:24:52.108:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/basicSetup,[file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/, jar:file:/C:/Users/albert/.m2/repository/org/glassfish/javax.faces/2.1.3/javax.faces-2.1.3.jar!/META-INF/resources/]},file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/
2011-10-25 14:24:52.108:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/basicSetup,[file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/, jar:file:/C:/Users/albert/.m2/repository/org/glassfish/javax.faces/2.1.3/javax.faces-2.1.3.jar!/META-INF/resources/]},file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/
2011-10-25 14:24:52.108:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/basicSetup,[file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/, jar:file:/C:/Users/albert/.m2/repository/org/glassfish/javax.faces/2.1.3/javax.faces-2.1.3.jar!/META-INF/resources/]},file:/C:/Users/albert/workspace/BasicSetup/src/main/webapp/
2011-10-25 14:24:52.149:WARN:/basicSetup:unavailable
java.lang.IllegalStateException: Application was not properly initialized at startup, could not find Factory: javax.faces.context.FacesContextFactory
    at javax.faces.FactoryFinder$FactoryManager.getFactory(FactoryFinder.java:967)
    at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:316)
    at javax.faces.webapp.FacesServlet.init(FacesServlet.java:302)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:456)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:276)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:779)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:255)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1212)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:610)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:453)
    at org.mortbay.jetty.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:256)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:224)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:167)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:224)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:89)
    at org.eclipse.jetty.server.Server.doStart(Server.java:262)
    at org.mortbay.jetty.plugin.JettyServer.doStart(JettyServer.java:65)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.mortbay.jetty.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:511)
    at org.mortbay.jetty.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:364)
    at org.mortbay.jetty.plugin.JettyRunMojo.execute(JettyRunMojo.java:514)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:107)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:534)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
[INFO] Started Jetty Server
2011-10-25 14:24:52.165:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:8080 STARTING
[INFO] Starting scanner at interval of 10 seconds.

Any thoughts ?


来源: stackexchange

问:
What's the point of using @Scoped with EJBs?
Usually I'm using @RequestScoped or @SessionScoped (from javax.enterprise.context) to inject objects (for instance in faces beans) using @Inject.
I am also using EJBs. As I understood, a set of stateless EJB copies (pool) is used to be injected to objects. The reason there are many copies is to ensure one instance of EJB isn't accessed concurrently. When speaking about stateful EJBs (again as I understood), one instance of such is bound to concrete injection point. And they are injected using @EJB (the stateless ones too).

Frequently I can see on the web examples of using @Stateless or @Stateful in conjunction with @Scoped. What is the meaning of them?

Edit: (trying to clarify as no one responded to this moment):

I'm especially interested whether such scoped annotations change anyhow (and if they - how) moment of creation of EJB's instance.
For my understanding: if I have, @EJB annotated field, object of proper class is injected there. If such EJB is stateless, container simply take free instance from the pool of pre-created instances. Pool can be resized if necessary. It is stateless, because object isn't guaranteed to be preserved across method calls of our class (i.e. class which has field containing reference to EJB).

We can also use stateful EJB and in that case one instance is preserved during method calls. As I think, it will be simply injected once per object creation. (There is also singleton EJB, which is shared between all objects).

I can't find the purpose of @Scoped annotations for EJB here.

Edit 2:

One can use such combination of annotations if class is to be injected via EJB and DI (by @Inject) mechanisms. This is rather, however, special case and not elegant. I am asking if you know any other reasons.

Edit 3:
Please see my comment under arjan's answer.

答:
A @Stateless or @Singleton bean may be explicitly scoped to prevent its scope being automatically modified to a scope that may be illegal. E.g. both these bean types are not allowed to be @RequestScoped. See this link for some more info: http://docs.jboss.org/resteasy/docs/2.0.0.GA/userguide/html/CDI.html

@Stateful makes a lot of sense to be (explicitly) scoped. Namely, without a scope you as a programmer have to take care to call the @Remove annotated method. This can be troublesome to guarantee, since such a bean is typically not used in a single method where you can call the @Remove method in a finally block. With a scope, the bean is exactly removed when the scope ends.

Furthermore, without a scope you can't always use injection to obtain a reference to a stateful bean's stub. Namely, every time the injection happens, you'll get a new instance. This is particularly troublesome when injecting a stateful bean in a request scoped (JSF) backing bean, where you have the intent to preserve the stateful bean across a couple of requests.

Then, in combination with @Named, you can also use a session bean directly as a backing bean to flatten your application layers (see e.g. http://jaxenter.com/java-ee-6-overview-35987-2.html). Obviously you want an explicit scope in that case. Now flattening your layers may not be a best practice in larger applications, but for smaller applications and/or people just beginning with Java EE there is definitely a wish to put business logic directly into the backing bean. It's then required that backing beans have access to the same kind of services (mainly transactions) that 'business beans' normally have.

Finally, Gavin King (CDI spec lead) has suggested to always use @Inject instead of @EJB. The only exception concerns remote EJBs, where @EJB is still used.

Part of the confusion around EJB and CDI is that CDI is a new component model in Java EE and still relatively new. Although they integrate fairly well with each other, they are still two different component models and not all best practices have been thought out yet. Reza Rahman (EG member, EJB book writer, and author of CDI implementation CanDI) has suggested that the EJB model could possibly be retrofitted in the future as a set of CDI services. Indeed, in Java EE 7 a step is being made by separating the transactional services from EJB and making them available via (CDI) annotations.

ContentLicense: CC BY-SA 3.0


问:
How to use listagg in hibernate
I am trying to use listagg function to generate a list of users.

Consider the following table

```<code> ROLE_ID    ENAME
---------- ----------
       4    CLARK
       4    KING
       4    MILLER
       7    ADAMS
       9    FORD
       9    JONES
</code>```

On using the following query in the SQL Developer

```<code>SELECT ROLE_ID,
       LISTAGG(ENAME, ',') WITHIN GROUP (ORDER BY ENAME) AS EMPLOYEES
FROM USERS
GROUP BY ROLE_ID;
</code>```

will result in the following in the console output

```<code>ROLE_ID EMPLOYEES
-----------------------------
4        CLARK,KING,MILLER
7        ADAMS
9        FORD, JONES
</code>```

My goal is try doing this in hibernate but I am not sure how to proceed.
Any help is appreciated.

答:
To use listagg in hibernate query

First register listagg function in Hibernate Dialect by extending Oracle10gDialect(in case you are using Oracle) or MySQLDialect(for MySQL)

public class CustomOracle10gDialect extends Oracle10gDialect {
     public CustomOracle10gDialect() {
         super();
         registerFunction("LISTAGG", new SQLFunctionTemplate(StandardBasicTypes.STRING,"LISTAGG(?1,',') WITHIN GROUP(ORDER BY ?1)"));
    }
}

Update your config file to use custom dialect.
spring.jpa.database-platform=com.abc.CustomOracle10gDialect
or
com.abc.CustomOracle10gDialect

Use LISTAGG()
Example -
select c.id, listagg(firstName) from Contacts c where  GROUP BY c.id

Title: How to use listagg in hibernate

Body:
I am trying to use listagg function to generate a list of users.

Consider the following table

 ROLE_ID    ENAME
---------- ----------
       4    CLARK
       4    KING
       4    MILLER
       7    ADAMS
       9    FORD
       9    JONES

On using the following query in the SQL Developer

SELECT ROLE_ID,
       LISTAGG(ENAME, ',') WITHIN GROUP (ORDER BY ENAME) AS EMPLOYEES
FROM USERS
GROUP BY ROLE_ID;

will result in the following in the console output

ROLE_ID EMPLOYEES
-----------------------------
4        CLARK,KING,MILLER
7        ADAMS
9        FORD, JONES

My goal is try doing this in hibernate but I am not sure how to proceed.
Any help is appreciated.

ContentLicense: CC BY-SA 4.0


问:
Combine two files and keep the non match lines
I am studying the sed command but I have a problem when combining 2 files.

file1.txt

```<code>A       1
C       3
E       5
</code>```

file2.txt

```<code>1 John Lennon
2 Mariah carey
3 Cool & The Gang
4 Westlife
5 Red Hot Chili Peppers
</code>```

desired output

```<code>1 John Lennon A
2 Mariah Carey
3 Cool & The Gang C
4 Westlife
5 Red Hot Chili Peppers E
</code>```

I try to make awk script like this:

```<code>awk 'FNR==NR{seen[$1]=$2; next} $1 in seen{seen[$1]=seen[$1] OFS $2} END{ for (e in seen) print e, seen[e]}' file2.txt file1.txt | sort -V
</code>```

but this output only display one word of the singer (John, Mariah, Cool, Westlife, and Red) and does not display the singer's full name. Is something wrong with my script?

答:
This can be done using a fairly simple 2 step process in awk and there is no need to use sort since we can process file2 in second phase:

```<code>awk 'FNR==NR{seen[$2]=$1; next} $1 in seen{$0 = $0 OFS seen[$1]} 1' file1 file2
</code>```

```<code>1 John Lennon A
2 Mariah carey
3 Cool & The Gang C
4 Westlife
5 Red Hot Chili Peppers E
</code>```

Body:
I am studying the sed command but I have a problem when combining 2 files.

file1.txt

A       1
C       3
E       5

file2.txt

1 John Lennon
2 Mariah carey
3 Cool & The Gang
4 Westlife
5 Red Hot Chili Peppers

desired output

1 John Lennon A
2 Mariah Carey
3 Cool & The Gang C
4 Westlife
5 Red Hot Chili Peppers E

I try to make awk script like this:

awk 'FNR==NR{seen[$1]=$2; next} $1 in seen{seen[$1]=seen[$1] OFS $2} END{ for (e in seen) print e, seen[e]}' file2.txt file1.txt | sort -V

but this output only display one word of the singer (John, Mariah, Cool, Westlife, and Red) and does not display the singer's full name. Is something wrong with my script?

Body:
This can be done using a fairly simple 2 step process in awk and there is no need to use sort since we can process file2 in second phase:

awk 'FNR==NR{seen[$2]=$1; next} $1 in seen{$0 = $0 OFS seen[$1]} 1' file1 file2

1 John Lennon A
2 Mariah carey
3 Cool & The Gang C
4 Westlife
5 Red Hot Chili Peppers E


问:
Convert numpy array to tuple
Note: This is asking for the reverse of the usual tuple-to-array conversion.

I have to pass an argument to a (wrapped c++) function as a nested tuple.  For example, the following works

```<code>X = MyFunction( ((2,2),(2,-2)) )
</code>```

whereas the following do not

```<code>X = MyFunction( numpy.array(((2,2),(2,-2))) )
X = MyFunction( [[2,2],[2,-2]] )
</code>```

Unfortunately, the argument I would like to use comes to me as a numpy array.  That array always has dimensions 2xN for some N, which may be quite large.

Is there an easy way to convert that to a tuple?  I know that I could just loop through, creating a new tuple, but would prefer if there's some nice access the numpy array provides.

If it's not possible to do this as nicely as I hope, what's the prettiest way to do it by looping, or whatever?

答:
If you like long cuts, here is another way
tuple(tuple(a_m.tolist()) for a_m in a )

```<code>from numpy import array
a = array([[1, 2],
           [3, 4]])
tuple(tuple(a_m.tolist()) for a_m in a )
</code>```

The output is
((1, 2), (3, 4))

Note just (tuple(a_m.tolist()) for a_m in a ) will give a generator expresssion.
Sort of inspired by @norok2's comment to  Greg von Winckel's answer

Title: Convert numpy array to tuple

Body:
Note: This is asking for the reverse of the usual tuple-to-array conversion.

I have to pass an argument to a (wrapped c++) function as a nested tuple.  For example, the following works

X = MyFunction( ((2,2),(2,-2)) )

whereas the following do not

X = MyFunction( numpy.array(((2,2),(2,-2))) )
X = MyFunction( [[2,2],[2,-2]] )

Unfortunately, the argument I would like to use comes to me as a numpy array.  That array always has dimensions 2xN for some N, which may be quite large.

Is there an easy way to convert that to a tuple?  I know that I could just loop through, creating a new tuple, but would prefer if there's some nice access the numpy array provides.

If it's not possible to do this as nicely as I hope, what's the prettiest way to do it by looping, or whatever?

Body:
If you like long cuts, here is another way
tuple(tuple(a_m.tolist()) for a_m in a )

from numpy import array
a = array([[1, 2],
           [3, 4]])
tuple(tuple(a_m.tolist()) for a_m in a )

The output is
((1, 2), (3, 4))

Note just (tuple(a_m.tolist()) for a_m in a ) will give a generator expresssion.
Sort of inspired by @norok2's comment to  Greg von Winckel's answer


问:
How to print only first element from JSON Array in ReactJs?
I have the following JSON Array data from which I want to print Charlie. How to do it?</p>

```<code>[ [ {
"ID": 1,
"Name" :"David"
},{
"ID": 2,
"Name" :"Antony"
}],[{
"ID": 1,
"Name" :"Bob"
},{
"ID": 2,
"Name" :"Charlie"
} ] ]
</code>```

答:
```<code>var response= [{
"ID": 1,
"Name" :"David",
},  {
"ID": 2,
"Name" :"Antony",
}];
</code>```

console.log(response[0].Name) will give you first element of Array and return data with Key 'Name'.

Body:
I have the following JSON Array data from which I want to print Charlie. How to do it?

[ [ {
"ID": 1,
"Name" :"David"
},{
"ID": 2,
"Name" :"Antony"
}],[{
"ID": 1,
"Name" :"Bob"
},{
"ID": 2,
"Name" :"Charlie"
} ] ]

Body:
var response= [{
"ID": 1,
"Name" :"David",
},  {
"ID": 2,
"Name" :"Antony",
}];

console.log(response[0].Name) will give you first element of Array and return data with Key 'Name'.


问:
Peewee - Can't connect to MySQL server on host
I'm developing a Flask based python app using the peewee ORM. I was initially connecting to the database that was being stored locally on my machine and I'm now trying to transition to connecting to the db remotely. I've set up the database in phpmyadmin via my server's cpanel section.

The Issue

I've set up my IP address to be able to remotely access my databases but I am getting the following error when I attempt to connect to the database:

```<code>Traceback (most recent call last):
  File "app.py", line 294, in <module>
    models.initialize()
  File "/Users/wyssuser/Desktop/dscraper/models.py", line 145, in initialize
    DATABASE.connect()
  File "/Library/Python/2.7/site-packages/peewee.py", line 2767, in connect
    self.__local.closed = False
  File "/Library/Python/2.7/site-packages/peewee.py", line 2688, in __exit__
    reraise(new_type, new_type(*exc_value.args), traceback)
  File "/Library/Python/2.7/site-packages/peewee.py", line 2766, in connect
    **self.connect_kwargs)
  File "/Library/Python/2.7/site-packages/peewee.py", line 3209, in _connect
    return mysql.connect(db=database, **conn_kwargs)
  File "/Library/Python/2.7/site-packages/pymysql/__init__.py", line 88, in Connect
    return Connection(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/pymysql/connections.py", line 644, in __init__
    self._connect()
  File "/Library/Python/2.7/site-packages/pymysql/connections.py", line 869, in _connect
    raise exc
peewee.OperationalError: (2003, "Can't connect to MySQL server on '142.157.25.22' ([Errno 61] Connection refused)")
</code>```

This is the portion of my code that references the database connection:

app.py

```<code>if __name__ == '__main__':
  models.initialize()
  app.run(debug=DEBUG, port=PORT, host=HOST)
</code>```

config.py

```<code>DATABASE = {
  'db': 'my_dbname',
  'host': '142.157.25.22',
  'port': 3306,
  'user': 'my_username',
  'passwd': 'my_pswd',
}
</code>```

models.py

```<code>from peewee import *
import config

DATABASE = MySQLDatabase(config.DATABASE['db'], host=config.DATABASE['host'], port=config.DATABASE['port'], user=config.DATABASE['user'], passwd=config.DATABASE['passwd'])

...all of my models related code

def initialize():
  print 'starting db connection'
  DATABASE.connect()
  print 'connected'
  DATABASE.create_tables([Batch, Company, User, Post],safe=True)
  DATABASE.close()
</code>```

I've also tried connecting to 'localhost' as the host but that doesn't seem to work here, is there a different host I should be connecting to?

答:
Solution is bad default port:
the example from peewee doc is

```<code># Connect to a MySQL database on network.
mysql_db = MySQLDatabase('my_app', user='app', password='db_password',
                         host='10.1.0.8', port=3316)
</code>```

but defaul port is 3306

Body:
I'm developing a Flask based python app using the peewee ORM. I was initially connecting to the database that was being stored locally on my machine and I'm now trying to transition to connecting to the db remotely. I've set up the database in phpmyadmin via my server's cpanel section.

The Issue

I've set up my IP address to be able to remotely access my databases but I am getting the following error when I attempt to connect to the database:

Traceback (most recent call last):
  File "app.py", line 294, in <module>
    models.initialize()
  File "/Users/wyssuser/Desktop/dscraper/models.py", line 145, in initialize
    DATABASE.connect()
  File "/Library/Python/2.7/site-packages/peewee.py", line 2767, in connect
    self.__local.closed = False
  File "/Library/Python/2.7/site-packages/peewee.py", line 2688, in __exit__
    reraise(new_type, new_type(*exc_value.args), traceback)
  File "/Library/Python/2.7/site-packages/peewee.py", line 2766, in connect
    **self.connect_kwargs)
  File "/Library/Python/2.7/site-packages/peewee.py", line 3209, in _connect
    return mysql.connect(db=database, **conn_kwargs)
  File "/Library/Python/2.7/site-packages/pymysql/__init__.py", line 88, in Connect
    return Connection(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/pymysql/connections.py", line 644, in __init__
    self._connect()
  File "/Library/Python/2.7/site-packages/pymysql/connections.py", line 869, in _connect
    raise exc
peewee.OperationalError: (2003, "Can't connect to MySQL server on '142.157.25.22' ([Errno 61] Connection refused)")

This is the portion of my code that references the database connection:

app.py

if __name__ == '__main__':
  models.initialize()
  app.run(debug=DEBUG, port=PORT, host=HOST)

config.py

DATABASE = {
  'db': 'my_dbname',
  'host': '142.157.25.22',
  'port': 3306,
  'user': 'my_username',
  'passwd': 'my_pswd',
}

models.py

from peewee import *
import config

DATABASE = MySQLDatabase(config.DATABASE['db'], host=config.DATABASE['host'], port=config.DATABASE['port'], user=config.DATABASE['user'], passwd=config.DATABASE['passwd'])

...all of my models related code

def initialize():
  print 'starting db connection'
  DATABASE.connect()
  print 'connected'
  DATABASE.create_tables([Batch, Company, User, Post],safe=True)
  DATABASE.close()

I've also tried connecting to 'localhost' as the host but that doesn't seem to work here, is there a different host I should be connecting to?

Body:
Solution is bad default port:
the example from peewee doc is

# Connect to a MySQL database on network.
mysql_db = MySQLDatabase('my_app', user='app', password='db_password',
                         host='10.1.0.8', port=3316)

but defaul port is 3306


问:
What does a lock statement do under the hood?
I see that for using objects which are not thread safe we wrap the code with a lock like this:

```<code>private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}
</code>```

So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?

答:
The lock statement is translated to calls to the Enter and Exit methods of Monitor.

The lock statement will wait indefinitely for the locking object to be released.

Body:
I see that for using objects which are not thread safe we wrap the code with a lock like this:

private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}

So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?


问:
Razor view model binding use javascript function
I have following model binding in reazor view .cshtml

```<code>@Html.TextBoxFor(m => m.cDate,
    new{
        @id = "textd",
        @type = "text"
    }
)
</code>```

I want to call a javascript function before binding like below

```<code>@Html.TextBoxFor(m => updatedateFormat(m.cDate),
    new{
        @id = "textd",
        @type = "text"
    }
)
</code>```

updatedateFormat is a javascript function.

I do have many options to do with c# only, But I am curious to know can we use javascript function with model binding.

I tried like below

```<code>@{
  string ccDate= @Convert.ToString("updatedateFormat(@Model.cDate)");
}
@Html.TextBoxFor(m => ccDate,
new
</code>```

But not working

Please advise.
Thanks

答:
Since it is not possible to trigger a Javascript function, when an input element or any other html element is rendered, you can use the document.ready event to achieve what your want:

```<code>@Html.TextBoxFor(m =>m.cDate,
    new{
        @id = "textd",
        @type = "text",
    }
)
</code>```

And when the document is ready:

```<code>$(document).ready(function () {
    var ccDate= document.getElementById('textd');
    updatedateFormat(ccDate);
})
</code>```

Or you could add a custom attribute such as data-onload to simulate a on load event:

```<code>@Html.TextBoxFor(m => m.cDate,
    new{
        @id = "textd",
        @type = "text",
        data_onload="updatedateFormat('@Model.cDate')"
    }
)
</code>```

And when the document is ready:

```<code>$(document).ready(function () {
    $('[data-onload]').each(function(){
    eval($(this).data('onload'));
  });
})
</code>```

If you only want to format the value of your property, you can do that using ToString() function inside the HTML helper:

```<code>@Html.TextBoxFor(m =>m.cDate,
    new{
        @id = "textd",
        @type = "text",
        @Value = Model.cDate.ToString("yyyy/MM/dd")
    }
)
</code>```

Body:
I have following model binding in reazor view .cshtml

@Html.TextBoxFor(m => m.cDate,
    new{
        @id = "textd",
        @type = "text"
    }
)

I want to call a javascript function before binding like below

@Html.TextBoxFor(m => updatedateFormat(m.cDate),
    new{
        @id = "textd",
        @type = "text"
    }
)

updatedateFormat is a javascript function.

I do have many options to do with c# only, But I am curious to know can we use javascript function with model binding.

I tried like below

@{
  string ccDate= @Convert.ToString("updatedateFormat(@Model.cDate)");
}
@Html.TextBoxFor(m => ccDate,
new

But not working

Please advise.
Thanks

Body:
Since it is not possible to trigger a Javascript function, when an input element or any other html element is rendered, you can use the document.ready event to achieve what your want:

@Html.TextBoxFor(m =>m.cDate,
    new{
        @id = "textd",
        @type = "text",
    }
)

And when the document is ready:

$(document).ready(function () {
    var ccDate= document.getElementById('textd');
    updatedateFormat(ccDate);
})

Or you could add a custom attribute such as data-onload to simulate a on load event:

@Html.TextBoxFor(m => m.cDate,
    new{
        @id = "textd",
        @type = "text",
        data_onload="updatedateFormat('@Model.cDate')"
    }
)

And when the document is ready:

$(document).ready(function () {
    $('[data-onload]').each(function(){
    eval($(this).data('onload'));
  });
})

If you only want to format the value of your property, you can do that using ToString() function inside the HTML helper:

@Html.TextBoxFor(m =>m.cDate,
    new{
        @id = "textd",
        @type = "text",
        @Value = Model.cDate.ToString("yyyy/MM/dd")
    }
)


问:
wxpython wx.TreeCtrl, which subitem of the tree fires the event wx.EVT_TREE_ITEM_ACTIVATED?
I'm making a tree ctrl and need to figure out where the double click came from.

Code:

```<code>def _initElementsOfTreePanel(self, panel):
    tree = wx.TreeCtrl(panel, -1, wx.Point(0, 0), wx.DefaultSize, wx.NO_BORDER | wx.TR_DEFAULT_STYLE)

    root = tree.AddRoot("Elements")
    items = []
    imglist = wx.ImageList(16, 16, True, 2)
    imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, wx.Size(16, 16)))
    imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16)))
    tree.AssignImageList(imglist)

# #        Create the element Tree (the left hand side panel). Places in it all the found functions
    def appendSubitems(item, func_list, tree):
        print item
        for func in func_list:
            itemid = tree.AppendItem(item, func.__name__, 1)
            print"GUIFrame._initElementsofTreePanel, func:",func.__name__,"id:",itemid

#        print "TreeItemId:",
    appendSubitems(tree.AppendItem(root, "Input functions", 0), self._elemdisco.input_functions, tree)
    appendSubitems(tree.AppendItem(root, "Processing functions", 0), self._elemdisco.processing_functions, tree)
    appendSubitems(tree.AppendItem(root, "Output functions", 0), self._elemdisco.output_functions, tree)
    appendSubitems(tree.AppendItem(root, "Other functions", 0), self._elemdisco.other_functions, tree)

    tree.ExpandAll()
    self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self._addNodeToSchema, self.treePanel.tree)

def _addNodeToSchema(self,event):
    print event.GetItem()
</code>```

Now the output shows that no matter what node double click on, it recognizes the same item to have fired the event. And it corresponds to no ID of any item that i know i've added, and no ID of the root.

Anyone know how I can get a reference to the object in the tree? I basically want to get its name, but this API won't let me :P

[EDIT]:Solver, but i think this is a framework bug. There's no reason why the event should return the same TreeItemID regardless of where the double click  actually occurs.

答:
'''multiple selection with drag event, shows the dragged items</p>

```<code>def On_Drag(self,event):
    select = (self.custom_tree.GetSelections())
    for i in range(len(select)):
        print(self.custom_tree.GetItemText(select[i]))'''
</code>```

Body:
I'm making a tree ctrl and need to figure out where the double click came from.

Code:

def _initElementsOfTreePanel(self, panel):
    tree = wx.TreeCtrl(panel, -1, wx.Point(0, 0), wx.DefaultSize, wx.NO_BORDER | wx.TR_DEFAULT_STYLE)

    root = tree.AddRoot("Elements")
    items = []
    imglist = wx.ImageList(16, 16, True, 2)
    imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, wx.Size(16, 16)))
    imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16)))
    tree.AssignImageList(imglist)

# #        Create the element Tree (the left hand side panel). Places in it all the found functions
    def appendSubitems(item, func_list, tree):
        print item
        for func in func_list:
            itemid = tree.AppendItem(item, func.__name__, 1)
            print"GUIFrame._initElementsofTreePanel, func:",func.__name__,"id:",itemid

#        print "TreeItemId:",
    appendSubitems(tree.AppendItem(root, "Input functions", 0), self._elemdisco.input_functions, tree)
    appendSubitems(tree.AppendItem(root, "Processing functions", 0), self._elemdisco.processing_functions, tree)
    appendSubitems(tree.AppendItem(root, "Output functions", 0), self._elemdisco.output_functions, tree)
    appendSubitems(tree.AppendItem(root, "Other functions", 0), self._elemdisco.other_functions, tree)

    tree.ExpandAll()
    self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self._addNodeToSchema, self.treePanel.tree)

def _addNodeToSchema(self,event):
    print event.GetItem()

Now the output shows that no matter what node double click on, it recognizes the same item to have fired the event. And it corresponds to no ID of any item that i know i've added, and no ID of the root.

Anyone know how I can get a reference to the object in the tree? I basically want to get its name, but this API won't let me :P

[EDIT]:Solver, but i think this is a framework bug. There's no reason why the event should return the same TreeItemID regardless of where the double click  actually occurs.

Body:
'''multiple selection with drag event, shows the dragged items

def On_Drag(self,event):
    select = (self.custom_tree.GetSelections())
    for i in range(len(select)):
        print(self.custom_tree.GetItemText(select[i]))'''


问:
Doctrine & Symfony - Get data from database with parameter on array column
Good afternoon,

I try to find, from my database specific users with a role which is passed in parameter to the query. However, I have "null" result currently.

The users class is like this example from Symfony Documentation.

This is my CustomerRepository:

```<code>class CustomerRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Customer::class);
    }

    public function findByRole(string $role)
    {
        return $this->getEntityManager()->createQuery(
            'SELECT c
             FROM App\Entity\Customer c
              WHERE c.roles IN (:role)'
        )
            ->setParameter(':role', $role)
            ->getResult()
        ;
    }
}
</code>```

I expect to return an array which contains one or several users who have the role.

答:
Good evening,

Thx for your help.

To resolve this problem, I considered that a User have only one role in application, in this context, the solution is like this:

```<code>public function findByRole(string $role, int $isActive = 1): ?Customer
{
    return $this->getEntityManager()->createQuery(
            'SELECT c
             FROM App\Entity\Cutomer c
             WHERE c.roles LIKE :role
             AND c.isActive = :isActive'
        )
        ->setParameters([
             ':role' => '%'.$role.'%',
             ':isActive' => $isActive,
        ])
        ->getOneOrNullResult()
    ;
}
</code>```

Body:
Good afternoon,

I try to find, from my database specific users with a role which is passed in parameter to the query. However, I have "null" result currently.

The users class is like this example from Symfony Documentation.

This is my CustomerRepository:

class CustomerRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Customer::class);
    }

    public function findByRole(string $role)
    {
        return $this->getEntityManager()->createQuery(
            'SELECT c
             FROM App\Entity\Customer c
              WHERE c.roles IN (:role)'
        )
            ->setParameter(':role', $role)
            ->getResult()
        ;
    }
}

I expect to return an array which contains one or several users who have the role.

Body:
Good evening,

Thx for your help.

To resolve this problem, I considered that a User have only one role in application, in this context, the solution is like this:

public function findByRole(string $role, int $isActive = 1): ?Customer
{
    return $this->getEntityManager()->createQuery(
            'SELECT c
             FROM App\Entity\Cutomer c
             WHERE c.roles LIKE :role
             AND c.isActive = :isActive'
        )
        ->setParameters([
             ':role' => '%'.$role.'%',
             ':isActive' => $isActive,
        ])
        ->getOneOrNullResult()
    ;
}


问:
How to remove jerky movement on chrome
I'm a developer for my fathers website. Yesterday, I made this custom cursor with vanilla Javascript and CSS : https://codepen.io/ZellRDesign/pen/PoqzgZX

After development, I tested it on my webapp.

Firefox : no problem, the code works very well and it is pretty awesome.

On Chrome : here I got my first problem, sometimes the custom cursor is jerky and I don't know how to reproduce this bug...
I got this bug only one time, but today, I share my code to friends and one of them say me "look the code is bugging"

Example of bug : https://i.imgur.com/PW3zCb1.gifv

So now, I have two questions :

how to patch the bug ?

and

how to improve the code to make it better ?

Thanks for help

const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
  cursor.setAttribute("style", "top: " + (e.pageY - 10) + "px; left: " + (e.pageX - 10) + "px;")
})

document.addEventListener('click', () => {
  cursor.classList.add("expand");

  setTimeout(() => {
    cursor.classList.remove("expand");
  }, 500)
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  height: 100vh;
  //cursor: none;
  background: rgb(27, 27, 27);
}

.cursor {
  width: 20px;
  height: 20px;
  border: 1px solid #FAB313;
  ;
  border-radius: 50%;
  position: absolute;
  transition-duration: 200ms;
  transition-timing-function: ease-out;
  animation: cursorAnim .5s infinite alternate;
  pointer-events: none;
}

.cursor::after {
  content: "";
  width: 20px;
  height: 20px;
  position: absolute;
  border: 8px solid #FAB313;
  ;
  border-radius: 50%;
  opacity: .5;
  top: -8px;
  left: -8px;
  animation: cursorAnim2 .5s infinite alternate;
}

@keyframes cursorAnim {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.7);
  }
}

@keyframes cursorAnim2 {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.4);
  }
}

@keyframes cursorAnim3 {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(3);
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

.expand {
  animation: cursorAnim3 .5s forwards;
  border: 1px solid #1E2648;
}</code>```

```

答:
Since I can't reproduce the issue on Chrome I think you could try to improve the overall performance by both using the transform property to move the cursor (instead of top and left properties) and the will-change property.

Since you are already using that property for the pulse animation I've inserted a a wrapper element and I've applied the transform there

const cursorW = document.querySelector('.cursor-wrapper');
const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
   cursorW.setAttribute("style",
        "transform: translate("+(e.pageX - 10)+"px, "+(e.pageY - 10)+"px)")
})

document.addEventListener('click', () => {
   cursor.classList.add("expand");

   setTimeout(() => {
      cursor.classList.remove("expand");
   }, 500)
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    margin: 0;
    height: 100vh;
    //cursor: none;
    background: rgb(27, 27, 27);
}

.cursor-wrapper {
  will-change: transform;
  transition: transform .25s 0s;
}

.cursor {
    width: 20px;
    height: 20px;
    border: 1px solid #FAB313;;
    border-radius: 50%;
    position: absolute;
    transition-duration: 200ms;
    transition-timing-function: ease-out;
    animation: cursorAnim .5s infinite alternate;
    pointer-events: none;
}

.cursor::after {
    content: "";
    width: 20px;
    height: 20px;
    position: absolute;
    border: 8px solid #FAB313;;
    border-radius: 50%;
    opacity: .5;
    top: -8px;
    left: -8px;
    animation: cursorAnim2 .5s infinite alternate;
}

@keyframes cursorAnim {
    from {
        transform: scale(1);
    }
    to {
        transform: scale(.7);
    }
}

@keyframes cursorAnim2 {
    from {
        transform: scale(1);
    }
    to {
        transform: scale(.4);
    }
}

@keyframes cursorAnim3 {
    0% {
        transform: scale(1);
    }
    50% {
        transform: scale(3);
    }
    100% {
        transform: scale(1);
        opacity: 0;
    }
}

.expand {
    animation: cursorAnim3 .5s forwards;
    border: 1px solid #1E2648;
}</code>```

```
</div>
</div>
</p>

<p>In the CSS the <code>.cursor-wrapper</code> class is defined like so:</p>

```.cursor-wrapper {
   will-change: transform;
   transition: transform .25s 0s;
}
```

The transform will take benefit from the GPU acceleration and the will-change property will let the browser know that this property is going to change (I've inserted it also on .cursor class)

Also the JS code is applied now to the .cursor-wrapper class.

Finally, feel free to change the animation speed.

Title: How to remove jerky movement on chrome

Body:
I'm a developer for my fathers website. Yesterday, I made this custom cursor with vanilla Javascript and CSS : https://codepen.io/ZellRDesign/pen/PoqzgZX

After development, I tested it on my webapp.

Firefox : no problem, the code works very well and it is pretty awesome.

On Chrome : here I got my first problem, sometimes the custom cursor is jerky and I don't know how to reproduce this bug...
I got this bug only one time, but today, I share my code to friends and one of them say me "look the code is bugging"

Example of bug : https://i.imgur.com/PW3zCb1.gifv

So now, I have two questions :

how to patch the bug ?

and

how to improve the code to make it better ?

Thanks for help

const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
  cursor.setAttribute("style", "top: " + (e.pageY - 10) + "px; left: " + (e.pageX - 10) + "px;")
})

document.addEventListener('click', () => {
  cursor.classList.add("expand");

  setTimeout(() => {
    cursor.classList.remove("expand");
  }, 500)
})

body {
  margin: 0;
  height: 100vh;
  //cursor: none;
  background: rgb(27, 27, 27);
}

.cursor {
  width: 20px;
  height: 20px;
  border: 1px solid #FAB313;
  ;
  border-radius: 50%;
  position: absolute;
  transition-duration: 200ms;
  transition-timing-function: ease-out;
  animation: cursorAnim .5s infinite alternate;
  pointer-events: none;
}

.cursor::after {
  content: "";
  width: 20px;
  height: 20px;
  position: absolute;
  border: 8px solid #FAB313;
  ;
  border-radius: 50%;
  opacity: .5;
  top: -8px;
  left: -8px;
  animation: cursorAnim2 .5s infinite alternate;
}

@keyframes cursorAnim {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.7);
  }
}

@keyframes cursorAnim2 {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.4);
  }
}

@keyframes cursorAnim3 {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(3);
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

.expand {
  animation: cursorAnim3 .5s forwards;
  border: 1px solid #1E2648;
}

Body:
Since I can't reproduce the issue on Chrome I think you could try to improve the overall performance by both using the transform property to move the cursor (instead of top and left properties) and the will-change property.

Since you are already using that property for the pulse animation I've inserted a a wrapper element and I've applied the transform there

const cursorW = document.querySelector('.cursor-wrapper');
const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
   cursorW.setAttribute("style",
        "transform: translate("+(e.pageX - 10)+"px, "+(e.pageY - 10)+"px)")
})

document.addEventListener('click', () => {
   cursor.classList.add("expand");

   setTimeout(() => {
      cursor.classList.remove("expand");
   }, 500)
})

body {
    margin: 0;
    height: 100vh;
    //cursor: none;
    background: rgb(27, 27, 27);
}

.cursor-wrapper {
  will-change: transform;
  transition: transform .25s 0s;
}

.cursor {
    width: 20px;
    height: 20px;
    border: 1px solid #FAB313;;
    border-radius: 50%;
    position: absolute;
    transition-duration: 200ms;
    transition-timing-function: ease-out;
    animation: cursorAnim .5s infinite alternate;
    pointer-events: none;
}

.cursor::after {
    content: "";
    width: 20px;
    height: 20px;
    position: absolute;
    border: 8px solid #FAB313;;
    border-radius: 50%;
    opacity: .5;
    top: -8px;
    left: -8px;
    animation: cursorAnim2 .5s infinite alternate;
}

@keyframes cursorAnim {
    from {
        transform: scale(1);
    }
    to {
        transform: scale(.7);
    }
}

@keyframes cursorAnim2 {
    from {
        transform: scale(1);
    }
    to {
        transform: scale(.4);
    }
}

@keyframes cursorAnim3 {
    0% {
        transform: scale(1);
    }
    50% {
        transform: scale(3);
    }
    100% {
        transform: scale(1);
        opacity: 0;
    }
}

.expand {
    animation: cursorAnim3 .5s forwards;
    border: 1px solid #1E2648;
}

<div class="cursor-wrapper">
  <div class="cursor"></div>
</div>

In the CSS the .cursor-wrapper class is defined like so:

.cursor-wrapper {
   will-change: transform;
   transition: transform .25s 0s;
}

The transform will take benefit from the GPU acceleration and the will-change property will let the browser know that this property is going to change (I've inserted it also on .cursor class)

Also the JS code is applied now to the .cursor-wrapper class.

Finally, feel free to change the animation speed.


问:
How to determine that a browser tab is selected and execute code in JavaScript?
I want to have one same page open on multiple browser tabs. When I click on ONE browser tab, I want a JavaScript function to be executed ONCE, just one time! Not that that function is being executed 3 times because that one same page is opened on 3 browser tabs for example.

I have tried:

```<code>window.addEventListener("focus", () => {
     console.log(document.hasFocus());
});
</code>```

This works fine if your cursor is focusing on a web browser and keeps switching between tabs on that browser.

But if you first focus your cursor on something else other than that web browser (e.g. computer desktop or code IDE) and then you click on a NON-ACTIVE browser tab, the above code will be executed two times, one time by the previous active tab and another time by the new active tab you just clicked on.

That is my problem.

How can I execute JavaScript code only one time when I click on a web browser tab? Any solution besides JavaScript code is also welcome e.g. tracking pixels or input field autofocus event, just to name samples. I did not mean that tracking pixels techniques will help. I am not using jQuery. I am using VueJs.

答:
You might want to use this ancient method and JS syntax, before you adopt it for your final coding style. Have some classic vanilla flavor. It never hurts.

document.body.onfocus = function(e){console.info(e.type)}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>should work exactly as requested...
but since this behavior is somewhat tied to the BOM, some browser vendors (with idiosyncratic behaviors) might require some sort of enforced filtering,  Opera comes to mind.

But it should be rock solid on all modern browsers including a bonus backward compatibility, as back as Windows 98 browser version. And\or the ancient and now probably forgoten NN 4.7. ( except for the console info event log, but that's not needed for the actual use anyway )</code>```

Body:
I want to have one same page open on multiple browser tabs. When I click on ONE browser tab, I want a JavaScript function to be executed ONCE, just one time! Not that that function is being executed 3 times because that one same page is opened on 3 browser tabs for example.

I have tried:

window.addEventListener("focus", () => {
     console.log(document.hasFocus());
});

This works fine if your cursor is focusing on a web browser and keeps switching between tabs on that browser.

But if you first focus your cursor on something else other than that web browser (e.g. computer desktop or code IDE) and then you click on a NON-ACTIVE browser tab, the above code will be executed two times, one time by the previous active tab and another time by the new active tab you just clicked on.

That is my problem.

How can I execute JavaScript code only one time when I click on a web browser tab? Any solution besides JavaScript code is also welcome e.g. tracking pixels or input field autofocus event, just to name samples. I did not mean that tracking pixels techniques will help. I am not using jQuery. I am using VueJs.

Body:
You might want to use this ancient method and JS syntax, before you adopt it for your final coding style. Have some classic vanilla flavor. It never hurts.

document.body.onfocus = function(e){console.info(e.type)}

should work exactly as requested...
but since this behavior is somewhat tied to the BOM, some browser vendors (with idiosyncratic behaviors) might require some sort of enforced filtering,  Opera comes to mind.

But it should be rock solid on all modern browsers including a bonus backward compatibility, as back as Windows 98 browser version. And\or the ancient and now probably forgoten NN 4.7. ( except for the console info event log, but that's not needed for the actual use anyway )


问:
Converter works for RequestParameter but not for RequestBody field
I have the following converter:

```<code>@Component
public class CountryEnumConverter implements Converter<String, CountryEnum> {

    @Override
    public CountryEnum convert(String country) {
        CountryEnum countryEnum = CountryEnum.getBySign(country);

        if (countryEnum == null) {
            throw new IllegalArgumentException(country + " - Country is not supported!");
        }

        return countryEnum;
    }
}
</code>```

Registered it is invoked when used for RequestParam

```<code>@GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
        Principal principal,
        @RequestParam CountryEnum country) {
    ....
}
</code>```

But this converter is never invoked when used for field in the RequstBody:

```<code>@GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
        Principal principal,
        @RequestBody MyBody myBody) {
    ....
}
</code>```

```<code>public class MyBody {

    @NotNull
    private CountryEnum country;

    public MyBody() {
    }

    public CountryEnum getCountry() {
        return country;
    }

    public void setCountry(CountryEnum country) {
        this.country = country;
    }

}
</code>```

答:
Your existing org.springframework.core.convert.converter.Converter instance will only work with data submitted as form encoded data. With @RequestBody you are sending JSON data which will be deserialized using using the Jackson library.

You can then create an instance of com.fasterxml.jackson.databind.util.StdConverter<IN, OUT>

```<code>public class StringToCountryTypeConverter extends StdConverter<String, CountryType> {

  @Override
  public CountryType convert(String value) {
      //convert and return
  }
}
</code>```

and then apply this on the target property:

```<code>public class MyBody {

    @NotNull
    @JsonDeserialize(converter = StringToCountryTypeConverter.class)
    private CountryEnum country;
}
</code>```

Given the similarity of the 2 interfaces I would expect that you could create one class to handle both scenarios:

```<code>public class StringToCountryTypeConverter extends StdConverter<String, CountryType>
           implements org.springframework.core.convert.converter.Converter<String, CountryType> {
  @Override
  public CountryType convert(String value) {
      //convert and return
  }
}
</code>```

Body:
I have the following converter:

@Component
public class CountryEnumConverter implements Converter<String, CountryEnum> {

    @Override
    public CountryEnum convert(String country) {
        CountryEnum countryEnum = CountryEnum.getBySign(country);

        if (countryEnum == null) {
            throw new IllegalArgumentException(country + " - Country is not supported!");
        }

        return countryEnum;
    }
}

Registered it is invoked when used for RequestParam

@GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
        Principal principal,
        @RequestParam CountryEnum country) {
    ....
}

But this converter is never invoked when used for field in the RequstBody:

@GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
        Principal principal,
        @RequestBody MyBody myBody) {
    ....
}

public class MyBody {

    @NotNull
    private CountryEnum country;

    public MyBody() {
    }

    public CountryEnum getCountry() {
        return country;
    }

    public void setCountry(CountryEnum country) {
        this.country = country;
    }

}

Body:
Your existing org.springframework.core.convert.converter.Converter instance will only work with data submitted as form encoded data. With @RequestBody you are sending JSON data which will be deserialized using using the Jackson library.

You can then create an instance of com.fasterxml.jackson.databind.util.StdConverter<IN, OUT>

public class StringToCountryTypeConverter extends StdConverter<String, CountryType> {

  @Override
  public CountryType convert(String value) {
      //convert and return
  }
}

and then apply this on the target property:

public class MyBody {

    @NotNull
    @JsonDeserialize(converter = StringToCountryTypeConverter.class)
    private CountryEnum country;
}

Given the similarity of the 2 interfaces I would expect that you could create one class to handle both scenarios:

public class StringToCountryTypeConverter extends StdConverter<String, CountryType>
           implements org.springframework.core.convert.converter.Converter<String, CountryType> {
  @Override
  public CountryType convert(String value) {
      //convert and return
  }
}


问:
Groovy Truthy question: String.split() produces empty array, but is 'true' ? How?
Below is a series of steps I have taken in the grooysh shell demonstrate the problem

String.split() => String[] as expected in the Java SDK. When I evaluate this as part of a continuing expression: changedDirs.split('\r\n').collect{ ... } my collect executes 1 time with an empty it. Let me grant: this code is running on a Jenkins server and Jenkins is known to have, let's say, a dialect of groovy running. But, regardless, when I test it locally with groovysh, I indeed get something I didn't expect: [] evaluates to truthy if it comes from String.split()

So: Can someone explain:

How this groovy code below produces a truthy for String.split() and not for a basic empty []

Is Jenkins doing something weird?

```<code>groovy:000> [] ? 'true' : 'false'
===> false
groovy:000> changedDirs = ''
===>
groovy:000> changedDirs.split('\r\n')
===> []
groovy:000> changedDirs.split('\r\n') ? true : false
===> true
groovy:000> result = changedDirs.split('\r\n')
===> []
groovy:000> result ? true : false
===> true
groovy:000> result.class
===> class [Ljava.lang.String;
groovy:000> [] as String[] ? true : false
===> false
groovy:000>
</code>```

答:
The result evaluates to true as boolean, because changedDirs.split('\r\n') produces String[] array with a single element - an empty string. Take a look at the following example:

```<code>groovy:000> ([] as String[]).class
===> class [Ljava.lang.String;
groovy:000> ([] as String[]) ? true : false
===> false
groovy:000> x = ([] as String[])
===> []
groovy:000> x.dump()
===> <[Ljava.lang.String;@5c41d037>
groovy:000> y = "".split(",")
===> []
groovy:000> y.class
===> class [Ljava.lang.String;
groovy:000> y.dump()
===> <[Ljava.lang.String;@79a1728c>
groovy:000> y ? true : false
===> true
groovy:000> y.length
===> 1
groovy:000> x.length
===> 0
groovy:000> y[0].dump()
===> <java.lang.String@0 value= hash=0>
groovy:000>
</code>```

In the "Groovy Truth", every non-empty array evaluates to true when calls asBoolean() method, no matter what is the value of the elements in the array.

If you look at the following Java code example, you will see that String.split(pattern) method produces a single element array in case of an empty string.

final class Test {

    public static void main(String[] args) {
        String[] array = "".split("\r\n");

        System.out.println(array.length); // prints: 1
    }
}
```

This SO question might be useful - Why does "split" on an empty string return a non-empty array?

Body:
Below is a series of steps I have taken in the grooysh shell demonstrate the problem

String.split() => String[] as expected in the Java SDK. When I evaluate this as part of a continuing expression: changedDirs.split('\r\n').collect{ ... } my collect executes 1 time with an empty it. Let me grant: this code is running on a Jenkins server and Jenkins is known to have, let's say, a dialect of groovy running. But, regardless, when I test it locally with groovysh, I indeed get something I didn't expect: [] evaluates to truthy if it comes from String.split()

So: Can someone explain:

How this groovy code below produces a truthy for String.split() and not for a basic empty []

Is Jenkins doing something weird?

groovy:000> [] ? 'true' : 'false'
===> false
groovy:000> changedDirs = ''
===>
groovy:000> changedDirs.split('\r\n')
===> []
groovy:000> changedDirs.split('\r\n') ? true : false
===> true
groovy:000> result = changedDirs.split('\r\n')
===> []
groovy:000> result ? true : false
===> true
groovy:000> result.class
===> class [Ljava.lang.String;
groovy:000> [] as String[] ? true : false
===> false
groovy:000>

Body:
The result evaluates to true as boolean, because changedDirs.split('\r\n') produces String[] array with a single element - an empty string. Take a look at the following example:

groovy:000> ([] as String[]).class
===> class [Ljava.lang.String;
groovy:000> ([] as String[]) ? true : false
===> false
groovy:000> x = ([] as String[])
===> []
groovy:000> x.dump()
===> <[Ljava.lang.String;@5c41d037>
groovy:000> y = "".split(",")
===> []
groovy:000> y.class
===> class [Ljava.lang.String;
groovy:000> y.dump()
===> <[Ljava.lang.String;@79a1728c>
groovy:000> y ? true : false
===> true
groovy:000> y.length
===> 1
groovy:000> x.length
===> 0
groovy:000> y[0].dump()
===> <java.lang.String@0 value= hash=0>
groovy:000>

In the "Groovy Truth", every non-empty array evaluates to true when calls asBoolean() method, no matter what is the value of the elements in the array.

If you look at the following Java code example, you will see that String.split(pattern) method produces a single element array in case of an empty string.

final class Test {

    public static void main(String[] args) {
        String[] array = "".split("\r\n");

        System.out.println(array.length); // prints: 1
    }
}

This SO question might be useful - Why does "split" on an empty string return a non-empty array?


问:
bottle.py: globally modify (rewrite) request path for testing a web-application?
I am setting up bottle.py with uWSGI run with $ uwsgi --http :1024 --wsgi-file app.py.
app.pycontains the default:

```<code>import bottle
application = bottle.default_app()
</code>```

and lots of route decorators and functions such as:

```<code>@bottle.route('/<A>/<B>')
def somedef():
    return bottle.template(...)
</code>```

This is temporarily being served from http://example.com/secret_URL/, which of course causes  to always be parsed as "secret_URL".

How can the URL be modified ("rewrite", strip the "secret_URL/") so that the web application, i.e. bottle does not "see" it?

I have found add_hook but so far I have not been able to modify the path of the request:

```<code>@bottle.hook('before_request')
def test():
    bottle.request.url = bottle.request.url.replace("secret_URL/","")
</code>```

The reason becomes clear:

The Request class wraps a WSGI environment and provides helpful
  methods to parse and access form data, cookies, file uploads and other
  metadata. Most of the attributes are read-only.

The docs also state:

Adding new attributes to a request actually adds them to the environ
  dictionary (as ‘bottle.request.ext.’). This is the recommended
  way to store and access request-specific data.

and

environ

The wrapped WSGI environ dictionary. This is the only real attribute. All other attributes actually are read-only properties.

bottle.request.environ contains, amongst others, REQUEST_URI, PATH_INFO, bottle.raw_path, bottle.request, bottle.request.urlparts and some objects.

Which of these can be written and need to be written for the desired effect?

This then also poses the question of how to handle such links on the client side HTML without changing every single href.

答:
By trial and error:

```<code>@bottle.hook('before_request')
def test():
    bottle.request.environ['PATH_INFO'] = bottle.request.environ['PATH_INFO'].replace("secret_URL/","")
</code>```

For the client:

relative URLs may be a solution, but they can break user copies (unless the browser replaces them) and the application needs to keep track of the path level

Origin-relative URLs may work with <base> (link below)

Related:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#href

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Examples

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

https://en.wikipedia.org/wiki/URL

From https://bottlepy.org/docs/stable/recipes.html?highlight=cache#ignore-trailing-slashes:

or add a WSGI middleware that strips trailing slashes from all URLs:

```<code>class StripPathMiddleware(object):
  def __init__(self, app):
    self.app = app
  def __call__(self, e, h):
    e['PATH_INFO'] = e['PATH_INFO'].rstrip('/')
    return self.app(e,h)

app = bottle.app()
myapp = StripPathMiddleware(app)
bottle.run(app=myapp)
</code>```

Body:
I am setting up bottle.py with uWSGI run with $ uwsgi --http :1024 --wsgi-file app.py.
app.pycontains the default:

import bottle
application = bottle.default_app()

and lots of route decorators and functions such as:

@bottle.route('//')
def somedef():
    return bottle.template(...)

This is temporarily being served from http://example.com/secret_URL/, which of course causes  to always be parsed as "secret_URL".

How can the URL be modified ("rewrite", strip the "secret_URL/") so that the web application, i.e. bottle does not "see" it?

I have found add_hook but so far I have not been able to modify the path of the request:

@bottle.hook('before_request')
def test():
    bottle.request.url = bottle.request.url.replace("secret_URL/","")

The reason becomes clear:

The Request class wraps a WSGI environment and provides helpful
  methods to parse and access form data, cookies, file uploads and other
  metadata. Most of the attributes are read-only.

The docs also state:

Adding new attributes to a request actually adds them to the environ
  dictionary (as ‘bottle.request.ext.’). This is the recommended
  way to store and access request-specific data.

and

environ

The wrapped WSGI environ dictionary. This is the only real attribute. All other attributes actually are read-only properties.

bottle.request.environ contains, amongst others, REQUEST_URI, PATH_INFO, bottle.raw_path, bottle.request, bottle.request.urlparts and some objects.

Which of these can be written and need to be written for the desired effect?

This then also poses the question of how to handle such links on the client side HTML without changing every single href.

Body:
By trial and error:

@bottle.hook('before_request')
def test():
    bottle.request.environ['PATH_INFO'] = bottle.request.environ['PATH_INFO'].replace("secret_URL/","")

For the client:

relative URLs may be a solution, but they can break user copies (unless the browser replaces them) and the application needs to keep track of the path level

Origin-relative URLs may work with <base> (link below)

Related:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#href

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Examples

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

https://en.wikipedia.org/wiki/URL

From https://bottlepy.org/docs/stable/recipes.html?highlight=cache#ignore-trailing-slashes:

or add a WSGI middleware that strips trailing slashes from all URLs:

class StripPathMiddleware(object):
  def __init__(self, app):
    self.app = app
  def __call__(self, e, h):
    e['PATH_INFO'] = e['PATH_INFO'].rstrip('/')
    return self.app(e,h)

app = bottle.app()
myapp = StripPathMiddleware(app)
bottle.run(app=myapp)


问:
How to add white space at the last position of a string?
I am trying to add 2 white space at the last position of a string but when I set this in a label I found no space. But if I added 2 white space with another character, it works ok. Then I tried to add 2 white space with some extra character and then trim these extra characters. But for all these case I observed no space when I placed this in a text label. I am trying this for the right alignment.

```<code>let name: String = self.cityModelArr[indexPos].countryShortName+"  12"
let endIndex = name.index(name.endIndex, offsetBy: -2)
let truncated = String(name[..<endIndex])
self.testLabel.text = truncated
</code>```

I have tried some more solutions from the internet but failed to achieve my goal.

答:
You can define your string like  </p>

```<code>let strData = "This is testing string"

 self.lblText.text = "\(strData) "
</code>```

Body:
I am trying to add 2 white space at the last position of a string but when I set this in a label I found no space. But if I added 2 white space with another character, it works ok. Then I tried to add 2 white space with some extra character and then trim these extra characters. But for all these case I observed no space when I placed this in a text label. I am trying this for the right alignment.

let name: String = self.cityModelArr[indexPos].countryShortName+"  12"
let endIndex = name.index(name.endIndex, offsetBy: -2)
let truncated = String(name[..<endIndex])
self.testLabel.text = truncated

I have tried some more solutions from the internet but failed to achieve my goal.

Body:
You can define your string like

let strData = "This is testing string"

 self.lblText.text = "\(strData) "


问:
how to split a string value that contains characters and numbers
I have a std::string s=n8Name4Surname. How can I obtain in 2 strings the Name and the Surname? THX

答: Use Boost tokenizer with the digits 0-9 as delimiters.  Then, throw away the string containing "n".  It's overkill, I realize...</p>


问:
flask_socketio is hanging using any message_queue as SocketIO argument
Given the following example, well it's a quite simple example according to the documentation. I've got an error using redis or any other provider as a message_queue. Browser just hangs, although, if I just set message_queue to None (uncomment the line). Everything works as expected. Also, I do have kombu, redis and eventlet package pip installed on the enviroment. Using flask-socketio==4.2.1

```<code>from flask import Flask, jsonify
from flask_socketio import SocketIO, emit

message_queue = "redis://127.0.0.1:6379"
# message_queue = None

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app,
                    async_mode='eventlet',
                    message_queue=message_queue,
                    manage_session=False,
                    logger=True,
                    engineio_logger=True)

@app.route('/')
def home():
    return """
        <html>
        <body>
        <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
        <script type="text/javascript" charset="utf-8">
        var socket = io();
        socket.on('connect', function() {
            socket.emit('my event', {data: 'Im connected!'});
        });

        socket.on('my response', function(data) {
            console.log(data);
        });
        </script>
        ok
        </body>
        </html>
    """

@socketio.on('my event')
def test_message(message):
    emit('my response', {'data': 'got it!'})
</code>```

That's what is logged:

```<code>Server initialized for eventlet.
 * Restarting with fsevents reloader
Server initialized for eventlet.
 * Debugger is active!
 * Debugger PIN: 609-071-851
(70237) wsgi starting up on http://127.0.0.1:5000
(70237) accepted ('127.0.0.1', 53303)
39982ab1b7f84dee8e8d34dee1141cec: Sending packet OPEN data {'sid': '39982ab1b7f84dee8e8d34dee1141cec', 'upgrades': ['websocket'], 'pingTimeout': 60000, 'pingInterval': 25000}
</code>```

using rabbit-mq i've got thouse logs from rabbit:

```<code>rabbit_1         | 2020-02-18 20:47:16.535 [info] <0.18859.0> accepting AMQP connection <0.18859.0> (172.31.0.1:46412 -> 172.31.0.6:5672)
rabbit_1         | 2020-02-18 20:47:16.581 [info] <0.18859.0> connection <0.18859.0> (172.31.0.1:46412 -> 172.31.0.6:5672): user 'rabbitmq' authenticated and granted access to vhost '/'
</code>```

=== updated

Patching eventlet in the beguining of the file, didn't changed the behavior.

```<code>import eventlet
eventlet.monkey_patch()
</code>```

The entire example script is stated. If you manage to make it run properly, please make a comment. Thanks.

答:
My guess is that this is due to now having the standard library monkey patched to be compatible with eventlet. Add the following two lines at the two of your script:

import eventlet
eventlet.monkey_patch()

from flask import Flask, jsonify
from flask_socketio import SocketIO, emit

message_queue = "redis://127.0.0.1:6379"
# message_queue = None

# ...
```

<p>For more information on monkey patching, see https://eventlet.net/doc/patching.html.</p>

<p>I've also needed to add the <code>run()</code> call at the bottom, you omitted that in your listing:</p>

<pre class="lang-py prettyprint-override"><code>socketio.run(app)
</code>```

With those two changes, I can run the Python script and nothing hangs for me. I suspect you may have been using flask run to run the server, but that is not the way to start the eventlet server, that only works for the Flask dev server. You have to use socketio.run(app) to start the eventlet server properly.

Body:
Given the following example, well it's a quite simple example according to the documentation. I've got an error using redis or any other provider as a message_queue. Browser just hangs, although, if I just set message_queue to None (uncomment the line). Everything works as expected. Also, I do have kombu, redis and eventlet package pip installed on the enviroment. Using flask-socketio==4.2.1

from flask import Flask, jsonify
from flask_socketio import SocketIO, emit

message_queue = "redis://127.0.0.1:6379"
# message_queue = None

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app,
                    async_mode='eventlet',
                    message_queue=message_queue,
                    manage_session=False,
                    logger=True,
                    engineio_logger=True)

@app.route('/')
def home():
    return """

        ok

    """

@socketio.on('my event')
def test_message(message):
    emit('my response', {'data': 'got it!'})

That's what is logged:

Server initialized for eventlet.
 * Restarting with fsevents reloader
Server initialized for eventlet.
 * Debugger is active!
 * Debugger PIN: 609-071-851
(70237) wsgi starting up on http://127.0.0.1:5000
(70237) accepted ('127.0.0.1', 53303)
39982ab1b7f84dee8e8d34dee1141cec: Sending packet OPEN data {'sid': '39982ab1b7f84dee8e8d34dee1141cec', 'upgrades': ['websocket'], 'pingTimeout': 60000, 'pingInterval': 25000}

using rabbit-mq i've got thouse logs from rabbit:

rabbit_1         | 2020-02-18 20:47:16.535 [info] <0.18859.0> accepting AMQP connection <0.18859.0> (172.31.0.1:46412 -> 172.31.0.6:5672)
rabbit_1         | 2020-02-18 20:47:16.581 [info] <0.18859.0> connection <0.18859.0> (172.31.0.1:46412 -> 172.31.0.6:5672): user 'rabbitmq' authenticated and granted access to vhost '/'

=== updated

Patching eventlet in the beguining of the file, didn't changed the behavior.

import eventlet
eventlet.monkey_patch()

The entire example script is stated. If you manage to make it run properly, please make a comment. Thanks.

Body:
My guess is that this is due to now having the standard library monkey patched to be compatible with eventlet. Add the following two lines at the two of your script:

import eventlet
eventlet.monkey_patch()

from flask import Flask, jsonify
from flask_socketio import SocketIO, emit

message_queue = "redis://127.0.0.1:6379"
# message_queue = None

# ...

For more information on monkey patching, see https://eventlet.net/doc/patching.html.

I've also needed to add the run() call at the bottom, you omitted that in your listing:

socketio.run(app)

With those two changes, I can run the Python script and nothing hangs for me. I suspect you may have been using flask run to run the server, but that is not the way to start the eventlet server, that only works for the Flask dev server. You have to use socketio.run(app) to start the eventlet server properly.


问:
Checking for an input username within a list box to display error message if the username is not unique
I am working on a project where I must display an error message if the username being input is not unique. I am attempting to  search within my Listbox to see if the username already exists. The program is running fine, but it does not work (find never == true even when the username I'm inputting is the exact same as another within my Listbox) I am pretty new to C# so I'm kind of just messing around with syntax but nothing seems to be working. Any help is highly appreciated!

```<code>    private void txt_Username_TextChanged(object sender, EventArgs e)
    {
       bool find = lb_Form1_ListUsers.ContainsFocus.Equals(txt_Username.Text);

        if (find == true)
        {
           lbl_Form1_UniqueError.Visible = true;
        }
        else
        {
            lbl_Form1_UniqueError.Visible = false;
        }

        find = false;
    }
</code>```

答:
Well, ContainsFocus returns true / false depending on if lb_Form1_ListUsers has or not keyboard focus; so
comparing this bool value with string txt_Username.Text doesn't have much sence.

Assuming that lb_Form1_ListUsers.Items contains values of type String (user names) we can query them if there's Any equals to txt_Username.Text

```<code>   using System.Linq;

   ...

   private void txt_Username_TextChanged(object sender, EventArgs e)
   {
     bool find = lb_Form1_ListUsers
       .Items
       .Cast<String>() //TODO: put the right type here if required
       .Any(item => item == txt_Username.Text);

     lbl_Form1_UniqueError.Visible = find;
   }
</code>```

Body:
I am working on a project where I must display an error message if the username being input is not unique. I am attempting to  search within my Listbox to see if the username already exists. The program is running fine, but it does not work (find never == true even when the username I'm inputting is the exact same as another within my Listbox) I am pretty new to C# so I'm kind of just messing around with syntax but nothing seems to be working. Any help is highly appreciated!

    private void txt_Username_TextChanged(object sender, EventArgs e)
    {
       bool find = lb_Form1_ListUsers.ContainsFocus.Equals(txt_Username.Text);

        if (find == true)
        {
           lbl_Form1_UniqueError.Visible = true;
        }
        else
        {
            lbl_Form1_UniqueError.Visible = false;
        }

        find = false;
    }

Body:
Well, ContainsFocus returns true / false depending on if lb_Form1_ListUsers has or not keyboard focus; so
comparing this bool value with string txt_Username.Text doesn't have much sence.

Assuming that lb_Form1_ListUsers.Items contains values of type String (user names) we can query them if there's Any equals to txt_Username.Text

   using System.Linq;

   ...

   private void txt_Username_TextChanged(object sender, EventArgs e)
   {
     bool find = lb_Form1_ListUsers
       .Items
       .Cast<String>() //TODO: put the right type here if required
       .Any(item => item == txt_Username.Text);

     lbl_Form1_UniqueError.Visible = find;
   }


问:
certificate signed by unknown authority when connect to remote kubernetes cluster using kubectl
I am using kubectl to connect remote kubernetes cluster(v1.15.2),I am copy config from remote server to local macOS:

```<code>scp -r root@ip:~/.kube/config ~/.kube
</code>```

and change the url to https://kube-ctl.example.com,I exposed the api server to the internet:

```<code>apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURvakNDQW9xZ0F3SUJBZ0lVU3FpUlZSU3FEOG1PemRCT1MyRzlJdGE0R2Nrd0RRWUpLb1pJaHZjTkFRRUwKQlFB92FERUxNQWtHQTFVRUJoTUNRMDR4RURBT0JnTlZCQWdUQjBKbGFVcHBibWN4RURBT0JnTlZCQWNUQjBKbAphVXBwYm1jeEREQUtCZ05WQkFvVEEyczRjekVTTUJBR0ExVUVDeE1KTkZCaGNtRmthV2R0TVJNd0VRWURWUVFECkV3cHJkV0psY201bGRHVnpNQ0FYR3RFNU1Ea3hNekUxTkRRd01Gb1lEekl4TVRrd09ESXdNVFUwTkRBd1dqQm8KTVFzd0NRWURWUVFHRXdKRFRqRVFNQTRHQTFVRUNCTUhRbVZwU21sdVp6RVFNQTRHQTFVRUJ4TUhRbVZwU21sdQpaekVNTUFvR0ExVUVDaE1EYXpoek1SSXdFQVlEVlFRTEV3azBVR0Z5WVdScFoyMHhFekFSQmdOVkJBTVRDbXQxClltVnlibVYwWlhNd2dnRWlNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0SUJEd0F3Z2dFS0FvSUJBUUNzOGFFR2R2TUgKb0E1eTduTjVydnAvQkEyTVM1RG1TNWwzQ0p4S3VMOGJ1bkF3alF1c0lTalUxVWlqeVdGOW03VzA3elZJaVJpRwpiYzZGT3JkSEJ2QXgzazBpT2pPRlduTHp1UjdaSFhqQ3lTbDJRam9YN3gzL0l1MERQelNHTXJLSzZETGpTRTk4CkdadEpjUi9OSmpiVFFJc3FXbWFEdUIyc3dmcEc1ZmlZU1A1KzVpcld1TG1pYjVnWnJYeUJJNlJ0dVV4K1NvdW0KN3RDKzJaVG5QdFF0QnFUZHprT3p3THhwZ0Zhd1kvSU1mbHBsaUlMTElOamcwRktxM21NOFpUa0xvNXcvekVmUApHT25GNkNFWlR6bkdrTWc2aUVGenNBcDU5N2lMUDBNTkR4YUNjcTRhdTlMdnMzYkdOZmpqdDd3WkxIVklLa0lGCm44Mk92cExGaElq2kFnTUJBQUdqUWpCQU1BNEdBMVVkRHdFQi93UUVBd0lCQmpBUEJnTlZIUk1CQWY4RUJUQUQKQVFIL01CMEdBMVVkRGdRV0JCUm0yWHpJSHNmVzFjMEFGZU9SLy9Qakc4dWdzREFOQmdrcWhraUc5dzBCQVFzRgpBQU9DQVFFQW1mOUozN3RYTys1dWRmT2RLejdmNFdMZyswbVJUeTBRSEVIblk5VUNLQi9vN2hLUVJHRXI3VjNMCktUeGloVUhvbHY1QzVUdG8zbUZJY2FWZjlvZlp0VVpvcnpxSUFwNE9Od1JpSnQ1Yk94K1d6SW5qN2JHWkhnZjkKSk8rUmNxQnQrUWsrejhTMmJKRG04WFdvMW5WdjJRNU1pUndPdnRIbnRxd3MvTlJ2bHBGV25ISHBEVExjOU9kVwpoMllzWVpEMmV4d0FRVDkxSlExVjRCdklrZGFPeW9USHZ6U2oybThSTzh6b3JBd09kS1NTdG9TZXdpOEhMeGI2ClhmaTRFbjR4TEE3a3pmSHFvcDZiSFF1L3hCa0JzYi9hd29kdDJKc2FnOWFZekxEako3S1RNYlQyRW52MlllWnIKSUhBcjEyTGVCRGRHZVd1eldpZDlNWlZJbXJvVnNRPT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    server: https://k8s-ctl.example.com
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    namespace: kube-system
    user: admin
  name: kubernetes
current-context: kubernetes
kind: Config
preferences: {}
users:
- name: admin
  user:
</code>```

when I get cluster pod info in my local Mac:

```<code>kubectl get pods --all-namespaces
</code>```

give this error:

```<code>Unable to connect to the server: x509: certificate signed by unknown authority
</code>```

when I access https://k8s-ctl.example.com in google chrome,the result is:

```<code>{
kind: "Status",
apiVersion: "v1",
metadata: { },
status: "Failure",
message: "Unauthorized",
reason: "Unauthorized",
code: 401
}
</code>```

what should I do to make access remote k8s cluster sucess using kubectl client?

One way I have tried to using this .kube/config generate by command,but get the same result:

```<code>apiVersion: v1
clusters:
- cluster:
    certificate-authority: ssl/ca.pem
    server: https://k8s-ctl.example.com
  name: default
contexts:
- context:
    cluster: default
    user: admin
  name: default
current-context: default
kind: Config
preferences: {}
users:
- name: admin
  user:
    client-certificate: ssl/admin.pem
    client-key: ssl/admin-key.pem
</code>```

答:
I've reproduced your problem and as you created your cluster following kubernetes-the-hard-way, you need to follow these steps to be able to access your cluster from a different console.

First you have to copy the following certificates created while you was bootstraping your cluster to ~/.kube/ directory in your local machine:

```<code>ca.pem
admin.pem
admin-key.pem
</code>```

After copying these files to your local machine, execute the following commands:

```<code>kubectl config set-cluster kubernetes-the-hard-way \
  --certificate-authority=~/.kube/ca.pem \
  --embed-certs=true \
  --server=https://${KUBERNETES_PUBLIC_ADDRESS}:6443
</code>```

```<code>kubectl config set-credentials admin \
  --client-certificate=~/.kube/admin.pem \
  --client-key=~/.kube/admin-key.pem
</code>```

```<code>kubectl config set-context kubernetes-the-hard-way \
  --cluster=kubernetes-the-hard-way \
  --user=admin
</code>```

```<code>kubectl config use-context kubernetes-the-hard-way
</code>```

Notice that you have to replace the ${KUBERNETES_PUBLIC_ADDRESS} variable with the remote address to your cluster.

Body:
I am using kubectl to connect remote kubernetes cluster(v1.15.2),I am copy config from remote server to local macOS:

scp -r root@ip:~/.kube/config ~/.kube

and change the url to https://kube-ctl.example.com,I exposed the api server to the internet:

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURvakNDQW9xZ0F3SUJBZ0lVU3FpUlZSU3FEOG1PemRCT1MyRzlJdGE0R2Nrd0RRWUpLb1pJaHZjTkFRRUwKQlFB92FERUxNQWtHQTFVRUJoTUNRMDR4RURBT0JnTlZCQWdUQjBKbGFVcHBibWN4RURBT0JnTlZCQWNUQjBKbAphVXBwYm1jeEREQUtCZ05WQkFvVEEyczRjekVTTUJBR0ExVUVDeE1KTkZCaGNtRmthV2R0TVJNd0VRWURWUVFECkV3cHJkV0psY201bGRHVnpNQ0FYR3RFNU1Ea3hNekUxTkRRd01Gb1lEekl4TVRrd09ESXdNVFUwTkRBd1dqQm8KTVFzd0NRWURWUVFHRXdKRFRqRVFNQTRHQTFVRUNCTUhRbVZwU21sdVp6RVFNQTRHQTFVRUJ4TUhRbVZwU21sdQpaekVNTUFvR0ExVUVDaE1EYXpoek1SSXdFQVlEVlFRTEV3azBVR0Z5WVdScFoyMHhFekFSQmdOVkJBTVRDbXQxClltVnlibVYwWlhNd2dnRWlNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0SUJEd0F3Z2dFS0FvSUJBUUNzOGFFR2R2TUgKb0E1eTduTjVydnAvQkEyTVM1RG1TNWwzQ0p4S3VMOGJ1bkF3alF1c0lTalUxVWlqeVdGOW03VzA3elZJaVJpRwpiYzZGT3JkSEJ2QXgzazBpT2pPRlduTHp1UjdaSFhqQ3lTbDJRam9YN3gzL0l1MERQelNHTXJLSzZETGpTRTk4CkdadEpjUi9OSmpiVFFJc3FXbWFEdUIyc3dmcEc1ZmlZU1A1KzVpcld1TG1pYjVnWnJYeUJJNlJ0dVV4K1NvdW0KN3RDKzJaVG5QdFF0QnFUZHprT3p3THhwZ0Zhd1kvSU1mbHBsaUlMTElOamcwRktxM21NOFpUa0xvNXcvekVmUApHT25GNkNFWlR6bkdrTWc2aUVGenNBcDU5N2lMUDBNTkR4YUNjcTRhdTlMdnMzYkdOZmpqdDd3WkxIVklLa0lGCm44Mk92cExGaElq2kFnTUJBQUdqUWpCQU1BNEdBMVVkRHdFQi93UUVBd0lCQmpBUEJnTlZIUk1CQWY4RUJUQUQKQVFIL01CMEdBMVVkRGdRV0JCUm0yWHpJSHNmVzFjMEFGZU9SLy9Qakc4dWdzREFOQmdrcWhraUc5dzBCQVFzRgpBQU9DQVFFQW1mOUozN3RYTys1dWRmT2RLejdmNFdMZyswbVJUeTBRSEVIblk5VUNLQi9vN2hLUVJHRXI3VjNMCktUeGloVUhvbHY1QzVUdG8zbUZJY2FWZjlvZlp0VVpvcnpxSUFwNE9Od1JpSnQ1Yk94K1d6SW5qN2JHWkhnZjkKSk8rUmNxQnQrUWsrejhTMmJKRG04WFdvMW5WdjJRNU1pUndPdnRIbnRxd3MvTlJ2bHBGV25ISHBEVExjOU9kVwpoMllzWVpEMmV4d0FRVDkxSlExVjRCdklrZGFPeW9USHZ6U2oybThSTzh6b3JBd09kS1NTdG9TZXdpOEhMeGI2ClhmaTRFbjR4TEE3a3pmSHFvcDZiSFF1L3hCa0JzYi9hd29kdDJKc2FnOWFZekxEako3S1RNYlQyRW52MlllWnIKSUhBcjEyTGVCRGRHZVd1eldpZDlNWlZJbXJvVnNRPT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    server: https://k8s-ctl.example.com
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    namespace: kube-system
    user: admin
  name: kubernetes
current-context: kubernetes
kind: Config
preferences: {}
users:
- name: admin
  user:

when I get cluster pod info in my local Mac:

kubectl get pods --all-namespaces

give this error:

Unable to connect to the server: x509: certificate signed by unknown authority

when I access https://k8s-ctl.example.com in google chrome,the result is:

{
kind: "Status",
apiVersion: "v1",
metadata: { },
status: "Failure",
message: "Unauthorized",
reason: "Unauthorized",
code: 401
}

what should I do to make access remote k8s cluster sucess using kubectl client?

One way I have tried to using this .kube/config generate by command,but get the same result:

apiVersion: v1
clusters:
- cluster:
    certificate-authority: ssl/ca.pem
    server: https://k8s-ctl.example.com
  name: default
contexts:
- context:
    cluster: default
    user: admin
  name: default
current-context: default
kind: Config
preferences: {}
users:
- name: admin
  user:
    client-certificate: ssl/admin.pem
    client-key: ssl/admin-key.pem

Body:
I've reproduced your problem and as you created your cluster following kubernetes-the-hard-way, you need to follow these steps to be able to access your cluster from a different console.

First you have to copy the following certificates created while you was bootstraping your cluster to ~/.kube/ directory in your local machine:

ca.pem
admin.pem
admin-key.pem

After copying these files to your local machine, execute the following commands:

kubectl config set-cluster kubernetes-the-hard-way \
  --certificate-authority=~/.kube/ca.pem \
  --embed-certs=true \
  --server=https://${KUBERNETES_PUBLIC_ADDRESS}:6443

kubectl config set-credentials admin \
  --client-certificate=~/.kube/admin.pem \
  --client-key=~/.kube/admin-key.pem

kubectl config set-context kubernetes-the-hard-way \
  --cluster=kubernetes-the-hard-way \
  --user=admin

kubectl config use-context kubernetes-the-hard-way

Notice that you have to replace the ${KUBERNETES_PUBLIC_ADDRESS} variable with the remote address to your cluster.


问:
Use of #pragma alias in c++
I would like to know what does the following piece of code do, when a user predefined macro __FLOATP__ is available

```<code>#ifdef __FLOATP__
#pragma alias   atanl  = atanf
#pragma alias   atan           = atanf
#endif
</code>```

So does the piece of code compile usages the of atanl and atan to atanf, when the macro __FLOATP__ is available?

答:
The #pragma directive is defined by the ANSI C standard for implementing directives that provide the compiler with various instructions. The presence of certain #pragma directives depends on the compiler.

In this case, as you correctly noted, #pragma alias acts when defining the __FLOATP__ macro. The #pragma alias indicates the linker that two identifier names are equivalent. I found this information here: #pragma alias.

Title: Use of #pragma alias in c++

Body:
I would like to know what does the following piece of code do, when a user predefined macro __FLOATP__ is available

#ifdef __FLOATP__
#pragma alias   atanl  = atanf
#pragma alias   atan           = atanf
#endif

So does the piece of code compile usages the of atanl and atan to atanf, when the macro __FLOATP__ is available?