问:
How do I define my pool of Actions in such a way that they depend on variables in GOAP?
I'm attempting to implement GOAP in my game. The game is a simulation-type game that would not only benefit from GOAP, but is almost essentially a requirement based on the scope of what an agent can do.

I have the following code. There's no planner in here, just the definitions of Actions, State etc

```<code>#include <vector>
#include <string>
#include <unordered_map>

class Condition
{
public:

    bool operator()(const int value) const
    {
        return m_min <= value && value <= m_max;
    }

    enum class OP : std::uint8_t
    {
        EE, LT, GT, LE, GE
    };

    Condition(const int min, const int max, const OP op)
    :
        m_op(op),
        m_min(min),
        m_max(max)
    {}

    static Condition CreateEE(const int goal)
    {
        return Condition(goal, goal, OP::EE);
    }

    static Condition CreateGT(const int goal)
    {
        return Condition(goal+1, std::numeric_limits<int>::max(), OP::GT);
    }

    static Condition CreateLT(const int goal)
    {
        return Condition(std::numeric_limits<int>::min(), goal-1, OP::LT);
    }

    static Condition CreateGE(const int goal)
    {
        return Condition(goal, std::numeric_limits<int>::max(), OP::GT);
    }

    static Condition CreateLE(const int goal)
    {
        return Condition(std::numeric_limits<int>::min(), goal, OP::LT);
    }

private:

    OP m_op;
    int m_min;
    int m_max;
};

class Effect
{
public:

    enum class OP : std::uint8_t
    {
        ADD, SUB, MUL, DIV, EQ
    };

    Effect(OP op, int value)
    :
        m_op(op),
        m_value(value)
    {

    }

protected:
    OP m_op;
    int m_value;
};

class Action
{
public:
    void AddPrereq(const std::string& name, Condition value)
    {
        m_prereqs.emplace_back(name,value);
    }

    void AddEffect(const std::string& name, Effect effect)
    {
        m_effects.emplace_back(name,effect);
    }

    void SetCost(const float cost)
    {
        m_cost = cost;
    }

private:

    float m_cost;

    std::vector<std::pair<std::string,Condition>> m_prereqs;
    std::vector<std::pair<std::string,Effect>> m_effects;
};

class WorldState
{
public:

    void AddFact(const std::string& name, const int value)
    {
        m_facts[name] = value;
    }

private:

    std::unordered_map<std::string,int> m_facts;
};

class GoalState
{
public:

    void AddCondition(const std::string& name, const Condition condition)
    {
        m_conditions.emplace_back(name, condition);
    }

private:
    std::vector<std::pair<std::string,Condition>> m_conditions;
};

int main()
{
    Action goTo;
    goTo.AddEffect("isAtPosition", Effect(Effect::OP::EQ, 1));

    Action pickUp;
    pickUp.AddPrereq("isAtPosition", Condition::CreateEE(1));
    pickUp.AddEffect("itemInPossession", Effect(Effect::OP::EQ, 1));

    Action drop;
    drop.AddPrereq("itemInPossession", Condition::CreateEE(1));
    drop.AddEffect("itemAtPosition", Effect(Effect::OP::EQ, 1));

    WorldState ws;
    ws.AddFact("itemAtPosition", 0);

    GoalState gs;
    gs.AddCondition("itemAtPosition", Condition::CreateGE(1));

    return 0;
}
</code>```

For now I'm just using boolean values, because for my test-case, it's about the agent moving to a position, picking up an item, and moving it to another position. Later on, a goal might be to move n items or something.

Actions would be:

Goto (puts agent in position)

PickUp (puts item in possession)

Goto (puts agent in position)

Drop (puts item in location) Goal Met!

But how do I use the Goto action here twice? It's effect is the same, setting the "isAtPosition" variable. Would I need to create a new state variable for "isAtItemPosition" vs "isAtDestinationPosition"?

Because that seems like I would be effectively crafting specific Actions for each possible Goal, with the effect of me determining all the possible sequences of Actions.

How do I encode the state information in such a way that the same actions from the pool can be applied at different stages, having a different effect? (Goto the item position vs goto the destination position).

答:
Yes, if you only have boolean values, then you need separate action for each location.

If you can, I would consider using a slightly more powerful representation, such as STRIPS, or PDDL. That will make it a lot easier to describe somewhat more complex scenarios, and it will have the added benefit that you can use off-the-shelf solvers to develop plans for your agents.

In PDDL you could have an action (move ?agent ?from ?to), with the precondition that the agent is at location ?from and the effect that they will be at location ?to after the action has been performed. For picking up an object you could have (pick-up ?agent ?object) with the precodition that both the agent and the object are at the same location. This is far more generic than fixed boolean actions, and will allow later extensions more easily.

Body:
I'm attempting to implement GOAP in my game. The game is a simulation-type game that would not only benefit from GOAP, but is almost essentially a requirement based on the scope of what an agent can do.

I have the following code. There's no planner in here, just the definitions of Actions, State etc

#include <vector>
#include <string>
#include <unordered_map>

class Condition
{
public:

    bool operator()(const int value) const
    {
        return m_min <= value && value <= m_max;
    }

    enum class OP : std::uint8_t
    {
        EE, LT, GT, LE, GE
    };

    Condition(const int min, const int max, const OP op)
    :
        m_op(op),
        m_min(min),
        m_max(max)
    {}

    static Condition CreateEE(const int goal)
    {
        return Condition(goal, goal, OP::EE);
    }

    static Condition CreateGT(const int goal)
    {
        return Condition(goal+1, std::numeric_limits<int>::max(), OP::GT);
    }

    static Condition CreateLT(const int goal)
    {
        return Condition(std::numeric_limits<int>::min(), goal-1, OP::LT);
    }

    static Condition CreateGE(const int goal)
    {
        return Condition(goal, std::numeric_limits<int>::max(), OP::GT);
    }

    static Condition CreateLE(const int goal)
    {
        return Condition(std::numeric_limits<int>::min(), goal, OP::LT);
    }

private:

    OP m_op;
    int m_min;
    int m_max;
};

class Effect
{
public:

    enum class OP : std::uint8_t
    {
        ADD, SUB, MUL, DIV, EQ
    };

    Effect(OP op, int value)
    :
        m_op(op),
        m_value(value)
    {

    }

protected:
    OP m_op;
    int m_value;
};

class Action
{
public:
    void AddPrereq(const std::string& name, Condition value)
    {
        m_prereqs.emplace_back(name,value);
    }

    void AddEffect(const std::string& name, Effect effect)
    {
        m_effects.emplace_back(name,effect);
    }

    void SetCost(const float cost)
    {
        m_cost = cost;
    }

private:

    float m_cost;

    std::vector<std::pair<std::string,Condition>> m_prereqs;
    std::vector<std::pair<std::string,Effect>> m_effects;
};

class WorldState
{
public:

    void AddFact(const std::string& name, const int value)
    {
        m_facts[name] = value;
    }

private:

    std::unordered_map<std::string,int> m_facts;
};

class GoalState
{
public:

    void AddCondition(const std::string& name, const Condition condition)
    {
        m_conditions.emplace_back(name, condition);
    }

private:
    std::vector<std::pair<std::string,Condition>> m_conditions;
};

int main()
{
    Action goTo;
    goTo.AddEffect("isAtPosition", Effect(Effect::OP::EQ, 1));

    Action pickUp;
    pickUp.AddPrereq("isAtPosition", Condition::CreateEE(1));
    pickUp.AddEffect("itemInPossession", Effect(Effect::OP::EQ, 1));

    Action drop;
    drop.AddPrereq("itemInPossession", Condition::CreateEE(1));
    drop.AddEffect("itemAtPosition", Effect(Effect::OP::EQ, 1));

    WorldState ws;
    ws.AddFact("itemAtPosition", 0);

    GoalState gs;
    gs.AddCondition("itemAtPosition", Condition::CreateGE(1));

    return 0;
}

For now I'm just using boolean values, because for my test-case, it's about the agent moving to a position, picking up an item, and moving it to another position. Later on, a goal might be to move n items or something.

Actions would be:

Goto (puts agent in position)

PickUp (puts item in possession)

Goto (puts agent in position)

Drop (puts item in location) Goal Met!

But how do I use the Goto action here twice? It's effect is the same, setting the "isAtPosition" variable. Would I need to create a new state variable for "isAtItemPosition" vs "isAtDestinationPosition"?

Because that seems like I would be effectively crafting specific Actions for each possible Goal, with the effect of me determining all the possible sequences of Actions.

How do I encode the state information in such a way that the same actions from the pool can be applied at different stages, having a different effect? (Goto the item position vs goto the destination position).


来源: stackexchange

问:
java.util.ConcurrentModificationException: null
I'm struggling to pinpoint the source class of this concurrent modification exception. I've run into these before but normally it'll be pretty easy to tell where the issue is occurring. We're unable to replicate this issue in lower environments. I'm providing the logs. Please let me know if you need any additional information.</p>

```<code>INFO  c.f.f.c.u.CallerInterceptor    - API :/v1/test/crossingTest/ Time Taken (in ms) : 1644
Apr 23, 2020 @ 08:33:08.884 2020-04-23 08:33:08,883 [nio-8080-exec-2] INFO  c.f.f.c.u.CallerInterceptor    - API :/v1/test/crossingTest/ Time Taken (in ms) : 1683
Apr 23, 2020 @ 08:33:08.886 cbz.com - [2020-04-23T12:33:06.949+0000] "POST /v1/test/crossingTest/ H
Apr 23, 2020 @ 08:33:08.888     at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:679)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
Apr 23, 2020 @ 08:33:08.888     at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.auth.RestApiAuthSecurityFilter.doFilter(RestApiAuthSecurityFilter.java:73)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.cache.CacheService.getFromCache(CacheService.java:76)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
Apr 23, 2020 @ 08:33:08.888     at java.lang.String.valueOf(String.java:2994)
Apr 23, 2020 @ 08:33:08.888     at sun.reflect.GeneratedMethodAccessor142.invoke(Unknown Source)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.util.CallerInterceptor.upldateConsumerLog(CallerInterceptor.java:168)
Apr 23, 2020 @ 08:33:08.888     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
Apr 23, 2020 @ 08:33:08.888     at java.lang.reflect.Method.invoke(Method.java:498)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888 java.util.ConcurrentModificationException: null
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:626)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
Apr 23, 2020 @ 08:33:08.888     at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
Apr 23, 2020 @ 08:33:08.888     at sun.reflect.GeneratedMethodAccessor74.invoke(Unknown Source)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at java.lang.reflect.Method.invoke(Method.java:498)
Apr 23, 2020 @ 08:33:08.888 2020-04-23 08:33:08,887 [nio-8080-exec-8] ERROR .c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.util.ConcurrentModificationException] with root cause
Apr 23, 2020 @ 08:33:08.888     at java.util.AbstractCollection.toString(AbstractCollection.java:461)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.aspectj.AspectJAfterReturningAdvice.afterReturning(AspectJAfterReturningAdvice.java:66)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:56)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
Apr 23, 2020 @ 08:33:08.888     at java.lang.StringBuilder.append(StringBuilder.java:131)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
Apr 23, 2020 @ 08:33:08.888     at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.util.CallerInterceptor.afterExecution(CallerInterceptor.java:140)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.controller.BusinessServiceController$$EnhancerBySpringCGLIB$$cd31598c.evaluateCrossingTest(<generated>)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90)
Apr 23, 2020 @ 08:33:08.888     at java.util.ArrayList$Itr.next(ArrayList.java:859)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
Apr 23, 2020 @ 08:33:08.888     at org.cloudfoundry.router.ClientCertificateMapper.doFilter(ClientCertificateMapper.java:77)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.889     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
Apr 23, 2020 @ 08:33:08.889     at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
Apr 23, 2020 @ 08:33:08.889     at java.lang.Thread.run(Thread.java:748)
Apr 23, 2020 @ 08:33:08.889     at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
Apr 23, 2020 @ 08:33:08.889     at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
Apr 23, 2020 @ 08:33:08.889     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
Apr 23, 2020 @ 08:33:08.889     at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
</code>```

答:
The source method for the error was
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.cache.CacheService.getFromCache(CacheService.java:76)</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm struggling to pinpoint the source class of this concurrent modification exception. I've run into these before but normally it'll be pretty easy to tell where the issue is occurring. We're unable to replicate this issue in lower environments. I'm providing the logs. Please let me know if you need any additional information.

INFO  c.f.f.c.u.CallerInterceptor    - API :/v1/test/crossingTest/ Time Taken (in ms) : 1644
Apr 23, 2020 @ 08:33:08.884 2020-04-23 08:33:08,883 [nio-8080-exec-2] INFO  c.f.f.c.u.CallerInterceptor    - API :/v1/test/crossingTest/ Time Taken (in ms) : 1683
Apr 23, 2020 @ 08:33:08.886 cbz.com - [2020-04-23T12:33:06.949+0000] "POST /v1/test/crossingTest/ H
Apr 23, 2020 @ 08:33:08.888     at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:679)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
Apr 23, 2020 @ 08:33:08.888     at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.auth.RestApiAuthSecurityFilter.doFilter(RestApiAuthSecurityFilter.java:73)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.cache.CacheService.getFromCache(CacheService.java:76)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
Apr 23, 2020 @ 08:33:08.888     at java.lang.String.valueOf(String.java:2994)
Apr 23, 2020 @ 08:33:08.888     at sun.reflect.GeneratedMethodAccessor142.invoke(Unknown Source)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.util.CallerInterceptor.upldateConsumerLog(CallerInterceptor.java:168)
Apr 23, 2020 @ 08:33:08.888     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
Apr 23, 2020 @ 08:33:08.888     at java.lang.reflect.Method.invoke(Method.java:498)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888 java.util.ConcurrentModificationException: null
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:626)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
Apr 23, 2020 @ 08:33:08.888     at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
Apr 23, 2020 @ 08:33:08.888     at sun.reflect.GeneratedMethodAccessor74.invoke(Unknown Source)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at java.lang.reflect.Method.invoke(Method.java:498)
Apr 23, 2020 @ 08:33:08.888 2020-04-23 08:33:08,887 [nio-8080-exec-8] ERROR .c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.util.ConcurrentModificationException] with root cause
Apr 23, 2020 @ 08:33:08.888     at java.util.AbstractCollection.toString(AbstractCollection.java:461)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.aspectj.AspectJAfterReturningAdvice.afterReturning(AspectJAfterReturningAdvice.java:66)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:56)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
Apr 23, 2020 @ 08:33:08.888     at java.lang.StringBuilder.append(StringBuilder.java:131)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
Apr 23, 2020 @ 08:33:08.888     at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.util.CallerInterceptor.afterExecution(CallerInterceptor.java:140)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at com.business.xxxx.cbzbusservice.controller.BusinessServiceController$$EnhancerBySpringCGLIB$$cd31598c.evaluateCrossingTest(<generated>)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90)
Apr 23, 2020 @ 08:33:08.888     at java.util.ArrayList$Itr.next(ArrayList.java:859)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Apr 23, 2020 @ 08:33:08.888     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
Apr 23, 2020 @ 08:33:08.888     at org.cloudfoundry.router.ClientCertificateMapper.doFilter(ClientCertificateMapper.java:77)
Apr 23, 2020 @ 08:33:08.888     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
Apr 23, 2020 @ 08:33:08.889     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
Apr 23, 2020 @ 08:33:08.889     at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
Apr 23, 2020 @ 08:33:08.889     at java.lang.Thread.run(Thread.java:748)
Apr 23, 2020 @ 08:33:08.889     at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
Apr 23, 2020 @ 08:33:08.889     at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
Apr 23, 2020 @ 08:33:08.889     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
Apr 23, 2020 @ 08:33:08.889     at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)


问:
Why does a nested loop perform much faster than the flattened one?
UPDATE

Sorry guys but the pervious number is INACCURATE. When I tested the previous code I used tqdm to see the expected time and the function will hurt the performance when the iterable object is very long. So I get 18.22s, which is 9 times longer than 2.43s.

HOWEVER, the conclusion is CONSISTENT: The nested loop is much FASTER. When the iteration time is 100^5, the difference is significant: 321.49 vs 210.05. There is about 1.53-time gap between them. Generally, we don't face this kind of long iteration, I'm just curious to know reason of the anomalistic situation.

My python version is 3.7.3. I use 13-inch MacBookPro2019 with 2.4 GHz Intel Core i5. The OS is macOS Mojave 10.14.6

I found a weird situation in python as follows:

import time

start = time.time()
# flattened loop
for i in range(100**4):
    pass
print(time.time() - start) # 18.22(Wrong! Should be 3.09)

# nested loop
start = time.time()
for i in range(100):
    for j in range(100):
        for k in range(100):
            for l in range(100):
                pass
print(time.time() - start) # 2.43
```

The two kinds of loops above have the same iteration times. However the nested loop(2.43s) is running much faster that the flattened one(18.22s). The difference is bigger with the increasing of the iteration time. Hoes does this happen?

答:
2.43s is a certainly a bit too small compared to 18.22s. Surprisingly, the nested loop does seem to be slightly faster on my machine all the time. The cause could be that it's machine dependent.

Another possible reason could be that in the first loop, very large numbers have to be assigned to the iterating variable while in the second loop they are all simply within 100. The given two loops run at 4.2s and 3.9s on my machine; and increasing a zero to 1e9, it takes 43.3s and 39.2s respectively.

Body:
UPDATE

Sorry guys but the pervious number is INACCURATE. When I tested the previous code I used tqdm to see the expected time and the function will hurt the performance when the iterable object is very long. So I get 18.22s, which is 9 times longer than 2.43s.

HOWEVER, the conclusion is CONSISTENT: The nested loop is much FASTER. When the iteration time is 100^5, the difference is significant: 321.49 vs 210.05. There is about 1.53-time gap between them. Generally, we don't face this kind of long iteration, I'm just curious to know reason of the anomalistic situation.

My python version is 3.7.3. I use 13-inch MacBookPro2019 with 2.4 GHz Intel Core i5. The OS is macOS Mojave 10.14.6

I found a weird situation in python as follows:

import time

start = time.time()
# flattened loop
for i in range(100**4):
    pass
print(time.time() - start) # 18.22(Wrong! Should be 3.09)

# nested loop
start = time.time()
for i in range(100):
    for j in range(100):
        for k in range(100):
            for l in range(100):
                pass
print(time.time() - start) # 2.43

The two kinds of loops above have the same iteration times. However the nested loop(2.43s) is running much faster that the flattened one(18.22s). The difference is bigger with the increasing of the iteration time. Hoes does this happen?


问:
AEM 6.1 and 6.5 switching on local machine
~We have some projects still running in AEM 6.1 SP2 (the move to newest version of AEM is in progress) and new projects in AEM 6.5.
AEM 6.1 runs in java 8 and AEM 6.5 runs in java 11.
For us developers this switching between jdk versions is difficult in our local environment, quite often we get our AEM instances corrupted or maven project imports are no longer working properly in IDE.
Anyone else had this situation? What are the best practices for such a situation?</p>

答:
My recommendation would be to set up vagrant box instances to your specs (AEM version + Java) and use automated deployments. This way, you can bring up a preconfigured instances in minutes by executing a single vagrant up command, run your automated deployment, and test your projects. If your instance gets corrupted, run a vagrant destroy command, bring up a new instance again with 0 configurations needed for the next deployment. You willincrease your productivity manifolds with this approach.

I have been using this approach for years and it has saved hours of devops work during critical project timelines


问:
Check the repeated words in a string and keep a count in javascript
I am trying to find repeated words in a string and keep a count of how many times it was repeated.
How do I do it in javascript.

 let checkWords = "I am not gonna live forever, but I wanna live while I am alive"; ```
</div>
</div>
</p>

<p>I am looking for output like this <strong>I = 3</strong>, <strong>am = 2</strong>, <strong>not = 1</strong> and so on, also is it possible to find the individual letter as <strong>I = 3</strong>, <strong>a = 6</strong>, <strong>m = 2</strong>. </p>

<p>I found a similar answer which I tried to use in my string, which works too but can anyone explain me why is the obj and undefined used here</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let str = "I am not gonna live forever, but I wanna live while I am alive",
    split = str.split(" "),
    obj = {};

for (let i = 0; i < split.length; i++) {
  if (obj[split[i]] === undefined) {
    obj[split[i]] = 1;
  } else {
    obj[split[i]]++;
  }
}

console.log(obj)</code>```

答:
Firstly convert the given string to an array. To do that use string.split("").

Secondly, create an map which will store word as key and count as value.

Now iterate through the stringArray and store the current word to the map. And increase the count for the word each time the word is found.

Check the below code.

let words = "I am not gonna live forever, but I wanna live while I am alive";

function countRepeatedWords(sentence) {
  let words = sentence.split(" ");
  let wordMap = {};

  for (let i = 0; i < words.length; i++) {
    let currentWordCount = wordMap[words[i]];
    let count = currentWordCount ? currentWordCount : 0;
    wordMap[words[i]] = count + 1;
  }
  return wordMap;
}

console.log(countRepeatedWords(words));
```

I hope this helps you.

Body:
I am trying to find repeated words in a string and keep a count of how many times it was repeated.
How do I do it in javascript.

 let checkWords = "I am not gonna live forever, but I wanna live while I am alive";

I am looking for output like this I = 3, am = 2, not = 1 and so on, also is it possible to find the individual letter as I = 3, a = 6, m = 2.

I found a similar answer which I tried to use in my string, which works too but can anyone explain me why is the obj and undefined used here

let str = "I am not gonna live forever, but I wanna live while I am alive",
    split = str.split(" "),
    obj = {};

for (let i = 0; i < split.length; i++) {
  if (obj[split[i]] === undefined) {
    obj[split[i]] = 1;
  } else {
    obj[split[i]]++;
  }
}

console.log(obj)

Body:
Firstly convert the given string to an array. To do that use string.split("").

Secondly, create an map which will store word as key and count as value.

Now iterate through the stringArray and store the current word to the map. And increase the count for the word each time the word is found.

Check the below code.

let words = "I am not gonna live forever, but I wanna live while I am alive";

function countRepeatedWords(sentence) {
  let words = sentence.split(" ");
  let wordMap = {};

  for (let i = 0; i < words.length; i++) {
    let currentWordCount = wordMap[words[i]];
    let count = currentWordCount ? currentWordCount : 0;
    wordMap[words[i]] = count + 1;
  }
  return wordMap;
}

console.log(countRepeatedWords(words));

I hope this helps you.


问:
creating .jar and FileNotFoundException
```<code>BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
Scanner sc = new Scanner(reader);
</code>```

My code works in ide and i have this file.txt even in all folders of project file. I am exporting the project to jar in 3 different ides(netbeans, intellij idea, eclipse), then i run the jar file but i get this error(double clicking on the jar doesnt unfortunately work on me so i use java -jar on cmd to run);

```<code>Exception in thread "main" java.io.FileNotFoundException: file.txt (the system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileReader.<init>(Unknown Source)
</code>```

it works if i give the fullpath of the file in the code but i will send the project to someone else so folder will be changed, when i try solutions like InputStream etc. I get nullpointerexception.

答:
Create a "files" folder near your jar and put your files inside it. Try this code block:</p>

```<code>String filePath = System.getProperty("user.dir")
        + File.separator
        + "files"
        + File.separator + "file.txt";
try {
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    Scanner sc = new Scanner(reader);
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Title: creating .jar and FileNotFoundException

Body:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
Scanner sc = new Scanner(reader);

My code works in ide and i have this file.txt even in all folders of project file. I am exporting the project to jar in 3 different ides(netbeans, intellij idea, eclipse), then i run the jar file but i get this error(double clicking on the jar doesnt unfortunately work on me so i use java -jar on cmd to run);

Exception in thread "main" java.io.FileNotFoundException: file.txt (the system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileReader.<init>(Unknown Source)

it works if i give the fullpath of the file in the code but i will send the project to someone else so folder will be changed, when i try solutions like InputStream etc. I get nullpointerexception.

Body:
Create a "files" folder near your jar and put your files inside it. Try this code block:

String filePath = System.getProperty("user.dir")
        + File.separator
        + "files"
        + File.separator + "file.txt";
try {
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    Scanner sc = new Scanner(reader);
} catch (Exception e) {
    e.printStackTrace();
}


问:
How to make setState take effect immediately?
There is an input element in my code:

```<code><input id="input" className="ml-2" type="number" name="Qty" min="1" max="999" value={qty} onChange={(e) => {changeQty(e)}}/>
</code>```

And the onChange handler is:

```<code>    const changeQty = (e) => {
        setQty(e.target.value);
        console.log(qty);
    }
</code>```

So I suppose that whatever I enter in the input field will be printed out in the console, but the fact is there is delay.

For example, the default value is 1, then I type 2, then 1 will be printed out. Then I type 3, then 2 will be printed out. The number printed out is the previous one I entered instead of the current one, as shown below:

Could anyone tell me how to remove the delay?

I read useState set method not reflecting change immediately, but still cannot solve it.

I tried the code below as the answer indicates,

```<code>useEffect(() => {
    setQty(document.getElementById("input").value)
}, [qty]);
</code>```

but an error ReferenceError: Cannot access 'qty' before initialization occurred.

Thanks!

答:
The problem is that setQty is asynchronous.
Try this:

```<code>useEffect(() => {
console.log(qty);
</code>```

}, [qty]);

You will normally get current value in this console.log.
In your code, your console.log may execute before the state is updated because setQty not synchronous as you may think

Body:
There is an input element in my code:

<input id="input" className="ml-2" type="number" name="Qty" min="1" max="999" value={qty} onChange={(e) => {changeQty(e)}}/>

And the onChange handler is:

    const changeQty = (e) => {
        setQty(e.target.value);
        console.log(qty);
    }

So I suppose that whatever I enter in the input field will be printed out in the console, but the fact is there is delay.

For example, the default value is 1, then I type 2, then 1 will be printed out. Then I type 3, then 2 will be printed out. The number printed out is the previous one I entered instead of the current one, as shown below:

Could anyone tell me how to remove the delay?

I read useState set method not reflecting change immediately, but still cannot solve it.

I tried the code below as the answer indicates,

useEffect(() => {
    setQty(document.getElementById("input").value)
}, [qty]);

but an error ReferenceError: Cannot access 'qty' before initialization occurred.

Thanks!

Body:
The problem is that setQty is asynchronous.
Try this:

useEffect(() => {
console.log(qty);

}, [qty]);

You will normally get current value in this console.log.
In your code, your console.log may execute before the state is updated because setQty not synchronous as you may think


问:
Attach a branch to another, performing the same commands on both
Something I often find myself doing is this:

```<code>[dev and master branches are on the same commit]
git checkout master
[do some minor fixes]
git add . & git commit-m"minor fix"
git push
git checkout dev
git rebase master
git push
git checkout master
</code>```

Is there a way of avoiding the git checkout dev part? I am imagining something along the lines of git checkout master & git attach master dev, which would cause all commands performed on master to be performed on the dev branch as well (assuming they start at the same point).

答:
git branch -f dev master as suggested by a comment will work only if you want dev to be at exactly the same commit as master. Then just run it right after git commit.

If there's something more on dev you want preserved, and you really want a rebase, use either a regular bash alias or a git alias:

$> git config alias.devattach '!git checkout dev && git rebase master && git push && git checkout master'

Doing git devattach will perform all these for you, stopping whenever one of the command in the pipe fails.

EDIT Missed you wanted this parametrized, so:

$> git config alias.attach '!git checkout $2 && git rebase $1 && git push && git checkout $1'

Now git attach master dev does what you wanted.

Body:
Something I often find myself doing is this:

[dev and master branches are on the same commit]
git checkout master
[do some minor fixes]
git add . & git commit-m"minor fix"
git push
git checkout dev
git rebase master
git push
git checkout master

Is there a way of avoiding the git checkout dev part? I am imagining something along the lines of git checkout master & git attach master dev, which would cause all commands performed on master to be performed on the dev branch as well (assuming they start at the same point).


问:
Error copying files to blob storage - Azure
I am trying to upload files using Jenkins to Azure blob storage while uploading files AZCopy asks for confirmation which ends up in error.

```<code>[2018/03/09 10:11:11][WARNING] Incomplete operation with different
command line detected at the journal directory
"/var/lib/jenkins/Microsoft/Azure/AzCopy".
 Do you want to overwrite the journal to start a new operation? Choose
 Yes to overwrite, choose No to cancel current operation. (Yes/No)
 [2018/03/09 10:11:11][ERROR] The operation was canceled because user
 chose not to overwrite the existing journal file.
  [Pipeline] }
</code>```

Can anyone please help with this error, how can I force azcopy to overwrite files?

答:
This might be a little late but try adding this flag

```<code>--overwrite=[true|false|ifSourceNewer|prompt]
</code>```

Got answer from AzCopy Docs

ContentLicense: CC BY-SA 3.0

Body:
I am trying to upload files using Jenkins to Azure blob storage while uploading files AZCopy asks for confirmation which ends up in error.

[2018/03/09 10:11:11][WARNING] Incomplete operation with different
command line detected at the journal directory
"/var/lib/jenkins/Microsoft/Azure/AzCopy".
 Do you want to overwrite the journal to start a new operation? Choose
 Yes to overwrite, choose No to cancel current operation. (Yes/No)
 [2018/03/09 10:11:11][ERROR] The operation was canceled because user
 chose not to overwrite the existing journal file.
  [Pipeline] }

Can anyone please help with this error, how can I force azcopy to overwrite files?

Body:
This might be a little late but try adding this flag

--overwrite=[true|false|ifSourceNewer|prompt]

Got answer from AzCopy Docs


问:
Why does the singly linked list not insert correctly
I have a single linked list that I can insert up to 4 char values into. My goal is to get the insert to work which I do have working but the problem is that if the head of the Linked List is a greater value than the oters, it only will populate with the head

I have a structure of

```<code>struct listNode {
char data; /
struct listNode *nextPtr;
};
</code>```

I have an insert function of

```<code>    void insert(ListNode *sPtr, char value)
    {
    ListNode *newPtr;
    ListNode *previousPtr;
    ListNode *currentPtr;

    newPtr = malloc(sizeof(ListNode)); // create node

    if (newPtr != NULL) {
        newPtr->data = value;
        newPtr->nextPtr = NULL;
        previousPtr = NULL;
        currentPtr = sPtr;

        while (currentPtr != NULL && value >= currentPtr->data) {
            previousPtr = currentPtr;
            currentPtr = currentPtr->nextPtr;

        } // end while

        // insert new node at beginning of list
        if (previousPtr == NULL) {
            newPtr->nextPtr = sPtr;
            sPtr = newPtr;
        } // end if
        else { // insert new node between previousPtr and currentPtr
            previousPtr->nextPtr = newPtr;
            newPtr->nextPtr = currentPtr;
        } // end else
    } // end if
    else {
        printf("%c not inserted. No memory available.\n", value);
    } // end else
    } // end function insert
</code>```

In my print list

```<code>    void printList(ListNode *currentPtr)
{
    puts("The list is:");

    // while not the end of the list
    while (currentPtr != NULL) {
        printf("%c --> ", currentPtr->data);
        currentPtr = currentPtr->nextPtr;
    } // end while

    puts("NULL\n");
} // end function printList
</code>```

In my main

```<code>int main(void)
{
ListNode *startPtr = NULL;
ListNode *newPtr = NULL;
ListNode *headPtr = NULL;
unsigned int choice = 4;
char item;

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

newPtr = malloc(sizeof(ListNode)); // create node

headPtr = newPtr;

if (newPtr != NULL) { // is space available
    newPtr->data = item;
    newPtr->nextPtr = NULL;
    startPtr = newPtr;
}

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);
}
</code>```

So if I ran the code and entered in K Q L R
you would see

```<code> Input order:   K Q L R
 Output order:  K L Q R
</code>```

But if I entered in R Q L K
I would get

```<code> Input order:   R Q L K
 Output order:     R
</code>```

Why does this happen and how could I fix it?

答:
When you insert the new node in front, you update the head: sPtr = newPtr;. However, the change of sPtr will not be seen by the caller.

For that you need to declare void insert(ListNode **sPtr, char value) and where ever you use sPtr, now write *sPtr.

Now call the function like:

```<code>insert(&headPtr, item);
</code>```

Body:
I have a single linked list that I can insert up to 4 char values into. My goal is to get the insert to work which I do have working but the problem is that if the head of the Linked List is a greater value than the oters, it only will populate with the head

I have a structure of

struct listNode {
char data; /
struct listNode *nextPtr;
};

I have an insert function of

    void insert(ListNode *sPtr, char value)
    {
    ListNode *newPtr;
    ListNode *previousPtr;
    ListNode *currentPtr;

    newPtr = malloc(sizeof(ListNode)); // create node

    if (newPtr != NULL) {
        newPtr->data = value;
        newPtr->nextPtr = NULL;
        previousPtr = NULL;
        currentPtr = sPtr;

        while (currentPtr != NULL && value >= currentPtr->data) {
            previousPtr = currentPtr;
            currentPtr = currentPtr->nextPtr;

        } // end while

        // insert new node at beginning of list
        if (previousPtr == NULL) {
            newPtr->nextPtr = sPtr;
            sPtr = newPtr;
        } // end if
        else { // insert new node between previousPtr and currentPtr
            previousPtr->nextPtr = newPtr;
            newPtr->nextPtr = currentPtr;
        } // end else
    } // end if
    else {
        printf("%c not inserted. No memory available.\n", value);
    } // end else
    } // end function insert

In my print list

    void printList(ListNode *currentPtr)
{
    puts("The list is:");

    // while not the end of the list
    while (currentPtr != NULL) {
        printf("%c --> ", currentPtr->data);
        currentPtr = currentPtr->nextPtr;
    } // end while

    puts("NULL\n");
} // end function printList

In my main

int main(void)
{
ListNode *startPtr = NULL;
ListNode *newPtr = NULL;
ListNode *headPtr = NULL;
unsigned int choice = 4;
char item;

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

newPtr = malloc(sizeof(ListNode)); // create node

headPtr = newPtr;

if (newPtr != NULL) { // is space available
    newPtr->data = item;
    newPtr->nextPtr = NULL;
    startPtr = newPtr;
}

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);
}

So if I ran the code and entered in K Q L R
you would see

 Input order:   K Q L R
 Output order:  K L Q R

But if I entered in R Q L K
I would get

 Input order:   R Q L K
 Output order:     R

Why does this happen and how could I fix it?

Body:
When you insert the new node in front, you update the head: sPtr = newPtr;. However, the change of sPtr will not be seen by the caller.

For that you need to declare void insert(ListNode **sPtr, char value) and where ever you use sPtr, now write *sPtr.

Now call the function like:

insert(&headPtr, item);


问:
Two Database tables related in two different ways...?
Im sort of scratching my head on this one.  Here's the scenario.  Im using Doctrine and YAML schema files:

I have a table User and a table Event

User looks like this:

```<code>User:
    columns:
        id:
            type: integer(7)
        email:
            type: string(100)
        display_name:
            type: string(255)
        fb_id:
            type: string(100)
    relations:
        Event:
            type: many
            refClass: UserEvent
</code>```

Event looks like this:

```<code>Event:
    columns:
        id:
            type: integer(7)
        initiator_id:
            type: integer(7)
        loc_latitude:
            type: decimal(11)
        loc_longitude:
            type: decimal(11)
        4sq_id:
            type: integer(11)
    relations:
        User:
            type: one
            local: initiator_id
            foreign: id
        User:
            type: many
            refClass: UserEvent
</code>```

As you can see the problem is this: A User (or 'initiator') can start many events, and an event can belong to one User ('initiator').  However, an event can also have many Users who join it, and a User can Join many events.

So Event and User end up being related in two different fashions.  How does this work?  Is it possible to do it this way or am i missing something?

答: I think you just need one many-to-many relationship between the two tables. UserEvent will tell you what users have what events (and vice versa)... and joining through UserEvent and adding WHERE user.id = event.initiator_id will give you access to a user's initiated events, assuming they also belong to those events.</p>

Body:
Im sort of scratching my head on this one.  Here's the scenario.  Im using Doctrine and YAML schema files:

I have a table User and a table Event

User looks like this:

User:
    columns:
        id:
            type: integer(7)
        email:
            type: string(100)
        display_name:
            type: string(255)
        fb_id:
            type: string(100)
    relations:
        Event:
            type: many
            refClass: UserEvent

Event looks like this:

Event:
    columns:
        id:
            type: integer(7)
        initiator_id:
            type: integer(7)
        loc_latitude:
            type: decimal(11)
        loc_longitude:
            type: decimal(11)
        4sq_id:
            type: integer(11)
    relations:
        User:
            type: one
            local: initiator_id
            foreign: id
        User:
            type: many
            refClass: UserEvent

As you can see the problem is this: A User (or 'initiator') can start many events, and an event can belong to one User ('initiator').  However, an event can also have many Users who join it, and a User can Join many events.

So Event and User end up being related in two different fashions.  How does this work?  Is it possible to do it this way or am i missing something?


问:
Retrieve data between certain hours of day
I am trying to write a query to retrieve data between midnight and 7am of the current day.  I know I am on the right track but cannot get the syntax correct...</p>

```<code>SELECT * FROM `monthly`
WHERE LogDateTime >= date_sub(curdate('07:00:00'),INTERVAL 1 hour)
</code>```

答:
You should read a bit about how to filter data and some build in functions too. Just in case you are using MySQL then you code will be as follows:

```<code>SELECT *
FROM monthly
WHERE LogDateTime between CURDATE() and DATE_ADD(CURDATE(), INTERVAL 7 HOUR)
</code>```

Here i am using built-in MySQL function CURDATE and DATE_ADD. Please note that it will include both the upper and lower limits.

Following are some references for you:

https://www.mysqltutorial.org/mysql-curdate/

https://www.mysqltutorial.org/mysql-between/

https://www.mysqltutorial.org/mysql-where/

Just a small comment thought not related to your question, you should not be using * for selecting columns. Using * is not recommended at all. You better write each and every column name in your SELECT statement

Body:
I am trying to write a query to retrieve data between midnight and 7am of the current day.  I know I am on the right track but cannot get the syntax correct...

SELECT * FROM `monthly`
WHERE LogDateTime >= date_sub(curdate('07:00:00'),INTERVAL 1 hour)

Body:
You should read a bit about how to filter data and some build in functions too. Just in case you are using MySQL then you code will be as follows:

SELECT *
FROM monthly
WHERE LogDateTime between CURDATE() and DATE_ADD(CURDATE(), INTERVAL 7 HOUR)

Here i am using built-in MySQL function CURDATE and DATE_ADD. Please note that it will include both the upper and lower limits.

Following are some references for you:

https://www.mysqltutorial.org/mysql-curdate/

https://www.mysqltutorial.org/mysql-between/

https://www.mysqltutorial.org/mysql-where/

Just a small comment thought not related to your question, you should not be using * for selecting columns. Using * is not recommended at all. You better write each and every column name in your SELECT statement


问:
How can I optimize my array filtering by date times?
I wrote this simple filter array per data time, but not sure if it's good way.

Example data:

```<code>[
  {
    "content": "test1",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test2",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test3",
    "createdAt": "2020-05-27T13:46:14.000Z"
  }
]
</code>```

And i want to convert it like this:

```<code> {
      "Fri May 29 2020": [
        {
          "content": "test1",
          "createdAt": "2020-05-29T13:46:14.000Z"
        },
        {
          "content": "test2",
          "createdAt": "2020-05-29T13:46:14.000Z"
        }
      ],
      "Wed May 27 2020": [
        {
          "content": "test3",
          "createdAt": "2020-05-27T13:46:14.000Z"
        }
      ]
    }
</code>```

And there is my code:

```<code>let usedDates = new Set();
let logs = {};

for(let log of data) {
    const date = new Date(log.createdAt).toDateString();
    if(usedDates.has(date)) continue;

    logs[date] = data.filter((e) => date == new Date(e.createdAt).toDateString());
    usedDates.add(date);
}
</code>```

yeah it works, but not sure if it's good way.

答:
For big arrays it hasn't a good performance: you walk throw data array (for loop) and for each step you call a filter on the full data.
The costs rise to the square.</p>

Body:
I wrote this simple filter array per data time, but not sure if it's good way.

Example data:

[
  {
    "content": "test1",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test2",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test3",
    "createdAt": "2020-05-27T13:46:14.000Z"
  }
]

And i want to convert it like this:

 {
      "Fri May 29 2020": [
        {
          "content": "test1",
          "createdAt": "2020-05-29T13:46:14.000Z"
        },
        {
          "content": "test2",
          "createdAt": "2020-05-29T13:46:14.000Z"
        }
      ],
      "Wed May 27 2020": [
        {
          "content": "test3",
          "createdAt": "2020-05-27T13:46:14.000Z"
        }
      ]
    }

And there is my code:

let usedDates = new Set();
let logs = {};

for(let log of data) {
    const date = new Date(log.createdAt).toDateString();
    if(usedDates.has(date)) continue;

    logs[date] = data.filter((e) => date == new Date(e.createdAt).toDateString());
    usedDates.add(date);
}

yeah it works, but not sure if it's good way.


问:
Prevent GROUP_CONCAT from returning empty string when grouped results are null in SPARQL
I have a SPARQL query that is returning what I want, save one thing.  When I use GROUP_CONCAT I receive back an empty string in the result.  I would like it to simply be null in the return set when the values getting grouped are null.  You can see in my example below my ?team results return "" instead of simply null like ?end is returning.  In the case of the empty string, my ?person values are actually null.  Is there a way I can get ?team to return null as well?

SPARQL Query:

```<code>SELECT ?event ?start ?end ?team {
    SELECT ?event ?start ?end (GROUP_CONCAT(DISTINCT ?person;SEPARATOR=",") AS ?team) {
        ?event a cls:Event ;
            prop:startDate ?start .

        OPTIONAL {
            ?event prop:endDate ?end .
            ?event prop:teamMember ?person .
        }

        FILTER (?start >= "2020-05-25" && ?start < "2020-08-31")
    } GROUP BY ?event ?start ?end
} ORDER BY ?start
</code>```

Results:

```<code>| event       | start      | end        | team                                                         |
|-------------|------------|------------|--------------------------------------------------------------|
| event:Test1 | 2020-05-27 |            | ""                                                           |
| event:Test3 | 2020-05-28 | 2020-05-29 | "http://foo.bar/person/smith,http://foo.bar/person/williams" |
| event:Test2 | 2020-05-29 |            | ""                                                           |
</code>```

答:
I am afraid the SPARQL specification (see here) confirms what you observe as the right behaviour.

To see why this is the case, imagine that instead of doing a GROUP_CONCAT, you were doing a COUNT. Then you if a team has no members, you would want to see 0, not null.

In order to get what you want, I'd try this as a first iteration:

```<code>SELECT ?event ?start ?end ?team {

    BIND(IF(?team_temp = "", ?team_temp, ?unboundVariable) AS ?team)
#The above check if ?team_temp = "". If it is not, then there is a team and you use ?team-temp as ?team. Otherwise, if ?team_temp = "", you use some unbound variable as ?team, and this unbound variable will be null.

    {SELECT ?event ?start ?end (GROUP_CONCAT(DISTINCT ?person;SEPARATOR=",") AS ?team_temp) {
            ?event a cls:Event ;
                prop:startDate ?start .

            OPTIONAL { ?event prop:endDate ?end }
            OPTIONAL { ?event prop:teamMember ?person }
#Notice that if we want to match ?end and ?person optionally AND independently, then we need two optional statements above here, instead of one large one.

            FILTER (?start >= "2020-05-25" && ?start < "2020-08-31")
        } GROUP BY ?event ?start ?end}
    } ORDER BY ?start
</code>```

Body:
I have a SPARQL query that is returning what I want, save one thing.  When I use GROUP_CONCAT I receive back an empty string in the result.  I would like it to simply be null in the return set when the values getting grouped are null.  You can see in my example below my ?team results return "" instead of simply null like ?end is returning.  In the case of the empty string, my ?person values are actually null.  Is there a way I can get ?team to return null as well?

SPARQL Query:

SELECT ?event ?start ?end ?team {
    SELECT ?event ?start ?end (GROUP_CONCAT(DISTINCT ?person;SEPARATOR=",") AS ?team) {
        ?event a cls:Event ;
            prop:startDate ?start .

        OPTIONAL {
            ?event prop:endDate ?end .
            ?event prop:teamMember ?person .
        }

        FILTER (?start >= "2020-05-25" && ?start < "2020-08-31")
    } GROUP BY ?event ?start ?end
} ORDER BY ?start

Results:

| event       | start      | end        | team                                                         |
|-------------|------------|------------|--------------------------------------------------------------|
| event:Test1 | 2020-05-27 |            | ""                                                           |
| event:Test3 | 2020-05-28 | 2020-05-29 | "http://foo.bar/person/smith,http://foo.bar/person/williams" |
| event:Test2 | 2020-05-29 |            | ""                                                           |

Body:
I am afraid the SPARQL specification (see here) confirms what you observe as the right behaviour.

To see why this is the case, imagine that instead of doing a GROUP_CONCAT, you were doing a COUNT. Then you if a team has no members, you would want to see 0, not null.

In order to get what you want, I'd try this as a first iteration:

SELECT ?event ?start ?end ?team {

    BIND(IF(?team_temp = "", ?team_temp, ?unboundVariable) AS ?team)
#The above check if ?team_temp = "". If it is not, then there is a team and you use ?team-temp as ?team. Otherwise, if ?team_temp = "", you use some unbound variable as ?team, and this unbound variable will be null.

    {SELECT ?event ?start ?end (GROUP_CONCAT(DISTINCT ?person;SEPARATOR=",") AS ?team_temp) {
            ?event a cls:Event ;
                prop:startDate ?start .

            OPTIONAL { ?event prop:endDate ?end }
            OPTIONAL { ?event prop:teamMember ?person }
#Notice that if we want to match ?end and ?person optionally AND independently, then we need two optional statements above here, instead of one large one.

            FILTER (?start >= "2020-05-25" && ?start < "2020-08-31")
        } GROUP BY ?event ?start ?end}
    } ORDER BY ?start


问:
Align only one span center
Basically I have the following:

```<code><td>
<span id="sp1">foo</span>
<span id="sp12">foo</span>
</td>
</code>```

How can I align sp1 on the left and sp2 on the center?

I have tried using text-align and the position attributes but none worked.

This didn't work, for instance:

```<code><td style="text-align:left">
<span id="sp1">foo</span>
<span style="text-align:center" align="center" id="sp12">foo</span>
</td>
</code>```

答:
Aside  text-align you could use float:

table {
  width: 100%;
  background: linear-gradient(to left, white 50%, gray 50%);/* show center */
}

td {
  text-align: center;
}

#sp1 {
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>
      <span id="sp1">foo</span>
      <span id="sp12">foo</span>
    </td>
  </tr>
</table></code>```

To set #sp2 right on the middle, transform can finalize it , but it can then overflow the floatting element:

table {
  width: 100%;
  background: linear-gradient(to left, white 50%, gray 50%);/* show center */
}

td {
  text-align: center;
}

#sp1 {
  float: left;
}
#sp12 {
display:inline-block;
transform:translatex(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>
      <span id="sp1">foo</span>
      <span id="sp12">foo</span>
    </td>
  </tr>
</table></code>```

Title: Align only one span center

Body:
Basically I have the following:

foo
foo

How can I align sp1 on the left and sp2 on the center?

I have tried using text-align and the position attributes but none worked.

This didn't work, for instance:

foo
foo

Body:
Aside  text-align you could use float:

table {
  width: 100%;
  background: linear-gradient(to left, white 50%, gray 50%);/* show center */
}

td {
  text-align: center;
}

#sp1 {
  float: left;
}

<table>
  <tr>
    <td>
      <span id="sp1">foo</span>
      <span id="sp12">foo</span>
    </td>
  </tr>
</table>

To set #sp2 right on the middle, transform can finalize it , but it can then overflow the floatting element:

table {
  width: 100%;
  background: linear-gradient(to left, white 50%, gray 50%);/* show center */
}

td {
  text-align: center;
}

#sp1 {
  float: left;
}
#sp12 {
display:inline-block;
transform:translatex(-50%);
}

<table>
  <tr>
    <td>
      <span id="sp1">foo</span>
      <span id="sp12">foo</span>
    </td>
  </tr>
</table>


问:
CS50 - pset2 - substitution output not valid ASCII text
I am not sure what my code for pset2 substitution is missing. When I run Check50, it gives out the following output:

```<code>:) substitution.c exists
:) substitution.c compiles
:( encrypts "A" as "Z" using ZYXWVUTSRQPONMLKJIHGFEDCBA as key
    output not valid ASCII text
:( encrypts "a" as "z" using ZYXWVUTSRQPONMLKJIHGFEDCBA as key
    output not valid ASCII text
:( encrypts "ABC" as "NJQ" using NJQSUYBRXMOPFTHZVAWCGILKED as key
    output not valid ASCII text
:( encrypts "XyZ" as "KeD" using NJQSUYBRXMOPFTHZVAWCGILKED as key
    output not valid ASCII text
:) encrypts "This is CS50" as "Cbah ah KH50" using YUKFRNLBAVMWZTEOGXHCIPJSQD as key
:) encrypts "This is CS50" as "Cbah ah KH50" using yukfrnlbavmwzteogxhcipjsqd as key
:) encrypts "This is CS50" as "Cbah ah KH50" using YUKFRNLBAVMWZteogxhcipjsqd as key
:) encrypts all alphabetic characters using DWUSXNPQKEGCZFJBTLYROHIAVM as key
:) handles lack of key
:) handles invalid key length
:) handles invalid characters in key
:) handles duplicate characters in key
:) handles multiple duplicate characters in key
</code>```

As one can observe that my code is doing fine for most cases but giving output not valid ASCII text for some which I am not able to figure out.

Here is what my code looks like

```<code>#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }
    else
    {
        if (strlen(argv[1]) != 26)
        {
            printf("Key must contain 26 characters\n");
            return 1;
        }
        else if (strlen(argv[1]) == 26)
        {
            for(int i = 0; i <= strlen(argv[1]); i++)
            {
                if (isdigit(argv[1][i]))
                {
                    printf("Key must only contain alphabetic characters\n");
                    return 1;
                }
            }
            for(int l = 0; l <= strlen(argv[1]); l++)
            {
                for(int j = 0; j < l; j++)
                {
                    if(argv[1][j] == argv[1][l])
                    {
                        printf("Key must not contain repeated characters\n");
                        return 1;
                    }
                }
            }
        }
    }
    string key = argv[1];
    string uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string lowers = "abcdefghijklmnopqrstuvwxyz";
    char upper_key[26], lower_key[26];
    string text = get_string("Plain Text: ");
    char ciphertext[strlen(text)];
    for(int i = 0; i < 26; i++)
    {
        upper_key[i] = toupper(key[i]);
    }
    for(int i = 0; i < 26; i++)
    {
        lower_key[i] = tolower(key[i]);
    }
    for(int i = 0; i < strlen(text); i++)
    {
        if(isupper(text[i]))
        {
            for(int j = 0; j < 26; j++)
            {
                if (text[i] == uppers[j])
                {
                    ciphertext[i] = upper_key[j];
                }
            }
        }
        else if(islower(text[i]))
        {
            for(int j = 0; j < 26; j++)
            {
                if(text[i] == lowers[j])
                {
                    ciphertext[i] = lower_key[j];
                }
            }
        }
        else
        {
            ciphertext[i] = text[i];
        }
    }
    printf("ciphertext: %s\n", ciphertext);
}

</code>```

I am quite new to coding and any help would be very much appreciated...

答:
Because of not terminating ciphertext as pointed out by Eugene, your code read from the outside of ciphertext.  The following is the memory access error, and here is the link to reproduce/debug any segfaults in the future. </p>

```<code>Plain Text:
  Memory access error: reading from the outside of a memory space; abort execution.
  # Reading 1 bytes from 0xffd04071 will read undefined values.
  #
  # The memory-space-to-be-read (start:0xffd0406c, size:5 bytes) is bound to 'ciphertext' at
  #    file:/substitution.c::49, 10
  #
  #  0xffd0406c               0xffd04070
  #  +------------------------------+
  #  | the memory-space-to-be-read  |......
  #  +------------------------------+
  #                                  ^~~~~~~~~~
  #        the read starts at 0xffd04071 that is right after the memory-space end.
  #
  # Stack trace (most recent call first) of the read.
  # [0]  file:/musl-1.1.10/src/string/memchr.c::25, 9
  # [1]  file:/musl-1.1.10/src/stdio/vfprintf.c::602, 8
  # [2]  file:/musl-1.1.10/src/stdio/vfprintf.c::678, 8
  # [3]  file:/musl-1.1.10/src/stdio/printf.c::13, 8
  # [4]  file:/substitution.c::85, 5
  # [5]  [libc-start-main]
</code>```

Body:
I am not sure what my code for pset2 substitution is missing. When I run Check50, it gives out the following output:

:) substitution.c exists
:) substitution.c compiles
:( encrypts "A" as "Z" using ZYXWVUTSRQPONMLKJIHGFEDCBA as key
    output not valid ASCII text
:( encrypts "a" as "z" using ZYXWVUTSRQPONMLKJIHGFEDCBA as key
    output not valid ASCII text
:( encrypts "ABC" as "NJQ" using NJQSUYBRXMOPFTHZVAWCGILKED as key
    output not valid ASCII text
:( encrypts "XyZ" as "KeD" using NJQSUYBRXMOPFTHZVAWCGILKED as key
    output not valid ASCII text
:) encrypts "This is CS50" as "Cbah ah KH50" using YUKFRNLBAVMWZTEOGXHCIPJSQD as key
:) encrypts "This is CS50" as "Cbah ah KH50" using yukfrnlbavmwzteogxhcipjsqd as key
:) encrypts "This is CS50" as "Cbah ah KH50" using YUKFRNLBAVMWZteogxhcipjsqd as key
:) encrypts all alphabetic characters using DWUSXNPQKEGCZFJBTLYROHIAVM as key
:) handles lack of key
:) handles invalid key length
:) handles invalid characters in key
:) handles duplicate characters in key
:) handles multiple duplicate characters in key

As one can observe that my code is doing fine for most cases but giving output not valid ASCII text for some which I am not able to figure out.

Here is what my code looks like

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }
    else
    {
        if (strlen(argv[1]) != 26)
        {
            printf("Key must contain 26 characters\n");
            return 1;
        }
        else if (strlen(argv[1]) == 26)
        {
            for(int i = 0; i <= strlen(argv[1]); i++)
            {
                if (isdigit(argv[1][i]))
                {
                    printf("Key must only contain alphabetic characters\n");
                    return 1;
                }
            }
            for(int l = 0; l <= strlen(argv[1]); l++)
            {
                for(int j = 0; j < l; j++)
                {
                    if(argv[1][j] == argv[1][l])
                    {
                        printf("Key must not contain repeated characters\n");
                        return 1;
                    }
                }
            }
        }
    }
    string key = argv[1];
    string uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string lowers = "abcdefghijklmnopqrstuvwxyz";
    char upper_key[26], lower_key[26];
    string text = get_string("Plain Text: ");
    char ciphertext[strlen(text)];
    for(int i = 0; i < 26; i++)
    {
        upper_key[i] = toupper(key[i]);
    }
    for(int i = 0; i < 26; i++)
    {
        lower_key[i] = tolower(key[i]);
    }
    for(int i = 0; i < strlen(text); i++)
    {
        if(isupper(text[i]))
        {
            for(int j = 0; j < 26; j++)
            {
                if (text[i] == uppers[j])
                {
                    ciphertext[i] = upper_key[j];
                }
            }
        }
        else if(islower(text[i]))
        {
            for(int j = 0; j < 26; j++)
            {
                if(text[i] == lowers[j])
                {
                    ciphertext[i] = lower_key[j];
                }
            }
        }
        else
        {
            ciphertext[i] = text[i];
        }
    }
    printf("ciphertext: %s\n", ciphertext);
}

I am quite new to coding and any help would be very much appreciated...

Body:
Because of not terminating ciphertext as pointed out by Eugene, your code read from the outside of ciphertext.  The following is the memory access error, and here is the link to reproduce/debug any segfaults in the future.

Plain Text:
  Memory access error: reading from the outside of a memory space; abort execution.
  # Reading 1 bytes from 0xffd04071 will read undefined values.
  #
  # The memory-space-to-be-read (start:0xffd0406c, size:5 bytes) is bound to 'ciphertext' at
  #    file:/substitution.c::49, 10
  #
  #  0xffd0406c               0xffd04070
  #  +------------------------------+
  #  | the memory-space-to-be-read  |......
  #  +------------------------------+
  #                                  ^~~~~~~~~~
  #        the read starts at 0xffd04071 that is right after the memory-space end.
  #
  # Stack trace (most recent call first) of the read.
  # [0]  file:/musl-1.1.10/src/string/memchr.c::25, 9
  # [1]  file:/musl-1.1.10/src/stdio/vfprintf.c::602, 8
  # [2]  file:/musl-1.1.10/src/stdio/vfprintf.c::678, 8
  # [3]  file:/musl-1.1.10/src/stdio/printf.c::13, 8
  # [4]  file:/substitution.c::85, 5
  # [5]  [libc-start-main]


问:
How to use ModernWPF Programaticially
ModernWPF is a great project, as it restyles my WPF app in modern UI style. The docs tell what XAML changes to be done to activate the styling. Unfortunately I am working with an application that is not XAML based (Python.NET).

I tried already to add the dictionaries programaticially like:

```<code>    app = Application()
    app.Resources.MergedDictionaries.Add(ModernWpf.ThemeResources())
    app.Resources.MergedDictionaries.Add(ModernWpf.Controls.XamlControlsResources())
    app.Run(win)
</code>```

The main window win is created via XAML:

```<code><Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ui="http://schemas.modernwpf.com/2019"
    Title="Enterprisey-FireDrop Express" Width="640" Height="480"
    ui:WindowHelper.UseModernWindowStyle="True">
   ...
</Window>
</code>```

Any hints?

答:
In C# the following seems to work, but I'm not sure if the same can be done in Python since I don't know Python at all:</p>

```<code>var app = new Application();

var themeResources = new ModernWpf.ThemeResources();
((ISupportInitialize)themeResources).BeginInit();
app.Resources.MergedDictionaries.Add(themeResources);
((ISupportInitialize)themeResources).EndInit();

app.Resources.MergedDictionaries.Add(new ModernWpf.Controls.XamlControlsResources());
app.Run(new MainWindow());
</code>```

Title: How to use ModernWPF Programaticially

Body:
ModernWPF is a great project, as it restyles my WPF app in modern UI style. The docs tell what XAML changes to be done to activate the styling. Unfortunately I am working with an application that is not XAML based (Python.NET).

I tried already to add the dictionaries programaticially like:

    app = Application()
    app.Resources.MergedDictionaries.Add(ModernWpf.ThemeResources())
    app.Resources.MergedDictionaries.Add(ModernWpf.Controls.XamlControlsResources())
    app.Run(win)

The main window win is created via XAML:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ui="http://schemas.modernwpf.com/2019"
    Title="Enterprisey-FireDrop Express" Width="640" Height="480"
    ui:WindowHelper.UseModernWindowStyle="True">
   ...
</Window>

Any hints?

Body:
In C# the following seems to work, but I'm not sure if the same can be done in Python since I don't know Python at all:

var app = new Application();

var themeResources = new ModernWpf.ThemeResources();
((ISupportInitialize)themeResources).BeginInit();
app.Resources.MergedDictionaries.Add(themeResources);
((ISupportInitialize)themeResources).EndInit();

app.Resources.MergedDictionaries.Add(new ModernWpf.Controls.XamlControlsResources());
app.Run(new MainWindow());


问:
git push rejected
I give up!
Whenever I try to push I get a stupid:

```<code>! [rejected]        master -> master (non-fast forward)
error: failed to push some refs to 'git@github.com:companyX/projectX.git'
</code>```

Our team has a new git setup. Instead of making private branches I now Forked our main repository (on github) to create my own copy.

At some point what I did was:

```<code>$ git fetch upstream master:upstreammaster
</code>```

So here is my current setup::

```<code>$ git branch
master
* upstreammaster

$ git remote -v
origin  git@github.com:userX/projectX.git
upstream    git@github.com:companyX/projectX.git
</code>```

where userX is my private repository.

So I go and make some changes to my upstreammaster branch, and the PULL from "upstream master".
Everything merges and stuff:

```<code>$ git pull upstream master
remote: Counting objects: 95, done.
remote: Compressing objects: 100% (60/60), done.
remote: Total 60 (delta 54), reused 0 (delta 0)
Unpacking objects: 100% (60/60), done.
From git@github.com:companyX/projectX
 * branch            master     -> FETCH_HEAD
Merge made by recursive.
stuff                      |  165 ++++++++++++--------
stuff                      |   35 ++--
stuff                       |  107 ++++++++++---
stuff                       |  105 ++++++++++---
stuff             |   24 ++--
stuff               |    9 +-
stuff                   |   53 +++----
stuff            |   44 +++---
stuff              |   52 +++----
stuff |   32 +----
stuff          |    4 +-
 stuff             |  138 ++++++++---------
stuff     |   58 ++++----
stuff    |  115 ++++++++------
stuff          |    5 +-
stuff                       |   39 ++---
stuff                        |   28 ++--
 17 files changed, 560 insertions(+), 453 deletions(-)
</code>```

but then when I try to do:

```<code>$ git push upstream master
To git@github.com:companyX/projectX.git
 ! [rejected]        master -> master (non-fast forward)
error: failed to push some refs to 'git@github.com:companyX/projectX.git'
</code>```

Any help would be greately appreciated! If you need clarification please ask, I will reply!

答:
Jarret Hardie is correct.  Or, first merge your changes back into master and then try the push.  By default, git push pushes all branches that have names that match on the remote -- and no others.  So those are your two choices -- either specify it explicitly like Jarret said or merge back to a common branch and then push.

There's been talk about this on the Git mail list and it's clear that this behavior is not about to change anytime soon -- many developers rely on this behavior in their workflows.

Edit/Clarification

Assuming your upstreammaster branch is ready to push then you could do this:

Pull in any changes from the upstream.

$ git pull upstream master

Switch to my local master branch

$ git checkout master

Merge changes in from upstreammaster

$ git merge upstreammaster

Push my changes up

$ git push upstream

Another thing that you may want to do before pushing is to rebase your changes against upstream/master so that your commits are all together.  You can either do that as a separate step between #1 and #2 above (git rebase upstream/master) or you can do it as part of your pull (git pull --rebase upstream master)

ContentLicense: CC BY-SA 2.5

Title: git push rejected

Body:
I give up!
Whenever I try to push I get a stupid:

! [rejected]        master -> master (non-fast forward)
error: failed to push some refs to 'git@github.com:companyX/projectX.git'

Our team has a new git setup. Instead of making private branches I now Forked our main repository (on github) to create my own copy.

At some point what I did was:

$ git fetch upstream master:upstreammaster

So here is my current setup::

$ git branch
master
* upstreammaster

$ git remote -v
origin  git@github.com:userX/projectX.git
upstream    git@github.com:companyX/projectX.git

where userX is my private repository.

So I go and make some changes to my upstreammaster branch, and the PULL from "upstream master".
Everything merges and stuff:

$ git pull upstream master
remote: Counting objects: 95, done.
remote: Compressing objects: 100% (60/60), done.
remote: Total 60 (delta 54), reused 0 (delta 0)
Unpacking objects: 100% (60/60), done.
From git@github.com:companyX/projectX
 * branch            master     -> FETCH_HEAD
Merge made by recursive.
stuff                      |  165 ++++++++++++--------
stuff                      |   35 ++--
stuff                       |  107 ++++++++++---
stuff                       |  105 ++++++++++---
stuff             |   24 ++--
stuff               |    9 +-
stuff                   |   53 +++----
stuff            |   44 +++---
stuff              |   52 +++----
stuff |   32 +----
stuff          |    4 +-
 stuff             |  138 ++++++++---------
stuff     |   58 ++++----
stuff    |  115 ++++++++------
stuff          |    5 +-
stuff                       |   39 ++---
stuff                        |   28 ++--
 17 files changed, 560 insertions(+), 453 deletions(-)

but then when I try to do:

$ git push upstream master
To git@github.com:companyX/projectX.git
 ! [rejected]        master -> master (non-fast forward)
error: failed to push some refs to 'git@github.com:companyX/projectX.git'

Any help would be greately appreciated! If you need clarification please ask, I will reply!

OwnerDisplayName: Pat Notz

LastEditorDisplayName: Pat Notz


问:
How to paste with keyboard in test Android studio
Im trying to use the paste function when I longclick on a text input and the "paste" option appears. I have tried to click with

```<code>onView(withText("Paste"))
            .perform(click(), pressImeActionButton());
</code>```

using espresso but it does not work. How can i click the little paste prompt that appears?

答:
It's not exactly what you were asking for but given that I don't think it's possible to do this with Espresso you might consider doing (ctrl + v) to perform paste in UIAutomator in your tests:

```<code>UiDevice
    .getInstance(InstrumentationRegistry.getInstrumentation())
    .pressKeyCode(KeyEvent.KEYCODE_V, KeyEvent.META_CTRL_MASK)
</code>```

You might want to have a look at the Espresso & UIAutomator - the perfect tandem article.

Body:
Im trying to use the paste function when I longclick on a text input and the "paste" option appears. I have tried to click with

onView(withText("Paste"))
            .perform(click(), pressImeActionButton());

using espresso but it does not work. How can i click the little paste prompt that appears?

Body:
It's not exactly what you were asking for but given that I don't think it's possible to do this with Espresso you might consider doing (ctrl + v) to perform paste in UIAutomator in your tests:

UiDevice
    .getInstance(InstrumentationRegistry.getInstrumentation())
    .pressKeyCode(KeyEvent.KEYCODE_V, KeyEvent.META_CTRL_MASK)

You might want to have a look at the Espresso & UIAutomator - the perfect tandem article.