问:
Searchfield to search for specific planets
I tried adding a search field to search for planets.
Can someone help me to fix this please?

The error I get is this:
    TypeError: Cannot read property 'state' of undefined
    handleChange
    C:/Users/charl/Desktop/IRONHACK/Paperbox/paperbox/src/pages/Home.js:29
      26 |    }
      27 |
      28 |    handleChange(e){ // eslint-disable-next-line

29 |        const planetssearchlist = this.state.planets.filter(planet => {
           | ^  30 |             if(planet.name){
        31 |                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
        32 |                    return true

```<code>import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/"
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data.results;
            this.setState({planets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    handleChange(e){ // eslint-disable-next-line
        const planetssearchlist = this.state.planets.filter(planet => {
             if(planet.name){
                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
            this.setState({
                planets:planetssearchlist
            })
        })
    }

    render() {
        return (

        <div>
            <h1>Star Wars Planets</h1>

            <form>
                <input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
            </form>

            {
                this.state.planets.map((planet,i) => (
                        <p key={i}>{planet.name}</p>
                ))
            }

        </div>

        )
    }
}

export default Home
</code>```

答:
Try using an arrow function for handleChange method like this:

```<code>handleChange = (e) => {

}
</code>```

Body:
I tried adding a search field to search for planets.
Can someone help me to fix this please?

The error I get is this:
    TypeError: Cannot read property 'state' of undefined
    handleChange
    C:/Users/charl/Desktop/IRONHACK/Paperbox/paperbox/src/pages/Home.js:29
      26 |    }
      27 |
      28 |    handleChange(e){ // eslint-disable-next-line

29 |        const planetssearchlist = this.state.planets.filter(planet => {
           | ^  30 |             if(planet.name){
        31 |                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
        32 |                    return true

import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/"
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data.results;
            this.setState({planets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    handleChange(e){ // eslint-disable-next-line
        const planetssearchlist = this.state.planets.filter(planet => {
             if(planet.name){
                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
            this.setState({
                planets:planetssearchlist
            })
        })
    }

    render() {
        return (

Star Wars Planets

            <form>
                <input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
            </form>

            {
                this.state.planets.map((planet,i) => (

{planet.name}

                ))
            }

        )
    }
}

export default Home

Body:
Try using an arrow function for handleChange method like this:

handleChange = (e) => {

}


来源: stackexchange

问:
Is there a way to tell how many tables are aggregated by wildcards in BigQuery Standard SQL?
Say I have tables in BigQuery with the format table_name_YYYYMMDD. I know in standard SQL you can use wildcards with _TABLE_SUFFIX to select a range of tables in a query like this:

```<code>SELECT
  user_id
FROM `project.dataset.table_name_*`
WHERE _TABLE_SUFFIX BETWEEN '20200520' AND '20200525'
</code>```

My question is whether there is a way to tell the number of tables that were actually selected in the end (i.e. 20200520, 20200521, 20200522, 20200523, 20200524, 20200525 would be 6 tables).

In my case, I have a query that uses 30 tables to create a monthly summary, but sometimes one or more of those 30 tables might not exist, in which case I would like to throw an error instead of silently querying less than the 30 tables I expect. (I know this can be done in Legacy SQL with TABLE_DATE_RANGE but I was wondering if there is a way to accomplish it in Standard SQL).

答:
You can use Jobs.Get API to see referencedTables attributes which is array of all tables touched by query

Or you can use INFORMATION_SCHEMA.TABLES to just simply count number of tables matching your pattern. Something like

```<code>SELECT COUNT(1)
FROM yourDataset.INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME BETWEEN 'table_name_20200520' AND 'table_name_20200525'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Say I have tables in BigQuery with the format table_name_YYYYMMDD. I know in standard SQL you can use wildcards with _TABLE_SUFFIX to select a range of tables in a query like this:

SELECT
  user_id
FROM `project.dataset.table_name_*`
WHERE _TABLE_SUFFIX BETWEEN '20200520' AND '20200525'

My question is whether there is a way to tell the number of tables that were actually selected in the end (i.e. 20200520, 20200521, 20200522, 20200523, 20200524, 20200525 would be 6 tables).

In my case, I have a query that uses 30 tables to create a monthly summary, but sometimes one or more of those 30 tables might not exist, in which case I would like to throw an error instead of silently querying less than the 30 tables I expect. (I know this can be done in Legacy SQL with TABLE_DATE_RANGE but I was wondering if there is a way to accomplish it in Standard SQL).

Body:
You can use Jobs.Get API to see referencedTables attributes which is array of all tables touched by query

Or you can use INFORMATION_SCHEMA.TABLES to just simply count number of tables matching your pattern. Something like

SELECT COUNT(1)
FROM yourDataset.INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME BETWEEN 'table_name_20200520' AND 'table_name_20200525'


问:
Does Hibernate allow getdate()?
Currently I'm working on to get the value (verifyCount) for the current day so, in my query for SQL Server is like below

```<code>select verifyCount from VerifyUser where idNo = 'ABC1234'
and cast(createdDatetime as Date) = cast(getdate() as Date)
</code>```

and in my Hibernate function, I'm using below query

```<code>public Integer doInHibernate(Session session) throws HibernateException, SQLException {
  String query = "SELECT vu .verifyCount FROM VerifyUser vu "
                + "WHERE vu .idNo= '"+ idNo+ "'"
                + "AND cast(pl.createdDatetime as Date) = cast(getdate() as Date)";

  Query q = session.createQuery(query);
  return (Integer) q.uniqueResult();
}
</code>```

But I hit error as below

```<code>2020-06-02 07:02:28.018 [WebContainer : 0] ERROR k.c.m.b.w.AbstractGeneralErrorRequestListener
  [n/a] - null
  java.lang.NullPointerException: null
  at org.hibernate.dialect.function.CastFunction.render(CastFunction.java:56)
  at org.hibernate.hql.ast.SqlGenerator.endFunctionTemplate(SqlGenerator.java:214)
  at org.hibernate.hql.antlr.SqlGeneratorBase.methodCall(SqlGeneratorBase.java:2325)
  at org.hibernate.hql.antlr.SqlGeneratorBase.simpleExpr(SqlGeneratorBase.java:2699)
  at org.hibernate.hql.antlr.SqlGeneratorBase.expr(SqlGeneratorBase.java:1465)
  at org.hibernate.hql.antlr.SqlGeneratorBase.binaryComparisonExpression(SqlGeneratorBase.java:2940)
  at org.hibernate.hql.antlr.SqlGeneratorBase.comparisonExpr(SqlGeneratorBase.java:1280)
  at org.hibernate.hql.antlr.SqlGeneratorBase.booleanExpr(SqlGeneratorBase.java:910)
  at org.hibernate.hql.antlr.SqlGeneratorBase.booleanOp(SqlGeneratorBase.java:2858)
  at org.hibernate.hql.antlr.SqlGeneratorBase.booleanExpr(SqlGeneratorBase.java:890)
  at org.hibernate.hql.antlr.SqlGeneratorBase.whereExpr(SqlGeneratorBase.java:768)
  at org.hibernate.hql.antlr.SqlGeneratorBase.selectStatement(SqlGeneratorBase.java:191)
  at org.hibernate.hql.antlr.SqlGeneratorBase.statement(SqlGeneratorBase.java:119)
  at org.hibernate.hql.ast.QueryTranslatorImpl.generate(QueryTranslatorImpl.java:240)
  at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:207)
  at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:138)
  at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
  at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
  at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)
  at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
  at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
  at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
  at java.lang.reflect.Method.invoke(Method.java:508)
  at org.springframework.orm.hibernate3.HibernateTemplate$CloseSuppressingInvocationHandler.invoke(HibernateTemplate.java:1387)
at com.sun.proxy.$Proxy2575.createQuery(Unknown Source)
</code>```

I suspect the CAST or getdate() function cannot be used in HQL query.

Really appreciate if there is any idea or solution.

答:
HQL uses current_date() to get the current date.
You could try replacing getdate() with current_date() and check if it resolves the null pointer issue.

Title: Does Hibernate allow getdate()?

Body:
Currently I'm working on to get the value (verifyCount) for the current day so, in my query for SQL Server is like below

select verifyCount from VerifyUser where idNo = 'ABC1234'
and cast(createdDatetime as Date) = cast(getdate() as Date)

and in my Hibernate function, I'm using below query

public Integer doInHibernate(Session session) throws HibernateException, SQLException {
  String query = "SELECT vu .verifyCount FROM VerifyUser vu "
                + "WHERE vu .idNo= '"+ idNo+ "'"
                + "AND cast(pl.createdDatetime as Date) = cast(getdate() as Date)";

  Query q = session.createQuery(query);
  return (Integer) q.uniqueResult();
}

But I hit error as below

2020-06-02 07:02:28.018 [WebContainer : 0] ERROR k.c.m.b.w.AbstractGeneralErrorRequestListener
  [n/a] - null
  java.lang.NullPointerException: null
  at org.hibernate.dialect.function.CastFunction.render(CastFunction.java:56)
  at org.hibernate.hql.ast.SqlGenerator.endFunctionTemplate(SqlGenerator.java:214)
  at org.hibernate.hql.antlr.SqlGeneratorBase.methodCall(SqlGeneratorBase.java:2325)
  at org.hibernate.hql.antlr.SqlGeneratorBase.simpleExpr(SqlGeneratorBase.java:2699)
  at org.hibernate.hql.antlr.SqlGeneratorBase.expr(SqlGeneratorBase.java:1465)
  at org.hibernate.hql.antlr.SqlGeneratorBase.binaryComparisonExpression(SqlGeneratorBase.java:2940)
  at org.hibernate.hql.antlr.SqlGeneratorBase.comparisonExpr(SqlGeneratorBase.java:1280)
  at org.hibernate.hql.antlr.SqlGeneratorBase.booleanExpr(SqlGeneratorBase.java:910)
  at org.hibernate.hql.antlr.SqlGeneratorBase.booleanOp(SqlGeneratorBase.java:2858)
  at org.hibernate.hql.antlr.SqlGeneratorBase.booleanExpr(SqlGeneratorBase.java:890)
  at org.hibernate.hql.antlr.SqlGeneratorBase.whereExpr(SqlGeneratorBase.java:768)
  at org.hibernate.hql.antlr.SqlGeneratorBase.selectStatement(SqlGeneratorBase.java:191)
  at org.hibernate.hql.antlr.SqlGeneratorBase.statement(SqlGeneratorBase.java:119)
  at org.hibernate.hql.ast.QueryTranslatorImpl.generate(QueryTranslatorImpl.java:240)
  at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:207)
  at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:138)
  at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
  at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
  at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)
  at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
  at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
  at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
  at java.lang.reflect.Method.invoke(Method.java:508)
  at org.springframework.orm.hibernate3.HibernateTemplate$CloseSuppressingInvocationHandler.invoke(HibernateTemplate.java:1387)
at com.sun.proxy.$Proxy2575.createQuery(Unknown Source)

I suspect the CAST or getdate() function cannot be used in HQL query.

Really appreciate if there is any idea or solution.


问:
java.lang.IllegalStateException: The remote endpoint was in state [TEXT_PARTIAL_WRITING] which is an invalid state for called method
my code:

```<code>myStompClient = new WebSocketStompClient(new SockJsClient(list));
mySession = myStompClient
        .connect(WEBSOCKET_URI, bankHeaders, new StompSessionHandlerAdapter() {
            @Override
            public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
                StompHeaders stompHeadersSubscribe = new StompHeaders();
                stompHeadersSubscribe.setDestination(CONSUMER_TECH_QUEUE);
                session.subscribe(stompHeadersSubscribe, new MyStompFrameHandler());// <-- this line fails
                .....
        }).get(5, TimeUnit.SECONDS);
</code>```

Sometimes I see in logs following:

```<code>org.springframework.messaging.MessageDeliveryException: nested exception is java.lang.IllegalStateException: The remote endpoint was in state [TEXT_PARTIAL_WRITING] which is an invalid state for called method, failedMessage=GenericMessage [payload=byte[0], headers={simpMessageType=SUBSCRIBE, stompCommand=SUBSCRIBE, nativeHeaders={destination=[/user/queue/consumer/tech], id=[0]}, simpSubscriptionId=0, simpSessionId=e8a5b506-9c09-1a7b-4674-4aecb6567426, simpDestination=/user/queue/consumer/tech}]
    at org.springframework.messaging.simp.stomp.DefaultStompSession.execute(DefaultStompSession.java:281)
    at org.springframework.messaging.simp.stomp.DefaultStompSession.subscribe(DefaultStompSession.java:312)
    at com.finvale.SimpleBankSimulator$1.afterConnected(SimpleBankSimulator.java:98)
    at org.springframework.messaging.simp.stomp.DefaultStompSession.handleMessage(DefaultStompSession.java:421)
    at org.springframework.web.socket.messaging.WebSocketStompClient$WebSocketTcpConnectionHandlerAdapter.handleMessage(WebSocketStompClient.java:342)
    at org.springframework.web.socket.sockjs.client.AbstractClientSockJsSession.handleMessageFrame(AbstractClientSockJsSession.java:271)
    at org.springframework.web.socket.sockjs.client.AbstractClientSockJsSession.handleFrame(AbstractClientSockJsSession.java:213)
    at org.springframework.web.socket.sockjs.client.WebSocketTransport$ClientSockJsWebSocketHandler.handleTextMessage(WebSocketTransport.java:162)
    at org.springframework.web.socket.handler.AbstractWebSocketHandler.handleMessage(AbstractWebSocketHandler.java:43)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.handleTextMessage(StandardWebSocketHandlerAdapter.java:110)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.access$000(StandardWebSocketHandlerAdapter.java:42)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:81)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:78)
    at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:399)
    at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:500)
    at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:295)
    at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:130)
    at org.apache.tomcat.websocket.WsFrameClient.processSocketRead(WsFrameClient.java:79)
    at org.apache.tomcat.websocket.WsFrameClient.access$300(WsFrameClient.java:31)
    at org.apache.tomcat.websocket.WsFrameClient$WsFrameClientCompletionHandler.completed(WsFrameClient.java:137)
    at org.apache.tomcat.websocket.WsFrameClient$WsFrameClientCompletionHandler.completed(WsFrameClient.java:120)
    at sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:126)
    at sun.nio.ch.Invoker$2.run(Invoker.java:218)
    at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: The remote endpoint was in state [TEXT_PARTIAL_WRITING] which is an invalid state for called method
    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$StateMachine.checkState(WsRemoteEndpointImplBase.java:1224)
    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$StateMachine.textPartialStart(WsRemoteEndpointImplBase.java:1182)
    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.sendPartialString(WsRemoteEndpointImplBase.java:222)
    at org.apache.tomcat.websocket.WsRemoteEndpointBasic.sendText(WsRemoteEndpointBasic.java:49)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketSession.sendTextMessage(StandardWebSocketSession.java:203)
    at org.springframework.web.socket.adapter.AbstractWebSocketSession.sendMessage(AbstractWebSocketSession.java:101)
    at org.springframework.web.socket.sockjs.client.WebSocketClientSockJsSession.sendInternal(WebSocketClientSockJsSession.java:126)
    at org.springframework.web.socket.sockjs.client.AbstractClientSockJsSession.sendMessage(AbstractClientSockJsSession.java:152)
    at org.springframework.web.socket.messaging.WebSocketStompClient$WebSocketTcpConnectionHandlerAdapter.send(WebSocketStompClient.java:383)
    at org.springframework.messaging.simp.stomp.DefaultStompSession.execute(DefaultStompSession.java:278)
    ... 26 more
</code>```

Sometimes it happens, sometimes - not.

I cannot understand reason, please clarify.

答:
I had this problem, and came up with a different approach which, as far as I can tell (this sort of issue seems to be reported about 4 times in stackOverflow...) has not been explored.

Catch the error, and if the write is busy, wait a while for it to complete and try again, like this. Thoughts?

```<code>static public void write(Session sess, String msg) {
    /*
     * to thwart the error: 'remote endpoint was in state [TEXT_FULL_WRITING] which
     * is an invalid state for called method use basic'
     * try, try again...
     */
    RemoteEndpoint.Basic basicRemote = sess.getBasicRemote();
    int i = 0; // tries...
    boolean bWriteSucceeded = false;
    if (verbose) {
        ; // you know... dump something somewhere...
    }
    if (sess.isOpen()) {
        for (i = 0; i < 10 && !bWriteSucceeded; i++) {
            try {
                // Crap. Sometimes getting this:
                // The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid
                // state for called method
                basicRemote.sendText(msg);
                bWriteSucceeded = true;
            } catch (IOException e) {
                // Enhance the auto-generated catch block to try again...
                // TODO: check for if (e == java.io.EOFException))
                if (i < 10 && !bWriteSucceeded) {
                    msleep(20);
                    System.out.println("Write tried:" + i + "times and failed.");
                    continue;
                } // Admit failure.
                System.out.println("Write failed: " + i + " retries. Dumping stackTrace");
                e.printStackTrace();
            }
        }
    }
    // succeed on first time and say nothing...
    if (bWriteSucceeded && i > 0)
        System.out.println("Write took " + i + " tries to succeed.");
    else
        System.out.println("Write failed after " + i + " retries.");
}
</code>```

And my version of msleep is just:

```<code>static void msleep(int ms) {
    try {
        System.out.printf("Sleeping...");
        Thread.sleep(ms);
        } catch (InterruptedException e) {
            System.out.printf("Exception caught");
            }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
my code:

myStompClient = new WebSocketStompClient(new SockJsClient(list));
mySession = myStompClient
        .connect(WEBSOCKET_URI, bankHeaders, new StompSessionHandlerAdapter() {
            @Override
            public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
                StompHeaders stompHeadersSubscribe = new StompHeaders();
                stompHeadersSubscribe.setDestination(CONSUMER_TECH_QUEUE);
                session.subscribe(stompHeadersSubscribe, new MyStompFrameHandler());// <-- this line fails
                .....
        }).get(5, TimeUnit.SECONDS);

Sometimes I see in logs following:

org.springframework.messaging.MessageDeliveryException: nested exception is java.lang.IllegalStateException: The remote endpoint was in state [TEXT_PARTIAL_WRITING] which is an invalid state for called method, failedMessage=GenericMessage [payload=byte[0], headers={simpMessageType=SUBSCRIBE, stompCommand=SUBSCRIBE, nativeHeaders={destination=[/user/queue/consumer/tech], id=[0]}, simpSubscriptionId=0, simpSessionId=e8a5b506-9c09-1a7b-4674-4aecb6567426, simpDestination=/user/queue/consumer/tech}]
    at org.springframework.messaging.simp.stomp.DefaultStompSession.execute(DefaultStompSession.java:281)
    at org.springframework.messaging.simp.stomp.DefaultStompSession.subscribe(DefaultStompSession.java:312)
    at com.finvale.SimpleBankSimulator$1.afterConnected(SimpleBankSimulator.java:98)
    at org.springframework.messaging.simp.stomp.DefaultStompSession.handleMessage(DefaultStompSession.java:421)
    at org.springframework.web.socket.messaging.WebSocketStompClient$WebSocketTcpConnectionHandlerAdapter.handleMessage(WebSocketStompClient.java:342)
    at org.springframework.web.socket.sockjs.client.AbstractClientSockJsSession.handleMessageFrame(AbstractClientSockJsSession.java:271)
    at org.springframework.web.socket.sockjs.client.AbstractClientSockJsSession.handleFrame(AbstractClientSockJsSession.java:213)
    at org.springframework.web.socket.sockjs.client.WebSocketTransport$ClientSockJsWebSocketHandler.handleTextMessage(WebSocketTransport.java:162)
    at org.springframework.web.socket.handler.AbstractWebSocketHandler.handleMessage(AbstractWebSocketHandler.java:43)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.handleTextMessage(StandardWebSocketHandlerAdapter.java:110)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.access$000(StandardWebSocketHandlerAdapter.java:42)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:81)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:78)
    at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:399)
    at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:500)
    at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:295)
    at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:130)
    at org.apache.tomcat.websocket.WsFrameClient.processSocketRead(WsFrameClient.java:79)
    at org.apache.tomcat.websocket.WsFrameClient.access$300(WsFrameClient.java:31)
    at org.apache.tomcat.websocket.WsFrameClient$WsFrameClientCompletionHandler.completed(WsFrameClient.java:137)
    at org.apache.tomcat.websocket.WsFrameClient$WsFrameClientCompletionHandler.completed(WsFrameClient.java:120)
    at sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:126)
    at sun.nio.ch.Invoker$2.run(Invoker.java:218)
    at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: The remote endpoint was in state [TEXT_PARTIAL_WRITING] which is an invalid state for called method
    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$StateMachine.checkState(WsRemoteEndpointImplBase.java:1224)
    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$StateMachine.textPartialStart(WsRemoteEndpointImplBase.java:1182)
    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.sendPartialString(WsRemoteEndpointImplBase.java:222)
    at org.apache.tomcat.websocket.WsRemoteEndpointBasic.sendText(WsRemoteEndpointBasic.java:49)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketSession.sendTextMessage(StandardWebSocketSession.java:203)
    at org.springframework.web.socket.adapter.AbstractWebSocketSession.sendMessage(AbstractWebSocketSession.java:101)
    at org.springframework.web.socket.sockjs.client.WebSocketClientSockJsSession.sendInternal(WebSocketClientSockJsSession.java:126)
    at org.springframework.web.socket.sockjs.client.AbstractClientSockJsSession.sendMessage(AbstractClientSockJsSession.java:152)
    at org.springframework.web.socket.messaging.WebSocketStompClient$WebSocketTcpConnectionHandlerAdapter.send(WebSocketStompClient.java:383)
    at org.springframework.messaging.simp.stomp.DefaultStompSession.execute(DefaultStompSession.java:278)
    ... 26 more

Sometimes it happens, sometimes - not.

I cannot understand reason, please clarify.

Body:
I had this problem, and came up with a different approach which, as far as I can tell (this sort of issue seems to be reported about 4 times in stackOverflow...) has not been explored.

Catch the error, and if the write is busy, wait a while for it to complete and try again, like this. Thoughts?

static public void write(Session sess, String msg) {
    /*
     * to thwart the error: 'remote endpoint was in state [TEXT_FULL_WRITING] which
     * is an invalid state for called method use basic'
     * try, try again...
     */
    RemoteEndpoint.Basic basicRemote = sess.getBasicRemote();
    int i = 0; // tries...
    boolean bWriteSucceeded = false;
    if (verbose) {
        ; // you know... dump something somewhere...
    }
    if (sess.isOpen()) {
        for (i = 0; i < 10 && !bWriteSucceeded; i++) {
            try {
                // Crap. Sometimes getting this:
                // The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid
                // state for called method
                basicRemote.sendText(msg);
                bWriteSucceeded = true;
            } catch (IOException e) {
                // Enhance the auto-generated catch block to try again...
                // TODO: check for if (e == java.io.EOFException))
                if (i < 10 && !bWriteSucceeded) {
                    msleep(20);
                    System.out.println("Write tried:" + i + "times and failed.");
                    continue;
                } // Admit failure.
                System.out.println("Write failed: " + i + " retries. Dumping stackTrace");
                e.printStackTrace();
            }
        }
    }
    // succeed on first time and say nothing...
    if (bWriteSucceeded && i > 0)
        System.out.println("Write took " + i + " tries to succeed.");
    else
        System.out.println("Write failed after " + i + " retries.");
}

And my version of msleep is just:

static void msleep(int ms) {
    try {
        System.out.printf("Sleeping...");
        Thread.sleep(ms);
        } catch (InterruptedException e) {
            System.out.printf("Exception caught");
            }

}


问:
Question about Java synchronized
The Java documentation says that "it is not possible for two invocations of synchronized methods on the same object to interleave".  What I need to know is whether synchronized will also prevent a synchronized method in two different instances of the same class from interleaving.

E.g. class Worker has method called process().  We have several instances of Worker running in their own threads.  We want to prevent more than one instance running the process() method simultaneously.  Will synchronized do this?

Thanks.

答:
No; synchronized only prevents multiple threads from simultaneously executing the method in the same instance. If you have n instances, there could be n threads, each executing the method in one of the instances.

If you need to ensure that only one thread may execute the method across all instances, you should make the method static, or make the method non-synchronized and rather use a synchronized block inside the method to lock on a private static field.

Edit: Note that synchronizing on a private instance variable is preferrable to having a synchronized method or to synchronize on this, and that locking on a private static instance variable is preferrable to having a static synchronized method or an instance method that synchronizes on this.getClass(). The reason is that this and this.getClass() are object references that are accessible throughout the program, so anybody may synchronize on these objects, and thereby block threads that want to call your method.

Edit: Also, see @Cowan's comment below - summary: if you really want to lock on the class, you might want to use synchronized (Worker.class) rather than synchronized (this.getClass()), depending on what effect you want in the case of subclassing.

Title: Question about Java synchronized


问:
What are the roles of _read and read in Node JS streams?
I'm really just looking for clarification on how these work. IMO the documentation on streams is somewhat lacking, and there actually aren't a lot of resources out their that comprehensively explain explain how they're are meant to work and be extended.

My question can be broken down into two parts

One, What is the role of the _read function within the stream module? When I run this code it endlessly prints out "hello world" until null is pushed onto the stream buffer. This seems to indicate that _read is called in some kind of loop that waits for a null in the buffer, but I can't find documentation anywhere that states this in explicit terms.

```<code>var Readable = require('stream').Readable
var rs = Readable()

rs._read = function () {
    rs.push("hello world")
    rs.push(null)
};

rs.on("data", function(data){
    console.log("some data", data)
})
</code>```

Two, what does read actually do? My understanding is that read consumes data from the read stream buffer, and fires the data event. Is that all that's going on here?

答:
read() is something that a consumer of the readStream calls if they want to specifically read some bytes from the stream (when the stream is not flowing).

_read() is an internal method that is part of the internal implementation of the read stream.  The internals of the stream call this method (it is NOT to be called from the outside) when the stream is flowing and the stream wants to get more data from the source.  When called the _read() method pushes data with .push(data) or if it has no more data, then it does a .push(null).

You can see an explanation and example here in this article.

```<code>_read(size) {
    if (this.data.length) {
        const chunk = this.data.slice(0, size);
        this.data = this.data.slice(size, this.data.length);
        this.push(chunk);
    } else {
        this.push(null); // 'end', no more data
    }
}
</code>```

If you were implementing a read stream to some custom source of data, then you would implement the _read() method to fetch up to the size amount of data from your source and .push() that data into the stream.

Body:
I'm really just looking for clarification on how these work. IMO the documentation on streams is somewhat lacking, and there actually aren't a lot of resources out their that comprehensively explain explain how they're are meant to work and be extended.

My question can be broken down into two parts

One, What is the role of the _read function within the stream module? When I run this code it endlessly prints out "hello world" until null is pushed onto the stream buffer. This seems to indicate that _read is called in some kind of loop that waits for a null in the buffer, but I can't find documentation anywhere that states this in explicit terms.

var Readable = require('stream').Readable
var rs = Readable()

rs._read = function () {
    rs.push("hello world")
    rs.push(null)
};

rs.on("data", function(data){
    console.log("some data", data)
})

Two, what does read actually do? My understanding is that read consumes data from the read stream buffer, and fires the data event. Is that all that's going on here?

Body:
read() is something that a consumer of the readStream calls if they want to specifically read some bytes from the stream (when the stream is not flowing).

_read() is an internal method that is part of the internal implementation of the read stream.  The internals of the stream call this method (it is NOT to be called from the outside) when the stream is flowing and the stream wants to get more data from the source.  When called the _read() method pushes data with .push(data) or if it has no more data, then it does a .push(null).

You can see an explanation and example here in this article.

_read(size) {
    if (this.data.length) {
        const chunk = this.data.slice(0, size);
        this.data = this.data.slice(size, this.data.length);
        this.push(chunk);
    } else {
        this.push(null); // 'end', no more data
    }
}

If you were implementing a read stream to some custom source of data, then you would implement the _read() method to fetch up to the size amount of data from your source and .push() that data into the stream.


问:
React JS and css pseudo element ::after ::before
As a React beginner I'm currently struggling with it for rendering styled components with the use of pseudo elements ::after and ::before.

Here is the sass style for a button: https://jsfiddle.net/r8qwhfvx/
It is what I try to achieve in React: changing the style of my button on hover using pseudo elements.

But how to use ::after / ::before in the className of button components for instance? JSX syntax unable the use of ::after / ::before in the components className.

I'm just able to write this:

```<code>return(
    <button className='infoBtn'></button>
);
</code>```

Please check jsfiddle link.

答:
className JSX attribute is a string variable, which will be set as the class attribute value on the HTML element when it will be rendered by React. CSS pseudo elements can appear in CSS code, not as a class name for a HTML element.

So you need to give a class name to your button using className JSX attribute, then define CSS rules for this class. To do so you need to choose a strategy to setup CSS in your React app. There is multiple solutions :

use a plain old CSS file imported in your index.js or index.html

use a plain old style element in your index.html (these 2 options are global, like in plain old 90's web development)

use JSX "style" attribute : <Component style={{here put CSS object}} /> : https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/

use CSS modules (if you are using create-react-app) : https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/

use styled-components or any other CSS-in-JS option, there is a lot of solutions, I mention styled-components since it is one of the most popular

With all of these options you will be able to use CSS pseudo-element. For SASS you may have to setup a CSS preprocessor. If you are using create-react-app (https://create-react-app.dev/docs/adding-a-sass-stylesheet/) or styled-components (https://styled-components.com/docs/faqs#can-i-nest-rules) you're good to go, it's build in. Well for styled-components I'm not sure if it is a true full SASS support though.

Good luck with that !

Body:
As a React beginner I'm currently struggling with it for rendering styled components with the use of pseudo elements ::after and ::before.

Here is the sass style for a button: https://jsfiddle.net/r8qwhfvx/
It is what I try to achieve in React: changing the style of my button on hover using pseudo elements.

But how to use ::after / ::before in the className of button components for instance? JSX syntax unable the use of ::after / ::before in the components className.

I'm just able to write this:

return(
    <button className='infoBtn'></button>
);

Please check jsfiddle link.


问:
Mql4 undeclared identifier for delete object
I am using the code from the example here Keep order details in arrays?

I am getting an error of listOfTrades - undeclared identifier when I add the code in the

```<code>void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();

   delete(listOfTrades);

  }
</code>```

I have a feeling it is because listOfTrades is declared in the OnInit() and not outside global but not sure how that would affect it.

Main.mql

```<code>#include <CTrade.mqh>

int OnInit()
  {
    CArrayObj *listOfTrades=new CArrayObj;
  }

void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();

   delete(listOfTrades);

  }
</code>```

答:
Yes, you have to declare that globally, before calling OnInit(). Missed that point in the mentioned question, will update.

If you pass the object by pointer somehow void OnTick(){ doSomeFunction(listOfTrades); } then you should make sure the same variable name is not used (at least in the same file), otherwise you will have warnings that some day may become a bug.

```<code>void doSomeFunction(CArrayObj* _listOfTrades)// not "listOfTrades" !!!
  {
   for(int i=_listOfTrades.Total()-1;i>=0;i--)
     {
      CTrade* trade=_listOfTrades.At(i);
      // action with CTrade object
     }
  }
</code>```

Body:
I am using the code from the example here Keep order details in arrays?

I am getting an error of listOfTrades - undeclared identifier when I add the code in the

void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();

   delete(listOfTrades);

  }

I have a feeling it is because listOfTrades is declared in the OnInit() and not outside global but not sure how that would affect it.

Main.mql

#include <CTrade.mqh>

int OnInit()
  {
    CArrayObj *listOfTrades=new CArrayObj;
  }

void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();

   delete(listOfTrades);

  }

Body:
Yes, you have to declare that globally, before calling OnInit(). Missed that point in the mentioned question, will update.

If you pass the object by pointer somehow void OnTick(){ doSomeFunction(listOfTrades); } then you should make sure the same variable name is not used (at least in the same file), otherwise you will have warnings that some day may become a bug.

void doSomeFunction(CArrayObj* _listOfTrades)// not "listOfTrades" !!!
  {
   for(int i=_listOfTrades.Total()-1;i>=0;i--)
     {
      CTrade* trade=_listOfTrades.At(i);
      // action with CTrade object
     }
  }


问:
Why this function acts like loop when it executed couple times
Why is this function acts like loop when it executed couple times did this counter stored in the add function or not

let counter = 0;

function add() {
  return counter++;
}

console.log(add());
console.log(add());
console.log(add());
console.log(add());
```
<p>if it increments I don't understand its difference from this while loop</p>
```let i = 0;
while(i <= 3){
  console.log(i)
  i++;
}
```

答:
that add() function if executed couple time it will act like loop but not real loop because this doesn't need condition to stop iterating so this is the function not the loop
and even if it iterates it take no condition

Body:
Why is this function acts like loop when it executed couple times did this counter stored in the add function or not

let counter = 0;

function add() {
  return counter++;
}

console.log(add());
console.log(add());
console.log(add());
console.log(add());

if it increments I don't understand its difference from this while loop

let i = 0;
while(i <= 3){
  console.log(i)
  i++;
}


问:
Adding AWS Cognito User Pool role using CDK
I have deployed https://github.com/aws-samples/amazon-elasticsearch-service-with-cognito to my stack, and am trying to add a master group as per https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/fgac.html#fgac-walkthrough-iam

So I have added to the following https://github.com/aws-samples/amazon-elasticsearch-service-with-cognito/blob/master/lib/search-stack.ts#L50

```<code>diff --git a/lib/search-stack.ts b/lib/search-stack.ts
index 85de0c0..2493c92 100644
--- a/lib/search-stack.ts
+++ b/lib/search-stack.ts
@@ -3,7 +3,7 @@

 import { Fn, Stack, Construct, StackProps, CfnParameter, CfnOutput } from '@aws-cdk/core';
 import { CfnDomain } from '@aws-cdk/aws-elasticsearch';
-import { UserPoolAttribute, CfnUserPoolDomain, CfnIdentityPool, CfnIdentityPoolRoleAttachment, CfnUserPool } from '@aws-cdk/aws-cognito';
+import { UserPoolAttribute, CfnUserPoolDomain, CfnIdentityPool, CfnIdentityPoolRoleAttachment, CfnUserPool, CfnUserPoolGroup } from '@aws-cdk/aws-cognito';
 import { Role, ManagedPolicy, ServicePrincipal, FederatedPrincipal } from '@aws-cdk/aws-iam';
 import { CustomResource } from '@aws-cdk/aws-cloudformation';

@@ -55,6 +55,19 @@ export class SearchStack extends Stack {
       }, "sts:AssumeRoleWithWebIdentity")
     });

+    // create two groups, one for admins one for users
+
+    new CfnUserPoolGroup(this, "AdminsGroup", {
+      groupName: "master-user-group",
+      userPoolId: idPool.ref,
+
+    });
+
+    new CfnUserPoolGroup(this, "UsersGroup", {
+      groupName: "limited-user-group",
+      userPoolId: idPool.ref,
+    });
+
     const esRole = new Role(this, "esRole", {
       assumedBy: new ServicePrincipal('es.amazonaws.com'),
       managedPolicies: [ManagedPolicy.fromAwsManagedPolicyName("AmazonESCognitoAccess")]
~
</code>```

but after redeploying the roles are not being created!

any advice is much appreciated.

答:
OK, I needed to use:

```<code>
    new CfnUserPoolGroup(this, "AdminsGroup", {
      groupName: "master-user-group",
      userPoolId: userPool.ref
    });

    new CfnUserPoolGroup(this, "UsersGroup", {
      groupName: "limited-user-group",
      userPoolId: userPool.ref
    });

</code>```

instead of idPool.ref

Body:
I have deployed https://github.com/aws-samples/amazon-elasticsearch-service-with-cognito to my stack, and am trying to add a master group as per https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/fgac.html#fgac-walkthrough-iam

So I have added to the following https://github.com/aws-samples/amazon-elasticsearch-service-with-cognito/blob/master/lib/search-stack.ts#L50

diff --git a/lib/search-stack.ts b/lib/search-stack.ts
index 85de0c0..2493c92 100644
--- a/lib/search-stack.ts
+++ b/lib/search-stack.ts
@@ -3,7 +3,7 @@

 import { Fn, Stack, Construct, StackProps, CfnParameter, CfnOutput } from '@aws-cdk/core';
 import { CfnDomain } from '@aws-cdk/aws-elasticsearch';
-import { UserPoolAttribute, CfnUserPoolDomain, CfnIdentityPool, CfnIdentityPoolRoleAttachment, CfnUserPool } from '@aws-cdk/aws-cognito';
+import { UserPoolAttribute, CfnUserPoolDomain, CfnIdentityPool, CfnIdentityPoolRoleAttachment, CfnUserPool, CfnUserPoolGroup } from '@aws-cdk/aws-cognito';
 import { Role, ManagedPolicy, ServicePrincipal, FederatedPrincipal } from '@aws-cdk/aws-iam';
 import { CustomResource } from '@aws-cdk/aws-cloudformation';

@@ -55,6 +55,19 @@ export class SearchStack extends Stack {
       }, "sts:AssumeRoleWithWebIdentity")
     });

+    // create two groups, one for admins one for users
+
+    new CfnUserPoolGroup(this, "AdminsGroup", {
+      groupName: "master-user-group",
+      userPoolId: idPool.ref,
+
+    });
+
+    new CfnUserPoolGroup(this, "UsersGroup", {
+      groupName: "limited-user-group",
+      userPoolId: idPool.ref,
+    });
+
     const esRole = new Role(this, "esRole", {
       assumedBy: new ServicePrincipal('es.amazonaws.com'),
       managedPolicies: [ManagedPolicy.fromAwsManagedPolicyName("AmazonESCognitoAccess")]
~

but after redeploying the roles are not being created!

any advice is much appreciated.

Body:
OK, I needed to use:

    new CfnUserPoolGroup(this, "AdminsGroup", {
      groupName: "master-user-group",
      userPoolId: userPool.ref
    });

    new CfnUserPoolGroup(this, "UsersGroup", {
      groupName: "limited-user-group",
      userPoolId: userPool.ref
    });

instead of idPool.ref


问:
Getting bash to ignore bash keywords in a script
I have a script in bash which uses the HTK toolkit. One of the files that the HTK tool uses is called do and is present within a directory called hmm_1/. Now, when I need to call a particular tool from within the HTK toolkit, I do it like so:

some HTK command -H hmm_1/do -H hmm_1/<something else> and so on. I just noticed that gvim highlights the do file name in the above command, thinking it is a keyword. However, it is a file name. My question is:

Will bash interpret it as a keyword or does bash know better (it is just a gvim quirk).

How can I get bash to "know" that some variable names, though innocuously named like keywords are not that and are instead filenames?

Note: I cannot change the name of the file now. I will have to backtrack through a large number of steps.

I just don't know how to phrase this question. Help in editing the question line is most welcome.

答: As part of a path, keywords will be ignored. They will only be interpreted as a keyword at the beginning of a command. It would be best to simply consider gvim's highlighting to be a minor annoyance and ignore it.


问:
Speeding up normal distribution probability mass allocation
We have N users with P avg. points per user, where each point is a single value between 0 and 1. We need to distribute the mass of each point using a normal distribution with a known density of 0.05 as the points have some uncertainty. Additionally, we need to wrap the mass around 0 and 1 such that e.g. a point at 0.95 will also allocate mass around 0. I've provided a working example below, which bins the normal distribution into D=50 bins. The example uses the Python typing module, but you can ignore that if you'd like.

```<code>from typing import List, Any
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt

D = 50
BINS: List[float] = np.linspace(0, 1, D + 1).tolist()

def probability_mass(distribution: Any, x0: float, x1: float) -> float:
    """
    Computes the area under the distribution, wrapping at 1.
    The wrapping is done by adding the PDF at +- 1.
    """
    assert x1 > x0
    return (
        (distribution.cdf(x1) - distribution.cdf(x0))
        + (distribution.cdf(x1 + 1) - distribution.cdf(x0 + 1))
        + (distribution.cdf(x1 - 1) - distribution.cdf(x0 - 1))
    )

def point_density(x: float) -> List[float]:
    distribution: Any = scipy.stats.norm(loc=x, scale=0.05)
    density: List[float] = []
    for i in range(D):
        density.append(probability_mass(distribution, BINS[i], BINS[i + 1]))
    return density

def user_density(points: List[float]) -> Any:

    # Find the density of each point
    density: Any = np.array([point_density(p) for p in points])

    # Combine points and normalize
    combined = density.sum(axis=0)
    return combined / combined.sum()

if __name__ == "__main__":

    # Example for one user
    data: List[float] = [.05, .3, .5, .5]
    density = user_density(data)

    # Example for multiple users (N = 2)
    print([user_density(x) for x in [[.3, .5], [.7, .7, .7, .9]]])

    ### NB: THE REMAINING CODE IS FOR ILLUSTRATION ONLY!
    ### NB: THE IMPORTANT THING IS TO COMPUTE THE DENSITY FAST!
    middle: List[float] = []
    for i in range(D):
        middle.append((BINS[i] + BINS[i + 1]) / 2)
    plt.bar(x=middle, height=density, width=1.0 / D + 0.001)
    plt.xlim(0, 1)
    plt.xlabel("x")
    plt.ylabel("Density")
    plt.show()
</code>```

In this example N=1, D=50, P=4. However, we want to scale this approach to N=10000 and P=100 while being as fast as possible. It's unclear to me how we'd vectorize this approach. How do we best speed up this?

EDIT

The faster solution can have slightly different results. For instance, it could approximate the normal distribution instead of using the precise normal distribution.

EDIT2

We only care about computing density using the user_density() function. The plot is only to help explain the approach. We do not care about the plot itself :)

EDIT3

Note that P is the avg. points per user. Some users may have more and some may have less. If it helps, you can assume that we can throw away points such that all users have a max of 2 * P points. It's fine to ignore this part while benchmarking as long as the solution can handle a flexible # of points per user.

答:
This would be my vectorized approach:

```<code>data = np.array([0.05, 0.3, 0.5, 0.5])

np.random.seed(31415)
# random noise
randoms = np.random.normal(0,1,(len(data), int(1e5))) * 0.05

# samples with noise
samples = data[:,None] + randoms

# wrap [0,1]
samples = (samples % 1).ravel()

# histogram
hist, bins, patches = plt.hist(samples, bins=BINS, density=True)
</code>```

Output:

Body:
We have N users with P avg. points per user, where each point is a single value between 0 and 1. We need to distribute the mass of each point using a normal distribution with a known density of 0.05 as the points have some uncertainty. Additionally, we need to wrap the mass around 0 and 1 such that e.g. a point at 0.95 will also allocate mass around 0. I've provided a working example below, which bins the normal distribution into D=50 bins. The example uses the Python typing module, but you can ignore that if you'd like.

from typing import List, Any
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt

D = 50
BINS: List[float] = np.linspace(0, 1, D + 1).tolist()

def probability_mass(distribution: Any, x0: float, x1: float) -> float:
    """
    Computes the area under the distribution, wrapping at 1.
    The wrapping is done by adding the PDF at +- 1.
    """
    assert x1 > x0
    return (
        (distribution.cdf(x1) - distribution.cdf(x0))
        + (distribution.cdf(x1 + 1) - distribution.cdf(x0 + 1))
        + (distribution.cdf(x1 - 1) - distribution.cdf(x0 - 1))
    )

def point_density(x: float) -> List[float]:
    distribution: Any = scipy.stats.norm(loc=x, scale=0.05)
    density: List[float] = []
    for i in range(D):
        density.append(probability_mass(distribution, BINS[i], BINS[i + 1]))
    return density

def user_density(points: List[float]) -> Any:

    # Find the density of each point
    density: Any = np.array([point_density(p) for p in points])

    # Combine points and normalize
    combined = density.sum(axis=0)
    return combined / combined.sum()

if __name__ == "__main__":

    # Example for one user
    data: List[float] = [.05, .3, .5, .5]
    density = user_density(data)

    # Example for multiple users (N = 2)
    print([user_density(x) for x in [[.3, .5], [.7, .7, .7, .9]]])

    ### NB: THE REMAINING CODE IS FOR ILLUSTRATION ONLY!
    ### NB: THE IMPORTANT THING IS TO COMPUTE THE DENSITY FAST!
    middle: List[float] = []
    for i in range(D):
        middle.append((BINS[i] + BINS[i + 1]) / 2)
    plt.bar(x=middle, height=density, width=1.0 / D + 0.001)
    plt.xlim(0, 1)
    plt.xlabel("x")
    plt.ylabel("Density")
    plt.show()

In this example N=1, D=50, P=4. However, we want to scale this approach to N=10000 and P=100 while being as fast as possible. It's unclear to me how we'd vectorize this approach. How do we best speed up this?

EDIT

The faster solution can have slightly different results. For instance, it could approximate the normal distribution instead of using the precise normal distribution.

EDIT2

We only care about computing density using the user_density() function. The plot is only to help explain the approach. We do not care about the plot itself :)

EDIT3

Note that P is the avg. points per user. Some users may have more and some may have less. If it helps, you can assume that we can throw away points such that all users have a max of 2 * P points. It's fine to ignore this part while benchmarking as long as the solution can handle a flexible # of points per user.

Body:
This would be my vectorized approach:

data = np.array([0.05, 0.3, 0.5, 0.5])

np.random.seed(31415)
# random noise
randoms = np.random.normal(0,1,(len(data), int(1e5))) * 0.05

# samples with noise
samples = data[:,None] + randoms

# wrap [0,1]
samples = (samples % 1).ravel()

# histogram
hist, bins, patches = plt.hist(samples, bins=BINS, density=True)

Output:


问:
Ingestion port for seq in serilog
I've installed seq on a local server using dockers, here the docker command:

```<code>docker run -d \
 --restart unless-stopped \
 --name seq \
 -e ACCEPT_EULA=Y \
 -v /var/log/seq:/data \
 -p 8680:80 \
 -p 8631:5431 \
 datalust/seq:latest
</code>```

Then, I configured my project to send Logs to the server using app.config files. File extract here:

```<code><!-- log server -->
<add key="serilog:using:Seq" value="Serilog.Sinks.Seq" />
<add key="serilog:write-to:Seq.serverUrl" value="http://192.168.1.200:8680" />
<add key="serilog:write-to:Seq.apiKey" value="CONFIGURED-API-KEY-HERE" />
<add key="serilog:write-to:Seq.restrictedToMinimumLevel" value="Debug"/>
</code>```

I couldn't get it to work until I changed server port to 8680. Before I was getting System.Net.Sockets.SocketException: Connection refused exception.

The point is, shouldn't I use 8631 port instead of 8680? 8680 port is just for website, 8631 should be ingestion port. Am I missing something?

答:
The problem is the port mapping:

```<code>-p 8631:5431
</code>```

The Seq ingestion port is port 5341, not 5431, so this needs to be:

```<code>-p 8631:5341
</code>```

Title: Ingestion port for seq in serilog

Body:
I've installed seq on a local server using dockers, here the docker command:

docker run -d \
 --restart unless-stopped \
 --name seq \
 -e ACCEPT_EULA=Y \
 -v /var/log/seq:/data \
 -p 8680:80 \
 -p 8631:5431 \
 datalust/seq:latest

Then, I configured my project to send Logs to the server using app.config files. File extract here:

<add key="serilog:using:Seq" value="Serilog.Sinks.Seq" />
<add key="serilog:write-to:Seq.serverUrl" value="http://192.168.1.200:8680" />
<add key="serilog:write-to:Seq.apiKey" value="CONFIGURED-API-KEY-HERE" />
<add key="serilog:write-to:Seq.restrictedToMinimumLevel" value="Debug"/>

I couldn't get it to work until I changed server port to 8680. Before I was getting System.Net.Sockets.SocketException: Connection refused exception.

The point is, shouldn't I use 8631 port instead of 8680? 8680 port is just for website, 8631 should be ingestion port. Am I missing something?

Body:
The problem is the port mapping:

-p 8631:5431

The Seq ingestion port is port 5341, not 5431, so this needs to be:

-p 8631:5341


问:
Cannot Understand The Exception
This is the code :

```<code>import java.awt.*;
import javax.swing.*;

class tester {
JFrame fr;
JPanel p;
Graphics g;

tester() {
 buildGUI();
}

public void buildGUI() {
 fr=new JFrame();
 p=new JPanel();
 p.setBackground(Color.red);
 g.setColor(Color.black);
 g.drawOval(18,45,78,39);
 g.fillOval(18,45,78,39);
 fr.add(p);
 fr.setVisible(true);
 fr.setSize(500,500);
}

 public static void main(String args[]) {
  new tester();
 }
}
</code>```

These are the exceptions produced when i try to run the code :

Exception in thread "main" java.lang.NullPointerException
        at tester.buildGUI(tester.java:17)
        at tester.<init>(tester.java:10)
        at tester.main(tester.java:26)

Why do i get these exceptions?
How can i solve it.

答:
You haven't initialized Graphics g

You should implement a paint method and move the logic for drawing the background into that (see the JavaDoc on paint)

Title: Cannot Understand The Exception

Body:
This is the code :

import java.awt.*;
import javax.swing.*;

class tester {
JFrame fr;
JPanel p;
Graphics g;

tester() {
 buildGUI();
}

public void buildGUI() {
 fr=new JFrame();
 p=new JPanel();
 p.setBackground(Color.red);
 g.setColor(Color.black);
 g.drawOval(18,45,78,39);
 g.fillOval(18,45,78,39);
 fr.add(p);
 fr.setVisible(true);
 fr.setSize(500,500);
}

 public static void main(String args[]) {
  new tester();
 }
}

These are the exceptions produced when i try to run the code :

Exception in thread "main" java.lang.NullPointerException
        at tester.buildGUI(tester.java:17)
        at tester.<init>(tester.java:10)
        at tester.main(tester.java:26)

Why do i get these exceptions?
How can i solve it.


问:
R Arules Item Frequency Plot Rotate Axis labels
I'm doing some pattern mining in R using library(arules). Using ItemFrequencyPlot I am trying to rotate the x-axis labels and scale the axis names.

```<code>library(arules)
data(Adult)
itemFrequencyPlot(Adult, topN=20, cex.names=0.7, las = 2, srt = 90, main = "Item frequency plot") #example
</code>```

Scaling I can do with cex.names. However, when it comes to rotating the axis labels, I'm having a hard time doing so. I have tried both variations of las and srt. In all, it seems a bit clunky, so perhaps there is another way for visualising it?

How to rotate the axis labels (and access other graphical elements of the item frequency plot to tweak it)?

答:
itemFrequencyPlot does not appear to allow you to control those labels, but it is after all just a barplot, which does give you more control of the appearance. So just make your own. Here is how. Get the top 20 frequencies. Leave lots of room for the long axis labels. And plot!

```<code>iF20 = rev(tail(sort(itemFrequency(Adult)), 20))
par(mar=c(12,4,1,1))
barplot(iF20, las=2, cex.names=0.8)
</code>```

Body:
I'm doing some pattern mining in R using library(arules). Using ItemFrequencyPlot I am trying to rotate the x-axis labels and scale the axis names.

library(arules)
data(Adult)
itemFrequencyPlot(Adult, topN=20, cex.names=0.7, las = 2, srt = 90, main = "Item frequency plot") #example

Scaling I can do with cex.names. However, when it comes to rotating the axis labels, I'm having a hard time doing so. I have tried both variations of las and srt. In all, it seems a bit clunky, so perhaps there is another way for visualising it?

How to rotate the axis labels (and access other graphical elements of the item frequency plot to tweak it)?

Body:
itemFrequencyPlot does not appear to allow you to control those labels, but it is after all just a barplot, which does give you more control of the appearance. So just make your own. Here is how. Get the top 20 frequencies. Leave lots of room for the long axis labels. And plot!

iF20 = rev(tail(sort(itemFrequency(Adult)), 20))
par(mar=c(12,4,1,1))
barplot(iF20, las=2, cex.names=0.8)


问:
nifi ingestion with 10,000+ sensor data?
I am planning to use nifi to ingest data from more than 10,000 sensors. There are 50-100 types of sensors which will send a specific metric to nifi.

I am pondering over whether I should assign 1 port number to listen to all the sensors or I should assign 1 port for each type of sensor to facilitate my data pipeline. which is the better option?

Is there a upper limit of the no of ports which I can "listen" using nifi?

答:
I agree with the other answer that once scaling comes into play, an external load balancer in front of NiFi would be helpful.

In regards to the flow design, I would suggest using a single exposed port to ingest all the data, and then use RouteOnAttribute or RouteOnContent processors to direct specific sensor inputs into different flow segments.

One of the strengths of NiFi is the generic nature of flows given sufficient parameterization, so taking advantage of flowfile attributes to handle different data types dynamically scales and performs better than duplicating a lot of flow segments to statically handle slightly differing data.

The performance overhead to run multiple ingestion ports vs. a single port and routed flowfiles is substantial, so this will give you a large performance improvement. You can also organize your flow segments into hierarchical nested groups using the Process Group features, to keep different flow segments cleanly organized and enforce access controls as well.

2020-06-02 Edit to answer questions in comments

Yes, you would have a lot of relationships coming out of the initial RouteOnAttribute processor at the ingestion port. However, you can segment these (route all flowfiles with X attribute in "family" X here, Y here, etc.) and send each to a different process group which encapsulates more specific logic.

Think of it like a physical network: at a large organization, you don't buy 1000 external network connections and hook each individual user's machine directly to the internet. Instead, you obtain one (plus redundancy/backup) large connection to the internet and use a router internally to direct the traffic to the appropriate endpoint. This has management benefits as well as cost, scalability, etc.

The overhead of multiple ingestion ports is that you have additional network requirements (S2S is very efficient when communicating, but there is overhead on a connection basis), multiple ports to be opened and monitored, and CPU to schedule & run each port's ingestion logic.

I've observed this pattern in practice at scale in multinational commercial and government organizations, and the performance improvement was significant when switching to a "single port; route flowfiles" pattern vs. "input port per flow" design. It is possible to accomplish what you want with either design, but I think this will be much more performant and easier to build & maintain.


问:
How to use references/pointers with mathematical operations in c++?
I'm pretty new to C++ pointers and references. Say I have two variables i1 and i2, is there a way I can track their difference (or any other operation), even if one of them changes. My attempt at this is shown below, as well as what I want to achieve.

int i1 = 20;
int i2 = 20;
int*r1 = &i1;
int*r2 = &i2;
int s  = *r1-*r2;
std::cout << s << std::endl;
i1 = 40;
std::cout << s << std::endl;
//OUTPUT
//0 <- 20-20
//0 <- How do I make this 20, since 40-20 is 20
```

答:
What you are asking for is not doable, as you can't take a reference to an expression. Once you have saved the result of the expression *r1 - *r2 into your s variable, you would have to perform the *r1 - *r2 expression again after updating the source values to save a new result into s, eg:

```<code>int  i1 = 20;
int  i2 = 20;
int *r1 = &i1;
int *r2 = &i2;
int  s  = *r1 - *r2;
std::cout << s << std::endl;
i1 = 40;
s = *r1 - *r2; // <-- ADD THIS!
std::cout << s << std::endl;
//OUTPUT
//0 <- 20-20
//20 <- 40-20
</code>```

Live Demo

For what you are attempting, you might consider using use a lambda instead, let it capture references to the original variables, and then you can invoke the lambda when needed so it can calculate a new result each time, eg:

```<code>int i1 = 20;
int i2 = 20;
auto s = [&]{ return i1 - i2; };
std::cout << s() << std::endl;
i1 = 40;
std::cout << s() << std::endl;
//OUTPUT
//0 <- 20-20
//20 <- 40-20
</code>```

Live Demo

Body:
What you are asking for is not doable, as you can't take a reference to an expression. Once you have saved the result of the expression *r1 - *r2 into your s variable, you would have to perform the *r1 - *r2 expression again after updating the source values to save a new result into s, eg:

int  i1 = 20;
int  i2 = 20;
int *r1 = &i1;
int *r2 = &i2;
int  s  = *r1 - *r2;
std::cout << s << std::endl;
i1 = 40;
s = *r1 - *r2; // <-- ADD THIS!
std::cout << s << std::endl;
//OUTPUT
//0 <- 20-20
//20 <- 40-20

Live Demo

For what you are attempting, you might consider using use a lambda instead, let it capture references to the original variables, and then you can invoke the lambda when needed so it can calculate a new result each time, eg:

int i1 = 20;
int i2 = 20;
auto s = [&]{ return i1 - i2; };
std::cout << s() << std::endl;
i1 = 40;
std::cout << s() << std::endl;
//OUTPUT
//0 <- 20-20
//20 <- 40-20

Live Demo


问:
Flutter: How to save user's input from a ListView.builder of TextFields
I'm trying to save user's input from a ListView.builder of TextFields in a list of objects when he presses a button. Screnshot

I would like that when the user presses the button save, all the hello words were storaged as the text property of my object.

That is my code:

```<code>class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    ListData listData = Provider.of<ListData>(context, listen: false);

    return Scaffold(
      appBar: AppBar(
        title: Text('Add Textfields'),
        actions: <Widget>[
          FlatButton(
            color: Colors.red,
            onPressed: () {},
            child: Text('Save'),
          ),
        ],
      ),
      body: ListView(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 50),
            child: TextFieldBuilder(),
          ),
          SizedBox(height: 50),
          FlatButton(
            onPressed: () {
              listData.addTextField();
            },
            child: Text(
              'Add',
              style: TextStyle(
                letterSpacing: 4,
                fontWeight: FontWeight.w900,
                fontSize: 16,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

The Builderclass:

```<code>class TextFieldBuilder extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<ListData>(
      builder: (context, listData, child) {
        return ListView.builder(
          itemCount: listData.textFieldList.length,
          itemBuilder: (context, index) {
            return TextFieldWidget(index: index);
          },
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
        );
      },
    );
  }
}
</code>```

TextFieldWidget:

```<code>class TextFieldWidget extends StatelessWidget {
  final int index;

  TextFieldWidget({this.index});

  @override
  Widget build(BuildContext context) {
    return TextField(
      textAlign: TextAlign.center,
    );
  }
}
</code>```

And the list of objects:

```<code>class TextFieldData {
  String text;

  TextFieldData({this.text});
}

class ListData extends ChangeNotifier {
  List<TextFieldData> textFieldList = [];

  void addTextField() {
    textFieldList.add(TextFieldData());
    notifyListeners();
  }
}
</code>```

答:
I finally got the solution:

First creating a List<TextEditingController> and after a for loop in the 'Save' button. Here is the code:

```<code>class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    ListData listData = Provider.of<ListData>(context, listen: false);

    return Scaffold(
      appBar: AppBar(
        title: Text('Add Textfields'),
        actions: <Widget>[
          FlatButton(
            color: Colors.red,
            onPressed: () {
              for (int i = 0; i < listData.textFieldList.length; i++) {
                listData.textFieldList[i].text = listData.controllers[i].text;      // for loop
              }
            },
            child: Text('Save'),
          ),
        ],
      ),
      body: ListView(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 50),
            child: TextFieldBuilder(),
          ),
          SizedBox(height: 50),
          FlatButton(
            onPressed: () {
              listData.addTextField();
            },
            child: Text(
              'Add',
              style: TextStyle(
                letterSpacing: 4,
                fontWeight: FontWeight.w900,
                fontSize: 16,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

The Builder class:

```<code>class TextFieldBuilder extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<ListData>(
      builder: (context, listData, child) {
        return ListView.builder(
          itemCount: listData.textFieldList.length,
          itemBuilder: (context, index) {
            //adds a controller to the controller list
            listData.controllers.add(new TextEditingController());

            //added the controller to the widget
            return TextFieldWidget(controller: listData.controllers[index],);
          },
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
        );
      },
    );
  }
}
</code>```

TextFieldWidget:

```<code>//set the controller inside the widget
class TextFieldWidget extends StatelessWidget {
  final TextEditingController controller;

  TextFieldWidget({this.controller});

  @override
  Widget build(BuildContext context) {
    return TextField(
      textAlign: TextAlign.center,
      controller: controller,
    );
  }
}
</code>```

And the list of objects and TextEditingControllers:

```<code>class TextFieldData {
  String text;

  TextFieldData({this.text});
}

class ListData extends ChangeNotifier {
  List<TextFieldData> textFieldList = [];
  List<TextEditingController> controllers = new List();    //list of controllers

  void addTextField() {
    textFieldList.add(TextFieldData());
    notifyListeners();
  }
}
</code>```

Body:
I'm trying to save user's input from a ListView.builder of TextFields in a list of objects when he presses a button. Screnshot

I would like that when the user presses the button save, all the hello words were storaged as the text property of my object.

That is my code:

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    ListData listData = Provider.of<ListData>(context, listen: false);

    return Scaffold(
      appBar: AppBar(
        title: Text('Add Textfields'),
        actions: <Widget>[
          FlatButton(
            color: Colors.red,
            onPressed: () {},
            child: Text('Save'),
          ),
        ],
      ),
      body: ListView(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 50),
            child: TextFieldBuilder(),
          ),
          SizedBox(height: 50),
          FlatButton(
            onPressed: () {
              listData.addTextField();
            },
            child: Text(
              'Add',
              style: TextStyle(
                letterSpacing: 4,
                fontWeight: FontWeight.w900,
                fontSize: 16,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

The Builderclass:

class TextFieldBuilder extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<ListData>(
      builder: (context, listData, child) {
        return ListView.builder(
          itemCount: listData.textFieldList.length,
          itemBuilder: (context, index) {
            return TextFieldWidget(index: index);
          },
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
        );
      },
    );
  }
}

TextFieldWidget:

class TextFieldWidget extends StatelessWidget {
  final int index;

  TextFieldWidget({this.index});

  @override
  Widget build(BuildContext context) {
    return TextField(
      textAlign: TextAlign.center,
    );
  }
}

And the list of objects:

class TextFieldData {
  String text;

  TextFieldData({this.text});
}

class ListData extends ChangeNotifier {
  List<TextFieldData> textFieldList = [];

  void addTextField() {
    textFieldList.add(TextFieldData());
    notifyListeners();
  }
}

Body:
I finally got the solution:

First creating a List<TextEditingController> and after a for loop in the 'Save' button. Here is the code:

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    ListData listData = Provider.of<ListData>(context, listen: false);

    return Scaffold(
      appBar: AppBar(
        title: Text('Add Textfields'),
        actions: <Widget>[
          FlatButton(
            color: Colors.red,
            onPressed: () {
              for (int i = 0; i < listData.textFieldList.length; i++) {
                listData.textFieldList[i].text = listData.controllers[i].text;      // for loop
              }
            },
            child: Text('Save'),
          ),
        ],
      ),
      body: ListView(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 50),
            child: TextFieldBuilder(),
          ),
          SizedBox(height: 50),
          FlatButton(
            onPressed: () {
              listData.addTextField();
            },
            child: Text(
              'Add',
              style: TextStyle(
                letterSpacing: 4,
                fontWeight: FontWeight.w900,
                fontSize: 16,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

The Builder class:

class TextFieldBuilder extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<ListData>(
      builder: (context, listData, child) {
        return ListView.builder(
          itemCount: listData.textFieldList.length,
          itemBuilder: (context, index) {
            //adds a controller to the controller list
            listData.controllers.add(new TextEditingController());

            //added the controller to the widget
            return TextFieldWidget(controller: listData.controllers[index],);
          },
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
        );
      },
    );
  }
}

TextFieldWidget:

//set the controller inside the widget
class TextFieldWidget extends StatelessWidget {
  final TextEditingController controller;

  TextFieldWidget({this.controller});

  @override
  Widget build(BuildContext context) {
    return TextField(
      textAlign: TextAlign.center,
      controller: controller,
    );
  }
}

And the list of objects and TextEditingControllers:

class TextFieldData {
  String text;

  TextFieldData({this.text});
}

class ListData extends ChangeNotifier {
  List<TextFieldData> textFieldList = [];
  List<TextEditingController> controllers = new List();    //list of controllers

  void addTextField() {
    textFieldList.add(TextFieldData());
    notifyListeners();
  }
}


问:
How does prepend preserve immutability of a List but append does not?
If we append an element to a list, how is preserving the immutability of the list in Scala? Should not a new list be made? In java if you add a letter to be the first character, then a new String would be made, and strings are immutable in Java. What is the reason for append to be linear time in Scala? Is it to traverse through the whole list and to add at the end or it is linear because we need to create a whole new list since changing the object? </p>

答:
Both prepend and append to a List result in a new List and thus preserve immutability of the List. We can check this like so

```<code>val l = List(1)
l.prepended(0)
l.appended(2)
l             // just has List(1) instead of List(0,1,2)
</code>```

Prepend is constant time because it does not copy the entire list. Instead it just creates new object that holds a reference to the new head and the reference to the previous tail.

```<code>def prepended[B >: A](elem: B): List[B] = elem :: this   // new ::(elem, this)
</code>```

Append is linear time because it does copy the entire list

```<code>def appended[B >: A](elem: B): CC[B] = {
  val b = iterableFactory.newBuilder[B]
  ...
  b ++= this  // copy of the entire list happens here
  b += elem
  b.result()
}
</code>```

Also note retrieving the last element of a List is linear time because List is implemented as a singly linked list, so it does not know the reference to the last element.

Addressing the comment, List can be an efficient structure despite new List being returned as long as you use it correctly in prepend fashion. Sometimes you will have to reverse the list at the end to get the required order, however this is a one-off traversal. Performance should always in the end be measured within particular circumstance by, say, sbt-jmh.

Also be careful not to confuse Array with List. Former is not really a true Scala collection

```<code>implicitly[Array[Int] <:< Iterable[Int]] // error
</code>```

which demonstrates Array is not a subtype of the base of Scala collections. Array is a Java Array and should be used only if measurements absolutely dictate it.

Body:
Both prepend and append to a List result in a new List and thus preserve immutability of the List. We can check this like so

val l = List(1)
l.prepended(0)
l.appended(2)
l             // just has List(1) instead of List(0,1,2)

Prepend is constant time because it does not copy the entire list. Instead it just creates new object that holds a reference to the new head and the reference to the previous tail.

def prepended[B >: A](elem: B): List[B] = elem :: this   // new ::(elem, this)

Append is linear time because it does copy the entire list

def appended[B >: A](elem: B): CC[B] = {
  val b = iterableFactory.newBuilder[B]
  ...
  b ++= this  // copy of the entire list happens here
  b += elem
  b.result()
}

Also note retrieving the last element of a List is linear time because List is implemented as a singly linked list, so it does not know the reference to the last element.

Addressing the comment, List can be an efficient structure despite new List being returned as long as you use it correctly in prepend fashion. Sometimes you will have to reverse the list at the end to get the required order, however this is a one-off traversal. Performance should always in the end be measured within particular circumstance by, say, sbt-jmh.

Also be careful not to confuse Array with List. Former is not really a true Scala collection

implicitly[Array[Int] <:< Iterable[Int]] // error

which demonstrates Array is not a subtype of the base of Scala collections. Array is a Java Array and should be used only if measurements absolutely dictate it.


答:
You use functions for this purpose, e.g. </p>

```<code>#include <iostream>

int main()
{
    int i1 = 20;
    int i2 = 20;
    auto s = [&i1, &i2] { return i1 - i2; };

    std::cout << s() << std::endl;
    i1 = 40;
    std::cout << s() << std::endl;
}
</code>```

Title: How to use references/pointers with mathematical operations in c++?

Body:
I'm pretty new to C++ pointers and references. Say I have two variables i1 and i2, is there a way I can track their difference (or any other operation), even if one of them changes. My attempt at this is shown below, as well as what I want to achieve.

int i1 = 20;
int i2 = 20;
int*r1 = &i1;
int*r2 = &i2;
int s  = *r1-*r2;
std::cout << s << std::endl;
i1 = 40;
std::cout << s << std::endl;
//OUTPUT
//0 <- 20-20
//0 <- How do I make this 20, since 40-20 is 20

Body:
You use functions for this purpose, e.g.

#include <iostream>

int main()
{
    int i1 = 20;
    int i2 = 20;
    auto s = [&i1, &i2] { return i1 - i2; };

    std::cout << s() << std::endl;
    i1 = 40;
    std::cout << s() << std::endl;
}


问:
textfield value changing detect in php
```<code> <input name="aa" type="text" id="aa" value="please enter your name" size="22"            maxlength="60" />
 <input name="aab" type="text" id="aab" value="please enter your email" size="22"            maxlength="60" />
</code>```

i have a textfield and it's value is "please enter your name"(likewise i have many fields.i want to add the value to the database only if the value is changed.(if user entered a name)

i used php isset function and it does not work properly.
 how to detect that in php?

答: You should do this on the frontend with a ready-made validation library, e.g. in jQuery or Prototype. Clearly you also need some validation on the backend, however 'garbage in, garbage out' applies and you should tidy your input data before it gets anywhere near you PHP code.</p>

Title: textfield value changing detect in php

Body:
 <input name="aa" type="text" id="aa" value="please enter your name" size="22"            maxlength="60" />
 <input name="aab" type="text" id="aab" value="please enter your email" size="22"            maxlength="60" />

i have a textfield and it's value is "please enter your name"(likewise i have many fields.i want to add the value to the database only if the value is changed.(if user entered a name)

i used php isset function and it does not work properly.
 how to detect that in php?


问:
Filtering by author and counting all numbers im txt file - Linux terminal, bash
I need help with two hings

1)the file.txt has the format of a list of films
, in which they are authors in different lines, year of publication, title, e.g.

```<code>author1
year1
title1
author2
year2
title2
author3
year3
title3
author4
year4
title4
</code>```

I need to show only book titles whose author is "Joanne Rowling"

2)
one.txt contains numbers and letters for example like:

```<code>dada4dawdaw54 232dawdawdaw 53 34dadasd
77dkwkdw
65 23 laka 23
</code>```

I need to sum all of them and receive score - here it should 561

I tried something like that:

```<code>awk '{for(i=1;i<=NF;i++)s+=$i}END{print s}' plik2.txt
</code>```

but it doesn't make sense

答:
For the 1st question, the solution of okulkarni is great.

For the 2nd question, one solution is

```<code>sed 's/[^0-9]/ /g' one.txt | awk '{for(i=1;i<=NF;i++) sum+= $i} END { print sum}'
</code>```

The sed command converts all non-numeric characters into spaces, while the awk command sums the numbers, line by line.

Body:
I need help with two hings

1)the file.txt has the format of a list of films
, in which they are authors in different lines, year of publication, title, e.g.

author1
year1
title1
author2
year2
title2
author3
year3
title3
author4
year4
title4

I need to show only book titles whose author is "Joanne Rowling"

2)
one.txt contains numbers and letters for example like:

dada4dawdaw54 232dawdawdaw 53 34dadasd
77dkwkdw
65 23 laka 23

I need to sum all of them and receive score - here it should 561

I tried something like that:

awk '{for(i=1;i<=NF;i++)s+=$i}END{print s}' plik2.txt

but it doesn't make sense

Body:
For the 1st question, the solution of okulkarni is great.

For the 2nd question, one solution is

sed 's/[^0-9]/ /g' one.txt | awk '{for(i=1;i<=NF;i++) sum+= $i} END { print sum}'

The sed command converts all non-numeric characters into spaces, while the awk command sums the numbers, line by line.


问:
dynamic delegate to pass a method as parameter in C#
Is there any way to use DLR to reference a method in C#?

In dynamic languages like JavaScript or Python I could easily pass a method as an argument to another method. In C# being statically typed language, I either use Delegate type which needs lots of casting:

```<code>public static void AddMethod(Delegate del)
{
    // implementation
}
</code>```

and then use casting whenever I call this method

```<code>static void Main(string[] args)
{
    AddMethod(new Func<object, bool>(Test));
}

public static bool Test(object obj)
{
    return true;
}
</code>```

Or, I need to define dozens of overloads to satisfy any method calls:

```<code>public static void AddMethod<TResult>(Func<TResult> method)
{
}

public static void AddMethod<T, TResult>(Func<T, TResult> method)
{
}

public static void AddMethod<T1, T2, TResult>(Func<T1, T2, TResult> method)
{
}

public static void AddMethod<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> method)
{
}
</code>```

Is there any cleaner way to define an argument as a placeholder for all other methods? (I'm trying to avoid MethodInfo or other Reflection stuff here)

I was trying something like this:

```<code>public delegate dynamic DynamicDelegate(params dynamic[] args);

public static void AddMethod(DynamicDelegate method)
{
}
</code>```

But the compiler doesn't seem to accept a statically typed method for a dynamically declared delegates!

Any other thoughts?

答:
see below</p>

```<code>    Logger coreLogger;
    Logger coreErrorLogger;

    public Core()
    {
        PassByReference timestamp = new PassByReference(Timestamp);

        coreLogger = Logger.GetLogger("LiTHiuM Core");
        coreLogger.SetFormat("[{0}][LiTHiuM Core]: ", timestamp);
        coreLogger.AddLogger(Log);

        coreErrorLogger = Logger.GetLogger("LiTHiuM Core Error");
        coreErrorLogger.SetFormat("[{0}][LiTHiuM Core (ERROR)]: ", timestamp);
        coreErrorLogger.AddLogger(Error);

    }

    public string Timestamp(params dynamic[] args)
    {
        return DateTime.Now.ToString();
    }
</code>```

```<code>    public delegate dynamic Reference(params dynamic[] args);

    public class PassByReference
    {
        Reference reference;

        public PassByReference(Reference reference)
        {
            this.reference = reference;
        }
        public override string ToString()
        {
            return this.reference().ToString();
        }
    }

</code>```

```<code>    public class Logger
    {

        static Dictionary<string, Logger> logFormatDict = new Dictionary<string, Logger>();
        private List<LoggerDelegate> loggerDelegates = new List<LoggerDelegate>();
        public static Logger GetLogger(string name)
        {
            if (logFormatDict.ContainsKey(name))
            {
                return logFormatDict[name];
            }
            else
            {
                var newLogFormat = new Logger(name, "");
                logFormatDict.Add(name, newLogFormat);
                return newLogFormat;
            }
        }

        private event LoggerDelegate loggingEvent;
        private Logger(string name, string format, params dynamic[] args)
        {
            this.Name = name;
            this.format = format;
            this.args = args;
        }
        public void AddLogger(LoggerDelegate logger)
        {
            if (!loggerDelegates.Contains(logger))
            {
                loggingEvent += logger;
                loggerDelegates.Add(logger);
            }
        }

        public void RemoveLogger(LoggerDelegate logger)
        {
            if (loggerDelegates.Contains(logger))
            {
                loggingEvent -= logger;
                loggerDelegates.Remove(logger);
            }
        }

        public void Log(string text, params dynamic[] args)
        {
            this.Invoke(String.Format(text, args));
        }

        public void Invoke(string text, params dynamic[] args)
        {
            loggingEvent.Invoke(this.ToString() + text, args);
        }

        public void SetFormat(string format, params dynamic[] args)
        {
            this.args = args;
            this.format = format;
        }
        public string Name
        {
            get;
            set;
        }
        string format;
        dynamic[] args;

        public override string ToString()
        {
            return String.Format(format, args);
        }
    }

</code>```

Body:
Is there any way to use DLR to reference a method in C#?

In dynamic languages like JavaScript or Python I could easily pass a method as an argument to another method. In C# being statically typed language, I either use Delegate type which needs lots of casting:

public static void AddMethod(Delegate del)
{
    // implementation
}

and then use casting whenever I call this method

static void Main(string[] args)
{
    AddMethod(new Func<object, bool>(Test));
}

public static bool Test(object obj)
{
    return true;
}

Or, I need to define dozens of overloads to satisfy any method calls:

public static void AddMethod<TResult>(Func<TResult> method)
{
}

public static void AddMethod<T, TResult>(Func<T, TResult> method)
{
}

public static void AddMethod<T1, T2, TResult>(Func<T1, T2, TResult> method)
{
}

public static void AddMethod<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> method)
{
}

Is there any cleaner way to define an argument as a placeholder for all other methods? (I'm trying to avoid MethodInfo or other Reflection stuff here)

I was trying something like this:

public delegate dynamic DynamicDelegate(params dynamic[] args);

public static void AddMethod(DynamicDelegate method)
{
}

But the compiler doesn't seem to accept a statically typed method for a dynamically declared delegates!

Any other thoughts?

Body:
see below

    Logger coreLogger;
    Logger coreErrorLogger;

    public Core()
    {
        PassByReference timestamp = new PassByReference(Timestamp);

        coreLogger = Logger.GetLogger("LiTHiuM Core");
        coreLogger.SetFormat("[{0}][LiTHiuM Core]: ", timestamp);
        coreLogger.AddLogger(Log);

        coreErrorLogger = Logger.GetLogger("LiTHiuM Core Error");
        coreErrorLogger.SetFormat("[{0}][LiTHiuM Core (ERROR)]: ", timestamp);
        coreErrorLogger.AddLogger(Error);

    }

    public string Timestamp(params dynamic[] args)
    {
        return DateTime.Now.ToString();
    }

    public delegate dynamic Reference(params dynamic[] args);

    public class PassByReference
    {
        Reference reference;

        public PassByReference(Reference reference)
        {
            this.reference = reference;
        }
        public override string ToString()
        {
            return this.reference().ToString();
        }
    }

    public class Logger
    {

        static Dictionary<string, Logger> logFormatDict = new Dictionary<string, Logger>();
        private List<LoggerDelegate> loggerDelegates = new List<LoggerDelegate>();
        public static Logger GetLogger(string name)
        {
            if (logFormatDict.ContainsKey(name))
            {
                return logFormatDict[name];
            }
            else
            {
                var newLogFormat = new Logger(name, "");
                logFormatDict.Add(name, newLogFormat);
                return newLogFormat;
            }
        }

        private event LoggerDelegate loggingEvent;
        private Logger(string name, string format, params dynamic[] args)
        {
            this.Name = name;
            this.format = format;
            this.args = args;
        }
        public void AddLogger(LoggerDelegate logger)
        {
            if (!loggerDelegates.Contains(logger))
            {
                loggingEvent += logger;
                loggerDelegates.Add(logger);
            }
        }

        public void RemoveLogger(LoggerDelegate logger)
        {
            if (loggerDelegates.Contains(logger))
            {
                loggingEvent -= logger;
                loggerDelegates.Remove(logger);
            }
        }

        public void Log(string text, params dynamic[] args)
        {
            this.Invoke(String.Format(text, args));
        }

        public void Invoke(string text, params dynamic[] args)
        {
            loggingEvent.Invoke(this.ToString() + text, args);
        }

        public void SetFormat(string format, params dynamic[] args)
        {
            this.args = args;
            this.format = format;
        }
        public string Name
        {
            get;
            set;
        }
        string format;
        dynamic[] args;

        public override string ToString()
        {
            return String.Format(format, args);
        }
    }