问:
log4j - Intercept logging created within a class/method
I have an App which has many ejb Timer methods which are fired at various intervals, in an attempt to log the performance of these scheduled tasks I have written two methods which log the start and end of every task and records some info such as name, running duration and log info each time the timer fires

The intention with log info was to intercept all logging statements raised from within these methods, output to a string and save...I am doing this by creating a new WriterAppender, appending to the Logger for all logging levels, then when the timer completes capture the string output and remove the appender

This works well but it seems to have 2 unwanted effects:

1) It is stopping any logging from the timer class appearing in our normal file appender logs, eg. the log messages are being captured but they now don't appear in our normal logs (which are configured to show everything > INFO

2) Logging statements from different timers which overlap are appearing in each other logs, I guess this is the result of the Logger working on a single thread, not sure if theres a way around this?

I am no expert in log4j so I am hoping someone can point out a simple fix for 1, 2 or both

Code below shows the 2 methods which are called at start and end of every job

```<code>private Writer w = new StringWriter();
private WriterAppender wa;
private Logger logOutput = Logger.getLogger(ScheduledActions.class);

private TimerEvent logStartTimerEvent(ScheduledTask task){

    RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
    TimerEvent event = new TimerEvent(task);

    //Initialise a new log appender to intercept all log4j entries
    w = new StringWriter();
    Layout l = new PatternLayout("%m%n");
    wa = new WriterAppender(l, w);
    wa.setEncoding("UTF-8");
    wa.setThreshold(Level.ALL);
    wa.activateOptions();

    // Add it to logger
    logOutput = Logger.getLogger(ScheduledActions.class);
    logOutput.addAppender(wa);

    //Push this timer event to redis
    redisActions.addToFixedLengthList(RedisItem.TIMER_HISTORY.getKey()+"_"+task.getName(), gson.toJson(event), 100L);

    return event;
}

private void logEndTimerEvent(TimerEvent event){

    try{

        RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
        event.setLogInfo(w.toString());
        event.setEndTime(new Date());
        redisActions.editLastMemberInList(RedisItem.TIMER_HISTORY.getKey()+"_"+event.getTask().getName(), gson.toJson(event));
        w.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        //clean up the temp log appender
        logOutput.removeAppender(wa);
        wa.close();

    }

}
</code>```

答:
My final solution is adding an Appender with ThreadContextMapFilter.

```<code>    // With %X you will see the thread context values
    var layout = PatternLayout.newBuilder()
            .withPattern("%d{ISO8601_OFFSET_DATE_TIME_HHCMM} [%t] %-5level %c{1.} %X %msg%n%throwable")
            .build();

    var appender = FileAppender.newBuilder()
            .setName(fileId)
            .withFileName("/tmp/my-file.log")
            .setLayout(layout)
            // --- IMPORTANT PART ---
            .setFilter(new ThreadContextMapFilter(
                    Map.of("my-key", List.of("my-value")), true, null, null))
            .build();

    // Add the appender
    // https://logging.apache.org/log4j/2.x/manual/customconfig.html
    appender.start();
    final LoggerContext context = LoggerContext.getContext(false);
    final Configuration config = context.getConfiguration();
    config.addAppender(appender);
    config.getRootLogger().addAppender(appender, null, null);
    context.updateLoggers();

    // --- IMPORTANT PART ---
    try (var ignore = CloseableThreadContext.put("my-key", "my-value")) {
        // the logs here will be captured by the appender
        log.info("This log WILL be captured by the appender");

        // Note: In case you start threads from here,
        // you should pass the ThreadContext to them.
    }

    log.info("This log will NOT be captured by the appender");

    // Wait for the logs to be flushed. Any improvement ideas?
    // https://stackoverflow.com/a/71081005/1121497
    try {
        Thread.sleep(500);
    } catch (InterruptedException ignore) {
    }

    // Remove the appender
    final LoggerContext context = LoggerContext.getContext(false);
    final Configuration config = context.getConfiguration();
    config.getRootLogger().removeAppender(appender.getName());
    context.updateLoggers();
    appender.stop();
</code>```

Body:
I have an App which has many ejb Timer methods which are fired at various intervals, in an attempt to log the performance of these scheduled tasks I have written two methods which log the start and end of every task and records some info such as name, running duration and log info each time the timer fires

The intention with log info was to intercept all logging statements raised from within these methods, output to a string and save...I am doing this by creating a new WriterAppender, appending to the Logger for all logging levels, then when the timer completes capture the string output and remove the appender

This works well but it seems to have 2 unwanted effects:

1) It is stopping any logging from the timer class appearing in our normal file appender logs, eg. the log messages are being captured but they now don't appear in our normal logs (which are configured to show everything > INFO

2) Logging statements from different timers which overlap are appearing in each other logs, I guess this is the result of the Logger working on a single thread, not sure if theres a way around this?

I am no expert in log4j so I am hoping someone can point out a simple fix for 1, 2 or both

Code below shows the 2 methods which are called at start and end of every job

private Writer w = new StringWriter();
private WriterAppender wa;
private Logger logOutput = Logger.getLogger(ScheduledActions.class);

private TimerEvent logStartTimerEvent(ScheduledTask task){

    RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
    TimerEvent event = new TimerEvent(task);

    //Initialise a new log appender to intercept all log4j entries
    w = new StringWriter();
    Layout l = new PatternLayout("%m%n");
    wa = new WriterAppender(l, w);
    wa.setEncoding("UTF-8");
    wa.setThreshold(Level.ALL);
    wa.activateOptions();

    // Add it to logger
    logOutput = Logger.getLogger(ScheduledActions.class);
    logOutput.addAppender(wa);

    //Push this timer event to redis
    redisActions.addToFixedLengthList(RedisItem.TIMER_HISTORY.getKey()+"_"+task.getName(), gson.toJson(event), 100L);

    return event;
}

private void logEndTimerEvent(TimerEvent event){

    try{

        RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
        event.setLogInfo(w.toString());
        event.setEndTime(new Date());
        redisActions.editLastMemberInList(RedisItem.TIMER_HISTORY.getKey()+"_"+event.getTask().getName(), gson.toJson(event));
        w.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        //clean up the temp log appender
        logOutput.removeAppender(wa);
        wa.close();

    }

}

Body:
My final solution is adding an Appender with ThreadContextMapFilter.

    // With %X you will see the thread context values
    var layout = PatternLayout.newBuilder()
            .withPattern("%d{ISO8601_OFFSET_DATE_TIME_HHCMM} [%t] %-5level %c{1.} %X %msg%n%throwable")
            .build();

    var appender = FileAppender.newBuilder()
            .setName(fileId)
            .withFileName("/tmp/my-file.log")
            .setLayout(layout)
            // --- IMPORTANT PART ---
            .setFilter(new ThreadContextMapFilter(
                    Map.of("my-key", List.of("my-value")), true, null, null))
            .build();

    // Add the appender
    // https://logging.apache.org/log4j/2.x/manual/customconfig.html
    appender.start();
    final LoggerContext context = LoggerContext.getContext(false);
    final Configuration config = context.getConfiguration();
    config.addAppender(appender);
    config.getRootLogger().addAppender(appender, null, null);
    context.updateLoggers();

    // --- IMPORTANT PART ---
    try (var ignore = CloseableThreadContext.put("my-key", "my-value")) {
        // the logs here will be captured by the appender
        log.info("This log WILL be captured by the appender");

        // Note: In case you start threads from here,
        // you should pass the ThreadContext to them.
    }

    log.info("This log will NOT be captured by the appender");

    // Wait for the logs to be flushed. Any improvement ideas?
    // https://stackoverflow.com/a/71081005/1121497
    try {
        Thread.sleep(500);
    } catch (InterruptedException ignore) {
    }

    // Remove the appender
    final LoggerContext context = LoggerContext.getContext(false);
    final Configuration config = context.getConfiguration();
    config.getRootLogger().removeAppender(appender.getName());
    context.updateLoggers();
    appender.stop();


来源: stackexchange

答:
There is actually no url for the image, that is an SVG, the entire image is drawn in the <path ....>

To use that image just copy the SVG, that is everything from:

```<code><svg xmlns="....

</svg>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Url in side of svg xmlns

Body:
I am trying to find url of this image:https://i.stack.imgur.com/Kfi6M.png
Page url:https://jobs.tnaa.com/jobsearch/results?Page=1&occupation=RN&city=&radius=20&state1=ALL&specialty=&GeoType=State

But there is no link except then svg xmlns. Can someone explain me what how can i find the url to this image and what is svg xmlns?

        <svg xmlns="http://www.w3.org/6000/png" width="600" height="600" viewBox="0 0 105 105">
            <path d="M473.85,66a1.29,1.29,0,0,1-.05-.24c0-.18,0-.36,0-.53V24a2.08,2.08,0,0,1,.06-.74,1.54,1.54,0,0,1,.3,0H578a2.79,2.79,0,0,1,.75.05c0,.1,0,.19,0,.28s0,.29,0,.44V81.33c0,.23,0,.45,0,.7a2.37,2.37,0,0,1-.31.06h-5.31l-.24,0-.22-.48Q569.49,74,566.3,66.5c-.07-.17-.15-.33-.22-.47-.53-.06-7.43-.06-7.88,0-.42.91-.8,1.86-1.2,2.81s-.8,1.89-1.2,2.83l-1.2,2.84-1.2,2.84c-.39.94-.8,1.89-1.2,2.83S551.41,82.08,551,83s-.78,1.89-1.24,2.9c-.61-1.4-1.16-2.72-1.71-4l-1.68-4-1.67-4L543,70l-1.68-4A2.09,2.09,0,0,0,541,66h-7.34l-.15,0c-.19.1-.21.29-.28.45L531.5,70.6l-7.2,17.07c0,.12-.11.23-.15.34s-.11-.09-.11-.14,0-.29,0-.43V66.66A1.6,1.6,0,0,0,524,66l-.47,0c-3.52,0-6.33,0-6.7.05-.13.16-.08.34-.08.52l.06,4.69.09,8.62a5.45,5.45,0,0,1,0,.56,1,1,0,0,1-.36-.39l-4.34-5.92-5.63-7.68-.15-.2a.5.5,0,0,0-.51-.26,4.51,4.51,0,0,1-.52,0H474.53A2.64,2.64,0,0,1,473.85,66Zm0,6.3q0,24.19,0,48.38a1.16,1.16,0,0,0,0,.18,1.52,1.52,0,0,0,.73.07H578c.15,0,.31,0,.47,0s.19,0,.31-.07V88.35c0-.15,0-.29,0-.44a1.64,1.64,0,0,0-.07-.28h-3.25a.7.7,0,0,0-.17.06c.06.14.1.27.16.41.41,1,.83,2,1.25,3,.05.13.15.25.09.42a1.81,1.81,0,0,1-.61.06H569.7a2.24,2.24,0,0,1-.31-.05l-.06-.07a.36.36,0,0,1,0-.09l-.06-.13q-3.4-8.86-6.83-17.72l-.12-.32a.08.08,0,0,0,0,0l0-.09s0,0,0,0h0s-.07,0-.07.06q-1.67,4.38-3.31,8.76a.38.38,0,0,0,0,.15,1.18,1.18,0,0,0,.56,0c1,0,1.94,0,2.91,0l.56,0a1.73,1.73,0,0,1,.12.2c.59,1.68,1.17,3.37,1.76,5.06a1.23,1.23,0,0,1,0,.19,1,1,0,0,1-.57.06H556.5c-.56,1.32-1,2.65-1.58,4a1.7,1.7,0,0,1-.28,0H544.9a1.7,1.7,0,0,1-.28,0c-.07-.16-.15-.32-.21-.48-.39-1-.78-2-1.18-3-.06-.16-.08-.35-.25-.45-.7,0-10.8,0-11.24,0-.07.16-.15.33-.22.51-.38,1-.76,2-1.15,3-.07.16-.09.35-.29.48l-.65,0H517.87c-.88,0-.68.07-1.16-.59l-8.28-11.27-1.68-2.28c-.05-.07-.09-.18-.25-.15a9.26,9.26,0,0,0,0,1.29c0,.42,0,.84,0,1.26s0,.87,0,1.31,0,.87,0,1.31,0,.87,0,1.3,0,.84,0,1.26,0,.87,0,1.31l0,1.31c0,.43,0,.87,0,1.3s0,.84,0,1.26a8.5,8.5,0,0,1,0,1.33,4.07,4.07,0,0,1-.47,0h-6.3a.75.75,0,0,1-.48-.09,2.45,2.45,0,0,1,0-.61V72.93c0-.16,0-.32,0-.49s0-.21,0-.32a1.5,1.5,0,0,0-.69-.06H474.11a1.87,1.87,0,0,0-.25,0A.65.65,0,0,0,473.81,72.25Zm9.64,19.3-.54,0c0-.11,0-.2-.05-.3s0-.22,0-.33c0-5.33,0-10.65,0-16a1.5,1.5,0,0,1,0-.56,1,1,0,0,1,.53-.07c2.06,0,4.13,0,6.19,0a.91.91,0,0,1,.53.08c0,.11,0,.24,0,.36.07,4.11,0,16.25-.05,16.76C489.66,91.57,487.27,91.59,483.45,91.55Zm28.94,32.08H474.13a2.3,2.3,0,0,0-.28.06,11,11,0,0,0,0,2.56l.71,0h38.2a2.3,2.3,0,0,0,.28-.06,16.83,16.83,0,0,0,0-2.56Zm24.79-50.24c-.54,1.41-1.07,2.82-1.6,4.24s-1,2.62-1.48,3.92c-.05.13-.14.26-.07.41.4.05,5.51.09,6.51,0a2.11,2.11,0,0,0,.28,0c-.05-.15-.09-.29-.14-.43-1.39-3.81-3.1-8.25-3.3-8.58A3.46,3.46,0,0,0,537.18,73.39Zm35.06,54c-.14-.2-.3-.39-.43-.6a1.77,1.77,0,0,1-.36-.59l.38-.27a1.9,1.9,0,0,0,.63-.75,2.08,2.08,0,0,0-1.39-2.9,4.21,4.21,0,0,0-1.17-.19c-.89,0-1.77,0-2.66,0a1.43,1.43,0,0,0-.28.07c0,.09,0,.15,0,.21,0,1.79,0,3.59,0,5.38a2.07,2.07,0,0,0,0,.3c.3,0,.57,0,.85,0a1.56,1.56,0,0,0,.8-.08c.09-.49,0-1,.08-1.44.85-.17.95-.13,1.39.48l.38.52.4.52h1.52l.28,0Zm-3.52-4a2,2,0,0,1,.28,0,7.22,7.22,0,0,1,.93,0,.93.93,0,0,1,.9.6.87.87,0,0,1-.73,1.17,3.69,3.69,0,0,1-1.37,0A6,6,0,0,1,568.72,123.47Zm-50.33.88a3.07,3.07,0,0,1-.85.06h-.78a2.69,2.69,0,0,1-.84-.06,5.42,5.42,0,0,1,0-1.06,5.76,5.76,0,0,0,0-1.1,4.36,4.36,0,0,0-1.69,0c0,.46,0,1,0,1.43s0,1,0,1.45,0,1,0,1.5a13.61,13.61,0,0,0,0,1.43,4.15,4.15,0,0,0,1.69,0c0-.35,0-.72,0-1.09a5.9,5.9,0,0,1,0-1.11,2.76,2.76,0,0,1,.85,0q.39,0,.78,0a2.28,2.28,0,0,1,.82.06,6,6,0,0,1,0,1.11,6.71,6.71,0,0,0,0,1.1,4,4,0,0,0,1.66,0,2.4,2.4,0,0,0,0-.28c0-1.75,0-3.51,0-5.27a2.19,2.19,0,0,0,0-.27,4.92,4.92,0,0,0-1.67,0C518.38,122.92,518.46,123.63,518.39,124.35Zm29,3.66c0-.14,0-.3,0-.46v-1.4c0-.13,0-.26.1-.36a11.68,11.68,0,0,1,2.38,0,.76.76,0,0,1,.06.47c0,.48,0,1,0,1.45a1.61,1.61,0,0,0,.06.35,9.72,9.72,0,0,0,1.62,0,1.07,1.07,0,0,0,0-.21c0-1.83,0-3.65,0-5.47a.59.59,0,0,0-.05-.19,1.24,1.24,0,0,0-.57-.06,4.51,4.51,0,0,0-.52,0c-.18,0-.38-.05-.57.1,0,.13,0,.27,0,.41,0,.47,0,.94,0,1.41a2.21,2.21,0,0,1-.05.33,7.2,7.2,0,0,1-1.22,0,3.54,3.54,0,0,1-1.25-.08c0-.17,0-.33,0-.49v-1.35c0-.11,0-.21,0-.34-.48,0-.93,0-1.38,0a1.07,1.07,0,0,0-.27.07c-.07.62-.05,5.46,0,5.86A5.23,5.23,0,0,0,547.4,128Zm-22-3.54c-.57,0-1.14,0-1.71,0-.16,0-.32,0-.46-.11a2.07,2.07,0,0,1,.06-1l.52,0h2.08a.81.81,0,0,0,.52-.09,4,4,0,0,0,0-1.14,1.6,1.6,0,0,0-.27,0h-4.32a1.59,1.59,0,0,0-.3.06c0,.09,0,.15,0,.21,0,1.81,0,3.62,0,5.42a1,1,0,0,0,0,.24,1.6,1.6,0,0,0,.27,0h4.43a1.77,1.77,0,0,0,.3-.06,3.35,3.35,0,0,0-.05-1.18h-2.83l-.41,0a2.91,2.91,0,0,1,0-1.1l.53,0h1.82a.47.47,0,0,0,.41-.12,5,5,0,0,0,0-1A1.94,1.94,0,0,0,525.44,124.47Zm50,1.3a.81.81,0,0,1,.52-.1c.61,0,1.22,0,1.82,0,.14,0,.27,0,.42,0a2.17,2.17,0,0,0,0-1.13l-.53,0H576a.89.89,0,0,1-.51-.07,1.8,1.8,0,0,1,0-1,1,1,0,0,1,.5-.06h2.19a.57.57,0,0,0,.47-.12c0-.16,0-.35,0-.55a1.4,1.4,0,0,0,0-.57l-.38,0h-4.06c-.15,0-.32,0-.44.11s0,.09,0,.13v5.47a.79.79,0,0,0,.06.22c.42,0,3.57.08,4.65,0a2,2,0,0,0,.32,0,3.34,3.34,0,0,0,0-1.18c-.55,0-1.09,0-1.62,0a13,13,0,0,1-1.64,0A3.23,3.23,0,0,1,575.47,125.77Zm-41.35,2c-.15-.33-.3-.65-.46-1-.66-1.4-1.31-2.8-2-4.21a.86.86,0,0,0-.29-.45h-1.63c-.06.12-.14.23-.19.34-.17.36-.34.71-.5,1.07-.63,1.34-1.27,2.68-1.89,4-.07.15-.2.3-.14.48a5.62,5.62,0,0,0,1.67,0,12,12,0,0,1,.55-1.07l.22,0c.71,0,1.42,0,2.13,0a.46.46,0,0,1,.5.33c.1.27.23.53.34.79a7.32,7.32,0,0,0,1.75,0A2.13,2.13,0,0,0,534.12,127.77Zm-2.74-2.12a.65.65,0,0,1-.17.08,6.8,6.8,0,0,1-1.42,0,8.52,8.52,0,0,1,.57-1.46c0-.13.06-.29.23-.36A8.33,8.33,0,0,1,531.38,125.65Zm34.83,2.2c-.35-.85-2.52-5.39-2.73-5.69a6.19,6.19,0,0,0-1.73,0l-2.63,5.61a1.42,1.42,0,0,0-.07.22,4.91,4.91,0,0,0,1.71,0c.23-.33.28-.75.54-1.06a19.91,19.91,0,0,1,2.68,0c.27.32.29.77.57,1.09a6.6,6.6,0,0,0,1.69,0A1.13,1.13,0,0,0,566.21,127.85Zm-2.79-2.21c-.13.15-.32.09-.48.1a5.42,5.42,0,0,1-.57,0,.85.85,0,0,1-.53-.09,3.88,3.88,0,0,1,.34-.89c.12-.29.25-.59.41-.94A7.06,7.06,0,0,1,563.42,125.64ZM558,122.4a4,4,0,0,0-2.32-.36,3.52,3.52,0,0,0-1.59.55,2.89,2.89,0,0,0-1.37,2.62,3,3,0,0,0,2.24,2.84,4.38,4.38,0,0,0,2.46,0,2.92,2.92,0,0,0,1.27-.72,1.35,1.35,0,0,0,.18-.25l-.51-.44c-.18-.14-.32-.34-.54-.4l-.08,0-.2.15a1.94,1.94,0,0,1-1.49.42,1.62,1.62,0,0,1-1.38-.89,1.75,1.75,0,0,1-.16-1.23,1.69,1.69,0,0,1,1.65-1.37,1.94,1.94,0,0,1,1.3.38l.37.27a7,7,0,0,0,1-.91A2.24,2.24,0,0,0,558,122.4ZM541.23,124v3.49a.81.81,0,0,0,.1.55,3.44,3.44,0,0,0,.79,0,1.64,1.64,0,0,0,.84-.1c0-.18,0-.37,0-.57,0-1.13,0-2.25,0-3.38a.89.89,0,0,1,.09-.59c.12,0,.26,0,.39,0h1.09a2.71,2.71,0,0,0,.37,0c0-.29,0-.57,0-.84a3.16,3.16,0,0,0,0-.32.71.71,0,0,0-.47-.08,47.82,47.82,0,0,0-5.1.07,2.79,2.79,0,0,0,0,1,.48.48,0,0,0,.09.21c.6,0,1.19,0,1.84,0C541.22,123.68,541.23,123.86,541.23,124Zm-2.1,2.79h-2.29a.21.21,0,0,1-.21-.18,3.24,3.24,0,0,1,0-.44v-3.48a1.14,1.14,0,0,0-.07-.56,9.66,9.66,0,0,0-1.32,0,2,2,0,0,0-.28,0c-.09.41-.11,2.83-.07,5.48,0,.13,0,.25,0,.39a1.31,1.31,0,0,0,.22.05h4.37a.46.46,0,0,0,.16-.06,1.13,1.13,0,0,0,0-.18v-.94A1.17,1.17,0,0,0,539.13,126.82Z" transform="translate(-473.79 -23.23)">
            </path>
        </svg>

Body:
There is actually no url for the image, that is an SVG, the entire image is drawn in the <path ....>

To use that image just copy the SVG, that is everything from:

<svg xmlns="....

</svg>


问:
return nested array solidity
Is it possible to return an array in solidity?

```<code>// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;

contract Test {
    constructor() {}
    function multiArray() external pure returns (uint256[2][] memory doubleArray) {
        doubleArray[0] = [uint(12345678),uint(1234567)];
      return doubleArray;
    }
}
</code>```

this does not work, but I thought with solidity > 0.8.0 it should be possible, also with "ABIEncoderV2"?

答:
Solidity support 1D array only. Multidimensional arrays are yet to come.

```<code>// SPDX-License-Identifier: GPL-3.0;
pragma  solidity >=0.7.0 <0.9.0;
contract Test{
    string[] A=["A","B"];
    function fun() public view  returns(string[] memory){
        return A;
}
}
</code>```

Title: return nested array solidity

Body:
Is it possible to return an array in solidity?

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;

contract Test {
    constructor() {}
    function multiArray() external pure returns (uint256[2][] memory doubleArray) {
        doubleArray[0] = [uint(12345678),uint(1234567)];
      return doubleArray;
    }
}

this does not work, but I thought with solidity > 0.8.0 it should be possible, also with "ABIEncoderV2"?

Body:
Solidity support 1D array only. Multidimensional arrays are yet to come.

// SPDX-License-Identifier: GPL-3.0;
pragma  solidity >=0.7.0 <0.9.0;
contract Test{
    string[] A=["A","B"];
    function fun() public view  returns(string[] memory){
        return A;
}
}


问:
MongoError: Unrecognized expression '$last' ("version": "5.0.4")
When I tried to project in aggregate

I am using this MongoDB version ("version": "5.0.4")

```<code>                {
                    $project: {
                        _id: 1,
                        feeling: 1,
                        updated_date: 1,
                        created_date: 1,
                        activity_type: 1,
                        activityCount: { $size: "$activity" },
                        activity_count: 1,
                        activity_tipped_count: 1,
                        activity_upvote_count: 1,
                        activity: { $last: "$activity" },
                        product: 1,
                        property: 1,
                        shared_post: 1,
                        post: 1,
                        user: 1,
                        rss_delete: 1,
                    },
                },
</code>```

It gives this error

```<code>MongoError: Unrecognized expression '$last'
    at Connection.<anonymous> (/Users/mac/Documents/WORK DISK/A PROJECTS/OutSourcing/Revstance-node-v3 /revstancev3/node_modules/mongodb/lib/core/connection/pool.js:453:61)
    at Connection.emit (node:events:390:28)
    at Connection.emit (node:domain:475:12)
    at processMessage (/Users/mac/Documents/WORK DISK/A PROJECTS/OutSourcing/Revstance-node-v3 /revstancev3/node_modules/mongodb/lib/core/connection/connection.js:456:10)
    at Socket.<anonymous> (/Users/mac/Documents/WORK DISK/A PROJECTS/OutSourcing/Revstance-node-v3 /revstancev3/node_modules/mongodb/lib/core/connection/connection.js:625:15)
    at Socket.emit (node:events:390:28)
    at Socket.emit (node:domain:475:12)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at Socket.Readable.push (node:internal/streams/readable:228:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:199:23) {
  ok: 0,
  code: 168,
  codeName: 'InvalidPipelineOperator'
}
</code>```

Thanks in advance any help means a lot for me

答:
I'm guessing that this is a failure in the driver to differentiate between the $last aggregation accumulator and $last alias for $arrayElemAt(-1). Per the documentation at https://docs.mongodb.com/manual/reference/operator/aggregation/last/, the accumulation operator is not valid in a $project stage.

Maybe try replacing it with this:

activity: { $arrayElemAt: [ "$activity", -1 ] }

Body:
When I tried to project in aggregate

I am using this MongoDB version ("version": "5.0.4")

                {
                    $project: {
                        _id: 1,
                        feeling: 1,
                        updated_date: 1,
                        created_date: 1,
                        activity_type: 1,
                        activityCount: { $size: "$activity" },
                        activity_count: 1,
                        activity_tipped_count: 1,
                        activity_upvote_count: 1,
                        activity: { $last: "$activity" },
                        product: 1,
                        property: 1,
                        shared_post: 1,
                        post: 1,
                        user: 1,
                        rss_delete: 1,
                    },
                },

It gives this error

MongoError: Unrecognized expression '$last'
    at Connection.<anonymous> (/Users/mac/Documents/WORK DISK/A PROJECTS/OutSourcing/Revstance-node-v3 /revstancev3/node_modules/mongodb/lib/core/connection/pool.js:453:61)
    at Connection.emit (node:events:390:28)
    at Connection.emit (node:domain:475:12)
    at processMessage (/Users/mac/Documents/WORK DISK/A PROJECTS/OutSourcing/Revstance-node-v3 /revstancev3/node_modules/mongodb/lib/core/connection/connection.js:456:10)
    at Socket.<anonymous> (/Users/mac/Documents/WORK DISK/A PROJECTS/OutSourcing/Revstance-node-v3 /revstancev3/node_modules/mongodb/lib/core/connection/connection.js:625:15)
    at Socket.emit (node:events:390:28)
    at Socket.emit (node:domain:475:12)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at Socket.Readable.push (node:internal/streams/readable:228:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:199:23) {
  ok: 0,
  code: 168,
  codeName: 'InvalidPipelineOperator'
}

Thanks in advance any help means a lot for me


问:
Use 'import module' or 'from module import'?
I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python and I'm trying to start off with best practices in mind.

Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?

答: To add to what people have said about from x import *: besides making it more difficult to tell where names came from, this throws off code checkers like Pylint.  They will report those names as undefined variables.

OwnerDisplayName: kRON

OwnerDisplayName: DNS

ContentLicense: CC BY-SA 2.5


问:
Can't use .indexof on JSON string because it has no method 'indexof' javascript
I have some JSON parsed, but I would like to take a link I get from the JSON, find an identifier in the link that makes it different (e.g. www.foo.com/IDENTIFIER/home), and have that identifier as a string to plug into another function that uses the identifier.

Here's the code where I try to use indexOf to find the preidentifier path index so I can then get the index of the identifier after it (that code hasn't been written yet because I'm stuck here). This also uses JSONP.

```<code>$.jsonp({
    "url": "http://foo.com&callback=?",
    "data": {
    "alt": "json-in-script"
    },
    "success": function (data) {
        var link = data[0].link;
        var jsonText = JSON.stringify(link);

        // the below code returns string
        console.log('jsonText string?'+typeof jsonText);

        // the below code returns that this method has no object indexOf
        var index = jsonText.indexof("pre-identifier-path/");

    },
    "error": function () {
    }
});
</code>```

Thank you for your time, sorry if this a tad confusing.

答:
The method should be named indexOf, it's case sensitive. Ex.:

```<code>jsonText.indexOf("pre-identifier-path/");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some JSON parsed, but I would like to take a link I get from the JSON, find an identifier in the link that makes it different (e.g. www.foo.com/IDENTIFIER/home), and have that identifier as a string to plug into another function that uses the identifier.

Here's the code where I try to use indexOf to find the preidentifier path index so I can then get the index of the identifier after it (that code hasn't been written yet because I'm stuck here). This also uses JSONP.

$.jsonp({
    "url": "http://foo.com&callback=?",
    "data": {
    "alt": "json-in-script"
    },
    "success": function (data) {
        var link = data[0].link;
        var jsonText = JSON.stringify(link);

        // the below code returns string
        console.log('jsonText string?'+typeof jsonText);

        // the below code returns that this method has no object indexOf
        var index = jsonText.indexof("pre-identifier-path/");

    },
    "error": function () {
    }
});

Thank you for your time, sorry if this a tad confusing.

Body:
The method should be named indexOf, it's case sensitive. Ex.:

jsonText.indexOf("pre-identifier-path/");


问:
startActivityForResult is deprecated, I'm trying to update my code
i'm new to android. just trying to make a webview app instead of an actual mobile app, then i'll use my flask app as a mobile app.

the app works fine as it is, no problems at all but startActivityForResult is giving me a warning.
here's the code:

```<code>    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

        //checking for storage permission to write images for upload
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, perms, FCR);

            //checking for WRITE_EXTERNAL_STORAGE permission
        } else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, FCR);

            //checking for CAMERA permissions
        } else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, FCR);
        }
        if (mUMA != null) {
            mUMA.onReceiveValue(null);
        }
        mUMA = filePathCallback;
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
                takePictureIntent.putExtra("PhotoPath", mCM);
            } catch (IOException ex) {
                Log.e(TAG, "Image file creation failed", ex);
            }
            if (photoFile != null) {
                mCM = "file:" + photoFile.getAbsolutePath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            } else {
                takePictureIntent = null;
            }
        }
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("*/*");
        if (multiple_files) {
            contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        }
        Intent[] intentArray;
        if (takePictureIntent != null) {
            intentArray = new Intent[]{takePictureIntent};
        } else {
            intentArray = new Intent[0];
        }

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
        startActivityForResult(chooserIntent, FCR);

        return true;
    }
</code>```

here's onActivityResult i still couldn't make it work...

```<code> @Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    super.onActivityResult(requestCode, resultCode, intent);
    Uri[] results = null;
    if(resultCode== Activity.RESULT_OK){
        if(requestCode == FCR){
            if(null == mUMA){
                return;
            }
            if(intent == null || intent.getData() == null){
                if(mCM != null){
                    results = new Uri[]{Uri.parse(mCM)};
                }
            }else{
                String dataString = intent.getDataString();
                if(dataString != null){
                    results = new Uri[]{Uri.parse(dataString)};
                } else {
                    if(multiple_files) {
                        if (intent.getClipData() != null) {
                            final int numSelectedFiles = intent.getClipData().getItemCount();
                            results = new Uri[numSelectedFiles];
                            for (int i = 0; i < numSelectedFiles; i++) {
                                results[i] = intent.getClipData().getItemAt(i).getUri();
                            }
                        }
                    }
                }
            }
        }
    }
    mUMA.onReceiveValue(results);
    mUMA = null;
}
</code>```

答:
Replace startActivityForResult with Callback for for Activity Result

```<code>Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityIntent.launch(chooserIntent);
</code>```

Callback for for Activity Result - startActivityIntent

```<code>ActivityResultLauncher<Intent> startActivityIntent = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
               // Add same code that you want to add in onActivityResult method
            }
        });
</code>```

For more info check official documentation.

Body:
i'm new to android. just trying to make a webview app instead of an actual mobile app, then i'll use my flask app as a mobile app.

the app works fine as it is, no problems at all but startActivityForResult is giving me a warning.
here's the code:

    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

        //checking for storage permission to write images for upload
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, perms, FCR);

            //checking for WRITE_EXTERNAL_STORAGE permission
        } else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, FCR);

            //checking for CAMERA permissions
        } else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, FCR);
        }
        if (mUMA != null) {
            mUMA.onReceiveValue(null);
        }
        mUMA = filePathCallback;
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
                takePictureIntent.putExtra("PhotoPath", mCM);
            } catch (IOException ex) {
                Log.e(TAG, "Image file creation failed", ex);
            }
            if (photoFile != null) {
                mCM = "file:" + photoFile.getAbsolutePath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            } else {
                takePictureIntent = null;
            }
        }
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("*/*");
        if (multiple_files) {
            contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        }
        Intent[] intentArray;
        if (takePictureIntent != null) {
            intentArray = new Intent[]{takePictureIntent};
        } else {
            intentArray = new Intent[0];
        }

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
        startActivityForResult(chooserIntent, FCR);

        return true;
    }

here's onActivityResult i still couldn't make it work...

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    super.onActivityResult(requestCode, resultCode, intent);
    Uri[] results = null;
    if(resultCode== Activity.RESULT_OK){
        if(requestCode == FCR){
            if(null == mUMA){
                return;
            }
            if(intent == null || intent.getData() == null){
                if(mCM != null){
                    results = new Uri[]{Uri.parse(mCM)};
                }
            }else{
                String dataString = intent.getDataString();
                if(dataString != null){
                    results = new Uri[]{Uri.parse(dataString)};
                } else {
                    if(multiple_files) {
                        if (intent.getClipData() != null) {
                            final int numSelectedFiles = intent.getClipData().getItemCount();
                            results = new Uri[numSelectedFiles];
                            for (int i = 0; i < numSelectedFiles; i++) {
                                results[i] = intent.getClipData().getItemAt(i).getUri();
                            }
                        }
                    }
                }
            }
        }
    }
    mUMA.onReceiveValue(results);
    mUMA = null;
}

Body:
Replace startActivityForResult with Callback for for Activity Result

Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityIntent.launch(chooserIntent);

Callback for for Activity Result - startActivityIntent

ActivityResultLauncher<Intent> startActivityIntent = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
               // Add same code that you want to add in onActivityResult method
            }
        });

For more info check official documentation.


问:
google colab, cv2_imshow throws error: 'NoneType' object has no attribute 'clip'
I am learning the basics of OpenCV and while running the following piece of code in google colab, it gives an error.

```<code>from google.colab.patches import cv2_imshow
import cv2
img=cv2.imread("geeks14.png")
cv2_imshow(img)
</code>```

The error is

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-569c91be5363> in <module>()
      2 import cv2
      3 img=cv2.imread("geeks14.png")
----> 4 cv2_imshow(img)

/usr/local/lib/python3.7/dist-packages/google/colab/patches/__init__.py in cv2_imshow(a)
     20       image.
     21   """
---> 22   a = a.clip(0, 255).astype('uint8')
     23   # cv2 stores colors as BGR; convert to RGB
     24   if a.ndim == 3:

AttributeError: 'NoneType' object has no attribute 'clip
</code>```

答:
there are two ways to fix this.

Goto the image you uploaded on Google colab, align your cursor on it, 3 dots will show, scroll to copy path, copy this path and paste in your code.

This error is as a result of having your image in a path not defined. Don't upload in sample folder. When you click on the menu to upload files, right click and upload your image as a single file.

Body:
I am learning the basics of OpenCV and while running the following piece of code in google colab, it gives an error.

from google.colab.patches import cv2_imshow
import cv2
img=cv2.imread("geeks14.png")
cv2_imshow(img)

The error is

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-569c91be5363> in <module>()
      2 import cv2
      3 img=cv2.imread("geeks14.png")
----> 4 cv2_imshow(img)

/usr/local/lib/python3.7/dist-packages/google/colab/patches/__init__.py in cv2_imshow(a)
     20       image.
     21   """
---> 22   a = a.clip(0, 255).astype('uint8')
     23   # cv2 stores colors as BGR; convert to RGB
     24   if a.ndim == 3:

AttributeError: 'NoneType' object has no attribute 'clip


问:
How to transform a string into a list of char and int using a list comprehension in Python
Given the following string:

```<code>"[10,20]"
</code>```

I want to create the following list using a list comprehension in Python:

```<code>['[', 10, ',', 20, ']']
</code>```

Being 10 and 20 integers and the rest of the elements in the list chars.

I assume that I would need a to use something similar to what itertools.groupby(iterable, key=None) provides:

Make an iterator that returns consecutive keys and groups from the
iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the iterable
needs to already be sorted on the same key function.

However Python's group by returns an iterator with consecutive keys and groups. In my case the keys would change so I guess I'd need a similar iterator that returns the groups based on a filter. Any ideas?

答:
Group by whether this character is numeric or not. This can be done using the str.isnumeric function as the key argument to groupby().

```<code>s = "[10,20]"
g = itertools.groupby(s, key=str.isnumeric)
</code>```

Then, for the True groups, convert it to an integer. Leave False groups as-is.
Since the values of the groupby are iterators where each element is a separate character, you need to join it with "" to convert it into a single string, and optionally convert that string to an integer.

```<code>lst = [int("".join(chars)) if is_numeric else "".join(chars) for is_numeric, chars in g]
</code>```

Which gives:

```<code>['[', 10, ',', 20, ']']
</code>```

In one line:

```<code>lst = [                  int("".join(chars))
      if is_numeric else "".join(chars)
      for is_numeric, chars in itertools.groupby(s, key=str.isnumeric)
      ]
</code>```

Body:
Given the following string:

"[10,20]"

I want to create the following list using a list comprehension in Python:

['[', 10, ',', 20, ']']

Being 10 and 20 integers and the rest of the elements in the list chars.

I assume that I would need a to use something similar to what itertools.groupby(iterable, key=None) provides:

Make an iterator that returns consecutive keys and groups from the
iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the iterable
needs to already be sorted on the same key function.

However Python's group by returns an iterator with consecutive keys and groups. In my case the keys would change so I guess I'd need a similar iterator that returns the groups based on a filter. Any ideas?

Body:
Group by whether this character is numeric or not. This can be done using the str.isnumeric function as the key argument to groupby().

s = "[10,20]"
g = itertools.groupby(s, key=str.isnumeric)

Then, for the True groups, convert it to an integer. Leave False groups as-is.
Since the values of the groupby are iterators where each element is a separate character, you need to join it with "" to convert it into a single string, and optionally convert that string to an integer.

lst = [int("".join(chars)) if is_numeric else "".join(chars) for is_numeric, chars in g]

Which gives:

['[', 10, ',', 20, ']']

In one line:

lst = [                  int("".join(chars))
      if is_numeric else "".join(chars)
      for is_numeric, chars in itertools.groupby(s, key=str.isnumeric)
      ]


问:
How to export Azure Data Factory ARM template using Automation script to local drive?
I want to export the Azure Data Factory ARM template(from studio) to local drive using Automation script to push it to GitLab as ADF doesn't support native integration with GitLab.
How to export ADF ARM template through automation script (PowerShell, CLi, RestAPI etc.).
Please see attached ADF ARM template export page.

答:
This is a known limitation. You cannot programmatically export the ARM template.

The export template feature doesn't support exporting Azure Data
Factory resources. To learn about how you can export Data Factory
resources, see Copy or clone a data factory in Azure Data
Factory.

There are a number of similar requests shared here ADF shall be able to export ARM template by powershell as Ideas and feedback, you can upvote or add one too for official MS response.


问:
Where does React put the continuous build files when using create-react-app
I'm using create-react-app. When I run npm start (react-scripts start) it continuously builds the changes for me and does it magic. But what is the output folder for that? I know when I build it manually where the files go.

I want to use firebase emulator to serve the current version (the continuous build) of my react all but I don't understand where's the output folder or how to achieve it.

答:
tl;dr

run npm run build, not npm run start

More Detail

react-scripts start runs webpack-dev-server internally. As a default setting, webpack-dev-server serves bundled files from memory and does not write files in directory.
If you want to write files with webpack-dev-sever, you could set writeToDisk option to true in your dev server configuration.

However, I dont think this is what you want to serve on firebase emulator. Webpack-dev-server does not build optimal app for production, and you also need to use react-app-rewired to customize dev server configuration in cra template.

What you want to do is npm run build to run react-scripts build, which builds optimized production app in /build directory.


问:
In Java Swing (using swingx) how to sort rows in one table in same order as another table
I have a table with x num of rows, I have a second table with the same number of rows but different columns and metadata, they have different table models. but each row represents the same object (a song).

I want to synchronize row sorting between the two tables so for example if I sort on column 2 of table 1 then rows of the table will be sorted in the same order. But currently, I just have sorted by matching sort keys so sort on the same column (but because different data get different results)

e.g

Starting point

```<code>Table 1
1    tom
2    jane
3    fred
4    steve
5    jim

Table 2
1    oranges
2    apples
3    pears
4    lemons
5    plums
</code>```

If I sort by table 1, column 2 Ascending I want to get

```<code>Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
5    plums
3    pears
4    lemons
1    oranges
</code>```

but I get

```<code>Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
4    lemons
1    oranges
3    pears
5    plums
</code>```

My sorting is done by calling setSortKeys() on table 2 to the getSortKeys() of table 1 and vice versa. I can see why it doesn't work, I am telling table 2 to sort by column 2 ascending the same as table 1 but of course these columns have different data in each table. But I can't work out a way to get table 2 to sort to the final order of table 1 instead.

One solution would be for both tables to share the same table model and just show the columns relevant to their table, but that would require a major rework of the code, so I am hoping for a more specific solution just to resolve the sorting issue.

I am using Java 11, and swingx latest version 1.6.4 (i know very old)  but this delegates sorting to standard Java (earlier version that I was previously using had its own sorting) so not really a swingx question.

The real world situation, within my application is as follows, each row represents a song, and the tabs show metadata for that song. the tabs under the edit menu all share same model and all work using the setSortKeys() method described above. So here i have sorted on Mood Aggressive column

Edit metadata tab

and if I go to another tab, we see the rows are sorted in same order

Another Edit metadata tab, sorted same order

but if I go to the Edit ID3 tab, we see the rows have been sorted in different order.

ID3 Edit tab sorted different order

This is because ID3 Edit tab shows the metadata in different format (ID3) and has different table model so column x represent in the model stores different data.

Note because all models store the rowno in first column, sorting my the rowno column works for all tabs.

So from a user point of view they are just viewing different tabs of the same table, and therefore would expect sort to be consistent for the tabs

答:
Have a prototype working.

So using swingx we implement a subclass of TableSortController and override toggleSortOrder() and set this as the rowSorter of the main table

```<code>        public void toggleSortOrder(int column)
        {
            .........
            setSortKeys(newKeys);

            for(int i=0; i < getModelWrapper().getRowCount(); i++)
            {
                SecondTable.instanceOf().getRealModel()
                    .setValueAt(convertRowIndexToView(i), i, ID3TagNames.INDEX_SYNC_SORT);
            }

            newKeys = new ArrayList<>();
            SecondTable.instanceOf().getTable().getRowSorter().setSortKeys(newKeys);

            newKeys.add(new SortKey(ID3TagNames.INDEX_SYNC_SORT, this.getFirstInCycle()));
            SecondTable.instanceOf().getTable().getRowSorter().setSortKeys(newKeys);

        }
</code>```

Logic is does a normal sort on main table, then sets hidden column on second table to store the view index of each row. Then remove any existing sort on second table, then sort by hidden column.

Note the two calls to setSortKey() are needed because if you sort by one column on main table, and then do another sort in both cases will be sorting second table by INDEX_SYNC_SORT ascending and hence the following code in superclass DefaultRowSorter.setSortKeys()
will prevent a sort being done because the sortkey will be the same as previous sort

```<code>        if (!this.sortKeys.equals(old)) {
            fireSortOrderChanged();
            if (viewToModel == null) {
                // Currently unsorted, use sort so that internal fields
                // are correctly set.
                sort();
            } else {
                sortExistingData();
            }
        }
</code>```

For now in this prototype we have a default sort controller on the SecondTable as we don't want this to do the special processing as well. But probably want to sort on both and therefore would need the toggleSort() code to check what table they are linked to and act accordingly.

Body:
I have a table with x num of rows, I have a second table with the same number of rows but different columns and metadata, they have different table models. but each row represents the same object (a song).

I want to synchronize row sorting between the two tables so for example if I sort on column 2 of table 1 then rows of the table will be sorted in the same order. But currently, I just have sorted by matching sort keys so sort on the same column (but because different data get different results)

e.g

Starting point

Table 1
1    tom
2    jane
3    fred
4    steve
5    jim

Table 2
1    oranges
2    apples
3    pears
4    lemons
5    plums

If I sort by table 1, column 2 Ascending I want to get

Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
5    plums
3    pears
4    lemons
1    oranges

but I get

Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
4    lemons
1    oranges
3    pears
5    plums

My sorting is done by calling setSortKeys() on table 2 to the getSortKeys() of table 1 and vice versa. I can see why it doesn't work, I am telling table 2 to sort by column 2 ascending the same as table 1 but of course these columns have different data in each table. But I can't work out a way to get table 2 to sort to the final order of table 1 instead.

One solution would be for both tables to share the same table model and just show the columns relevant to their table, but that would require a major rework of the code, so I am hoping for a more specific solution just to resolve the sorting issue.

I am using Java 11, and swingx latest version 1.6.4 (i know very old)  but this delegates sorting to standard Java (earlier version that I was previously using had its own sorting) so not really a swingx question.

The real world situation, within my application is as follows, each row represents a song, and the tabs show metadata for that song. the tabs under the edit menu all share same model and all work using the setSortKeys() method described above. So here i have sorted on Mood Aggressive column

Edit metadata tab

and if I go to another tab, we see the rows are sorted in same order

Another Edit metadata tab, sorted same order

but if I go to the Edit ID3 tab, we see the rows have been sorted in different order.

ID3 Edit tab sorted different order

This is because ID3 Edit tab shows the metadata in different format (ID3) and has different table model so column x represent in the model stores different data.

Note because all models store the rowno in first column, sorting my the rowno column works for all tabs.

So from a user point of view they are just viewing different tabs of the same table, and therefore would expect sort to be consistent for the tabs

Body:
Have a prototype working.

So using swingx we implement a subclass of TableSortController and override toggleSortOrder() and set this as the rowSorter of the main table

        public void toggleSortOrder(int column)
        {
            .........
            setSortKeys(newKeys);

            for(int i=0; i < getModelWrapper().getRowCount(); i++)
            {
                SecondTable.instanceOf().getRealModel()
                    .setValueAt(convertRowIndexToView(i), i, ID3TagNames.INDEX_SYNC_SORT);
            }

            newKeys = new ArrayList<>();
            SecondTable.instanceOf().getTable().getRowSorter().setSortKeys(newKeys);

            newKeys.add(new SortKey(ID3TagNames.INDEX_SYNC_SORT, this.getFirstInCycle()));
            SecondTable.instanceOf().getTable().getRowSorter().setSortKeys(newKeys);

        }

Logic is does a normal sort on main table, then sets hidden column on second table to store the view index of each row. Then remove any existing sort on second table, then sort by hidden column.

Note the two calls to setSortKey() are needed because if you sort by one column on main table, and then do another sort in both cases will be sorting second table by INDEX_SYNC_SORT ascending and hence the following code in superclass DefaultRowSorter.setSortKeys()
will prevent a sort being done because the sortkey will be the same as previous sort

        if (!this.sortKeys.equals(old)) {
            fireSortOrderChanged();
            if (viewToModel == null) {
                // Currently unsorted, use sort so that internal fields
                // are correctly set.
                sort();
            } else {
                sortExistingData();
            }
        }

For now in this prototype we have a default sort controller on the SecondTable as we don't want this to do the special processing as well. But probably want to sort on both and therefore would need the toggleSort() code to check what table they are linked to and act accordingly.


问:
Possible for input/useState not to be set on button click?
Do I need to worry that fetchClassesSearchedByName(searchName); will not have a searchName value? Is it possible my button click is faster than searchName being set?

```<code>// On input
const [searchName, setSearchName] = useState('');

// Text input
<input
    type='text'
    value={searchName}
    onChange={(e) => setSearchName(e.target.value)}
/>

// On button click
const searchNameBtn = (e) => {
        fetchClassesSearchedByName(searchName);
}
</code>```

Thank you

答:
setState is asynchronous, so it is possible if you've got the reflexes of an old west gunslinger.

Your default value is '', though, so I don't think you'll need any error handling as long as fetchClassesSearchedByName can take an empty string.

Body:
Do I need to worry that fetchClassesSearchedByName(searchName); will not have a searchName value? Is it possible my button click is faster than searchName being set?

// On input
const [searchName, setSearchName] = useState('');

// Text input
<input
    type='text'
    value={searchName}
    onChange={(e) => setSearchName(e.target.value)}
/>

// On button click
const searchNameBtn = (e) => {
        fetchClassesSearchedByName(searchName);
}

Thank you


问:
Time-dependent, repeatable pseudo-random number
I need to generate a repeatable pseudo-random number that is dependent on the current time and a server secret. For example, this mechanism should generate a new pseudo-random number every minute. The next minute's random number should not be easily predictable.

Furthermore, I need to solve this in a stateless fashion (e.g., without storing a generated value in a database). It is possible that a server node might be asked to create such a number multiple times within the same minute, and it needs to generate the same number each time. Also, multiple server nodes (with the same server secret) need to generate the same number within a given time frame. The purpose of all this is not related to solving a security problem (e.g. a token generator), so it's not strictly necessary to use cryptographically secure PRNGs.

Linear-congruential PRNGs produce repeatable series of numbers when initialized with the same seed, so I could seed the PRNG with the combination of time and server secret and get the first random number it produces to meet my criteria. However, this type of PRNG typically uses a simple formula of next = (current * multiplier + offset) & mask, and, given a few known times and corresponding random numbers, it seems like it would be not all that hard to figure out the server secret (and then predict all future numbers in advance).

To make this sort of reverse engineering harder, I pull and discard a fixed number (e.g., 1000) of values from the freshly seeded PRNG before I get the "real" random number that I use. My thinking is that reverse-engineering 1000 cycles of next = (current * multiplier + offset) & mask would be significantly more difficult that reverse-engineering just a single cycle.

I am wondering if my thinking here is even correct. Is it true that figuring out a linear-congruential PRNG's seed is more difficult based on the 1000th value after seeding than it is for the first value of a freshly seeded generator? If so, how many iterations are sufficient before it stops increasing the difficulty?

If I'm completely off here, what are some better alternatives that fulfill the above stated criteria (repeatability, statelessness)?

答:
In a way, this is how Time-based one-time passwords (TOTPs) work, so you can use a similar solution.

To get a time value that changes every N seconds, you can use the following formula.

floor(timestamp / N)

Then, you can either turn that into a string or interpret it as bytes. Just pass it to something like HMAC in order to turn it into a pseudo-random value.

HMAC(SecretKey, floor(timestamp / N))

Here's a simple implementation in Python. This should be fairly similar in other languages too.

import hmac
import time

# Duration that each value lasts, in seconds
duration = 60

# Generate randomly instead of using a phrase
secret_key = b"very epic secret key"

timestamp = int(time.time())
timestamp = int(timestamp / duration)
timestamp = timestamp.to_bytes(8, "big")

value = hmac.digest(secret_key, timestamp, "sha256")
print(value.hex())
```
<p>You can also turn the value into an integer, or use it in other ways.</p>
<pre class="lang-py prettyprint-override"><code>value_int = int.from_bytes(value, "big")
</code>```

Body:
In a way, this is how Time-based one-time passwords (TOTPs) work, so you can use a similar solution.

To get a time value that changes every N seconds, you can use the following formula.

floor(timestamp / N)

Then, you can either turn that into a string or interpret it as bytes. Just pass it to something like HMAC in order to turn it into a pseudo-random value.

HMAC(SecretKey, floor(timestamp / N))

Here's a simple implementation in Python. This should be fairly similar in other languages too.

import hmac
import time

# Duration that each value lasts, in seconds
duration = 60

# Generate randomly instead of using a phrase
secret_key = b"very epic secret key"

timestamp = int(time.time())
timestamp = int(timestamp / duration)
timestamp = timestamp.to_bytes(8, "big")

value = hmac.digest(secret_key, timestamp, "sha256")
print(value.hex())

You can also turn the value into an integer, or use it in other ways.

value_int = int.from_bytes(value, "big")


问:
Selecting a count into a variable in oracle
Hi I have been trying this today and haven't had any luck. this stored procedure does not work :(</p>

```<code>CREATE OR REPLACE PROCEDURE LEAD_PURGE(closed IN DATE,
oprtr IN INTEGER,
leadscount OUT INTEGER)

is
BEGIN

SELECT COUNT(*) FROM LEADS_DELETED INTO leadscount;

COMMIT;
END LEAD_PURGE;
</code>```

答:
The INTO clause is misplaced.  It should be:</p>

```<code>SELECT COUNT(*) INTO leadscount FROM LEADS_DELETED
</code>```

Body:
Hi I have been trying this today and haven't had any luck. this stored procedure does not work :(

CREATE OR REPLACE PROCEDURE LEAD_PURGE(closed IN DATE,
oprtr IN INTEGER,
leadscount OUT INTEGER)

is
BEGIN

SELECT COUNT(*) FROM LEADS_DELETED INTO leadscount;

COMMIT;
END LEAD_PURGE;

Body:
The INTO clause is misplaced.  It should be:

SELECT COUNT(*) INTO leadscount FROM LEADS_DELETED


问:
Remove or modify navigation drawer overlay shadow in Flutter
I created a Scaffold widget with appBar and drawer.

As I open the drawer, there is a shadow over the Scaffold's body widget. I'd like to either remove the shadow, make it not so "strong" or change the shade slightly.

I checked the docs and I didn't find any way to achieve this through public API.

Is there any way to remove the drawer menu's "drop shadow" on the body?

The elevation option is something different, even if I set it to 0, the overlay shadow on top of the body is still present.

This issue's description's screenshots might help clarify what I want.

答:
check this</p>
```<code>drawerTheme:
          DrawerThemeData(scrimColor: Colors.transparent, elevation: 0.5),
</code>```

Body:
check this

drawerTheme:
          DrawerThemeData(scrimColor: Colors.transparent, elevation: 0.5),


问:
For my df, I'm looking to find how many women senators have a YouTube account and then create a new df with those woman w/ a YouTube account
Here is my code w/ the dataset

```<code>function1 <- function(){
    dataset <- url("https://intro-datascience.s3.us-east-2.amazonaws.com/role.json")
    readlines <- jsonlite::fromJSON(dataset)
    newDf <- readlines$objects$person
    finalDf <- cbind(newDf, age = df$age)
    return(finalDf)
    }
</code>```

So far I created a function to tell me how many woman senators have YouTube accounts by subtracting 76 from the total number of male senators:

```<code>woman <- function(){
    a1 <- length(grep("female", df$gender))
    a2 <- length(grep("", df$youtubeid))-76
    return(sum(a1 + a2))
}
</code>```

But for creating the new df is where I am stuck with those woman w/ a YouTube account..

答:
Considering df is a dataframe generated from function1. Here is an alternative within tidyverse

Package

```<code>library(dplyr)
</code>```

Solution

Womens with youtubeid

Select only gender == "female", and cases in which youtubeid is not missing NA. To do that, I used filter() from dplyr. So we are filtering all rows that the statement is TRUE. In other words, if a row has gender as "female" and has no missing for "youtubeid" then I'm keeping that row. If not, I'm dropping that row. This way, in the final dataset, I only have females with youtubeid.

```<code>women_df <- df %>%
  filter(!is.na(youtubeid),
         gender == "female")
</code>```

How many women with youtube id?

```<code>women_df %>%
  nrow()
</code>```

output

```<code>[1] 16
</code>```

ps: I'm not sure why you are creating functions, but if you need a function for this, just wrap everything around a function (remember to include dplyr within the function if you want to send this to other people).

Body:
Here is my code w/ the dataset

function1 <- function(){
    dataset <- url("https://intro-datascience.s3.us-east-2.amazonaws.com/role.json")
    readlines <- jsonlite::fromJSON(dataset)
    newDf <- readlines$objects$person
    finalDf <- cbind(newDf, age = df$age)
    return(finalDf)
    }

So far I created a function to tell me how many woman senators have YouTube accounts by subtracting 76 from the total number of male senators:

woman <- function(){
    a1 <- length(grep("female", df$gender))
    a2 <- length(grep("", df$youtubeid))-76
    return(sum(a1 + a2))
}

But for creating the new df is where I am stuck with those woman w/ a YouTube account..

Body:
Considering df is a dataframe generated from function1. Here is an alternative within tidyverse

Package

library(dplyr)

Solution

Womens with youtubeid

Select only gender == "female", and cases in which youtubeid is not missing NA. To do that, I used filter() from dplyr. So we are filtering all rows that the statement is TRUE. In other words, if a row has gender as "female" and has no missing for "youtubeid" then I'm keeping that row. If not, I'm dropping that row. This way, in the final dataset, I only have females with youtubeid.

women_df <- df %>%
  filter(!is.na(youtubeid),
         gender == "female")

How many women with youtube id?

women_df %>%
  nrow()

output

[1] 16

ps: I'm not sure why you are creating functions, but if you need a function for this, just wrap everything around a function (remember to include dplyr within the function if you want to send this to other people).


问:
Postgres date value dynamic inserting
I am scratching my head trying to fix the following:

```<code>create or replace procedure my_schema.Test()
as $$

declare
    today date = now();

begin
    drop table if exists my_schema.tst_table;
    create table  my_schema.tst_table (
        todays_date varchar     );

    execute('
        insert into my_schema.tst_table
        values (' || today || ')
    ');

end;
$$
language plpgsql;
</code>```

Basically I am trying to dynamically insert the current date into a table which will be used in later steps.

The issue I am facing is that due to the today variable looking like '2022-02-11',  and because I am inserting the record dynamically, postgres is interpreting the "-" as a minus sign and inserting the value 2009 into my table.

Does anyone have a workaround for this?

答:
You can use the cast operator to force the value conversion to VARCHAR datatype:

```<code>execute('
    insert into my_schema.tst_table
    values ('today'::VARCHAR)
');
</code>```

Title: Postgres date value dynamic inserting

Body:
I am scratching my head trying to fix the following:

create or replace procedure my_schema.Test()
as $$

declare
    today date = now();

begin
    drop table if exists my_schema.tst_table;
    create table  my_schema.tst_table (
        todays_date varchar     );

    execute('
        insert into my_schema.tst_table
        values (' || today || ')
    ');

end;
$$
language plpgsql;

Basically I am trying to dynamically insert the current date into a table which will be used in later steps.

The issue I am facing is that due to the today variable looking like '2022-02-11',  and because I am inserting the record dynamically, postgres is interpreting the "-" as a minus sign and inserting the value 2009 into my table.

Does anyone have a workaround for this?

Body:
You can use the cast operator to force the value conversion to VARCHAR datatype:

execute('
    insert into my_schema.tst_table
    values ('today'::VARCHAR)
');


问:
Take differences between dates within id over a sequence (different rows) in R
I would like - for each id (cpf) - to take the differences, in months, between hire_date  and sep_date on the previous row. For example, I would like to take the difference between hire_date associated with Order 1 and sep_date associated with order 2 (and the same for ids with more than two Order values).

Not all observations have just two order values. Some may have significantly more. How can I write a code that accounts for that? In this case there are more than two rows for a id. So I would also need to make more than one difference.

I would always like to take a difference between a given hire_date (e.g. order 2) and the previous sep_Date (order 1) and so forth. For more than two rows: hire_date (order 3) - sep_date (order 2); hire_date (order 2) - sep_date (order 1)...

```<code>structure(list(cpf = c(234L, 234L, 245L, 245L, 245L, 555L, 555L
), hire_date = c("10-11-29", "13-7-29", "11-10-19", "13-3-20",
"13-5-20", "10-02-18", "13-11-21"), sep_date = c("13-4-18", "13-8-29",
"13-2-15", "13-4-20", NA, "13-10-20", NA), Order = c(1L, 2L,
1L, 2L, 3L, 1L, 2L)), class = "data.frame", row.names = c(NA,
-7L))

  cpf hire_date sep_date Order
1 234  10-11-29  13-4-18     1
2 234   13-7-29  13-8-29     2
3 245  11-10-19  13-2-15     1
4 245   13-3-20  13-4-20     2
5 245   13-5-20     <NA>     3
6 555  10-02-18 13-10-20     1
7 555  13-11-21     <NA>     2
</code>```

Any help would be appreciated!

答:
We can convert the date columns to Date class and do a group by difftime

```<code>library(dplyr)
library(lubridate)
df1 %>%
  mutate(across(hire_date:sep_date, dmy)) %>%
  group_by(cpf) %>%
  mutate(Month = as.numeric(difftime(hire_date,
     lag(sep_date), unit = "weeks"))/4) %>%
  ungroup
</code>```

Body:
I would like - for each id (cpf) - to take the differences, in months, between hire_date  and sep_date on the previous row. For example, I would like to take the difference between hire_date associated with Order 1 and sep_date associated with order 2 (and the same for ids with more than two Order values).

Not all observations have just two order values. Some may have significantly more. How can I write a code that accounts for that? In this case there are more than two rows for a id. So I would also need to make more than one difference.

I would always like to take a difference between a given hire_date (e.g. order 2) and the previous sep_Date (order 1) and so forth. For more than two rows: hire_date (order 3) - sep_date (order 2); hire_date (order 2) - sep_date (order 1)...

structure(list(cpf = c(234L, 234L, 245L, 245L, 245L, 555L, 555L
), hire_date = c("10-11-29", "13-7-29", "11-10-19", "13-3-20",
"13-5-20", "10-02-18", "13-11-21"), sep_date = c("13-4-18", "13-8-29",
"13-2-15", "13-4-20", NA, "13-10-20", NA), Order = c(1L, 2L,
1L, 2L, 3L, 1L, 2L)), class = "data.frame", row.names = c(NA,
-7L))

  cpf hire_date sep_date Order
1 234  10-11-29  13-4-18     1
2 234   13-7-29  13-8-29     2
3 245  11-10-19  13-2-15     1
4 245   13-3-20  13-4-20     2
5 245   13-5-20     <NA>     3
6 555  10-02-18 13-10-20     1
7 555  13-11-21     <NA>     2

Any help would be appreciated!

Body:
We can convert the date columns to Date class and do a group by difftime

library(dplyr)
library(lubridate)
df1 %>%
  mutate(across(hire_date:sep_date, dmy)) %>%
  group_by(cpf) %>%
  mutate(Month = as.numeric(difftime(hire_date,
     lag(sep_date), unit = "weeks"))/4) %>%
  ungroup


问:
Getting error parsing List in map with Poison in elixir
I am trying to parse an api query but I get an error in the following code:

```<code>apiUrl = "https://api.trivia.willfry.co.uk/questions?limit=1"
HTTPoison.start()
{:ok, req} = HTTPoison.get(apiUrl)

# Parses the request.
json = Poison.decode!(req.body)
parsed = Map.fetch!(json, :root)
</code>```

The error says:

```<code>(BadMapError) expected a map, got: [%{"category" => "Film and TV", "correctAnswer" => "\"A martini. Shaken, not stirred.\"", "id" => 29312, "incorrectAnswers" => ["\"Elementary, my dear Watson.\"", "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"", "\"Go ahead, make my day.\"", "\"I am a golden god!\"", "\"Toga! Toga!\"", "\"We rob banks.\"", "\"E.T. phone home.\"", "\"Here's Johnny!\"", "\"Made it, Ma! Top of the world!\"", "\"I have always depended on the kindness of strangers.\""], "question" => "Which of these quotes is from the film 'Goldfinger'?", "type" => "Multiple Choice"}]
:erlang.map_get(:root, [%{"category" => "Film and TV", "correctAnswer" => "\"A martini. Shaken, not stirred.\"", "id" => 29312, "incorrectAnswers" => ["\"Elementary, my dear Watson.\"", "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"", "\"Go ahead, make my day.\"", "\"I am a golden god!\"", "\"Toga! Toga!\"", "\"We rob banks.\"", "\"E.T. phone home.\"", "\"Here's Johnny!\"", "\"Made it, Ma! Top of the world!\"", "\"I have always depended on the kindness of strangers.\""], "question" => "Which of these quotes is from the film 'Goldfinger'?", "type" => "Multiple Choice"}])
(triv 0.1.0) lib/mix/tasks/request.ex:15: Mix.Tasks.Request.run/1
(mix 1.13.3) lib/mix/task.ex:397: anonymous fn/3 in Mix.Task.run_task/3
(mix 1.13.3) lib/mix/cli.ex:84: Mix.CLI.run_task/2
</code>```

I am running this code from a module which implements the Mix.Task behaviour.

答:
Your parsed JSON appears to be a list, not a map:

```<code>[
  %{
    "category" => "Film and TV",
    "correctAnswer" => "\"A martini. Shaken, not stirred.\"",
    "id" => 29312,
    "incorrectAnswers" => ["\"Elementary, my dear Watson.\"",
     "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"",
     "\"Go ahead, make my day.\"", "\"I am a golden god!\"", "\"Toga! Toga!\"",
     "\"We rob banks.\"", "\"E.T. phone home.\"", "\"Here's Johnny!\"",
     "\"Made it, Ma! Top of the world!\"",
     "\"I have always depended on the kindness of strangers.\""],
    "question" => "Which of these quotes is from the film 'Goldfinger'?",
    "type" => "Multiple Choice"
  }
]
</code>```

When you try calling Map.fetch!/2 on it, you're getting an exception because it's a list, not a map.

Body:
I am trying to parse an api query but I get an error in the following code:

apiUrl = "https://api.trivia.willfry.co.uk/questions?limit=1"
HTTPoison.start()
{:ok, req} = HTTPoison.get(apiUrl)

# Parses the request.
json = Poison.decode!(req.body)
parsed = Map.fetch!(json, :root)

The error says:

(BadMapError) expected a map, got: [%{"category" => "Film and TV", "correctAnswer" => "\"A martini. Shaken, not stirred.\"", "id" => 29312, "incorrectAnswers" => ["\"Elementary, my dear Watson.\"", "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"", "\"Go ahead, make my day.\"", "\"I am a golden god!\"", "\"Toga! Toga!\"", "\"We rob banks.\"", "\"E.T. phone home.\"", "\"Here's Johnny!\"", "\"Made it, Ma! Top of the world!\"", "\"I have always depended on the kindness of strangers.\""], "question" => "Which of these quotes is from the film 'Goldfinger'?", "type" => "Multiple Choice"}]
:erlang.map_get(:root, [%{"category" => "Film and TV", "correctAnswer" => "\"A martini. Shaken, not stirred.\"", "id" => 29312, "incorrectAnswers" => ["\"Elementary, my dear Watson.\"", "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"", "\"Go ahead, make my day.\"", "\"I am a golden god!\"", "\"Toga! Toga!\"", "\"We rob banks.\"", "\"E.T. phone home.\"", "\"Here's Johnny!\"", "\"Made it, Ma! Top of the world!\"", "\"I have always depended on the kindness of strangers.\""], "question" => "Which of these quotes is from the film 'Goldfinger'?", "type" => "Multiple Choice"}])
(triv 0.1.0) lib/mix/tasks/request.ex:15: Mix.Tasks.Request.run/1
(mix 1.13.3) lib/mix/task.ex:397: anonymous fn/3 in Mix.Task.run_task/3
(mix 1.13.3) lib/mix/cli.ex:84: Mix.CLI.run_task/2

I am running this code from a module which implements the Mix.Task behaviour.

Body:
Your parsed JSON appears to be a list, not a map:

[
  %{
    "category" => "Film and TV",
    "correctAnswer" => "\"A martini. Shaken, not stirred.\"",
    "id" => 29312,
    "incorrectAnswers" => ["\"Elementary, my dear Watson.\"",
     "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"",
     "\"Go ahead, make my day.\"", "\"I am a golden god!\"", "\"Toga! Toga!\"",
     "\"We rob banks.\"", "\"E.T. phone home.\"", "\"Here's Johnny!\"",
     "\"Made it, Ma! Top of the world!\"",
     "\"I have always depended on the kindness of strangers.\""],
    "question" => "Which of these quotes is from the film 'Goldfinger'?",
    "type" => "Multiple Choice"
  }
]

When you try calling Map.fetch!/2 on it, you're getting an exception because it's a list, not a map.


问:
How to create a splash screen for a Wear OS 3 app similar to the "big" apps?
I am searching for a possibility to make my Wear OS 3 app have a simple splash screen. I cannot find anything specific, but I read that Android 12 introduced an automatic splash screen for every app. Don't know if that applies to Wear OS 3 though.

I can see multiple Apps (e.g. Spotify and Strava) on my Galaxy Watch 4 starting with a similar splash screen: On click on the app icon in the "app drawer", the icon moves from the app drawer position to the center for 1-2 seconds while a black background appears. After that the app is shown. My guess would be those splash screens are generated by Android. But my app only shows a black screen until the app first draws. I artificially delayed the startup of my app via Thread.sleep in my OnCreate. (If that is a problem, please tell me how to artificially create a delay to test the splash screen)

If not clear already: I would like to have the same kind of splash screen as the others for my app.

Help is much appreciated! Thank you in advance for any suggestions

答:
Thanks @user3697030, great answer but I tweaked slightly the splash_background.xml, since you had a transparent background.

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/black"/>
        </shape>
    </item>
    <item
        android:width="@dimen/launch_icon_size"
        android:height="@dimen/launch_icon_size"
        android:gravity="center">
        <bitmap
            android:src="@drawable/ic_launcher_round"
            android:gravity="fill_horizontal|fill_vertical"/>
    </item>
</layer-list>
</code>```

Body:
Thanks @user3697030, great answer but I tweaked slightly the splash_background.xml, since you had a transparent background.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/black"/>
        </shape>
    </item>
    <item
        android:width="@dimen/launch_icon_size"
        android:height="@dimen/launch_icon_size"
        android:gravity="center">
        <bitmap
            android:src="@drawable/ic_launcher_round"
            android:gravity="fill_horizontal|fill_vertical"/>
    </item>
</layer-list>


问:
Positioning of bootstrap modal in blazor page
i am fairly new in web coding word so i ask sorry if there are some obvious error i am unaware of. I was challenging myself on using a modal inside a toy project i was working on, but i'm having some trouble

As you can see, my modal is not modal at all. It just appear under the grid.

```<code>@page "/"

<PageTitle>Index</PageTitle>

<div>
    <div>
        <h1 id="impListH">TestApp</h1> <button id="impListB" class="btn btn-primary" @onclick="@(() => { showModal = true; })" >Importa</button>
    </div>
    <br />
    <br />
    <DataGrid TItem="Employee" MySource="employees" Columns="columnDefinitions"></DataGrid>
</div>

@if (showModal)
{
    <div class="modal-dialog" tabindex="-1" role="dialog" style="display: initial;" id="myModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Omnes enim iucundum motum, quo sensus hilaretur.
                        <i>Quis istud possit, inquit, negare?</i>
                        <mark>Ego vero isti, inquam, permitto.</mark> Duo Reges: constructio interrete.
                    </p>
                    <FetchData />
                    <dl>
                        <dt><dfn>Stoici scilicet.</dfn></dt>
                        <dd>An hoc usque quaque, aliter in vita?</dd>
                        <dt><dfn>Erat enim Polemonis.</dfn></dt>
                        <dd>Quod cum accidisset ut alter alterum necopinato videremus, surrexit statim.</dd>
                    </dl>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary">Save changes</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
}
</code>```

i followed this answer to build the model. I really don't understand what is wrong. Can you help me?

答:
Wrap you div.modal-dialog with
 also I think that you have a double of div.modal-dialog

Body:
i am fairly new in web coding word so i ask sorry if there are some obvious error i am unaware of. I was challenging myself on using a modal inside a toy project i was working on, but i'm having some trouble

As you can see, my modal is not modal at all. It just appear under the grid.

@page "/"

<PageTitle>Index</PageTitle>

TestApp
 <button id="impListB" class="btn btn-primary" @onclick="@(() => { showModal = true; })" >Importa</button>

    <DataGrid TItem="Employee" MySource="employees" Columns="columnDefinitions"></DataGrid>

@if (showModal)
{

Modal title

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Omnes enim iucundum motum, quo sensus hilaretur.
                        Quis istud possit, inquit, negare?
                        Ego vero isti, inquam, permitto. Duo Reges: constructio interrete.

                    <FetchData />

<dfn>Stoici scilicet.</dfn>

An hoc usque quaque, aliter in vita?

<dfn>Erat enim Polemonis.</dfn>

Quod cum accidisset ut alter alterum necopinato videremus, surrexit statim.

                    <button type="button" class="btn btn-primary">Save changes</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

}

i followed this answer to build the model. I really don't understand what is wrong. Can you help me?

Body: Wrap you div.modal-dialog with <div class="modal" tabindex="-1"> also I think that you have a double of div.modal-dialog


问:
LightFace and showing busy image
i want that when LightFace will be shown then a busy image should come and display at the center of the modal box. i found there is no way to show LightFace with busy image programatically when content will be loading in the background. so i used a trick but did not work. in my case busy image shows in the dialog but not at center position.

here is my code

here i define a style sheet for my div

```<code>.BusyStyles
</code>```

{
            background-image: url('images/fbloader.gif');
            background-repeat: no-repeat; background-position: center center;
            height: 200;
            width: 300;
}

my JavaScript is

```<code>    <script language="javascript" type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function () {
        jQuery("#btnFeedback1").click(function () {
            var modal = new LightFace({
                draggable: true,
                height: 200,
                width: 300,
                title: 'My Profile',
                content: '<div css="BusyStyles"><div>',
                buttons: [
                { title: 'OK', event: function () { this.close(); } },
                { title: 'Close', event: function () { this.close(); } }
            ]
            });

            modal.open();
            modal.load('here i will load my ajax content calling pagemethod');
            return false;
        });
    });
</code>```

so what i have done that when i am showing LightFace modal dialog then a div is assigned as default content which has stylesheet. the style sheet has fixed height and width and as background image. i was trying to show the image at the center but image is not showing at the center instead image is showing at left top position.

so please guide me that how can show busy image at the center of the dialog.

basically i want that when i will call server side function by jquery then my dialog should show with busy image and when content will be available then i will show that content.
i am using asp.net and calling page method by jquery.

please guide me. thanks.

答:
Its

```<code><div class="BusyStyles"><div>
</code>```

and not

```<code><div css="BusyStyles"><div>
</code>```

Maybe this fixes your background issue...

Title: LightFace and showing busy image

Body:
i want that when LightFace will be shown then a busy image should come and display at the center of the modal box. i found there is no way to show LightFace with busy image programatically when content will be loading in the background. so i used a trick but did not work. in my case busy image shows in the dialog but not at center position.

here is my code

here i define a style sheet for my div

.BusyStyles

{
            background-image: url('images/fbloader.gif');
            background-repeat: no-repeat; background-position: center center;
            height: 200;
            width: 300;
}

my JavaScript is

Body:
Its

<div class="BusyStyles"><div>

and not

<div css="BusyStyles"><div>

Maybe this fixes your background issue...


问:
Intellij doesn't recognize angular modules, html elements, pipes, and so on
I'm having a problem getting angular language support running with a project that uses webpack (not sure if that's important, but without webpack everything works fine in intellij), and which is a multi module project consisting of java and an angular app.

The problem is that none of angular's modules are recognized

Says RouterModule is not an angular module.

No directive is matched for *ngFor and unresolved pipe async.

Though MatAutocompleteModule is correctly imported.

I've imported BrowserModule, CommonModule, and the project works perfectly fine. It's just intellij's detection that doesn't work.

I've installed @angular/language-service via npm. I've restarted the IDE (so many times).

What can I do to get this working?

dependencies (angular)

```<code>"@angular/animations": "~7.2.14",
"@angular/cdk": "~7.3.7",
"@angular/common": "~7.2.14",
"@angular/compiler": "~7.2.14",
"@angular/core": "~7.2.14",
"@angular/forms": "~7.2.14",
"@angular/material": "^7.3.7",
"@angular/platform-browser": "~7.2.14",
"@angular/platform-browser-dynamic": "~7.2.14",
"@angular/router": "~7.2.14",
</code>```

devDependencies (angular related)

```<code>"@angular-devkit/build-angular": "~0.13.0",
"@angular-devkit/build-ng-packagr": "~0.13.0",
"@angular/cli": "7.3.4",
"@angular/compiler-cli": "7.2.14",
"@ngtools/webpack": "7.3.4",
"@angular/language-service": "^7.2.14",
"angular-router-loader": "0.8.5",
"angular2-template-loader": "0.6.2",
"typescript": "3.2.4",
</code>```

答:
I ran into this issue while running IntelliJ IDEA version 2019.3.  I apparently needed to swap JetBrains accounts (from my old work account which was expired to my personal account which had an active license).  I downloaded the latest version which is 2021.3.2 and my issue is now resolved.

I believe that updating the latest Angular CLI (13.2.0) is what broke things.

Body:
I'm having a problem getting angular language support running with a project that uses webpack (not sure if that's important, but without webpack everything works fine in intellij), and which is a multi module project consisting of java and an angular app.

The problem is that none of angular's modules are recognized

Says RouterModule is not an angular module.

No directive is matched for *ngFor and unresolved pipe async.

Though MatAutocompleteModule is correctly imported.

I've imported BrowserModule, CommonModule, and the project works perfectly fine. It's just intellij's detection that doesn't work.

I've installed @angular/language-service via npm. I've restarted the IDE (so many times).

What can I do to get this working?

dependencies (angular)

"@angular/animations": "~7.2.14",
"@angular/cdk": "~7.3.7",
"@angular/common": "~7.2.14",
"@angular/compiler": "~7.2.14",
"@angular/core": "~7.2.14",
"@angular/forms": "~7.2.14",
"@angular/material": "^7.3.7",
"@angular/platform-browser": "~7.2.14",
"@angular/platform-browser-dynamic": "~7.2.14",
"@angular/router": "~7.2.14",

devDependencies (angular related)

"@angular-devkit/build-angular": "~0.13.0",
"@angular-devkit/build-ng-packagr": "~0.13.0",
"@angular/cli": "7.3.4",
"@angular/compiler-cli": "7.2.14",
"@ngtools/webpack": "7.3.4",
"@angular/language-service": "^7.2.14",
"angular-router-loader": "0.8.5",
"angular2-template-loader": "0.6.2",
"typescript": "3.2.4",


问:
Cannot download from terminal with curl -O
I try to download the something-something dataset onto a server with the command line. It is split into multiple parts, the small introduction file is for example downloaded here:

I tried to download this file with the following command:

curl -O https://developer.qualcomm.com/downloads/20bn-something-something-download-instructions?referrer=node/68935,

but the downloaded file is a small, corrupted file. I also tried to download the file with the addition of my username:

curl -O https://developer.qualcomm.com/downloads/20bn-something-something-download-instructions?referrer=node/68935 -u username:password,

but the outcome is the same. I also tried wget, but it doesn't work either.

Can anyone tell me what I am doing wrong here?

Thank you very much.

答: The solution to the problem is to use the Chrome extension Get cookies.txt to create a file for the cookies. Then you can use wget --load-cookies=cookies.txt <address> and it works fine.


问:
How can resolve **Uncaught Reference Error: io is not defined at client.js:1:16** error?
I am trying to create a real time chat app project using node and socket but when I try to run this using nodemon then it gives me error like

```<code>Uncaught ReferenceError: io is not defined
    at client.js:1:16
</code>```

and

```<code>GET http://localhost:3000/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)
</code>```

plz help me to get out from this frustration.
here are respective code:-

```<code>const express=require("express");

const http=require("http");

const app=express();

const server=http.createServer(app);

const io=require("socket.io")(server)

app.get("/",function (req,res) {
    res.sendFile(__dirname+"/index.html");
})

app.use(express.static(__dirname+"/public"))

io.on("connection",(socket)=> {
    console.log('Connected');

})

app.listen(process.env.PORT || 3000,function(){
    console.log('Running....');
})
</code>```

code at client.js:-

```<code>const socket = io()
let name;
let textarea=document.querySelector("#textarea");
let msgArea=document.querySelector(".mssg_area");
do{
    name = prompt("what do your friends call you?");
}while(!name);

textarea.addEventListener("keyup",function (e) {
    if(e.key==="Enter"){
        sendMessage(e.target.value);
    }
})

function sendMessage(message) {
    let msg={
        user:name,
        message:message
    }
    appendMessage(msg,"outgoing")
}

function appendMessage(msg,type) {
    let mainDiv=document.createElement("div")
    let className=type
    mainDiv.classList.add(className,"message")

    let markUp=`
    <h4>${msg.user}</h4>
    <p>${msg.message}</p>
    `
    mainDiv.innerHTML=markUp
    msgArea.appendChild(mainDiv)
}
</code>```

It would be very helpful to me if you resolve this issue. Thank you in advance!!

答:
on the client side you should install socket.io-client not socket.io

Client Api

Body:
I am trying to create a real time chat app project using node and socket but when I try to run this using nodemon then it gives me error like

Uncaught ReferenceError: io is not defined
    at client.js:1:16

and

GET http://localhost:3000/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)

plz help me to get out from this frustration.
here are respective code:-

const express=require("express");

const http=require("http");

const app=express();

const server=http.createServer(app);

const io=require("socket.io")(server)

app.get("/",function (req,res) {
    res.sendFile(__dirname+"/index.html");
})

app.use(express.static(__dirname+"/public"))

io.on("connection",(socket)=> {
    console.log('Connected');

})

app.listen(process.env.PORT || 3000,function(){
    console.log('Running....');
})

code at client.js:-

const socket = io()
let name;
let textarea=document.querySelector("#textarea");
let msgArea=document.querySelector(".mssg_area");
do{
    name = prompt("what do your friends call you?");
}while(!name);

textarea.addEventListener("keyup",function (e) {
    if(e.key==="Enter"){
        sendMessage(e.target.value);
    }
})

function sendMessage(message) {
    let msg={
        user:name,
        message:message
    }
    appendMessage(msg,"outgoing")
}

function appendMessage(msg,type) {
    let mainDiv=document.createElement("div")
    let className=type
    mainDiv.classList.add(className,"message")

    let markUp=`

${msg.user}

${msg.message}

    `
    mainDiv.innerHTML=markUp
    msgArea.appendChild(mainDiv)
}

It would be very helpful to me if you resolve this issue. Thank you in advance!!


问:
Wrong date format on iOS in Ionic5 hybrid app (Appery.io platform)
I did not try that but I got it working now in xcode simulator.
This function below works fine in Android but not in iPhone (Tracking-page):

const MyDate = new Date(timestamp + " UTC");
this.itemTimestamp = MyDate .toLocaleString();

In iPhone it gives INVALID DATE error.

I see the specification here: https://www.elliotjreed.com/blog/2019-03-20/invalid-date-format-in-javascript-on-ios-devices

But Appery says:
"The Date type value is a string which contains a UTC timestamp stored in ISO 8601 format with millisecond precision: YYYY-MM-DDThh:mm:ss.mmm."(https://docs.appery.io/reference/database-api-data-types#date)
I don't know if this is the issue in the platform or in the code of mine..
So what is the correct format for that platform with or w/o "Z" at the end?

答:
iOS supports the ISO format only, like '2022-02-10T21:26:11.119Z'

Z is the time zone offset specified as “Z” (for UTC) or either

More details you can find here: https://262.ecma-international.org/5.1/#sec-15.9.1.15

So in the case, if you don't set the timezone the UTC will be selected automatically ("Z")

It is better to set the timezone every time to avoid issues with the wrong timezone