问:
How to fail a spring job if exception is thrown?
I have a spring batch job which converts tsv file to json. I have specified the following listener which checks for exit code:

```<code>import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;

public class StepResultListener implements StepExecutionListener {
    @Override
    public void beforeStep(StepExecution stepExecution) {
        System.out.println("Called beforeStep().");
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        System.out.println("Called afterStep().");
        String exitCode = stepExecution.getExitStatus().getExitCode();
        if (exitCode.equals("FAILED")){
            return ExitStatus.FAILED;
        }
        return ExitStatus.COMPLETED;
    }
}
</code>```

I want to fail the the whole job if the step fails:

```<code>@Bean
    public Step stepOne(ObjectMapper mapper, IdProvider webIdProvider) {
        return stepBuilderFactory.get("stepOne")
                .<WebTaxonomy, WebTaxonomy> chunk(10)
                .reader(readerWeb())
                .processor(processorWeb(mapper, webIdProvider))
                .writer(writerWeb(mapper))
                .listener(new StepResultListener())
                .build();
    }
</code>```

However it still proceeds to complete the job. Any ideas how I can achieve this ?

this is my batch configuration:

```<code>@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

    private static final String OUTPUT_DATA_JSON = "target/web_taxonomy.json";
    private static final String OUTPUT_DATA_APP_JSON = "target/app_taxonomy.json";

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private JobExplorer jobExplorer;

    @Autowired
    private JobRepository jobRepository;

    @Bean
    public FlatFileItemReader<WebTaxonomy> readerWeb() {
        return new FlatFileItemReaderBuilder<WebTaxonomy>()
                .name("webTaxonomyItemReader")
                .resource(new ClassPathResource("/web_taxonomy.tsv"))
                .linesToSkip(1)
                .lineMapper(lineMapperWeb()).build();

    }

    @Bean
    public DefaultLineMapper<WebTaxonomy> lineMapperWeb() {
        DefaultLineMapper<WebTaxonomy> lineMapper = new DefaultLineMapper<>();
        lineMapper.setLineTokenizer(lineTokenizerWeb());
        lineMapper.setFieldSetMapper(new BeanWrapperFieldSetMapper<WebTaxonomy>() {
            {
                setTargetType(WebTaxonomy.class);
            }
        });
        return lineMapper;
    }

    @Bean
    public DelimitedLineTokenizer lineTokenizerWeb() {
        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(DelimitedLineTokenizer.DELIMITER_TAB);
        tokenizer.setNames("taxonomy_id", "website_name", "brand_name", "publisher", "category", "category_2",
                "category_3", "category_4", "category_5", "curated", "blacklist", "brand_1", "brand_2", "brand_3",
                "brand_4", "brand_5", "brand_6", "regex", "host", "source", "creation_date");
        return tokenizer;
    }

    @Autowired
    @Qualifier("webIdProvider")
    @Bean
    public WebTaxonomyItemProcessor processorWeb(ObjectMapper mapper, IdProvider webIdProvider) {
        Map<String, Long> webMapping = getMapping(mapper, "src/main/resources/web_taxonomy.json", "taxonomy_id", "website_name");
        Long maxID = Collections.max(webMapping.values());
        webIdProvider.setID(maxID);
        return new WebTaxonomyItemProcessor(webMapping, webIdProvider);
    }

    @Bean
    public Step stepOne(ObjectMapper mapper, IdProvider webIdProvider) {
        return stepBuilderFactory.get("stepOne")
                .<WebTaxonomy, WebTaxonomy> chunk(10)
                .reader(readerWeb())
                .processor(processorWeb(mapper, webIdProvider))
                .writer(writerWeb(mapper))
                .listener(new StepResultListener())
                .build();
    }

    @Autowired
    @Bean
    public FlatFileItemWriter<WebTaxonomy> writerWeb(ObjectMapper mapper) {
        return new FlatFileItemWriterBuilder<WebTaxonomy>()
                .name("WebTaxonomyJsonFileItemWriter")
                .resource(new FileSystemResource(OUTPUT_DATA_JSON))
                .lineAggregator(new JsonLineAggregator<>(mapper))
                .build();

    }

    @Bean
    public Job updateWebTaxonomy(ObjectMapper mapper, IdProvider webIdProvider) {
        return jobBuilderFactory.get("updateWebTaxonomy")
                .incrementer(new RunIdIncrementer())
                .start(stepOne(mapper, webIdProvider))
                .build();
    }

    // App job

    @Bean
    public FlatFileItemReader<AppTaxonomy> readerApp() {
        return new FlatFileItemReaderBuilder<AppTaxonomy>()
                .name("appTaxonomyItemReader")
                .resource(new ClassPathResource("/app_taxonomy.tsv"))
                .linesToSkip(1)
                .lineMapper(lineMapperApp()).build();

    }

    @Bean
    public DefaultLineMapper<AppTaxonomy> lineMapperApp() {
        DefaultLineMapper<AppTaxonomy> lineMapper = new DefaultLineMapper<>();
        lineMapper.setLineTokenizer(lineTokenizerApp());
        lineMapper.setFieldSetMapper(new BeanWrapperFieldSetMapper<AppTaxonomy>() {
            {
                setTargetType(AppTaxonomy.class);
            }
        });
        return lineMapper;
    }

    @Bean
    public DelimitedLineTokenizer lineTokenizerApp() {
        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(DelimitedLineTokenizer.DELIMITER_TAB);
        tokenizer.setNames("taxonomy_id", "app_name", "app_store", "app_package_name", "brand_name",
                "publisher", "category", "category_2", "category_3", "category_4", "category_5", "blacklist", "brand_1",
                "brand_2", "brand_3", "brand_4", "brand_5", "brand_6", "platform", "source", "creation_date");
        return tokenizer;
    }

    @Autowired
    @Qualifier("appIdProvider")
    @Bean
    public AppTaxonomyItemProcessor processorApp(ObjectMapper mapper, IdProvider appIDProvider) {
        Map<String, Long> appMapping = getMapping(mapper,"src/main/resources/app_taxonomy.json", "taxonomy_id", "app_package_name");
        Long maxID = Collections.max(appMapping.values());
        appIDProvider.setID(maxID);
        return new AppTaxonomyItemProcessor(appMapping, appIDProvider);
    }

    @Bean
    public Step stepTwo(ObjectMapper mapper, IdProvider appIDProvider) {
        return stepBuilderFactory.get("stepTwo")
                .<AppTaxonomy, AppTaxonomy> chunk(10)
                .reader(readerApp())
                .processor(processorApp(mapper, appIDProvider))
                .writer(writerApp(mapper))
                .listener(new StepResultListener())
                .build();
    }

    @Autowired
    @Bean
    public FlatFileItemWriter<AppTaxonomy> writerApp(ObjectMapper mapper) {
        return new FlatFileItemWriterBuilder<AppTaxonomy>()
                .name("AppTaxonomyJsonFileItemWriter")
                .resource(new FileSystemResource(OUTPUT_DATA_APP_JSON))
                .lineAggregator(new JsonLineAggregator<>(mapper))
                .build();

    }
    @Bean
    public Job updateAppTaxonomy(ObjectMapper mapper, IdProvider appIDProvider) {
        return jobBuilderFactory.get("updateAppTaxonomy")
                .incrementer(new RunIdIncrementer())
                .start(stepTwo(mapper, appIDProvider))
                .build();
    }

    @Bean
    public ResourcelessTransactionManager batchTransactionManager() {
        return new ResourcelessTransactionManager();
    }

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(15);
        taskExecutor.setMaxPoolSize(20);
        taskExecutor.setQueueCapacity(30);
        return taskExecutor;
    }

    @Bean
    public JobLauncher batchJobLauncher() throws Exception {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setTaskExecutor(taskExecutor()); // Or below line
        // jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
        jobLauncher.setJobRepository(jobRepository);
        jobLauncher.afterPropertiesSet();
        return jobLauncher;
    }

    @Bean
    public JobOperator jobOperator(JobRegistry jobRegistry) throws Exception {
        SimpleJobOperator jobOperator = new SimpleJobOperator();
        jobOperator.setJobExplorer(jobExplorer);
        jobOperator.setJobLauncher(batchJobLauncher());
        jobOperator.setJobRegistry(jobRegistry);
        jobOperator.setJobRepository(jobRepository);
        return jobOperator;
    }

    @Bean
    public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor(JobRegistry jobRegistry) {
        JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor = new JobRegistryBeanPostProcessor();
        jobRegistryBeanPostProcessor.setJobRegistry(jobRegistry);
        return jobRegistryBeanPostProcessor;
    }

    @Bean
    public ObjectMapper objectMapper(){
        return new ObjectMapper();
    }

    public void run1(ObjectMapper mapper, IdProvider appIDProvider) {
        Map<String, JobParameter> confMap = new HashMap<>();
        confMap.put("time", new JobParameter(System.currentTimeMillis()));
        JobParameters jobParameters = new JobParameters(confMap);
        try {
            batchJobLauncher().run(updateAppTaxonomy(mapper, appIDProvider), jobParameters);
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }

    }

    public void run2(ObjectMapper mapper, IdProvider webIdProvider) {
        Map<String, JobParameter> confMap = new HashMap<>();
        confMap.put("time", new JobParameter(System.currentTimeMillis()));
        JobParameters jobParameters = new JobParameters(confMap);
        try {
            batchJobLauncher().run(updateWebTaxonomy(mapper, webIdProvider), jobParameters);
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }
    }

    public Map<String, Long> getMapping(ObjectMapper mapper, String path, String id, String value){

        Map<String, Long> map = new HashMap<>();

        try {
            FileReader reader = new FileReader(path);
            BufferedReader bufferedReader = new BufferedReader(reader);

            String currentLine;
            while((currentLine=bufferedReader.readLine()) != null) {
                JsonNode node = mapper.readTree(currentLine);
                long taxonomyID = node.get(id).longValue();
                String key = node.get(value).textValue().toLowerCase();
                map.put(key, taxonomyID);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return map;

    }
}
</code>```

Body:
I have a spring batch job which converts tsv file to json. I have specified the following listener which checks for exit code:

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;

public class StepResultListener implements StepExecutionListener {
    @Override
    public void beforeStep(StepExecution stepExecution) {
        System.out.println("Called beforeStep().");
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        System.out.println("Called afterStep().");
        String exitCode = stepExecution.getExitStatus().getExitCode();
        if (exitCode.equals("FAILED")){
            return ExitStatus.FAILED;
        }
        return ExitStatus.COMPLETED;
    }
}

I want to fail the the whole job if the step fails:

@Bean
    public Step stepOne(ObjectMapper mapper, IdProvider webIdProvider) {
        return stepBuilderFactory.get("stepOne")
                .<WebTaxonomy, WebTaxonomy> chunk(10)
                .reader(readerWeb())
                .processor(processorWeb(mapper, webIdProvider))
                .writer(writerWeb(mapper))
                .listener(new StepResultListener())
                .build();
    }

However it still proceeds to complete the job. Any ideas how I can achieve this ?

this is my batch configuration:

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

    private static final String OUTPUT_DATA_JSON = "target/web_taxonomy.json";
    private static final String OUTPUT_DATA_APP_JSON = "target/app_taxonomy.json";

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private JobExplorer jobExplorer;

    @Autowired
    private JobRepository jobRepository;

    @Bean
    public FlatFileItemReader<WebTaxonomy> readerWeb() {
        return new FlatFileItemReaderBuilder<WebTaxonomy>()
                .name("webTaxonomyItemReader")
                .resource(new ClassPathResource("/web_taxonomy.tsv"))
                .linesToSkip(1)
                .lineMapper(lineMapperWeb()).build();

    }

    @Bean
    public DefaultLineMapper<WebTaxonomy> lineMapperWeb() {
        DefaultLineMapper<WebTaxonomy> lineMapper = new DefaultLineMapper<>();
        lineMapper.setLineTokenizer(lineTokenizerWeb());
        lineMapper.setFieldSetMapper(new BeanWrapperFieldSetMapper<WebTaxonomy>() {
            {
                setTargetType(WebTaxonomy.class);
            }
        });
        return lineMapper;
    }

    @Bean
    public DelimitedLineTokenizer lineTokenizerWeb() {
        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(DelimitedLineTokenizer.DELIMITER_TAB);
        tokenizer.setNames("taxonomy_id", "website_name", "brand_name", "publisher", "category", "category_2",
                "category_3", "category_4", "category_5", "curated", "blacklist", "brand_1", "brand_2", "brand_3",
                "brand_4", "brand_5", "brand_6", "regex", "host", "source", "creation_date");
        return tokenizer;
    }

    @Autowired
    @Qualifier("webIdProvider")
    @Bean
    public WebTaxonomyItemProcessor processorWeb(ObjectMapper mapper, IdProvider webIdProvider) {
        Map<String, Long> webMapping = getMapping(mapper, "src/main/resources/web_taxonomy.json", "taxonomy_id", "website_name");
        Long maxID = Collections.max(webMapping.values());
        webIdProvider.setID(maxID);
        return new WebTaxonomyItemProcessor(webMapping, webIdProvider);
    }

    @Bean
    public Step stepOne(ObjectMapper mapper, IdProvider webIdProvider) {
        return stepBuilderFactory.get("stepOne")
                .<WebTaxonomy, WebTaxonomy> chunk(10)
                .reader(readerWeb())
                .processor(processorWeb(mapper, webIdProvider))
                .writer(writerWeb(mapper))
                .listener(new StepResultListener())
                .build();
    }

    @Autowired
    @Bean
    public FlatFileItemWriter<WebTaxonomy> writerWeb(ObjectMapper mapper) {
        return new FlatFileItemWriterBuilder<WebTaxonomy>()
                .name("WebTaxonomyJsonFileItemWriter")
                .resource(new FileSystemResource(OUTPUT_DATA_JSON))
                .lineAggregator(new JsonLineAggregator<>(mapper))
                .build();

    }

    @Bean
    public Job updateWebTaxonomy(ObjectMapper mapper, IdProvider webIdProvider) {
        return jobBuilderFactory.get("updateWebTaxonomy")
                .incrementer(new RunIdIncrementer())
                .start(stepOne(mapper, webIdProvider))
                .build();
    }

    // App job

    @Bean
    public FlatFileItemReader<AppTaxonomy> readerApp() {
        return new FlatFileItemReaderBuilder<AppTaxonomy>()
                .name("appTaxonomyItemReader")
                .resource(new ClassPathResource("/app_taxonomy.tsv"))
                .linesToSkip(1)
                .lineMapper(lineMapperApp()).build();

    }

    @Bean
    public DefaultLineMapper<AppTaxonomy> lineMapperApp() {
        DefaultLineMapper<AppTaxonomy> lineMapper = new DefaultLineMapper<>();
        lineMapper.setLineTokenizer(lineTokenizerApp());
        lineMapper.setFieldSetMapper(new BeanWrapperFieldSetMapper<AppTaxonomy>() {
            {
                setTargetType(AppTaxonomy.class);
            }
        });
        return lineMapper;
    }

    @Bean
    public DelimitedLineTokenizer lineTokenizerApp() {
        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(DelimitedLineTokenizer.DELIMITER_TAB);
        tokenizer.setNames("taxonomy_id", "app_name", "app_store", "app_package_name", "brand_name",
                "publisher", "category", "category_2", "category_3", "category_4", "category_5", "blacklist", "brand_1",
                "brand_2", "brand_3", "brand_4", "brand_5", "brand_6", "platform", "source", "creation_date");
        return tokenizer;
    }

    @Autowired
    @Qualifier("appIdProvider")
    @Bean
    public AppTaxonomyItemProcessor processorApp(ObjectMapper mapper, IdProvider appIDProvider) {
        Map<String, Long> appMapping = getMapping(mapper,"src/main/resources/app_taxonomy.json", "taxonomy_id", "app_package_name");
        Long maxID = Collections.max(appMapping.values());
        appIDProvider.setID(maxID);
        return new AppTaxonomyItemProcessor(appMapping, appIDProvider);
    }

    @Bean
    public Step stepTwo(ObjectMapper mapper, IdProvider appIDProvider) {
        return stepBuilderFactory.get("stepTwo")
                .<AppTaxonomy, AppTaxonomy> chunk(10)
                .reader(readerApp())
                .processor(processorApp(mapper, appIDProvider))
                .writer(writerApp(mapper))
                .listener(new StepResultListener())
                .build();
    }

    @Autowired
    @Bean
    public FlatFileItemWriter<AppTaxonomy> writerApp(ObjectMapper mapper) {
        return new FlatFileItemWriterBuilder<AppTaxonomy>()
                .name("AppTaxonomyJsonFileItemWriter")
                .resource(new FileSystemResource(OUTPUT_DATA_APP_JSON))
                .lineAggregator(new JsonLineAggregator<>(mapper))
                .build();

    }
    @Bean
    public Job updateAppTaxonomy(ObjectMapper mapper, IdProvider appIDProvider) {
        return jobBuilderFactory.get("updateAppTaxonomy")
                .incrementer(new RunIdIncrementer())
                .start(stepTwo(mapper, appIDProvider))
                .build();
    }

    @Bean
    public ResourcelessTransactionManager batchTransactionManager() {
        return new ResourcelessTransactionManager();
    }

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(15);
        taskExecutor.setMaxPoolSize(20);
        taskExecutor.setQueueCapacity(30);
        return taskExecutor;
    }

    @Bean
    public JobLauncher batchJobLauncher() throws Exception {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setTaskExecutor(taskExecutor()); // Or below line
        // jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
        jobLauncher.setJobRepository(jobRepository);
        jobLauncher.afterPropertiesSet();
        return jobLauncher;
    }

    @Bean
    public JobOperator jobOperator(JobRegistry jobRegistry) throws Exception {
        SimpleJobOperator jobOperator = new SimpleJobOperator();
        jobOperator.setJobExplorer(jobExplorer);
        jobOperator.setJobLauncher(batchJobLauncher());
        jobOperator.setJobRegistry(jobRegistry);
        jobOperator.setJobRepository(jobRepository);
        return jobOperator;
    }

    @Bean
    public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor(JobRegistry jobRegistry) {
        JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor = new JobRegistryBeanPostProcessor();
        jobRegistryBeanPostProcessor.setJobRegistry(jobRegistry);
        return jobRegistryBeanPostProcessor;
    }

    @Bean
    public ObjectMapper objectMapper(){
        return new ObjectMapper();
    }

    public void run1(ObjectMapper mapper, IdProvider appIDProvider) {
        Map<String, JobParameter> confMap = new HashMap<>();
        confMap.put("time", new JobParameter(System.currentTimeMillis()));
        JobParameters jobParameters = new JobParameters(confMap);
        try {
            batchJobLauncher().run(updateAppTaxonomy(mapper, appIDProvider), jobParameters);
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }

    }

    public void run2(ObjectMapper mapper, IdProvider webIdProvider) {
        Map<String, JobParameter> confMap = new HashMap<>();
        confMap.put("time", new JobParameter(System.currentTimeMillis()));
        JobParameters jobParameters = new JobParameters(confMap);
        try {
            batchJobLauncher().run(updateWebTaxonomy(mapper, webIdProvider), jobParameters);
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }
    }

    public Map<String, Long> getMapping(ObjectMapper mapper, String path, String id, String value){

        Map<String, Long> map = new HashMap<>();

        try {
            FileReader reader = new FileReader(path);
            BufferedReader bufferedReader = new BufferedReader(reader);

            String currentLine;
            while((currentLine=bufferedReader.readLine()) != null) {
                JsonNode node = mapper.readTree(currentLine);
                long taxonomyID = node.get(id).longValue();
                String key = node.get(value).textValue().toLowerCase();
                map.put(key, taxonomyID);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return map;

    }
}


来源: stackexchange

问:
How to make slider in application window?
Good afternoon, when using the examples, I could not implement a slider for the entire scrolling of these applications.
How can I make a slider that scrolls data in a window with an image background, regardless of the size of the window?
I would like to understand how to read the data in the window when using the slider, regardless of the size of the window.

```<code>import controlP5.*;

ControlP5 cp5;
Textarea myTextarea;

void setup() {
  size(700,400);
  cp5 = new ControlP5(this);

  myTextarea = cp5.addTextarea("txt")
                  .setPosition(100,100)
                  .setSize(200,200)
                  .setFont(createFont("arial",12))
                  .setLineHeight(14)
                  .setColor(color(128))
                  .setColorBackground(color(255,100))
                  .setColorForeground(color(255,100));
                  ;
  myTextarea.setText("Lorem Ipsum is simply dummy text of the printing and typesetting"
                    +" industry. Lorem Ipsum has been the industry's standard dummy text"
                    +" ever since the 1500s, when an unknown printer took a galley of type"
                    +" and scrambled it to make a type specimen book. It has survived not"
                    +" only five centuries, but also the leap into electronic typesetting,"
                    +" remaining essentially unchanged. It was popularised in the 1960s"
                    +" with the release of Letraset sheets containing Lorem Ipsum passages,"
                    +" and more recently with desktop publishing software like Aldus"
                    +" PageMaker including versions of Lorem Ipsum."
                    );

  cp5.addSlider("changeWidth")
     .setRange(100,400)
     .setValue(200)
     .setPosition(100,20)
     .setSize(100,19)
     ;

  cp5.addSlider("changeHeight")
     .setRange(100,400)
     .setValue(200)
     .setPosition(100,40)
     .setSize(100,19)
     ;

}

void keyPressed() {
  if(key=='r') {
    myTextarea.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit."
                      +" Quisque sed velit nec eros scelerisque adipiscing vitae eu sem."
                      +" Quisque malesuada interdum lectus. Pellentesque pellentesque molestie"
                      +" vestibulum. Maecenas ultricies, neque at porttitor lacinia, tellus enim"
                      +" suscipit tortor, ut dapibus orci lorem non ipsum. Mauris ut velit velit."
                      +" Fusce at purus in augue semper tincidunt imperdiet sit amet eros."
                      +" Vestibulum nunc diam, fringilla vitae tristique ut, viverra ut felis."
                      +" Proin aliquet turpis ornare leo aliquam dapibus. Integer dui nisi, condimentum"
                      +" ut sagittis non, fringilla vestibulum sapien. Sed ullamcorper libero et massa"
                      +" congue in facilisis mauris lobortis. Fusce cursus risus sit amet leo imperdiet"
                      +" lacinia faucibus turpis tempus. Pellentesque pellentesque augue sed purus varius"
                      +" sed volutpat dui rhoncus. Lorem ipsum dolor sit amet, consectetur adipiscing elit"
                      );

  } else if(key=='c') {
    myTextarea.setColor(0xffffffff);
  }
}
void draw() {
  background(0);
  if(keyPressed && key==' ') {
    myTextarea.scroll((float)mouseX/(float)width);
  }
  if(keyPressed && key=='l') {
    myTextarea.setLineHeight(mouseY);
  }
}

void changeWidth(int theValue) {
  myTextarea.setWidth(theValue);
}

void changeHeight(int theValue) {
  myTextarea.setHeight(theValue);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Good afternoon, when using the examples, I could not implement a slider for the entire scrolling of these applications.
How can I make a slider that scrolls data in a window with an image background, regardless of the size of the window?
I would like to understand how to read the data in the window when using the slider, regardless of the size of the window.

import controlP5.*;

ControlP5 cp5;
Textarea myTextarea;

void setup() {
  size(700,400);
  cp5 = new ControlP5(this);

  myTextarea = cp5.addTextarea("txt")
                  .setPosition(100,100)
                  .setSize(200,200)
                  .setFont(createFont("arial",12))
                  .setLineHeight(14)
                  .setColor(color(128))
                  .setColorBackground(color(255,100))
                  .setColorForeground(color(255,100));
                  ;
  myTextarea.setText("Lorem Ipsum is simply dummy text of the printing and typesetting"
                    +" industry. Lorem Ipsum has been the industry's standard dummy text"
                    +" ever since the 1500s, when an unknown printer took a galley of type"
                    +" and scrambled it to make a type specimen book. It has survived not"
                    +" only five centuries, but also the leap into electronic typesetting,"
                    +" remaining essentially unchanged. It was popularised in the 1960s"
                    +" with the release of Letraset sheets containing Lorem Ipsum passages,"
                    +" and more recently with desktop publishing software like Aldus"
                    +" PageMaker including versions of Lorem Ipsum."
                    );

  cp5.addSlider("changeWidth")
     .setRange(100,400)
     .setValue(200)
     .setPosition(100,20)
     .setSize(100,19)
     ;

  cp5.addSlider("changeHeight")
     .setRange(100,400)
     .setValue(200)
     .setPosition(100,40)
     .setSize(100,19)
     ;

}

void keyPressed() {
  if(key=='r') {
    myTextarea.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit."
                      +" Quisque sed velit nec eros scelerisque adipiscing vitae eu sem."
                      +" Quisque malesuada interdum lectus. Pellentesque pellentesque molestie"
                      +" vestibulum. Maecenas ultricies, neque at porttitor lacinia, tellus enim"
                      +" suscipit tortor, ut dapibus orci lorem non ipsum. Mauris ut velit velit."
                      +" Fusce at purus in augue semper tincidunt imperdiet sit amet eros."
                      +" Vestibulum nunc diam, fringilla vitae tristique ut, viverra ut felis."
                      +" Proin aliquet turpis ornare leo aliquam dapibus. Integer dui nisi, condimentum"
                      +" ut sagittis non, fringilla vestibulum sapien. Sed ullamcorper libero et massa"
                      +" congue in facilisis mauris lobortis. Fusce cursus risus sit amet leo imperdiet"
                      +" lacinia faucibus turpis tempus. Pellentesque pellentesque augue sed purus varius"
                      +" sed volutpat dui rhoncus. Lorem ipsum dolor sit amet, consectetur adipiscing elit"
                      );

  } else if(key=='c') {
    myTextarea.setColor(0xffffffff);
  }
}
void draw() {
  background(0);
  if(keyPressed && key==' ') {
    myTextarea.scroll((float)mouseX/(float)width);
  }
  if(keyPressed && key=='l') {
    myTextarea.setLineHeight(mouseY);
  }
}

void changeWidth(int theValue) {
  myTextarea.setWidth(theValue);
}

void changeHeight(int theValue) {
  myTextarea.setHeight(theValue);
}


问:
Regarding applying animation to an image using dynamic CSS styles in React
I'm new to React. I have this image ("c-tile-img") inside a div ("c-tile-holder") and what I want to do is when I hover over the div or the image element I want to translate on Y-axis slightly like a hover effect. I used React useState hook to achieve this but when I run it nothing is triggered. Here is what I've so far...

**
Tile.jsx
**

```<code>const Tile = () => {

    const[isMousedOver, setMouseOver] = useState(false);

    function handleMouseOver() {
        setMouseOver(true);
    }

    function handleMouseOut() {
        setMouseOver(false);
    }

return (
        <React.Fragment>
            <div className="c-tiles">
                <a href="/work/help-scout/" className="c-tile c-tile-hs" aria-label="Help Scout Case Study"
                    style={{translate: isMousedOver ? '50': '0'}}
                    onMouseOut={handleMouseOut}
                    onMouseOver={handleMouseOver}>
                    <span className="c-tile-category">Mobile</span>
                    <h2 className="c-tile-title">Help Scout</h2>
                    <div className="c-tile-holder">
                        <img className="c-tile-img c-tile-img-hs lazy loaded" alt="Help Scout" aria-label="Help Scout image" data-ll-status="loaded"
                        src={headshot}/>
                    </div>
                </a>
</code>```

My CSS File

Tile.css

```<code>  .c-tile-holder {
    position: relative;
    max-width: 100%;
    margin: 0 auto;
    text-align: center;
  }

  .c-tile-img-hs {
    max-width: 80%;
  }
  .c-tile-img {
    position: relative;
    transition: all .4s ease-in-out;
    max-width: 100%;
    display: inline-block;
  }
  img {
    vertical-align: middle;
  }
  img {
    border-style: none;
  }

</code>```

Body:
I'm new to React. I have this image ("c-tile-img") inside a div ("c-tile-holder") and what I want to do is when I hover over the div or the image element I want to translate on Y-axis slightly like a hover effect. I used React useState hook to achieve this but when I run it nothing is triggered. Here is what I've so far...

**
Tile.jsx
**

const Tile = () => {

    const[isMousedOver, setMouseOver] = useState(false);

    function handleMouseOver() {
        setMouseOver(true);
    }

    function handleMouseOut() {
        setMouseOver(false);
    }

return (
        <React.Fragment>

                    Mobile

Help Scout

My CSS File

Tile.css

  .c-tile-holder {
    position: relative;
    max-width: 100%;
    margin: 0 auto;
    text-align: center;
  }

  .c-tile-img-hs {
    max-width: 80%;
  }
  .c-tile-img {
    position: relative;
    transition: all .4s ease-in-out;
    max-width: 100%;
    display: inline-block;
  }
  img {
    vertical-align: middle;
  }
  img {
    border-style: none;
  }


问:
Folium Django popup with multiple lines
I have a code

from map import test

def create_popup(data1,data2,data3):
popup = Popup(f" Location        : {data1}
"
" Last Time       : {data2}
"
" Last Status : {data3}
",
max_width=200)
return popup

But when i input let say popup1 = create_popup("X",test.data2,test.data3), it seems like my Popup only receive data 1 which is x and resulted

Location : X
Last Time : {data2}
Last Status : {data3}

test refer to test.py. Is there anyway to fix this code?

Thanks, i am using PyCharm

I would like to make a popup folium with 3 lines :
Location : data1
Last Time : test.data2
Last Status : test.data3

Title: Folium Django popup with multiple lines


问:
CI/CD using Github Actions and AWS EC2 instance
I have a dockerised fastapi app whith depends on mysql and redis which are all configured in docker-compose.yml. Want to implement a CI/CD using github actions and AWS EC2 instance. My EC2 instance has docker and docker-compose installed. Here are my questions.

What do I do to run the tests that depends on the test db?

How do I implement CD from github actions and AWS EC2 instance?

I might not be clear so please ask some questions for clarification. Thank you.

name: backend-api
on:
  push:
    branches: ["main"]
  pull_request:
    branches: ["main"]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - name: Set up Python 3.10
        uses: actions/setup-python@v3
        with:
          python-version: "3.10"
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install flake8 pytest
          if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
      - name: Lint with flake8
        run: |
          # stop the build if there are Python syntax errors or undefined names
          flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
          # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
          flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
      - name: Create .env file for configuration settings.
        uses: SpicyPizza/create-envfile@v1.3
        with:
          envkey_APP_ENV: ${{secrets.APP_ENV}}
          envkey_APP_HOST: ${{secrets.APP_HOST}}
          envkey_MYSQL_USER: ${{secrets.APP_ENV}}
          envkey_PROD_BASE_URL: ${{secrets.MYSQL_USER}}
          envkey_DEV_BASE_URL: ${{secrets.APP_ENV}}
          envkey_MYSQL_ROOT_PASSWORD: ${{secrets.MYSQL_ROOT_PASSWORD}}
          envkey_MYSQL_DATABASE: ${{secrets.MYSQL_DATABASE}}
          envkey_PRODUCTION_DB_URI: ${{secrets.PRODUCTION_DB_URI}}
          envkey_TEST_DB_URI: ${{secrets.TEST_DB_URI}}
          envkey_BASE_URL: ${{secrets.BASE_URL}}
          envkey_WALLET_PROVIDER_ACCESS_TOKEN: ${{secrets.WALLET_PROVIDER_ACCESS_TOKEN}}
          envkey_S3_BUCKET_NAME: ${{secrets.S3_BUCKET_NAME}}
          envkey_S3_ACCESS_SECRET: ${{secrets.S3_ACCESS_SECRET}}
          envkey_S3_ACCESS_KEY: ${{secrets.S3_ACCESS_KEY}}
          envkey_S3_BUCKET_REGION: ${{secrets.S3_BUCKET_REGION}}
          envkey_JWT_SECRET_KEY: ${{secrets.JWT_SECRET_KEY}}
          envkey_ETHERSCAN_API_URL: ${{secrets.ETHERSCAN_API_URL}}
          envkey_BLOCKCHAIN_API_URL: ${{secrets.BLOCKCHAIN_API_URL}}
          envkey_WALLET_PROVIDER_BASE_URL: ${{secrets.WALLET_PROVIDER_BASE_URL}}
          envkey_STRATEGY_PROVIDER_BASE_URL: ${{secrets.STRATEGY_PROVIDER_BASE_URL}}
          envkey_INDEX_PROVIDER_BASE_URL: ${{secrets.INDEX_PROVIDER_BASE_URL}}

      - name: Running Tests with pytest
        run: |
          pytest
  Deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Git pull
        env:
          AWS_EC2_PEM: ${{ secrets.AWS_EC2_PEM  }}
          AWS_EC2_PUBLIC_IP: ${{ secrets.AWS_EC2_PUBLIC_IP  }}
          AWS_EC2_USERNAME: ${{ secrets.AWS_EC2_USERNAME  }}
        run: |
          pwd
          echo "$AWS_EC2_PEM" > private_key && chmod 600 private_key
          ssh -o StrictHostKeyChecking=no -i private_key ${AWS_EC2_USERNAME}@${AWS_EC2_PUBLIC_IP}
            git checkout main &&
            git fetch --all &&
            git reset --hard origin/main &&
            git pull origin main &&
            touch .env
            docker-compose up -d --build
```


问:
Auto unlock screen in batch file
I want to run a batch file which set in task scheduler without display console window, my batch need open one wpf app at the end. I tried to set Security Options in task scheduler like this https://i.stack.imgur.com/IgfjU.png, the console window really disappear but my app run in background process (see in task manager) so that I can see it in screen. Since this reason, I change to lock screen by using LockWorkStation(); of user32.dll but I can't auto unlock it. So could I do to unlock the screen?

If can't do it, I want to display a image full screen on top while run batch to hide every thing or any else to notify user that machine under maintenance or in idle as ATM machine do. Currently, I can only open an image with maximized but not full screen. Please help me solve this.

Title: Auto unlock screen in batch file


问:
Swipeable html table row to show action button
I am building a Blazor Maui application and I would like to create a HTML table with action buttons such as Delete but shown only when swiping on the row.

Swipe works (only on mobile)

swipe works img

Managed to place into table but, my issue is I had to create an inner table into my table due the full row should be swiped and also because of "div cannot be nested inside tr" this solution causing alignment issue

Question:

How else could this be done without using a table inside the table?

source code:

.swipe-container {
  display: flex;
  overflow: auto;
  overflow-x: scroll;
  scroll-snap-type: x mandatory;
}

/* scrollbar should be hidden */
.swipe-container::-webkit-scrollbar {
  display: none;
}

/* main element should always snap into view */
.swipe-element {
  scroll-snap-align: start;
  font-family: sans-serif;
}

/* actions and element should be 100% wide */
.action,
.swipe-element {
  min-width: 100%;
}

.action {
  display: flex;
  align-items: center;
}

/* icon should remain sticky */
i {
  color: white;
  position: sticky;
  left: 16px;
  right: 16px;
}

/* action background colors */
.left {
  background-color: red;
}

.right {
  justify-content: flex-end;
  background-color: cornflowerblue;
}

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  text-align: left;
}

tr:nth-child(even) {
  background-color: #dddddd;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th width="10%">xx</th>
      <th width="20%">xxxxxx</th>
      <th width="30%">xxxxxx</th>
      <th width="30%">xxxxxx</th>
      <th width="10%">x</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td colspan="5">
        <div class="swipe-container">
          <!-- left action -->
          <div class="action left">
            <i class="material-icons">favorite</i>
          </div>
          <!-- swipeable element -->
          <div class="swipe-element" style="width:100%">
            <table>
              <tbody>
                <tr>
                  <td width="10%" valign=middle align=Center nowrap="nowrap">10</td>
                  <td width="20%" valign=middle align=Center>12345</td>
                  <td width="30%" valign=middle align=Center><input type="text" /></td>
                  <td width="30%" valign=middle align=Center><input type="text" /></td>
                  <td width="10%" valign=middle align=Center><input type="checkbox" /></td>
                </tr>
              </tbody>
            </table>
          </div>
          <!-- right action -->
          <div class="action right">
            <i class="material-icons">Delete</i>
          </div>
        </div>
      </td>
    </tr>
  </tbody>
</table></code>```

Codepen here

Body:
I am building a Blazor Maui application and I would like to create a HTML table with action buttons such as Delete but shown only when swiping on the row.

Swipe works (only on mobile)

swipe works img

Managed to place into table but, my issue is I had to create an inner table into my table due the full row should be swiped and also because of "div cannot be nested inside tr" this solution causing alignment issue

Question:

How else could this be done without using a table inside the table?

source code:

.swipe-container {
  display: flex;
  overflow: auto;
  overflow-x: scroll;
  scroll-snap-type: x mandatory;
}

/* scrollbar should be hidden */
.swipe-container::-webkit-scrollbar {
  display: none;
}

/* main element should always snap into view */
.swipe-element {
  scroll-snap-align: start;
  font-family: sans-serif;
}

/* actions and element should be 100% wide */
.action,
.swipe-element {
  min-width: 100%;
}

.action {
  display: flex;
  align-items: center;
}

/* icon should remain sticky */
i {
  color: white;
  position: sticky;
  left: 16px;
  right: 16px;
}

/* action background colors */
.left {
  background-color: red;
}

.right {
  justify-content: flex-end;
  background-color: cornflowerblue;
}

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  text-align: left;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

      xx
      xxxxxx
      xxxxxx
      xxxxxx
      x

            favorite

                  10
                  12345
                  <input type="text" />
                  <input type="text" />
                  <input type="checkbox" />

            Delete

Codepen here


问:
Configuring use NAT gateway only in specific request url
Condition:
1 Public subnet A in VPC (No private subnet)
Internet gateway is connected to VPC
1 NAT gateway is subnet A
One server instance resides in subnet A.

Question:
Is it possible to use NAT gateway in specific case, otherwise send request without NAT gateway?

Some API interface I'm using are whitelisted and only allow whitelisted IP (I assigned it to NAT gateway).

But regarding traffic cost, I want to use NAT gateway only when request to whitelisted API server.

Example)
1)
https://Some-Whitelisted-API-Server.com/get => Sent via NAT gateway so API server acknowledge it's whitelisted IP as request source

2)
https://AnyOtherRequest.com/get => Sent without NAT gateway -- request source IP is EIP of instance.

Is it possible to configure like above?
I guess I need to use nginx or apache server for url re-routing, but it would be great if above is possible.


问:
Flatten Nested QuerySet to a Pandas DataDrame
I am trying to fetch records of all devices with their related owners for the data as below

```<code>Device
======
.Id
.Name
.owner_id

Owner
=====
.Id
.Name
</code>```

How I try to get the data in django:

```<code>data = Device.objects.select_related('owner').values()
</code>```

Now I would need the data of all devices and their owner ( related record ) in a flattened pandas' DataFrame. e.g. a column like 'owner.name' is created in the dataframe. How can I do that?

Tried 'from_records' didn't work. Tried 'json_normalize' but cannot convert queryset to json first.

Thanks

Body:
I am trying to fetch records of all devices with their related owners for the data as below

Device
======
.Id
.Name
.owner_id

Owner
=====
.Id
.Name

How I try to get the data in django:

data = Device.objects.select_related('owner').values()

Now I would need the data of all devices and their owner ( related record ) in a flattened pandas' DataFrame. e.g. a column like 'owner.name' is created in the dataframe. How can I do that?

Tried 'from_records' didn't work. Tried 'json_normalize' but cannot convert queryset to json first.

Thanks


问:
I am facing an issue in using POST Request to a server
I am trying to send a file to the server using the Requests library in python. I have tried using the snippet from POSTMAN API. I am providing the program sample for reference. This is the `import requests

```<code>import requests
from requests.auth import HTTPBasicAuth
from requests.packages.urllib3.exceptions import InsecureRequestWarning
#from urllib3 import disable_warnings

url = "https://jazz,xxx.de/qm/service/com.ibm.rqm.integration.service.IIntegrationService/resources/<Project_Area>/attachment/"
filepath ="D:\\ETM\\varaiblelist.txt"
#headers = {"Content-Type": "multipart/form-data; boundary=<calculated when request is sent>","Content-Length":"<calculated when request is sent>","Accept":"*/*", "Accept-Encoding":"gzip, deflate, br"}
headers = {"Content-Type": "boundary=multipart/<multipart type>","Accept":"/"}

with open(filepath, 'rb') as fobj:
response = requests.post(url, headers=headers, files={'file': fobj},auth = HTTPBasicAuth('xxxx', 'xxxxx'), verify = False)

print(response)
print(response.headers)
</code>```

POSTMAN snippet copied.
The output is:

<Response [201]>
{'Date': 'Thu, 12 Jan 2023 06:07:45 GMT', 'X-Powered-By': 'Servlet/3.0', 'Strict-Transport-Security': 'max-age=31536000', 'Content-Location': 'slug__xxxxx', 'Location': 'https://jazz.xxx.de/qm/service/com.ibm.rqm.integration.service.IIntegrationService/resources/<Project_Area>/attachment/slug__xxxxx', 'Expires': 'Thu, 01 Dec 1994 16:00:00 GMT', 'Cache-Control': 'no-cache="set-cookie, set-cookie2"', 'Set-Cookie': 'JSA_SESSION_IDENTITY=xxxx; Path=/qm1; Secure; HttpOnly; SameSite=None;, JSESSIONID=xxxxxxxx; Path=/; Secure; HttpOnly; SameSite=None;', 'Content-Length': '0', 'Keep-Alive': 'timeout=5, max=100', 'Connection': 'Keep-Alive', 'Content-Language': 'en-US'}

It is able to create but when I use the Content-Location URL. It says Address not found. I am not able to solve this issue.

Body:
I am trying to send a file to the server using the Requests library in python. I have tried using the snippet from POSTMAN API. I am providing the program sample for reference. This is the `import requests

import requests
from requests.auth import HTTPBasicAuth
from requests.packages.urllib3.exceptions import InsecureRequestWarning
#from urllib3 import disable_warnings

url = "https://jazz,xxx.de/qm/service/com.ibm.rqm.integration.service.IIntegrationService/resources/<Project_Area>/attachment/"
filepath ="D:\\ETM\\varaiblelist.txt"
#headers = {"Content-Type": "multipart/form-data; boundary=<calculated when request is sent>","Content-Length":"<calculated when request is sent>","Accept":"*/*", "Accept-Encoding":"gzip, deflate, br"}
headers = {"Content-Type": "boundary=multipart/<multipart type>","Accept":"/"}

with open(filepath, 'rb') as fobj:
response = requests.post(url, headers=headers, files={'file': fobj},auth = HTTPBasicAuth('xxxx', 'xxxxx'), verify = False)

print(response)
print(response.headers)

POSTMAN snippet copied.
The output is:

<Response [201]>
{'Date': 'Thu, 12 Jan 2023 06:07:45 GMT', 'X-Powered-By': 'Servlet/3.0', 'Strict-Transport-Security': 'max-age=31536000', 'Content-Location': 'slug__xxxxx', 'Location': 'https://jazz.xxx.de/qm/service/com.ibm.rqm.integration.service.IIntegrationService/resources/<Project_Area>/attachment/slug__xxxxx', 'Expires': 'Thu, 01 Dec 1994 16:00:00 GMT', 'Cache-Control': 'no-cache="set-cookie, set-cookie2"', 'Set-Cookie': 'JSA_SESSION_IDENTITY=xxxx; Path=/qm1; Secure; HttpOnly; SameSite=None;, JSESSIONID=xxxxxxxx; Path=/; Secure; HttpOnly; SameSite=None;', 'Content-Length': '0', 'Keep-Alive': 'timeout=5, max=100', 'Connection': 'Keep-Alive', 'Content-Language': 'en-US'}

It is able to create but when I use the Content-Location URL. It says Address not found. I am not able to solve this issue.


问:
Acornjs: Property 'callee' does not exist on type 'Node'
I have following code:

const script = `
  const john = "893cf9d5-ad70-423c-7ea8-4e0f92d9c79b"
  const a = A.solve(john, {input: 1}, 5)
`
const parsedConstructorCaller = acorn.parseExpressionAt(script, 71, { ecmaVersion: 2020 })
if(parsedConstructorCaller.type === 'CallExpression'){
  console.log(parsedConstructorCaller.callee)
}
```
<p>It works perfectly on itself, the problem I am having is TypeScript being unable to find property <code>callee</code> on acorn.Node. This class is built into the library and defined as this:</p>
<pre class="lang-js prettyprint-override"><code>class Node {
  type: string
  start: number
  end: number
  loc?: SourceLocation
  sourceFile?: string
  range?: [number, number]
  constructor(parser: Parser, pos: number, loc?: SourceLocation)
}
</code>```

This is console log of parsedConstructorCaller, where you can see, that callee property can be present on Node class.

Node {
  type: 'CallExpression',
  start: 71,
  end: 99,
  callee: Node {
    type: 'MemberExpression',
    start: 71,
    end: 78,
    object: Node { type: 'Identifier', start: 71, end: 72, name: 'A' },
    property: Node { type: 'Identifier', start: 73, end: 78, name: 'solve' },
    computed: false,
    optional: false
  },
  arguments: [
    Node { type: 'Identifier', start: 79, end: 83, name: 'john' },
    Node {
      type: 'ObjectExpression',
      start: 85,
      end: 95,
      properties: [Array]
    },
    Node { type: 'Literal', start: 97, end: 98, value: 5, raw: '5' }
  ],
  optional: false
}
```

I am not really good with OOP and assume, that extending class is not necessary, because TypeScript likely wouldn't let you put data into that class unless it's defined somewhere in it's structure, meaning that it's most likely misuse on my side, rather than incompleteness/bug of the library. Also this is not problem only with callee property, it's also happening on other properties f.e.arguments.

Any guidance on solving this would be appreciated.

Body:
I have following code:

const script = `
  const john = "893cf9d5-ad70-423c-7ea8-4e0f92d9c79b"
  const a = A.solve(john, {input: 1}, 5)
`
const parsedConstructorCaller = acorn.parseExpressionAt(script, 71, { ecmaVersion: 2020 })
if(parsedConstructorCaller.type === 'CallExpression'){
  console.log(parsedConstructorCaller.callee)
}

It works perfectly on itself, the problem I am having is TypeScript being unable to find property callee on acorn.Node. This class is built into the library and defined as this:

class Node {
  type: string
  start: number
  end: number
  loc?: SourceLocation
  sourceFile?: string
  range?: [number, number]
  constructor(parser: Parser, pos: number, loc?: SourceLocation)
}

This is console log of parsedConstructorCaller, where you can see, that callee property can be present on Node class.

Node {
  type: 'CallExpression',
  start: 71,
  end: 99,
  callee: Node {
    type: 'MemberExpression',
    start: 71,
    end: 78,
    object: Node { type: 'Identifier', start: 71, end: 72, name: 'A' },
    property: Node { type: 'Identifier', start: 73, end: 78, name: 'solve' },
    computed: false,
    optional: false
  },
  arguments: [
    Node { type: 'Identifier', start: 79, end: 83, name: 'john' },
    Node {
      type: 'ObjectExpression',
      start: 85,
      end: 95,
      properties: [Array]
    },
    Node { type: 'Literal', start: 97, end: 98, value: 5, raw: '5' }
  ],
  optional: false
}

I am not really good with OOP and assume, that extending class is not necessary, because TypeScript likely wouldn't let you put data into that class unless it's defined somewhere in it's structure, meaning that it's most likely misuse on my side, rather than incompleteness/bug of the library. Also this is not problem only with callee property, it's also happening on other properties f.e.arguments.

Any guidance on solving this would be appreciated.


问:
MUI CSS flashes on page load with NextJs 13, MUI 5 and React 18
After upgrading to NextJs 13 and MUI 5, my website has a CSS flash on first page load. I run the static NextJs export: npm run build && npm run export. I can DM the website URL on request.

What I find confusing is the output of
<link rel="preload" href="/_next/static/css/72e8bb7ac2b40e6f.css" as="style" />
<link rel="stylesheet" href="/_next/static/css/72e8bb7ac2b40e6f.css" data-n-p="" />

...
```
<p>My packages:</p>
<pre class="lang-json prettyprint-override"><code>  "dependencies": {
    "@babel/node": "^7.10.5",
    "@emotion/cache": "^11.10.5",
    "@emotion/react": "^11.10.5",
    "@emotion/server": "^11.10.0",
    "@emotion/styled": "^11.10.5",
    "@fontsource/roboto": "^4.5.8",
    "@mui/material": "^5.11.4",
    "@mui/icons-material": "^5.11.0",
    "lodash": "^4.17.21",
    "material-ui-popup-state": "^5.0.4",
    "next": "^13.1.1",
    "node-html-parser": "^6.1.4",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-share": "^4.4.1",
    "styled-jsx": "^5.1.1",
    "tss-react": "^4.5.2"
  }
</code>```

_document.js:

class AppDocument extends Document {
  render() {
    return (

          <meta name="emotion-insertion-point" content="" />
          {this.props.emotionStyleTags}

          <NextScript />

Body:
After upgrading to NextJs 13 and MUI 5, my website has a CSS flash on first page load. I run the static NextJs export: npm run build && npm run export. I can DM the website URL on request.

What I find confusing is the output of
<link rel="preload" href="/_next/static/css/72e8bb7ac2b40e6f.css" as="style" />
<link rel="stylesheet" href="/_next/static/css/72e8bb7ac2b40e6f.css" data-n-p="" />

...

My packages:

  "dependencies": {
    "@babel/node": "^7.10.5",
    "@emotion/cache": "^11.10.5",
    "@emotion/react": "^11.10.5",
    "@emotion/server": "^11.10.0",
    "@emotion/styled": "^11.10.5",
    "@fontsource/roboto": "^4.5.8",
    "@mui/material": "^5.11.4",
    "@mui/icons-material": "^5.11.0",
    "lodash": "^4.17.21",
    "material-ui-popup-state": "^5.0.4",
    "next": "^13.1.1",
    "node-html-parser": "^6.1.4",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-share": "^4.4.1",
    "styled-jsx": "^5.1.1",
    "tss-react": "^4.5.2"
  }

_document.js:

class AppDocument extends Document {
  render() {
    return (

          <meta name="emotion-insertion-point" content="" />
          {this.props.emotionStyleTags}

          <NextScript />


问:
Filter DataFrame by Index array on a non-index column
I have an Index array ind and a DataFrame df. Now I want to filter df to show only those lines where the value in col1 (which is a regular column, no index) is contained in the array ind. How do I do that?


问:
Google App Script to Discord Message for every new row added

when i add new row, col M turn to yes, trigger col L to run and send to discord (this works)

lets assume i have 10 rows now, i delete row no 7, so now i have 9 rows, i want the code to know that i delete row 7, and re run the new message to discord in col L7,L8,L9 as the value in these cells have changed (this is still error)

now in row 10 is empty, and when added, it also does not trigger col L to run because it has been run previously (which is wrong because i have delete 1 row before, so this row logic should be just like point no 1)

```<code>function onChange() {
    var sheet = SpreadsheetApp.getActiveSheet();
    var lastRow = sheet.getLastRow();
    var lastSentRow = parseInt(PropertiesService.getScriptProperties().getProperty('lastSentRow')) || 0;
    var lastSentMessage = PropertiesService.getScriptProperties().getProperty('lastSentMessage') || "";
    var currentRow = 3;
    while (currentRow <= lastRow) {
        var value = sheet.getRange(currentRow,13).getValue(); // M column
        var message = sheet.getRange(currentRow,12).getValue(); // L column
        if (value === "yes" && message !== lastSentMessage) {
            sendDiscordMessage(message);
            PropertiesService.getScriptProperties().setProperty('lastSentRow', currentRow);
            PropertiesService.getScriptProperties().setProperty('lastSentMessage', message);
        }
        if(value === "no"){
            break;
        }
        currentRow++;
    }
}

function sendDiscordMessage(message) {
    var discordUrl = "https://discord.com/api/webhooks/xxx";
    var payload = {content: message};

    var params = {
        method: "POST",
        payload: JSON.stringify(payload),
        muteHttpExceptions : true,
        contentType: "application/json"
    };

    var response = UrlFetchApp.fetch(discordUrl, params);
    Logger.log(response.getContentText());
}
</code>```

Body:
when i add new row, col M turn to yes, trigger col L to run and send to discord (this works)

lets assume i have 10 rows now, i delete row no 7, so now i have 9 rows, i want the code to know that i delete row 7, and re run the new message to discord in col L7,L8,L9 as the value in these cells have changed (this is still error)

now in row 10 is empty, and when added, it also does not trigger col L to run because it has been run previously (which is wrong because i have delete 1 row before, so this row logic should be just like point no 1)

function onChange() {
    var sheet = SpreadsheetApp.getActiveSheet();
    var lastRow = sheet.getLastRow();
    var lastSentRow = parseInt(PropertiesService.getScriptProperties().getProperty('lastSentRow')) || 0;
    var lastSentMessage = PropertiesService.getScriptProperties().getProperty('lastSentMessage') || "";
    var currentRow = 3;
    while (currentRow <= lastRow) {
        var value = sheet.getRange(currentRow,13).getValue(); // M column
        var message = sheet.getRange(currentRow,12).getValue(); // L column
        if (value === "yes" && message !== lastSentMessage) {
            sendDiscordMessage(message);
            PropertiesService.getScriptProperties().setProperty('lastSentRow', currentRow);
            PropertiesService.getScriptProperties().setProperty('lastSentMessage', message);
        }
        if(value === "no"){
            break;
        }
        currentRow++;
    }
}

function sendDiscordMessage(message) {
    var discordUrl = "https://discord.com/api/webhooks/xxx";
    var payload = {content: message};

    var params = {
        method: "POST",
        payload: JSON.stringify(payload),
        muteHttpExceptions : true,
        contentType: "application/json"
    };

    var response = UrlFetchApp.fetch(discordUrl, params);
    Logger.log(response.getContentText());
}


问:
Convert MSSQL to utf-8
I have a problem with converting text from MSSQL (r2 2008) to utf-8, some of the characters are missing.

I'm converting 'Latin2' with 'Č Ć Š Ž Đ', but I'm not getting all of them converted, I have converted 'Ž' for example, but 'Č' becomes 'C'.

Here is how I'm currently converting:

```<code>iconv('CP1252', 'UTF-8', $str);
</code>```

many of the columns in MSSQL DB contain characters from above, I have to retrieve exact information and sync it to MySQL DB, without damaging any data, characters must stay the same.

Note: I'm using PHP.

I have tried some other encodings to use like input, but 'CP1252' is the closes I found to convert data, some others don't even find the 'Ž'  character, and some are just broken.

Title: Convert MSSQL to utf-8

Body:
I have a problem with converting text from MSSQL (r2 2008) to utf-8, some of the characters are missing.

I'm converting 'Latin2' with 'Č Ć Š Ž Đ', but I'm not getting all of them converted, I have converted 'Ž' for example, but 'Č' becomes 'C'.

Here is how I'm currently converting:

iconv('CP1252', 'UTF-8', $str);

many of the columns in MSSQL DB contain characters from above, I have to retrieve exact information and sync it to MySQL DB, without damaging any data, characters must stay the same.

Note: I'm using PHP.

I have tried some other encodings to use like input, but 'CP1252' is the closes I found to convert data, some others don't even find the 'Ž'  character, and some are just broken.


问:
Is there a way to store custom properties in database while logging with log4net using AdoNetAppender?
I am having a controller, where I inject the log4net dependency like this:

```<code>public CalendarController(ILogger<CalendarController> logger) : base(logger) { }

[HttpGet]
public List<MyClass> Get()
{
    var log = new
    {
        Message = "asd123",
        LogLevel = "Error",
        LogDate = DateTime.Now,
        EndpointName = "testendpoint",
        Username = "myusername",
        Userdomain = "mydomain"
    };
    _logger.LogError(JsonConvert.SerializeObject(log));
    return someValue;
}
</code>```

My db structure looks like this:

The log4net.config file looks like this:

```<code><log4net debug ="true">
    <root>
        <level value="WARN" />
        <appender-ref ref="AdoNetAppender" />
        <!--ENABLE THIS FOR DEBUGGING #1-->
        <!--<appender-ref ref="DebugAppender" />-->
    </root>
    <!-- ENABLE THIS FOR DEBUGGING #2-->
    <!--<appender name="DebugAppender" type="log4net.Appender.DebugAppender">
        <immediateFlush value="true" />
        <layout type="log4net.Layout.SimpleLayout" />
    </appender>-->
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
        <bufferSize value="1" />
        <connectionType value="System.Data.SqlClient.SqlConnection, System.Data" />
        <connectionString value="connectionStringPlaceHolder"/>
        <commandText value="INSERT INTO dbo.Logs (Message, LogLevel, LogDate, EndpointName, Username, Userdomain)
  VALUES (@message, @log_level, @log_date, @endpointname, @username, @userdomain)" />
    <parameter>
        <parameterName value="@message"/>
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%m" />
        </layout>
    </parameter>
    <parameter>
        <parameterName value="@log_level"/>
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%p" />
        </layout>
    </parameter>
    <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout"/>
    </parameter>
    <parameter>
        <parameterName value="@endpointname"/>
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.RawPropertyLayout">
            <key value="Endpointname" />
        </layout>
    </parameter>
    <parameter>
        <parameterName value="@username"/>
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%w" />
        </layout>
    </parameter>
    <parameter>
        <parameterName value="@userdomain" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.RawPropertyLayout">
            <key value="Userdomain" />
        </layout>
    </parameter>
    </appender>
</log4net>
</code>```

I thought RawProperty layouts is the thing I want, but it is not. How can I configure this XML, so that the parameters I gave to _logger.LogError() are correctly inserted into the database?

Body:
I am having a controller, where I inject the log4net dependency like this:

public CalendarController(ILogger<CalendarController> logger) : base(logger) { }

[HttpGet]
public List<MyClass> Get()
{
    var log = new
    {
        Message = "asd123",
        LogLevel = "Error",
        LogDate = DateTime.Now,
        EndpointName = "testendpoint",
        Username = "myusername",
        Userdomain = "mydomain"
    };
    _logger.LogError(JsonConvert.SerializeObject(log));
    return someValue;
}

My db structure looks like this:

The log4net.config file looks like this:

<log4net debug ="true">
    <root>
        <level value="WARN" />
        <appender-ref ref="AdoNetAppender" />

    </root>

    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
        <bufferSize value="1" />
        <connectionType value="System.Data.SqlClient.SqlConnection, System.Data" />
        <connectionString value="connectionStringPlaceHolder"/>
        <commandText value="INSERT INTO dbo.Logs (Message, LogLevel, LogDate, EndpointName, Username, Userdomain)
  VALUES (@message, @log_level, @log_date, @endpointname, @username, @userdomain)" />
    <parameter>
        <parameterName value="@message"/>
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%m" />
        </layout>
    </parameter>
    <parameter>
        <parameterName value="@log_level"/>
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%p" />
        </layout>
    </parameter>
    <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout"/>
    </parameter>
    <parameter>
        <parameterName value="@endpointname"/>
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.RawPropertyLayout">
            <key value="Endpointname" />
        </layout>
    </parameter>
    <parameter>
        <parameterName value="@username"/>
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%w" />
        </layout>
    </parameter>
    <parameter>
        <parameterName value="@userdomain" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.RawPropertyLayout">
            <key value="Userdomain" />
        </layout>
    </parameter>
    </appender>
</log4net>

I thought RawProperty layouts is the thing I want, but it is not. How can I configure this XML, so that the parameters I gave to _logger.LogError() are correctly inserted into the database?


问:
yarn symlinks wrong package in .bin of workspace in monorepo
I have two workspaces in my mono repo workspace-a and workspace-b. One depends on jest version 26 the other on 29. When I do yarn install it will install jest-26 in the root node_modules and the other one in node_modules of workspace-b.

It will then symlink the jest script in workspace-b/.bin/jest to the older jest version in the root node_modules.
So when I run yarn workspace workspace-b jest it will invoke jest-26 even though the dependency is states as 29 and it actually installed the correct version in the corresponding node_modules directory.

To me this behavior seems odd.

I could fix it and manually link it to the right version but I wonder if I did anything wrong in the setup or if this is the default behavior.

Here is a small repository to reproduce the behavior:
https://github.com/timbicker/yarn-workspace-bug/tree/main


问:
Is it possible to bring my graphDB from Neo4j to my Jupyter Notebook?
While working on a task, I need to extract graph data from neo4j to the Jupyter Notebook. So, is there any way of doing this.

I had read of using GDS, But I want to do some deep learning things, and I want to do it in jupyter Notebook or any other IDE.


问:
Prisma native query doesn't work.. why? why
Before I post it, I ask to them, But the CS center is not responded.

Here is my code.

const response = await this.prisma
      .$queryRaw<Gym>`SELECT * FROM \`Gym\` WHERE \`status\` != 'WITHDRAWAL' LIMIT 1 OFFSET 0;`;
```
<p>I tried too,</p>
```"prisma.$queryRaw`query`",
"prisma.$queryRaw<Model>`query`",
"prisma.$queryRaw<Model[]>`query`",
"prisma.$queryRaw(Prisma.sql`query`)",
"prisma.$queryRaw<Model>(Prisma.sql`query`)"
```
<p>But, output is error</p>
<pre class="lang-sql prettyprint-override"><code>SELECT * FROM `Gym` WHERE `status` != 'WITHDRAWAL' LIMIT 1 OFFSET 0; []
prisma:error
Invalid `prisma.$queryRaw()` invocation:

Raw query failed. Code: `N/A`. Message: `N/A`
[Nest] 17720  - 2023. 01. 12. 오후 6:09:37   ERROR [ExceptionsHandler]
Invalid `prisma.$queryRaw()` invocation:

Raw query failed. Code: `N/A`. Message: `N/A`
Error:
Invalid `prisma.$queryRaw()` invocation:

Raw query failed. Code: `N/A`. Message: `N/A`
    at RequestHandler.handleRequestError (D:\practice_ljy\trainning-api\node_modules\@prisma\client\runtime\index.js:35024:13)
    at RequestHandler.handleAndLogRequestError (D:\practice_ljy\trainning-api\node_modules\@prisma\client\runtime\index.js:34996:12)
    at RequestHandler.request (D:\practice_ljy\trainning-api\node_modules\@prisma\client\runtime\index.js:34991:12)
    at Proxy._request (D:\practice_ljy\trainning-api\node_modules\@prisma\client\runtime\index.js:36082:16)
</code>```

and the CS center is bad to me.
they don't answer correctly.

I hope that find the answer in here..

my Prisma&client version: 4.8.1

I want to know the cause of failure. the error Code is `N/A`, And I don't recognized.

Body:
Before I post it, I ask to them, But the CS center is not responded.

Here is my code.

const response = await this.prisma
      .$queryRaw<Gym>`SELECT * FROM \`Gym\` WHERE \`status\` != 'WITHDRAWAL' LIMIT 1 OFFSET 0;`;

I tried too,

"prisma.$queryRaw`query`",
"prisma.$queryRaw<Model>`query`",
"prisma.$queryRaw<Model[]>`query`",
"prisma.$queryRaw(Prisma.sql`query`)",
"prisma.$queryRaw<Model>(Prisma.sql`query`)"

But, output is error

SELECT * FROM `Gym` WHERE `status` != 'WITHDRAWAL' LIMIT 1 OFFSET 0; []
prisma:error
Invalid `prisma.$queryRaw()` invocation:

Raw query failed. Code: `N/A`. Message: `N/A`
[Nest] 17720  - 2023. 01. 12. 오후 6:09:37   ERROR [ExceptionsHandler]
Invalid `prisma.$queryRaw()` invocation:

Raw query failed. Code: `N/A`. Message: `N/A`
Error:
Invalid `prisma.$queryRaw()` invocation:

Raw query failed. Code: `N/A`. Message: `N/A`
    at RequestHandler.handleRequestError (D:\practice_ljy\trainning-api\node_modules\@prisma\client\runtime\index.js:35024:13)
    at RequestHandler.handleAndLogRequestError (D:\practice_ljy\trainning-api\node_modules\@prisma\client\runtime\index.js:34996:12)
    at RequestHandler.request (D:\practice_ljy\trainning-api\node_modules\@prisma\client\runtime\index.js:34991:12)
    at Proxy._request (D:\practice_ljy\trainning-api\node_modules\@prisma\client\runtime\index.js:36082:16)

and the CS center is bad to me.
they don't answer correctly.

I hope that find the answer in here..

my Prisma&client version: 4.8.1

I want to know the cause of failure. the error Code is `N/A`, And I don't recognized.


问:
I keep getting the following error "Cannot set headers after they are sent to the client" when i use headers.authorization in jwt
I'm working on a project and i can't seem to able to make jwt work, everytime i try to use authorization in my header and provide a valid token, my server crashes and it gives me the error in the title.
Here's my middleware for jwt :

```<code>const jwt = require("jsonwebtoken");

const config = process.env;

const verifyToken = (req, res, next) => {
  const token = req.headers["authorization"];
  // check if there's no token in the request
  if (!token) {
    return res.status(403).send("A token is required for authentication");
  }
  // Verify the JWT and decode the user ID
  try {
    const decoded = jwt.verify(token, config.TOKEN_KEY);
    // check if the token has expired
     if (decoded.exp < Date.now() / 1000) {
      return res.status(401).send({ message: 'Token has expired.' });
    }
    req.user = decoded;

  } catch (err) {
    res.status(400).send({ message: 'Invalid token.' });
  }
  return next();
}

module.exports = verifyToken;
</code>```

An example of one of the routes i try to access using an authenticated user's token :

```<code>const express = require("express");
const router = express.Router();
const categoryController = require('../controllers/categoryController');
const verifyToken = require('../middleware/auth');

router.get("/get_category", verifyToken,categoryController.get_category);
router.post("/create_category", categoryController.create_category);
router.post("/update_category", categoryController.update_category);
router.get("/delete_category/:_id", categoryController.delete_category);

module.exports = router;
</code>```

Body:
I'm working on a project and i can't seem to able to make jwt work, everytime i try to use authorization in my header and provide a valid token, my server crashes and it gives me the error in the title.
Here's my middleware for jwt :

const jwt = require("jsonwebtoken");

const config = process.env;

const verifyToken = (req, res, next) => {
  const token = req.headers["authorization"];
  // check if there's no token in the request
  if (!token) {
    return res.status(403).send("A token is required for authentication");
  }
  // Verify the JWT and decode the user ID
  try {
    const decoded = jwt.verify(token, config.TOKEN_KEY);
    // check if the token has expired
     if (decoded.exp < Date.now() / 1000) {
      return res.status(401).send({ message: 'Token has expired.' });
    }
    req.user = decoded;

  } catch (err) {
    res.status(400).send({ message: 'Invalid token.' });
  }
  return next();
}

module.exports = verifyToken;

An example of one of the routes i try to access using an authenticated user's token :

const express = require("express");
const router = express.Router();
const categoryController = require('../controllers/categoryController');
const verifyToken = require('../middleware/auth');

router.get("/get_category", verifyToken,categoryController.get_category);
router.post("/create_category", categoryController.create_category);
router.post("/update_category", categoryController.update_category);
router.get("/delete_category/:_id", categoryController.delete_category);

module.exports = router;


问:
Aiogram: how to set up sequential request processing?
I created a telegram bot (using the aiogram module) that runs a joke quiz and random chooses from the list of participants the fool of the day and the handsome of the day. The program consists of several main modules: a module for working with the database and a module where the logic is implemented. (To simplify, I removed everything unnecessary from the code.) The bot works and performs the tasks assigned to it. But there is one detail that doesn't work as we would like. To create interactivity when the user sends a message to start the quiz, the messages generated by the bot are sent with some delay (the pause variable). And if, during the execution of one request, the handsome man of day, for example, starts the second one (fool of day), it will start executing, and as a result, a mess of messages will be obtained. How can I make the second request wait for the first one to finish, and then run?

```<code>from config import token
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
from random import choice
import asyncio

bot = Bot(token)
dp = Dispatcher(bot)
pause = 2.1
name = choice(['Pit', 'Bob', 'Jenny', 'Buthead'])

@dp.message_handler(commands=["fool"])
async def fool(m: types.Message, res=False):
    phrases_pd = [
        "Attention ", "FEDERAL  FOOL WANTED ", "4 - satellite launched ", "3 - Interpol reports verified ",
        "2 - your friends are polled ♂", "1 - your social media profile has been analyzed "
    ]
    for text in phrases_pd:
        await m.answer(text=text)
        await asyncio.sleep(pause)
    await m.answer(text=f"Today is a fool of the day  - {name}!")

@dp.message_handler(commands=["cool"])
async def cool(m: types.Message, res=False):
    phrases_cool = [
        "ROLLING DRUM ", "We are looking for a handsome man in this chat", "Guessing on binary options ", "Analyzing the lunar horoscope ",
        "Lunar prism give me strength ", "SECTOR PRIZE ON THE DRUM "
    ]
    for text in phrases_cool:
        await m.answer(text=text)
        await asyncio.sleep(pause)
    await m.answer(text=f" Today handsome day - {name}")

if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)
</code>```

Body:
I created a telegram bot (using the aiogram module) that runs a joke quiz and random chooses from the list of participants the fool of the day and the handsome of the day. The program consists of several main modules: a module for working with the database and a module where the logic is implemented. (To simplify, I removed everything unnecessary from the code.) The bot works and performs the tasks assigned to it. But there is one detail that doesn't work as we would like. To create interactivity when the user sends a message to start the quiz, the messages generated by the bot are sent with some delay (the pause variable). And if, during the execution of one request, the handsome man of day, for example, starts the second one (fool of day), it will start executing, and as a result, a mess of messages will be obtained. How can I make the second request wait for the first one to finish, and then run?

from config import token
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
from random import choice
import asyncio

bot = Bot(token)
dp = Dispatcher(bot)
pause = 2.1
name = choice(['Pit', 'Bob', 'Jenny', 'Buthead'])

@dp.message_handler(commands=["fool"])
async def fool(m: types.Message, res=False):
    phrases_pd = [
        "Attention ", "FEDERAL  FOOL WANTED ", "4 - satellite launched ", "3 - Interpol reports verified ",
        "2 - your friends are polled ♂", "1 - your social media profile has been analyzed "
    ]
    for text in phrases_pd:
        await m.answer(text=text)
        await asyncio.sleep(pause)
    await m.answer(text=f"Today is a fool of the day  - {name}!")

@dp.message_handler(commands=["cool"])
async def cool(m: types.Message, res=False):
    phrases_cool = [
        "ROLLING DRUM ", "We are looking for a handsome man in this chat", "Guessing on binary options ", "Analyzing the lunar horoscope ",
        "Lunar prism give me strength ", "SECTOR PRIZE ON THE DRUM "
    ]
    for text in phrases_cool:
        await m.answer(text=text)
        await asyncio.sleep(pause)
    await m.answer(text=f" Today handsome day - {name}")

if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)


问:
How to combine objects and write out separately in if statement
In R ,there data object/tibble names are 'data1,data2,data3,data4.....data100'(they are have same structure)

how to combine all of them

how to out put to csv files separately

Below code failed, anyone can help?

```<code>library(tidyverse)
library(data.table)
file <- ls(pattern = 'data')
# rbind to a big dataframe
total_file <- rbindlist(file)

# write object to csv separately
for (i in c(1:100)){
  write.csv(paste0("data",i),paste0("data",i,".csv"))
}
</code>```

Body:
In R ,there data object/tibble names are 'data1,data2,data3,data4.....data100'(they are have same structure)

how to combine all of them

how to out put to csv files separately

Below code failed, anyone can help?

library(tidyverse)
library(data.table)
file <- ls(pattern = 'data')
# rbind to a big dataframe
total_file <- rbindlist(file)

# write object to csv separately
for (i in c(1:100)){
  write.csv(paste0("data",i),paste0("data",i,".csv"))
}


问:
Execution halt as the script not reading csv file
I have created R shiny App and moved that to production. The app is working fine in R studio but once I move to the production it is showing the following error in reading csv file part.

```<code>here() starts at /home/production/workspace.git
Warning in file(file, "rt") :
  cannot open file '/home/production/workspace.git/Shiny_App_for_CFM/status_var_list.csv': No such file or directory
Error in file(file, "rt") : cannot open the connection
Calls: runApp ... eval -> ..stacktraceon.. -> read.csv -> read.table -> file
Execution halted
</code>```

Line of code for reading csv file is included below:

```<code>library(here)
status_var <- read.csv(here('Shiny_App_for_CFM/status_var_list.csv'))
status_var <- data.frame(status_var)
</code>```

Body:
I have created R shiny App and moved that to production. The app is working fine in R studio but once I move to the production it is showing the following error in reading csv file part.

here() starts at /home/production/workspace.git
Warning in file(file, "rt") :
  cannot open file '/home/production/workspace.git/Shiny_App_for_CFM/status_var_list.csv': No such file or directory
Error in file(file, "rt") : cannot open the connection
Calls: runApp ... eval -> ..stacktraceon.. -> read.csv -> read.table -> file
Execution halted

Line of code for reading csv file is included below:

library(here)
status_var <- read.csv(here('Shiny_App_for_CFM/status_var_list.csv'))
status_var <- data.frame(status_var)


问:
AWS S3 Bucket not uploading image in Lambda deployment with error message "Input buffer contains unsupported image format"
I'm currently working with AWS S3 to upload images after processing with sharp, it uploads when I'm testing on my local environment, however, once, it gets into deployment in my Lambda API it shows this error "Input buffer contains unsupported image format". NB: The Lambda function has been given all necessary permissions.

Here's a snapshot of my code:

```<code>const img = req.file;
const fileName = uuid() + '.' + img.originalname.split('.')[1]
const compressedBuffer = await sharp(img.buffer)
  .resize({
    width: 300,
    fit: 'contain'
  })
  .toBuffer()
const uploadedImage = await s3.upload({
  Bucket: config.S3_BUCKET,
  Body: img.buffer,
  Key: 'users/profileImgs/'+fileName,
  ContentType: img.mimetype,
}).promise()
</code>```

Body:
I'm currently working with AWS S3 to upload images after processing with sharp, it uploads when I'm testing on my local environment, however, once, it gets into deployment in my Lambda API it shows this error "Input buffer contains unsupported image format". NB: The Lambda function has been given all necessary permissions.

Here's a snapshot of my code:

const img = req.file;
const fileName = uuid() + '.' + img.originalname.split('.')[1]
const compressedBuffer = await sharp(img.buffer)
  .resize({
    width: 300,
    fit: 'contain'
  })
  .toBuffer()
const uploadedImage = await s3.upload({
  Bucket: config.S3_BUCKET,
  Body: img.buffer,
  Key: 'users/profileImgs/'+fileName,
  ContentType: img.mimetype,
}).promise()


问:
Error View.java (java.lang.IllegalStateException: Fragment already added) only on samsung devices
I'm receiving via crashlitycs this error only by samsung devices.
I cant find why i receive this error, and there is no reference to a specific line in the code.

Stack trace

```<code>Fatal Exception: java.lang.IllegalStateException: Fragment already added
       at androidx.fragment.app.Fragment.setInitialSavedState(Fragment.java:828)
       at androidx.viewpager2.adapter.FragmentStateAdapter.ensureFragment(FragmentStateAdapter.java:269)
       at androidx.viewpager2.adapter.FragmentStateAdapter.onBindViewHolder(FragmentStateAdapter.java:175)
       at androidx.viewpager2.adapter.FragmentStateAdapter.onBindViewHolder(FragmentStateAdapter.java:67)
       at
</code>```

i've already check if fragment isAdded before fragment transactions

```<code>fun loadFragment(fragment: BaseFragment) {
        if(!fragment.isAdded) {
            ...
        }
    }
</code>```

How can i find where is the error?

Full stack trace:

```<code>Fatal Exception: java.lang.IllegalStateException: Fragment already added
       at androidx.fragment.app.Fragment.setInitialSavedState(Fragment.java:828)
       at androidx.viewpager2.adapter.FragmentStateAdapter.ensureFragment(FragmentStateAdapter.java:269)
       at androidx.viewpager2.adapter.FragmentStateAdapter.onBindViewHolder(FragmentStateAdapter.java:175)
       at androidx.viewpager2.adapter.FragmentStateAdapter.onBindViewHolder(FragmentStateAdapter.java:67)
       at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7254)
       at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7337)
       at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6194)
       at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6460)
       at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6300)
       at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6296)
       at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2330)
</code>```

Body:
I'm receiving via crashlitycs this error only by samsung devices.
I cant find why i receive this error, and there is no reference to a specific line in the code.

Stack trace

Fatal Exception: java.lang.IllegalStateException: Fragment already added
       at androidx.fragment.app.Fragment.setInitialSavedState(Fragment.java:828)
       at androidx.viewpager2.adapter.FragmentStateAdapter.ensureFragment(FragmentStateAdapter.java:269)
       at androidx.viewpager2.adapter.FragmentStateAdapter.onBindViewHolder(FragmentStateAdapter.java:175)
       at androidx.viewpager2.adapter.FragmentStateAdapter.onBindViewHolder(FragmentStateAdapter.java:67)
       at

i've already check if fragment isAdded before fragment transactions

fun loadFragment(fragment: BaseFragment) {
        if(!fragment.isAdded) {
            ...
        }
    }

How can i find where is the error?

Full stack trace:

Fatal Exception: java.lang.IllegalStateException: Fragment already added
       at androidx.fragment.app.Fragment.setInitialSavedState(Fragment.java:828)
       at androidx.viewpager2.adapter.FragmentStateAdapter.ensureFragment(FragmentStateAdapter.java:269)
       at androidx.viewpager2.adapter.FragmentStateAdapter.onBindViewHolder(FragmentStateAdapter.java:175)
       at androidx.viewpager2.adapter.FragmentStateAdapter.onBindViewHolder(FragmentStateAdapter.java:67)
       at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7254)
       at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7337)
       at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6194)
       at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6460)
       at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6300)
       at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6296)
       at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2330)


问:
Get back ImmersiveContextMenu in Windows 10
I recently downloaded JAWS Accessibility Program to try to check how screen readers read my website and then it changed some display/graphics settings. It changed my context menu style from Immersive Context Menu to the old-looking classic Context Menu.

I want this:

This is what I have:

I tried editing the registry and turning "ImmersiveContextMenu" in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\FlightedFeatures to 1

Downloading Windows ISO and installing windows on top of the current install (I don't want to reset my PC)

I tried scf /scannow and DISM /Online /Cleanup-Image /RestoreHealth

I don't have a restore point before the time I installed the app.


问:
Why do I need to restart karma?
I'm running some tutorials on Angular and unit testing. I have karma running (npm test), so while coding the tests are conveniently rerun and displayed automatically. This is all according to plan. But on some changes I get this error:

If I then revert the changes I just made, the error still persists even though the tests seems to be automatically rerun. So after this error occurred there seems to be no codechanges I can make to get rid of this error.

The only thing I found that works is to restart karma all together (CTRL+C and npm test).

So: Why does karma get stuck in the error and needs a restart?

Title: Why do I need to restart karma?


问:
Calling ImageMagick from C# (.net 6) on OSX: Getting "Library not loaded"
Im trying to use ImageMagick in a C# application on OSX.

My constraint is that I'm not allowed to install IM on the computer and I can't use homebrew or Magick.Net.

The application downloads ImageMagick-x86_64-apple-darwin20.1.0.tar.gz from https://imagemagick.org/script/download.php and unpacks this to ~/test/

I'm using CliWrap:

```<code>var home = "~/test/ImageMagick-7.0.10/";

var result = await Cli
                .Wrap(home + "magick")
                .WithArguments(new[] { "-quiet", inputPath, outputPath }, true)
                .WhenOSX(builder =>
                    builder.WithEnvironmentVariables(env =>
                        env
                            .Set("MAGICK_HOME", home)
                            .Set("DYLD_LIBRARY_PATH", home + "lib/"
                            .Set("PATH", home + "bin/"))
                    )
                .WithValidation(CommandResultValidation.None)
                .ExecuteBufferedAsync(cts.Token);
</code>```

When running this I'm getting:

```<code>dyld[97894]: Library not loaded: /ImageMagick-7.0.10/lib/libMagickCore-7.Q16HDRI.8.dylib
  Referenced from: /Users/niels/test/ImageMagick-7.0.10/bin/magick
  Reason: tried: '/ImageMagick-7.0.10/lib/libMagickCore-7.Q16HDRI.8.dylib' (no such file), '/usr/local/lib/libMagickCore-7.Q16HDRI.8.dylib' (no such file), '/usr/lib/libMagickCore-7.Q16HDRI.8.dylib' (no such file)
</code>```

What can I do?

Body:
Im trying to use ImageMagick in a C# application on OSX.

My constraint is that I'm not allowed to install IM on the computer and I can't use homebrew or Magick.Net.

The application downloads ImageMagick-x86_64-apple-darwin20.1.0.tar.gz from https://imagemagick.org/script/download.php and unpacks this to ~/test/

I'm using CliWrap:

var home = "~/test/ImageMagick-7.0.10/";

var result = await Cli
                .Wrap(home + "magick")
                .WithArguments(new[] { "-quiet", inputPath, outputPath }, true)
                .WhenOSX(builder =>
                    builder.WithEnvironmentVariables(env =>
                        env
                            .Set("MAGICK_HOME", home)
                            .Set("DYLD_LIBRARY_PATH", home + "lib/"
                            .Set("PATH", home + "bin/"))
                    )
                .WithValidation(CommandResultValidation.None)
                .ExecuteBufferedAsync(cts.Token);

When running this I'm getting:

dyld[97894]: Library not loaded: /ImageMagick-7.0.10/lib/libMagickCore-7.Q16HDRI.8.dylib
  Referenced from: /Users/niels/test/ImageMagick-7.0.10/bin/magick
  Reason: tried: '/ImageMagick-7.0.10/lib/libMagickCore-7.Q16HDRI.8.dylib' (no such file), '/usr/local/lib/libMagickCore-7.Q16HDRI.8.dylib' (no such file), '/usr/lib/libMagickCore-7.Q16HDRI.8.dylib' (no such file)

What can I do?


问:
WinForms OnInputLanguageChanging is not raised
I'm trying to override

```<code>protected override void OnInputLanguageChanging(System.Windows.Forms.InputLanguageChangingEventArgs e)
{
}
</code>```

In my Main Form class C# app (Tested on .NET Framework 4.7.2 and 4.8)

The expectation is to have it called, when the user tries to change the Windows language. Unfortunatelly it doesn't work, the method is not called, however the method OnInputLanguageChanged works perfectly but it's too late for me.
Is there any trick to have OnInputLanguageChanging working?
Thanks

Body:
I'm trying to override

protected override void OnInputLanguageChanging(System.Windows.Forms.InputLanguageChangingEventArgs e)
{
}

In my Main Form class C# app (Tested on .NET Framework 4.7.2 and 4.8)

The expectation is to have it called, when the user tries to change the Windows language. Unfortunatelly it doesn't work, the method is not called, however the method OnInputLanguageChanged works perfectly but it's too late for me.
Is there any trick to have OnInputLanguageChanging working?
Thanks


问:
Shopify - Can not get the authorization code from the redirect URL
I have created a shopify partner account and also created an APP that app has the client id and secret key. Now, I need to implement the shopify oauth system. To do that I am preparing the URL like this:

```<code>$shop  = '489207-2'; // Some shop name
$client_id = 'my-client-id';
$scope = 'write_products,read_shipping';
$redirect_uri = 'http://localhost:8888/practice/shopify/redirect.php';

$redirect_url  = "https://{$shop}.myshopify.com/admin/oauth/authorize?client_id={$client_id}&scope={$scope}&redirect_uri={$redirect_uri}&access_mode=per-user";
echo $redirect_url;
</code>```

So above code is generating a link and after click on that link I redirect to ths page:

Now why I can not click on the Install app button? Why it is disabled?

That was my code to test the oauth.

But I have tried another way which is from the Test your app section.

when I click on Select store its showing me this page:

Now, when I click on this Tidy Shopping Deelopment link it's redirect me to this link:

```<code>http://localhost:8888/practice/shopify/?hmac=c17c458f95d9237cbbfeff9acdcd99191e0c44eeed5d7424ec3cfe602942afaf&host=dGlkeS1zaG9wcGluZy1kZXZlbG9wbWVudC5teXNob3BpZnkuY29tL2FkbWlu&shop=tidy-shopping-development.myshopify.com&timestamp=1673514817
</code>```

Here I can't see the authorization code, why?

Body:
I have created a shopify partner account and also created an APP that app has the client id and secret key. Now, I need to implement the shopify oauth system. To do that I am preparing the URL like this:

$shop  = '489207-2'; // Some shop name
$client_id = 'my-client-id';
$scope = 'write_products,read_shipping';
$redirect_uri = 'http://localhost:8888/practice/shopify/redirect.php';

$redirect_url  = "https://{$shop}.myshopify.com/admin/oauth/authorize?client_id={$client_id}&scope={$scope}&redirect_uri={$redirect_uri}&access_mode=per-user";
echo $redirect_url;

So above code is generating a link and after click on that link I redirect to ths page:

Now why I can not click on the Install app button? Why it is disabled?

That was my code to test the oauth.

But I have tried another way which is from the Test your app section.

when I click on Select store its showing me this page:

Now, when I click on this Tidy Shopping Deelopment link it's redirect me to this link:

http://localhost:8888/practice/shopify/?hmac=c17c458f95d9237cbbfeff9acdcd99191e0c44eeed5d7424ec3cfe602942afaf&host=dGlkeS1zaG9wcGluZy1kZXZlbG9wbWVudC5teXNob3BpZnkuY29tL2FkbWlu&shop=tidy-shopping-development.myshopify.com&timestamp=1673514817

Here I can't see the authorization code, why?


问:
Is there any solution for showing footer conditionally in jspdf?
I'm having 3 options
1- show footer on all pages
2- show the footer on the first page only
3- show the footer on the last page only

I'm done with this part if we select 1st option its shows the footer perfectly on the first page but it's taking space on other pages as well. it should be not like this if we select to show the footer only first page it should not take up space on the second page and other pages.

same as it is if we select the 2nd option to show the footer on the last page only. it is showing perfectly on the last page only but it's taking space on the first page and other pages as well.

Does anyone have a solution?


问:
Custom field referance in nestjs/mogoose
This is code I am using to populate variants in product documents which is linked on custom field (variantId) but still I am not to fetch data correctly.

I have searched and found out about the virtual population in the mongoose library but nestjs/mongoose is unable to do it.

Please guide me how we can achieve this in nestjs.

```<code>export class Product {

  @Prop()
  productID: string;

  @Prop([{ type: [String], required: true, ref: VARIANT_MODEL }])
  variants: string[] | Variant[];

  @Prop({ default: true })
  isActive: boolean;

  @Prop({ default: false })
  isDeleted: boolean;

}

export type ProductDocument = Product & Document;
export const ProductSchema = SchemaFactory.createForClass(Product);
export const PRODUCT_MODEL = Product.name;
ProductSchema.virtual(PRODUCT_MODEL, {
  ref: VARIANT_MODEL,
  localField: 'variants',
  foreignField: 'variantId',
});

export class Variant {
  @Prop({ required: true })
  variantId: string;

  @Prop({ default: true })
  isActive: boolean;

  @Prop({ default: false })
  isDeleted: boolean;
}

export type VariantDocument = Variant & Document;
export const VariantSchema = SchemaFactory.createForClass(Variant);
export const VARIANT_MODEL = Variant.name;

</code>```

Body:
This is code I am using to populate variants in product documents which is linked on custom field (variantId) but still I am not to fetch data correctly.

I have searched and found out about the virtual population in the mongoose library but nestjs/mongoose is unable to do it.

Please guide me how we can achieve this in nestjs.

export class Product {

  @Prop()
  productID: string;

  @Prop([{ type: [String], required: true, ref: VARIANT_MODEL }])
  variants: string[] | Variant[];

  @Prop({ default: true })
  isActive: boolean;

  @Prop({ default: false })
  isDeleted: boolean;

}

export type ProductDocument = Product & Document;
export const ProductSchema = SchemaFactory.createForClass(Product);
export const PRODUCT_MODEL = Product.name;
ProductSchema.virtual(PRODUCT_MODEL, {
  ref: VARIANT_MODEL,
  localField: 'variants',
  foreignField: 'variantId',
});

export class Variant {
  @Prop({ required: true })
  variantId: string;

  @Prop({ default: true })
  isActive: boolean;

  @Prop({ default: false })
  isDeleted: boolean;
}

export type VariantDocument = Variant & Document;
export const VariantSchema = SchemaFactory.createForClass(Variant);
export const VARIANT_MODEL = Variant.name;