问:
Passing Numbers to a Sympy function in Python
I am practicing Python from Codewars. One of the questions was to take a function as an input given in string from, differentiate it and use the other input given as an integer and return the result. For example lets say the inputs are

```<code>stringf=x**2+2x
inputint=3
</code>```

def differentiate(stringf,inputint) should return 8. I managed to do this by using Sympy and eval. However when I take the derivate of the function with sympy.diff it converts a regular lambda function to something else which you cannot pass arguments. For example you can do f(1) in below code but you cannot do deffunc(1) it throws the error "TypeError: 'Add' object is not callable" because the type of deffunc becomes "<class 'sympy.core.add.Add'>" after sympy.diff.

```<code>def differentiate(equation, point):
    import sympy as sym

    f=lambda x:equation            #turn the string into a formula with x

    x= sym.symbols('x')
    deffunc=sym.diff(f(x),x)       #differentiate with respect to x

    strfunc=str(deffunc)           #convert the function to a string to be used in eval
    x=point
    f=eval(strfunc)

    return f
</code>```

I found a workaround by simply converting it to string then using eval but I was wondering is there a better way to pass the 'point' into the 'deffunc'?

Body:
I am practicing Python from Codewars. One of the questions was to take a function as an input given in string from, differentiate it and use the other input given as an integer and return the result. For example lets say the inputs are

stringf=x**2+2x
inputint=3

def differentiate(stringf,inputint) should return 8. I managed to do this by using Sympy and eval. However when I take the derivate of the function with sympy.diff it converts a regular lambda function to something else which you cannot pass arguments. For example you can do f(1) in below code but you cannot do deffunc(1) it throws the error "TypeError: 'Add' object is not callable" because the type of deffunc becomes "<class 'sympy.core.add.Add'>" after sympy.diff.

def differentiate(equation, point):
    import sympy as sym

    f=lambda x:equation            #turn the string into a formula with x

    x= sym.symbols('x')
    deffunc=sym.diff(f(x),x)       #differentiate with respect to x

    strfunc=str(deffunc)           #convert the function to a string to be used in eval
    x=point
    f=eval(strfunc)

    return f

I found a workaround by simply converting it to string then using eval but I was wondering is there a better way to pass the 'point' into the 'deffunc'?


来源: stackexchange

问:
how to make BERT predict new token
my problem looks like this:

```<code>tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForMaskedLM.from_pretrained('bert-base-uncased')
fill_mask_pipeline_pre = pipeline("fill-mask", model=model, tokenizer=tokenizer)
sentence_test = "Olaf is the chancellor of germany. [MASK] is the chancellor of germany."
prediction = fill_mask_pipeline_pre(sentence_test)[:3]
</code>```

--> the 1st prediction is "Olaf", which is the result I wanted.

However, if sentence_test is this:

```<code>sentence_test = "Scholz is the chancellor of germany. [MASK] is the chancellor of germany."
</code>```

... I want the prediction to be "Scholz".

Unfortunately this in never predicted, because BERT does not know the word Scholz.
BertTokenizer.from_pretrained('bert-base-uncased') turns Scholz into "sc" and  "##holz" .

**Is there a way how the new token can be predicted?
**

I tried adding the token to the tokenizer, but it still isn't predicted.

I also fine- tuned the model on text that contains the word "Scholz" a lot after adding the new word to the tokenizer, but it does not work either.

ContentLicense: CC BY-SA 4.0

Title: how to make BERT predict new token

Body:
my problem looks like this:

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForMaskedLM.from_pretrained('bert-base-uncased')
fill_mask_pipeline_pre = pipeline("fill-mask", model=model, tokenizer=tokenizer)
sentence_test = "Olaf is the chancellor of germany. [MASK] is the chancellor of germany."
prediction = fill_mask_pipeline_pre(sentence_test)[:3]

--> the 1st prediction is "Olaf", which is the result I wanted.

However, if sentence_test is this:

sentence_test = "Scholz is the chancellor of germany. [MASK] is the chancellor of germany."

... I want the prediction to be "Scholz".

Unfortunately this in never predicted, because BERT does not know the word Scholz.
BertTokenizer.from_pretrained('bert-base-uncased') turns Scholz into "sc" and  "##holz" .

**Is there a way how the new token can be predicted?
**

I tried adding the token to the tokenizer, but it still isn't predicted.

I also fine- tuned the model on text that contains the word "Scholz" a lot after adding the new word to the tokenizer, but it does not work either.


问:
Java Abstract Super Class is Being Ignored
I have a multi-project Java project set up using Gradle. Project B is dependent on Project A and imported via Gradle dependencies. Everything compiles just fine except for one class in Project B that extends an abstract class in Project A. This abstract class implements an interface in a library that I'm using. When I go to build the project I get the following error:

ExNihiloAELootTables is not abstract and does not override abstract method getName() in DataProvider (edited)

The abstract super class implements the method in question and so it appears that the abstract super class is being ignored/skipped over. While debugging, I copied the abstract class into the same package as the instance class, which fixed the issue, however other classes from Project A are being used and recognized in Project B without being copied over, so this is not a good fix.

I am at a loss at this point about what the issue may be. Any help would be appreciated.

Here is the project structure:

```<code>Main Project
|
+-- build.gradle
+-- settings.gradle
|
+-- Project A
|  |
|  +-- build.gradle
|  \-- Abstract Class
|
+-- Project B
|  |
|  +-- build.gradle
|  \-- Instance Class that extends Abstract Class from A
</code>```

Project repo and branch for reference: https://github.com/NovaMachina-Mods/ExNihiloSequentia/tree/sub-project-refactoring
(This branch is in the middle of a major refactor and so its pretty ugly right now.)

Edit:

Abstract Class from Project A

package novamachina.exnihilosequentia.datagen.api;

import com.google.common.collect.Multimap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mojang.logging.LogUtils;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DataProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.storage.loot.LootPool;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.LootTables;
import net.minecraft.world.level.storage.loot.ValidationContext;
import net.minecraft.world.level.storage.loot.entries.LootItem;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import net.minecraft.world.level.storage.loot.predicates.ExplosionCondition;
import net.minecraft.world.level.storage.loot.providers.number.ConstantValue;
import net.minecraftforge.registries.ForgeRegistries;
import novamachina.exnihilosequentia.common.utility.ExNihiloLogger;

public abstract class AbstractLootTableGenerator implements DataProvider {

  @Nonnull
  private static final Gson GSON =
      (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().create();

  @Nonnull private static final ExNihiloLogger logger = new ExNihiloLogger(LogUtils.getLogger());
  @Nonnull protected final Map<ResourceLocation, LootTable> lootTables = new HashMap<>();
  @Nonnull private final DataGenerator generator;
  @Nonnull private final String modId;

  protected AbstractLootTableGenerator(
      @Nonnull final DataGenerator generator, @Nonnull final String modId) {
    this.generator = generator;
    this.modId = modId;
  }

  @Override
  public void run(@Nonnull final CachedOutput cache) {
    lootTables.clear();
    @Nonnull final Path outFolder = generator.getOutputFolder();

    createLootTables();

    @Nonnull
    final ValidationContext validator =
        new ValidationContext(LootContextParamSets.ALL_PARAMS, function -> null, lootTables::get);
    lootTables.forEach((name, table) -> LootTables.validate(validator, name, table));
    @Nonnull final Multimap<String, String> problems = validator.getProblems();
    if (!problems.isEmpty()) {
      problems.forEach(
          (name, table) -> logger.warn("Found validation problem in " + name + ": " + table));
      throw new IllegalStateException("Failed to validate loot tables, see logs");
    } else {
      lootTables.forEach(
          (name, table) -> {
            @Nonnull final Path out = getPath(outFolder, name);

            try {
              DataProvider.saveStable(cache, LootTables.serialize(table), out);
            } catch (IOException e) {
              logger.error("Couldn't save loot table " + out);
              logger.error(Arrays.toString(e.getStackTrace()));
            }
          });
    }
  }

  @Nonnull
  @Override
  public String getName() {
    return "Loot Tables: " + modId;
  }

  @Nonnull
  protected LootPool.Builder createLootPoolBuilder() {
    return LootPool.lootPool().when(ExplosionCondition.survivesExplosion());
  }

  protected abstract void createLootTables();

  protected void register(@Nonnull final Block block, @Nonnull final LootPool.Builder... pools) {
    @Nonnull final LootTable.Builder builder = LootTable.lootTable();
    for (@Nonnull final LootPool.Builder pool : pools) {
      builder.withPool(pool);
    }
    register(block, builder);
  }

  protected void registerSelfDrop(@Nonnull final Block block) {
    register(block, singleItem(block));
  }

  @Nonnull
  private Path getPath(@Nonnull final Path outFolder, @Nonnull final ResourceLocation name) {
    return outFolder.resolve(
        "data/" + name.getNamespace() + "/loot_tables/" + name.getPath() + ".json");
  }

  private void register(@Nonnull final Block block, @Nonnull final LootTable.Builder table) {
    @Nullable final ResourceLocation resourceLocation = ForgeRegistries.BLOCKS.getKey(block);
    if (resourceLocation == null) {
      return;
    }
    register(resourceLocation, table);
  }

  private void register(
      @Nonnull final ResourceLocation registryName, @Nonnull final LootTable.Builder table) {
    if (lootTables.put(
            toTableLoc(registryName), table.setParamSet(LootContextParamSets.BLOCK).build())
        != null) {
      throw new IllegalStateException("Duplicate loot table: " + table);
    }
  }

  @Nonnull
  private LootPool.Builder singleItem(@Nonnull final ItemLike in) {
    return createLootPoolBuilder()
        .setRolls(ConstantValue.exactly(1))
        .add(LootItem.lootTableItem(in));
  }

  @Nonnull
  private ResourceLocation toTableLoc(@Nonnull final ResourceLocation registryName) {
    return new ResourceLocation(registryName.getNamespace(), "blocks/" + registryName.getPath());
  }
}

```
<p>Implemented Class from Project B:</p>
<pre class="lang-java prettyprint-override"><code>package novamachina.exnihiloae.datagen.common;

import net.minecraft.data.DataGenerator;
import novamachina.exnihiloae.common.init.ExNihiloAEBlocks;
import novamachina.exnihiloae.common.utility.ExNihiloAEConstants;
import novamachina.exnihilosequentia.datagen.api.AbstractLootTableGenerator;

public class ExNihiloAELootTables extends AbstractLootTableGenerator {

  public ExNihiloAELootTables(DataGenerator generator) {
    super(generator, ExNihiloAEConstants.ModIds.EX_NIHILO_AE);
  }

  @Override
  protected void createLootTables() {
    registerSelfDrop(ExNihiloAEBlocks.CRUSHED_SKYSTONE.get());
  }
}
</code>```

Body:
I have a multi-project Java project set up using Gradle. Project B is dependent on Project A and imported via Gradle dependencies. Everything compiles just fine except for one class in Project B that extends an abstract class in Project A. This abstract class implements an interface in a library that I'm using. When I go to build the project I get the following error:

ExNihiloAELootTables is not abstract and does not override abstract method getName() in DataProvider (edited)

The abstract super class implements the method in question and so it appears that the abstract super class is being ignored/skipped over. While debugging, I copied the abstract class into the same package as the instance class, which fixed the issue, however other classes from Project A are being used and recognized in Project B without being copied over, so this is not a good fix.

I am at a loss at this point about what the issue may be. Any help would be appreciated.

Here is the project structure:

Main Project
|
+-- build.gradle
+-- settings.gradle
|
+-- Project A
|  |
|  +-- build.gradle
|  \-- Abstract Class
|
+-- Project B
|  |
|  +-- build.gradle
|  \-- Instance Class that extends Abstract Class from A

Project repo and branch for reference: https://github.com/NovaMachina-Mods/ExNihiloSequentia/tree/sub-project-refactoring
(This branch is in the middle of a major refactor and so its pretty ugly right now.)

Edit:

Abstract Class from Project A

package novamachina.exnihilosequentia.datagen.api;

import com.google.common.collect.Multimap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mojang.logging.LogUtils;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DataProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.storage.loot.LootPool;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.LootTables;
import net.minecraft.world.level.storage.loot.ValidationContext;
import net.minecraft.world.level.storage.loot.entries.LootItem;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import net.minecraft.world.level.storage.loot.predicates.ExplosionCondition;
import net.minecraft.world.level.storage.loot.providers.number.ConstantValue;
import net.minecraftforge.registries.ForgeRegistries;
import novamachina.exnihilosequentia.common.utility.ExNihiloLogger;

public abstract class AbstractLootTableGenerator implements DataProvider {

  @Nonnull
  private static final Gson GSON =
      (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().create();

  @Nonnull private static final ExNihiloLogger logger = new ExNihiloLogger(LogUtils.getLogger());
  @Nonnull protected final Map<ResourceLocation, LootTable> lootTables = new HashMap<>();
  @Nonnull private final DataGenerator generator;
  @Nonnull private final String modId;

  protected AbstractLootTableGenerator(
      @Nonnull final DataGenerator generator, @Nonnull final String modId) {
    this.generator = generator;
    this.modId = modId;
  }

  @Override
  public void run(@Nonnull final CachedOutput cache) {
    lootTables.clear();
    @Nonnull final Path outFolder = generator.getOutputFolder();

    createLootTables();

    @Nonnull
    final ValidationContext validator =
        new ValidationContext(LootContextParamSets.ALL_PARAMS, function -> null, lootTables::get);
    lootTables.forEach((name, table) -> LootTables.validate(validator, name, table));
    @Nonnull final Multimap<String, String> problems = validator.getProblems();
    if (!problems.isEmpty()) {
      problems.forEach(
          (name, table) -> logger.warn("Found validation problem in " + name + ": " + table));
      throw new IllegalStateException("Failed to validate loot tables, see logs");
    } else {
      lootTables.forEach(
          (name, table) -> {
            @Nonnull final Path out = getPath(outFolder, name);

            try {
              DataProvider.saveStable(cache, LootTables.serialize(table), out);
            } catch (IOException e) {
              logger.error("Couldn't save loot table " + out);
              logger.error(Arrays.toString(e.getStackTrace()));
            }
          });
    }
  }

  @Nonnull
  @Override
  public String getName() {
    return "Loot Tables: " + modId;
  }

  @Nonnull
  protected LootPool.Builder createLootPoolBuilder() {
    return LootPool.lootPool().when(ExplosionCondition.survivesExplosion());
  }

  protected abstract void createLootTables();

  protected void register(@Nonnull final Block block, @Nonnull final LootPool.Builder... pools) {
    @Nonnull final LootTable.Builder builder = LootTable.lootTable();
    for (@Nonnull final LootPool.Builder pool : pools) {
      builder.withPool(pool);
    }
    register(block, builder);
  }

  protected void registerSelfDrop(@Nonnull final Block block) {
    register(block, singleItem(block));
  }

  @Nonnull
  private Path getPath(@Nonnull final Path outFolder, @Nonnull final ResourceLocation name) {
    return outFolder.resolve(
        "data/" + name.getNamespace() + "/loot_tables/" + name.getPath() + ".json");
  }

  private void register(@Nonnull final Block block, @Nonnull final LootTable.Builder table) {
    @Nullable final ResourceLocation resourceLocation = ForgeRegistries.BLOCKS.getKey(block);
    if (resourceLocation == null) {
      return;
    }
    register(resourceLocation, table);
  }

  private void register(
      @Nonnull final ResourceLocation registryName, @Nonnull final LootTable.Builder table) {
    if (lootTables.put(
            toTableLoc(registryName), table.setParamSet(LootContextParamSets.BLOCK).build())
        != null) {
      throw new IllegalStateException("Duplicate loot table: " + table);
    }
  }

  @Nonnull
  private LootPool.Builder singleItem(@Nonnull final ItemLike in) {
    return createLootPoolBuilder()
        .setRolls(ConstantValue.exactly(1))
        .add(LootItem.lootTableItem(in));
  }

  @Nonnull
  private ResourceLocation toTableLoc(@Nonnull final ResourceLocation registryName) {
    return new ResourceLocation(registryName.getNamespace(), "blocks/" + registryName.getPath());
  }
}

Implemented Class from Project B:

package novamachina.exnihiloae.datagen.common;

import net.minecraft.data.DataGenerator;
import novamachina.exnihiloae.common.init.ExNihiloAEBlocks;
import novamachina.exnihiloae.common.utility.ExNihiloAEConstants;
import novamachina.exnihilosequentia.datagen.api.AbstractLootTableGenerator;

public class ExNihiloAELootTables extends AbstractLootTableGenerator {

  public ExNihiloAELootTables(DataGenerator generator) {
    super(generator, ExNihiloAEConstants.ModIds.EX_NIHILO_AE);
  }

  @Override
  protected void createLootTables() {
    registerSelfDrop(ExNihiloAEBlocks.CRUSHED_SKYSTONE.get());
  }
}


问:
Throws java.lang.IllegalStateException: block()/blockFirst()/blockLast() when retrying invalid token
I am trying to update the token when I get a response with 401 status code.

In order to do that, I used web client. I know that this mainly used to do reactive development but since resttemplate will soon be deprecated I went for this option.

The issue I am facing is that when it does call the api endpoint to get the new token, it throws a 'java.lang.IllegalStateException: block()/blockFirst()/blockLast() '. And make sense as it stated in the exception message It is not supported in thread reactor-http-nio-3.

I saw that there is a map and flatmap option, but I couldn't figure out how to use it inside the doBeforeRetry() to make it process in a different stream.

I need to have that new token before retrying.

So the question is : How can I get the token via another call and then still do the retry ?

I was able to make it work by using a try catch but I would like to find the solution how to use it inside that retry method.

I also try to block the token request by replacing the token response by a Mono and block it by using myMono.toFuture().get() as stated here block()/blockFirst()/blockLast() are blocking error when calling bodyToMono AFTER exchange()

Here is the code :

Method responsible for the call :

```<code>public String getValueFromApi(HashMap<String, Object> filter) {
        String response = "";

        response = webclient
                .post()
                .uri(endpoint)
                .header("token", token.getToken())
                .bodyValue(filter)
                .retrieve()
                .bodyToMono(String.class)
                .retryWhen(Retry.max(3).doBeforeRetry(
                        retrySignal -> tokenService.getTokenFromApi(env)
                ).filter(InvalidTokenException.class::isInstance))
                .block();

        return response;
    }
</code>```

Method that retrieve the token :

```<code>public void getTokenFromApi(Environment env) {
        HashMap<String, String> requestBody = new HashMap<>();
        requestBody.put("name", "name");
        requestBody.put("password", "password");

        String response = WebClient
                .builder()
                .baseUrl(BASE_PATH)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .build()
                .post()
                .uri(tokenUri)
                .body(BodyInserters.fromValue(requestBody))
                .retrieve()
                .bodyToMono(String.class)
                .block();

        getTokenFromResponse(response);
    }

    private void getTokenFromResponse(String reponse) {
        JsonObject tokenObject = new Gson().fromJson(reponse, JsonObject.class);
        setToken(tokenObject.get("token").getAsString());
    }
</code>```

WebClient Builder :

```<code> @Bean
    public WebClient webClientForApi(WebClient.Builder webClientBuilder) {
        return webClientBuilder
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .filter(errorHandler())
                .filter(logRequest())
                .clone()
                .baseUrl(BASE_PATH)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.ACCEPT, "application/json")
                .build();
    }

    public ExchangeFilterFunction errorHandler() {
        return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            if (clientResponse.statusCode().equals(HttpStatus.UNAUTHORIZED)) {
                return Mono.error(InvalidTokenException::new);
            } else if (clientResponse.statusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
                return Mono.error(ApiInternalServerException::new);
            } else {
                return Mono.just(clientResponse);
            }
        });
    }

    private ExchangeFilterFunction logRequest() {
        return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
            logger.info("Request: {} {}", clientRequest.method(), clientRequest.url());
            clientRequest.headers().forEach((name, values) -> values.forEach(value -> logger.info("{}={}", name, value)));
            return Mono.just(clientRequest);
        });
    }
</code>```

Body:
I am trying to update the token when I get a response with 401 status code.

In order to do that, I used web client. I know that this mainly used to do reactive development but since resttemplate will soon be deprecated I went for this option.

The issue I am facing is that when it does call the api endpoint to get the new token, it throws a 'java.lang.IllegalStateException: block()/blockFirst()/blockLast() '. And make sense as it stated in the exception message It is not supported in thread reactor-http-nio-3.

I saw that there is a map and flatmap option, but I couldn't figure out how to use it inside the doBeforeRetry() to make it process in a different stream.

I need to have that new token before retrying.

So the question is : How can I get the token via another call and then still do the retry ?

I was able to make it work by using a try catch but I would like to find the solution how to use it inside that retry method.

I also try to block the token request by replacing the token response by a Mono and block it by using myMono.toFuture().get() as stated here block()/blockFirst()/blockLast() are blocking error when calling bodyToMono AFTER exchange()

Here is the code :

Method responsible for the call :

public String getValueFromApi(HashMap<String, Object> filter) {
        String response = "";

        response = webclient
                .post()
                .uri(endpoint)
                .header("token", token.getToken())
                .bodyValue(filter)
                .retrieve()
                .bodyToMono(String.class)
                .retryWhen(Retry.max(3).doBeforeRetry(
                        retrySignal -> tokenService.getTokenFromApi(env)
                ).filter(InvalidTokenException.class::isInstance))
                .block();

        return response;
    }

Method that retrieve the token :

public void getTokenFromApi(Environment env) {
        HashMap<String, String> requestBody = new HashMap<>();
        requestBody.put("name", "name");
        requestBody.put("password", "password");

        String response = WebClient
                .builder()
                .baseUrl(BASE_PATH)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .build()
                .post()
                .uri(tokenUri)
                .body(BodyInserters.fromValue(requestBody))
                .retrieve()
                .bodyToMono(String.class)
                .block();

        getTokenFromResponse(response);
    }

    private void getTokenFromResponse(String reponse) {
        JsonObject tokenObject = new Gson().fromJson(reponse, JsonObject.class);
        setToken(tokenObject.get("token").getAsString());
    }

WebClient Builder :

 @Bean
    public WebClient webClientForApi(WebClient.Builder webClientBuilder) {
        return webClientBuilder
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .filter(errorHandler())
                .filter(logRequest())
                .clone()
                .baseUrl(BASE_PATH)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.ACCEPT, "application/json")
                .build();
    }

    public ExchangeFilterFunction errorHandler() {
        return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            if (clientResponse.statusCode().equals(HttpStatus.UNAUTHORIZED)) {
                return Mono.error(InvalidTokenException::new);
            } else if (clientResponse.statusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
                return Mono.error(ApiInternalServerException::new);
            } else {
                return Mono.just(clientResponse);
            }
        });
    }

    private ExchangeFilterFunction logRequest() {
        return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
            logger.info("Request: {} {}", clientRequest.method(), clientRequest.url());
            clientRequest.headers().forEach((name, values) -> values.forEach(value -> logger.info("{}={}", name, value)));
            return Mono.just(clientRequest);
        });
    }


问:
MS Access 'error 9 subscript out of range' saving an Excel workbook with VBA
I have an Access database split into a front and back-end, still using the mdb file format as user level security is required.  Part of the db functionality is to create reports in Excel (via VBA).  One of my routines uses a blank excel workbook as a template and copies it to paste the report data into. Users in the office have MS Office 365 on their desktop machines and each user has their own copy of the front-end database.  The back end database sits on a server.  These users have always been able to run this report and when I recently gave them an updated copy of the front-end they could still run this report.  There was no change to the code that creates this report in the updated front-end database.

However there are some remote users on RDS.  They were using a previous version of Office and this report worked.  They were updated to Office 365 and the report worked.  I gave them the updated front-end and they could not run the report.  Below is the code:

```<code>Dim objExcel As Excel.Application
Dim objReportDataWrkbk As Excel.Workbook

'open Excel
On Error Resume Next
'Try first to use an existing instance.
Set objExcel = GetObject(, "Excel.Application")
If Err Then
    'Excel wasnt running
     Set objExcel = CreateObject("Excel.Application")
End If
On Error GoTo Err_ExportExternalReferralDataToExcel

'copy Excel template
objExcel.SheetsInNewWorkbook = 5
Set objReportDataWrkbk = objExcel.Workbooks.Add(strPathToExportTemplateFiles & strTemplateName)
objReportDataWrkbk.SaveAs strPathToTempExportFolder & strFileName
</code>```

For RDS users the SaveAs line throws the error 'Error 9 subscript out of range'

I have stepped through the code and the part that starts Excel works - I can see Excel open.
The line that copies the workbook works - I can see the workbook open in Excel.
It hits the SaveAs line and I get my error.

I have done a Debug.Print of strPathToTempExportFolder & strFileName - and the path is valid and the file name is not something odd that may prompt an error.
I have tried modifying strPathToTempExportFolder to save in another location and I still get the error.
I am told by the office IT that the users have relevant network permissions to copy files and save files in the locations I have been trying.
Is there something blindingly obvious that I am missing here.  Any help greatly appreciated.

Body:
I have an Access database split into a front and back-end, still using the mdb file format as user level security is required.  Part of the db functionality is to create reports in Excel (via VBA).  One of my routines uses a blank excel workbook as a template and copies it to paste the report data into. Users in the office have MS Office 365 on their desktop machines and each user has their own copy of the front-end database.  The back end database sits on a server.  These users have always been able to run this report and when I recently gave them an updated copy of the front-end they could still run this report.  There was no change to the code that creates this report in the updated front-end database.

However there are some remote users on RDS.  They were using a previous version of Office and this report worked.  They were updated to Office 365 and the report worked.  I gave them the updated front-end and they could not run the report.  Below is the code:

Dim objExcel As Excel.Application
Dim objReportDataWrkbk As Excel.Workbook

'open Excel
On Error Resume Next
'Try first to use an existing instance.
Set objExcel = GetObject(, "Excel.Application")
If Err Then
    'Excel wasnt running
     Set objExcel = CreateObject("Excel.Application")
End If
On Error GoTo Err_ExportExternalReferralDataToExcel

'copy Excel template
objExcel.SheetsInNewWorkbook = 5
Set objReportDataWrkbk = objExcel.Workbooks.Add(strPathToExportTemplateFiles & strTemplateName)
objReportDataWrkbk.SaveAs strPathToTempExportFolder & strFileName

For RDS users the SaveAs line throws the error 'Error 9 subscript out of range'

I have stepped through the code and the part that starts Excel works - I can see Excel open.
The line that copies the workbook works - I can see the workbook open in Excel.
It hits the SaveAs line and I get my error.

I have done a Debug.Print of strPathToTempExportFolder & strFileName - and the path is valid and the file name is not something odd that may prompt an error.
I have tried modifying strPathToTempExportFolder to save in another location and I still get the error.
I am told by the office IT that the users have relevant network permissions to copy files and save files in the locations I have been trying.
Is there something blindingly obvious that I am missing here.  Any help greatly appreciated.


问:
Trying to return error message for bad credentials on login form on Thymeleaf
This is my LoginController

```<code> @PostMapping("/login")
 @Transactional
public String login(@Valid @ModelAttribute("login") LoginRequest loginRequest, BindingResult result, HttpServletResponse response, Model model) {
    Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

    boolean no = authentication.isAuthenticated();
    if (!no) {
        model.addAttribute("loginError", true);
        logger.info("User is not auth");
        return "form_login";
    }

    SecurityContextHolder.getContext().setAuthentication(authentication);
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(user);
    response.addHeader(HttpHeaders.SET_COOKIE, jwtCookie.toString());

    model.addAttribute("login", loginRequest);

    return "redirect:/api/test/homePage";

}
</code>```

As you can see, I want to check is user authenticated, I mean does user insert good credentials. You can see that I tried like this:

```<code>   boolean no = authentication.isAuthenticated();
    if (!no) {
        model.addAttribute("loginError", true);
        logger.info("User is not auth");
        return "form_login";
    }
</code>```

But that return me a Whitelabel Error Page with 403 Forbidden, while I want to display error message on Thymeleaf user.

This is in thymeleaf:

```<code><p th:if="${loginError}" class="error">Wrong user or password</p>
</code>```

How I can check user credentials that he insert so if he enter wrong credentials show him wrong password/username?

Also my logger.info("User is not auth"); is not being printed even when user enter wrong credentials but I get 403 Forbidden.

Body:
This is my LoginController

 @PostMapping("/login")
 @Transactional
public String login(@Valid @ModelAttribute("login") LoginRequest loginRequest, BindingResult result, HttpServletResponse response, Model model) {
    Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

    boolean no = authentication.isAuthenticated();
    if (!no) {
        model.addAttribute("loginError", true);
        logger.info("User is not auth");
        return "form_login";
    }

    SecurityContextHolder.getContext().setAuthentication(authentication);
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(user);
    response.addHeader(HttpHeaders.SET_COOKIE, jwtCookie.toString());

    model.addAttribute("login", loginRequest);

    return "redirect:/api/test/homePage";

}

As you can see, I want to check is user authenticated, I mean does user insert good credentials. You can see that I tried like this:

   boolean no = authentication.isAuthenticated();
    if (!no) {
        model.addAttribute("loginError", true);
        logger.info("User is not auth");
        return "form_login";
    }

But that return me a Whitelabel Error Page with 403 Forbidden, while I want to display error message on Thymeleaf user.

This is in thymeleaf:

Wrong user or password

How I can check user credentials that he insert so if he enter wrong credentials show him wrong password/username?

Also my logger.info("User is not auth"); is not being printed even when user enter wrong credentials but I get 403 Forbidden.


问:
How can I stream then play YUV format with/without VLC/FFMPEG?
I'm able to play a local YUV file through VLC (as expected)

```<code>.\vlc.exe --demux rawvideo --rawvid-fps 25 --rawvid-width 480 --rawvid-height 360 --rawvid-chroma I420 out.yuv
</code>```

Also FFPLAY is playing well

```<code>.\ffplay.exe -f rawvideo -pixel_format yuv420p -video_size 480x360 out.yuv
</code>```

Conversion to YUV was done with FFMPEG

```<code>.\ffmpeg.exe -i "video.mp4" -c:v rawvideo -pixel_format yuv420p out.yuv
</code>```

However, I'm not able o stream it and play'it over local network.
I know, it sounds crazy :) but I plan to use VLC as a monitor/debugger for some YUV data.

The original MP4 file is streamed/played fine with VLC (test on the same computer)

```<code>.\vlc.exe "video.mp4" --sout="#std{access=http, mux=ts, dst=:55555/}"
.\vlc.exe http://192.168.0.174:55555/
</code>```

So the big question!
How can I stream the YUV format and VLC recognise an play it as well?

All that I tried with VLC is not playable.

Thanks for any hints!

Body:
I'm able to play a local YUV file through VLC (as expected)

.\vlc.exe --demux rawvideo --rawvid-fps 25 --rawvid-width 480 --rawvid-height 360 --rawvid-chroma I420 out.yuv

Also FFPLAY is playing well

.\ffplay.exe -f rawvideo -pixel_format yuv420p -video_size 480x360 out.yuv

Conversion to YUV was done with FFMPEG

.\ffmpeg.exe -i "video.mp4" -c:v rawvideo -pixel_format yuv420p out.yuv

However, I'm not able o stream it and play'it over local network.
I know, it sounds crazy :) but I plan to use VLC as a monitor/debugger for some YUV data.

The original MP4 file is streamed/played fine with VLC (test on the same computer)

.\vlc.exe "video.mp4" --sout="#std{access=http, mux=ts, dst=:55555/}"
.\vlc.exe http://192.168.0.174:55555/

So the big question!
How can I stream the YUV format and VLC recognise an play it as well?

All that I tried with VLC is not playable.

Thanks for any hints!


问:
How do I get a DECIMAL from a stored procudure using Hibernate?
I'm calling a SQL Server stored procedure using Hibernate. The stored procedure has a DECIMAL(30,25) output parameter named radius. How do I get that value?

Here's what I have tried but the value (i.e. radius) is rounded to four decimal places.

```<code>    StoredProcedureQuery query = entityManager.createStoredProcedureQuery("getRadius")
            .registerStoredProcedureParameter(
                    "id",
                    String.class,
                    ParameterMode.IN
                    )
            .registerStoredProcedureParameter(
                    "radius",
                    BigDecimal.class,
                    ParameterMode.OUT
                    ) //other in and out parameters excluded for brevity
            .setParameter("id", "product");

    query.execute();

    log.info("radius is {}", query.getOutputParameterValue("radius"));
</code>```

Body:
I'm calling a SQL Server stored procedure using Hibernate. The stored procedure has a DECIMAL(30,25) output parameter named radius. How do I get that value?

Here's what I have tried but the value (i.e. radius) is rounded to four decimal places.

    StoredProcedureQuery query = entityManager.createStoredProcedureQuery("getRadius")
            .registerStoredProcedureParameter(
                    "id",
                    String.class,
                    ParameterMode.IN
                    )
            .registerStoredProcedureParameter(
                    "radius",
                    BigDecimal.class,
                    ParameterMode.OUT
                    ) //other in and out parameters excluded for brevity
            .setParameter("id", "product");

    query.execute();

    log.info("radius is {}", query.getOutputParameterValue("radius"));


问:
How can i create version 1 of keystore using cmd?
If i create keystore using jre 8 using cmd and the keystore is version 3, how can i make it version 1? #new

Need help to create keystore version 1 using cmd for apk signing.


问:
Django SESSION_COOKIE_AGE vs set_expiry()
I have noticed different behavior between SESSION_COOKIE_AGE and set_expiry method. Usually, I am using set_expiry on login as it changes according to the user whether he/she selects REMEMBER BE or not.

I understand that if I set SESSION_SAVE_EVERY_REQUEST to True, this means that the expiration date will be updated every time on user activity. However, I noticed that the expiration date of the session is updated on user activity without setting SESSION_SAVE_EVERY_REQUEST (default: False) and without modifying the session. On the other side, it is not working that way if I set SESSION_COOKIE_AGE only without custom setting of set_expiry.

From the documentation, it is mentioned that if we set value using set_expiry:

the session will expire after that many seconds of inactivity

Is that means INACTIVITY in accessing the application or inactivity in modifying the session? And set_expiry equals SESSION_COOKIE_AGE plus SESSION_SAVE_EVERY_REQUEST=True?


问:
OpenAPI field validation precedence
Let's imagine I have a schema with 2 properties:

"properties": {
  "name": {
    "type": "string",
    "minLength": 2,
    "pattern": "<some unmatchable pattern>",
    "x-constraints": "Capitalized(required = true)"
  },
  "petType": {
    "type": "string",
    "minLength": 2,
    "pattern": "<some unmatchable pattern>",
    "x-constraints": "Capitalized(required = true)"
  }
}
```

What will happen if I send an invalid field? Is there any written in stone precedence of validation order? I.e. can a dependent service be sure it will always get the "Wrong length" error if name="a", even though other constraints don't match?

I tried official documentation but had no luck. Tests seem to return different error messages, but not sure if not due to the nature of test itself.

Title: OpenAPI field validation precedence

Body:
Let's imagine I have a schema with 2 properties:

"properties": {
  "name": {
    "type": "string",
    "minLength": 2,
    "pattern": "<some unmatchable pattern>",
    "x-constraints": "Capitalized(required = true)"
  },
  "petType": {
    "type": "string",
    "minLength": 2,
    "pattern": "<some unmatchable pattern>",
    "x-constraints": "Capitalized(required = true)"
  }
}

What will happen if I send an invalid field? Is there any written in stone precedence of validation order? I.e. can a dependent service be sure it will always get the "Wrong length" error if name="a", even though other constraints don't match?

I tried official documentation but had no luck. Tests seem to return different error messages, but not sure if not due to the nature of test itself.


问:
My Built Jar File not Working outside netbeans - NetBeans IDE 16
When I need to run .jar java file after build it from netbeans , the file not opening !
but I am not sure if the problem from netbeans or java , because I have old jar files built with netbeans that used to work, but after updating java, they don't all work anymore!

I tried running the file indirectly via the .bat file: java -jar myapp.jar , but it didn't work either


问:
Is there a performance penalty for scala functions with implicit parameters?
The code below shows consistent results on my machine: the code without implicits performs better

```<code>case class Config(appName: String, timeout: Int)

def appendWithImplicit(str: StringBuilder)(implicit config: Config): String = {
  val temp = new StringBuilder()
  temp.append(str).append(config.appName)
  temp.toString()
}

def appendNoImplicit(str: StringBuilder, appName: String, timeout:Int): String = {
  val temp = new StringBuilder()
  temp.append(str).append(appName)
  temp.toString()
}

implicit val config = Config("myapp", 100)
val iterations = 100000

var start = System.currentTimeMillis()
for(i <- 1 to iterations)
  appendWithImplicit(new StringBuilder(100, "foo"))
var end = System.currentTimeMillis()
println("method with implicit " + (end-start))

start = System.currentTimeMillis()
for(i <- 1 to iterations)
  appendNoImplicit(new StringBuilder(100, "foo"), config.appName, config.timeout)
end = System.currentTimeMillis()
println("method no implicit " + (end-start))
</code>```

Is it something specific to my methods ?

is is something related to the implicits in scala ?

Body:
The code below shows consistent results on my machine: the code without implicits performs better

case class Config(appName: String, timeout: Int)

def appendWithImplicit(str: StringBuilder)(implicit config: Config): String = {
  val temp = new StringBuilder()
  temp.append(str).append(config.appName)
  temp.toString()
}

def appendNoImplicit(str: StringBuilder, appName: String, timeout:Int): String = {
  val temp = new StringBuilder()
  temp.append(str).append(appName)
  temp.toString()
}

implicit val config = Config("myapp", 100)
val iterations = 100000

var start = System.currentTimeMillis()
for(i <- 1 to iterations)
  appendWithImplicit(new StringBuilder(100, "foo"))
var end = System.currentTimeMillis()
println("method with implicit " + (end-start))

start = System.currentTimeMillis()
for(i <- 1 to iterations)
  appendNoImplicit(new StringBuilder(100, "foo"), config.appName, config.timeout)
end = System.currentTimeMillis()
println("method no implicit " + (end-start))

Is it something specific to my methods ?

is is something related to the implicits in scala ?


问:
Can a table created from DDL with NULL data type hold normal data type later?
I am copying an existing table into a different environment using its DDL. Some of the columns are type 'NULL.' Right now the values for said column are NULL in the sample I am given, but they probably shouldnt be according to their names (will probably be dates, IDs, bool).
This is using databricks delta tables. It will be an automatic ingestion so I wont be able to update columns later.

Is this going to create issues if there is non null data in the future being ingested into this table? If so, how can I avoid this ingestion issue?

Example:

show create table oldEnv.tableName

```<code>
create table oldEnv.tableName(
col1 decimal(5,0),
col2 decimal(5,0),
col3 timestamp,
col4 string,
...
colX_flag,
colY_update_date,
colZ_ID
) using delta location db.location/path
</code>```

Can I just keep them as null and let databricks handle it when values come up?

Body:
I am copying an existing table into a different environment using its DDL. Some of the columns are type 'NULL.' Right now the values for said column are NULL in the sample I am given, but they probably shouldnt be according to their names (will probably be dates, IDs, bool).
This is using databricks delta tables. It will be an automatic ingestion so I wont be able to update columns later.

Is this going to create issues if there is non null data in the future being ingested into this table? If so, how can I avoid this ingestion issue?

Example:

show create table oldEnv.tableName

create table oldEnv.tableName(
col1 decimal(5,0),
col2 decimal(5,0),
col3 timestamp,
col4 string,
...
colX_flag,
colY_update_date,
colZ_ID
) using delta location db.location/path

Can I just keep them as null and let databricks handle it when values come up?


问:
Source environment variables before running cmake in VSCode
I am trying to build a large C++ framework in VSCode using CMakeTools and C/C++ Extensions in Visual Studio Code. I am browsing stackoverflow/github issues/any google suggestion and it looks like I am not the first person to encounter this, but I can not figure out for the life of me what am I doing wrong.

Here is the problem. I want to setup VSCode in a way to be able to build the framework (it is C++) right from VSCode using the built-in tools/extensions. Here is the process I was using up until now (in standard terminal in linux) and it also works in terminal run in VSCode:

```<code>cd /path-to-project-main-folder
source scripts/env.sh
cmake .
make -j 10
</code>```

Now the problem is that when I set up VSCode, open the folder where the framework is, VSCode recognizes it is cmake project and gives me the opportunity to build it. Problem is that when I try to build it, it does not set up the environment first and therefore uses wrong cmake (not the sourced one but the default one build in server) and also wrong libraries and some of them are not even recognized.
The problem is in the first line:

```<code>source scripts/env.sh
</code>```

where the environment variables are set and also PATHs to some libraries and programs. This line is not ran by VSCode before cmake and build.
Does anyone know a solution on how to configure CMakeTools extension to run:

```<code>source scripts/env.sh
</code>```

line before running cmake and then make?

Thank you

I was looking into some solutions using tasks.json, settings.json files or creating my own kit. But no solution worked for me or I did not completely undestood the solution:
https://github.com/microsoft/vscode-cmake-tools/blob/HEAD/docs/tasks.md

https://github.com/microsoft/vscode-cmake-tools/issues/2243

https://github.com/microsoft/vscode-cmake-tools/pull/995

VSCode: Set environment variables via script
and man pages of CMakeTools, VSCode,...

VScode remote development: How can I run a build task to source environment variables before running the real build task? ---> but I use cmake

VSCode, how to source environment variable files like setup.bash?

Body:
I am trying to build a large C++ framework in VSCode using CMakeTools and C/C++ Extensions in Visual Studio Code. I am browsing stackoverflow/github issues/any google suggestion and it looks like I am not the first person to encounter this, but I can not figure out for the life of me what am I doing wrong.

Here is the problem. I want to setup VSCode in a way to be able to build the framework (it is C++) right from VSCode using the built-in tools/extensions. Here is the process I was using up until now (in standard terminal in linux) and it also works in terminal run in VSCode:

cd /path-to-project-main-folder
source scripts/env.sh
cmake .
make -j 10

Now the problem is that when I set up VSCode, open the folder where the framework is, VSCode recognizes it is cmake project and gives me the opportunity to build it. Problem is that when I try to build it, it does not set up the environment first and therefore uses wrong cmake (not the sourced one but the default one build in server) and also wrong libraries and some of them are not even recognized.
The problem is in the first line:

source scripts/env.sh

where the environment variables are set and also PATHs to some libraries and programs. This line is not ran by VSCode before cmake and build.
Does anyone know a solution on how to configure CMakeTools extension to run:

source scripts/env.sh

line before running cmake and then make?

Thank you

I was looking into some solutions using tasks.json, settings.json files or creating my own kit. But no solution worked for me or I did not completely undestood the solution:
https://github.com/microsoft/vscode-cmake-tools/blob/HEAD/docs/tasks.md

https://github.com/microsoft/vscode-cmake-tools/issues/2243

https://github.com/microsoft/vscode-cmake-tools/pull/995

VSCode: Set environment variables via script
and man pages of CMakeTools, VSCode,...

VScode remote development: How can I run a build task to source environment variables before running the real build task? ---> but I use cmake

VSCode, how to source environment variable files like setup.bash?


问:
Softkeyboard width
I have a screen with 3 textfields.
In manififest I use:
android:windowSoftInputMode="adjustPan"

But when I tap on the most bottom TextView some blank space appears there (look at the picture)

How can I prevent it?

Title: Softkeyboard width


问:
How do i store the currently selected text to a variable in python?
I am trying to store the currently selected text in a variable. I am using the keyboard library to write text and execute certain key combinations. I am using the command 'keyboard.press_and_release('ctrl+a')' to select the current text, and my goal is to store that selected text in a variable named 'text'. This applies to any textbox, in any window whatsoever.

Any assistance in achieving this would be greatly appreciated.

I have attempted to use both pyautogui and pyperclip, however, neither have been successful. I considered alternative methods such as utilizing an external GUI to capture each keystroke and input, however, this approach is incredibly slow and inefficient.


问:
How to fix Devexpress Blazor update to 22.2.3 missing CSS?
I have updated my Balzor webpage from 21.2.4 to 22.2.3 like this :

```<code>PM> Install-Package DevExpress.Blazor -Version 22.2.3
</code>```

No problems so far. Followed the instruction here and launched the webpage.

Problem : the "_content/DevExpress.Blazor.Themes/blazing-berry.bs4.min.css" do not exist when checking the Chrome devtool? I thought the services.AddDevExpressBlazor(configure => configure.BootstrapVersion = BootstrapVersion.v4); would have added it, but no?

Got this in the Head :

```<code><link href="_content/DevExpress.Blazor.Themes/blazing-berry.bs4.min.css" asp-append-version="true" rel="stylesheet" />
    <link href="_content/DevExpress.Blazor.Themes/bootstrap-external.bs4.min.css" asp-append-version="true" rel="stylesheet" />
</code>```

How do I get the proper resources loaded?

Body:
I have updated my Balzor webpage from 21.2.4 to 22.2.3 like this :

PM> Install-Package DevExpress.Blazor -Version 22.2.3

No problems so far. Followed the instruction here and launched the webpage.

Problem : the "_content/DevExpress.Blazor.Themes/blazing-berry.bs4.min.css" do not exist when checking the Chrome devtool? I thought the services.AddDevExpressBlazor(configure => configure.BootstrapVersion = BootstrapVersion.v4); would have added it, but no?

Got this in the Head :

<link href="_content/DevExpress.Blazor.Themes/blazing-berry.bs4.min.css" asp-append-version="true" rel="stylesheet" />
    <link href="_content/DevExpress.Blazor.Themes/bootstrap-external.bs4.min.css" asp-append-version="true" rel="stylesheet" />

How do I get the proper resources loaded?


问:
Lodash - dynamically update parameters of a complex object using lodash
im trying to set values to an object dynamically passing the attribute that i need to set the value, for example. i need to set name for the object so i need to find this property in the object and set value 'new name'. but some property can be nested for example address.city.name so basically what i need to do is find where the property city is and set the new value to it. if i have one level i could do it easily using something like object[attribute] = newValue;
but sometime the property can be in nested object
object[path][attribute] = newValue;
i was able to accomplish this using the function bellow, but i would to know if its possible do this using lodash. I didn't find any function that find the way of the property

```<code>onEditDataCallback={(rowData, columnId, newValue) => {
                    const path = findPath(rowData, columnId);
                    if (path) {
                        rowData[path][columnId] = newValue;
                    } else {
                        rowData[columnId] = newValue;
                    }

                    return {
                        ...rowData
                    };
                }}

const findPath = (ob, key) => {
    const path = [];
    const keyExists = (obj) => {
        if (!obj || (typeof obj !== 'object' && !Array.isArray(obj))) {
            return false;
        } else if (obj.hasOwnProperty(key)) {
            return true;
        } else if (Array.isArray(obj)) {
            let parentKey = path.length ? path.pop() : '';

            for (let i = 0; i < obj.length; i++) {
                path.push(`${parentKey}[${i}]`);
                const result = keyExists(obj[i], key);
                if (result) {
                    return result;
                }
                path.pop();
            }
        } else {
            for (const k in obj) {
                path.push(k);
                const result = keyExists(obj[k], key);
                if (result) {
                    return result;
                }
                path.pop();
            }
        }
        return false;
    };

    keyExists(ob);

    return path.join('.');
};
</code>```

this is what im trying to avoid:

```<code>onEditDataCallback={(rowData, columnId, newValue) => {
                    const temporary = rowData;
                    switch (columnId) {
                        case 'city': {
                            temporary.address.city.name = newValue;
                            break;
                        }
                        case 'addressOne': {
                            temporary.address.addressOne = newValue;
                            break;
                        }
                        case 'postalCode': {
                            temporary.address.postalCode.key = newValue;
                            break;
                        }
                        default: {
                            temporary[columnId] = newValue;
                        }
                    }
                    return {
                        ...temporary

};
            }}
</code>```

Body:
im trying to set values to an object dynamically passing the attribute that i need to set the value, for example. i need to set name for the object so i need to find this property in the object and set value 'new name'. but some property can be nested for example address.city.name so basically what i need to do is find where the property city is and set the new value to it. if i have one level i could do it easily using something like object[attribute] = newValue;
but sometime the property can be in nested object
object[path][attribute] = newValue;
i was able to accomplish this using the function bellow, but i would to know if its possible do this using lodash. I didn't find any function that find the way of the property

onEditDataCallback={(rowData, columnId, newValue) => {
                    const path = findPath(rowData, columnId);
                    if (path) {
                        rowData[path][columnId] = newValue;
                    } else {
                        rowData[columnId] = newValue;
                    }

                    return {
                        ...rowData
                    };
                }}

const findPath = (ob, key) => {
    const path = [];
    const keyExists = (obj) => {
        if (!obj || (typeof obj !== 'object' && !Array.isArray(obj))) {
            return false;
        } else if (obj.hasOwnProperty(key)) {
            return true;
        } else if (Array.isArray(obj)) {
            let parentKey = path.length ? path.pop() : '';

            for (let i = 0; i < obj.length; i++) {
                path.push(`${parentKey}[${i}]`);
                const result = keyExists(obj[i], key);
                if (result) {
                    return result;
                }
                path.pop();
            }
        } else {
            for (const k in obj) {
                path.push(k);
                const result = keyExists(obj[k], key);
                if (result) {
                    return result;
                }
                path.pop();
            }
        }
        return false;
    };

    keyExists(ob);

    return path.join('.');
};

this is what im trying to avoid:

onEditDataCallback={(rowData, columnId, newValue) => {
                    const temporary = rowData;
                    switch (columnId) {
                        case 'city': {
                            temporary.address.city.name = newValue;
                            break;
                        }
                        case 'addressOne': {
                            temporary.address.addressOne = newValue;
                            break;
                        }
                        case 'postalCode': {
                            temporary.address.postalCode.key = newValue;
                            break;
                        }
                        default: {
                            temporary[columnId] = newValue;
                        }
                    }
                    return {
                        ...temporary

};
            }}


问:
Exception has occurred. _ClientSocketException (Failed host lookup: 'flutter-api.test')
```<code>import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Category{
  int id;
  String name;

  Category({
    required this.id,
    required this.name
  });

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(id: json['id'], name:json['name']);
  }
}

class Categories extends StatefulWidget {
  const Categories({super.key});

  @override
  CategoriesState createState() => CategoriesState();
}

class CategoriesState extends State<Categories> {
  late Future<List<Category>> futureCategories;

  Future<List<Category>> fetchCategories() async {
    http.Response response = await http.get(
      Uri.parse('http://flutter-api.test/api/categories')
    );

    List categories = jsonDecode(response.body);

    return categories.map((category) => Category.fromJson(category)).toList();

  }

  @override
  void initState() {
    super.initState();
    futureCategories = fetchCategories();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Categories'),
      ),
      body: FutureBuilder<List<Category>>(
        future: futureCategories,
        builder: (context, snapshot) {
          if(snapshot.hasData){
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                Category category = snapshot.data![index];
                return ListTile(
                  title: Text(category.name)
                );
              },
            );
          }else if(snapshot.hasError){
            return const Text('Something went wrong');
          }
          return const CircularProgressIndicator();
        }
      )
    );
  }
}
</code>```

This flutter app requests the laravel api to provide a list of categories from

http://flutter-api.test/api/categories

I ran my flutter app in my local environment and it worked well using the chrome browser(List of categories appeared)

However, it didn't work when i ran it through the android emulator.
It gives the below error

Exception has occurred.
_ClientSocketException (Failed host lookup: 'flutter-api.test')

I have already entered

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

in AndroidManifest.xml file

Body:
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Category{
  int id;
  String name;

  Category({
    required this.id,
    required this.name
  });

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(id: json['id'], name:json['name']);
  }
}

class Categories extends StatefulWidget {
  const Categories({super.key});

  @override
  CategoriesState createState() => CategoriesState();
}

class CategoriesState extends State<Categories> {
  late Future<List<Category>> futureCategories;

  Future<List<Category>> fetchCategories() async {
    http.Response response = await http.get(
      Uri.parse('http://flutter-api.test/api/categories')
    );

    List categories = jsonDecode(response.body);

    return categories.map((category) => Category.fromJson(category)).toList();

  }

  @override
  void initState() {
    super.initState();
    futureCategories = fetchCategories();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Categories'),
      ),
      body: FutureBuilder<List<Category>>(
        future: futureCategories,
        builder: (context, snapshot) {
          if(snapshot.hasData){
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                Category category = snapshot.data![index];
                return ListTile(
                  title: Text(category.name)
                );
              },
            );
          }else if(snapshot.hasError){
            return const Text('Something went wrong');
          }
          return const CircularProgressIndicator();
        }
      )
    );
  }
}

This flutter app requests the laravel api to provide a list of categories from

http://flutter-api.test/api/categories

I ran my flutter app in my local environment and it worked well using the chrome browser(List of categories appeared)

However, it didn't work when i ran it through the android emulator.
It gives the below error

Exception has occurred.
_ClientSocketException (Failed host lookup: 'flutter-api.test')

I have already entered

<uses-permission android:name="android.permission.INTERNET" />

in AndroidManifest.xml file


问:
Image sequence detection with Keras, Convolutional and Stateful Neural Network
I am trying to write a pretty complicated neural network (at least for me) in keras that needs to combine both a common CNN structure and an LSTM/GRU layer.

Basically, I have a dataset of climatological maps of the Mediterranean sea, each map details the wind, pressure and other parameters. I am studying Medicanes (Mediterranean hurricanes) and my goal is to create a neural network that can classify each map with a label zero if there is no trace of such hurricanes or one if the map contains one.

In order to achieve that I need a network with two parts:

feature extractor (normal CNN).

temporal layer (LSTM/GRU).

The main cause of this is that each map is correlated with the previous one because the formation and life cycle of a Medicane can take several days to complete.

Important note: the dataset is too big to be uploaded all at once so I have to work one batch at a time.

I am working with Keras and I found it pretty challenging to adapt its standard framework to my needs so I have come up with some peculiar flow to feed my data into the network.

In particular, I found it hard to pass both my batch size and my time-step parameter to the GRU layer using a more standard alternative.

This is what I tried:

I am positively sure I have overcomplicated the task, but, as I said I am not very proficient with Keras and TensorFlow.

The main problem was that I could not find a way to import the data both in a batch (for RAM reasons) and in a sequence of 10-15 pictures (to be used as the time steps in the GRU layer).

I solved this problem by importing batches of 120 maps in order (no shuffle) and I created a way to turn these batches into the sequence of images I needed then I proceeded to re-batch the sequences and feed them to the model manually.

Data Import

```<code>batch_size=120

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    "./Figures_1/Train",
    validation_split=None,
    subset=None,
    labels="inferred",
    label_mode="binary",
    color_mode="rgb",
    interpolation='bilinear',
    batch_size=batch_size,
    image_size=(600, 600),
    shuffle=False,
    seed=123
)
</code>```

Get a sequence of Images

Here, I break down the 120 map batches into sequences of 60 observations, and I return each sequence one at a time.

```<code>sequence_lengh=60

def sequence_x(train_dataset):

    x_numpy = np.asarray(list(map(lambda x: x[0], tfds.as_numpy(train_dataset))),dtype=object)

    for element in range(0,x_numpy.shape[0]):
        for i in range(0, x_numpy.shape[0],sequence_lengh):
            x_seq = x_numpy[element][i:i+sequence_lengh]
            yield x_seq

def sequence_y(train_dataset):

    y_numpy = np.asarray(list(map(lambda x: x[1], tfds.as_numpy(train_dataset))),dtype=object)

    for element in range(0,y_numpy.shape[0]):
        for i in range(0, y_numpy.shape[0],sequence_lengh):
            y_seq = y_numpy[element][i:i+sequence_lengh]
            yield y_seq
</code>```

CNN Model

I build the CNN model based on a pre-trained DenseNet

```<code>from keras.layers import TimeDistributed, GRU

def build_convnet(shape=(600, 600, 3)):

    inputs = keras.Input(shape = shape)
    x = inputs

    # preprocessing
    x = keras.applications.densenet.preprocess_input(x)

    #Convbase
    x = convBase(x)
    x = layers.Flatten()(x)

    # Fine tuning
    x = keras.layers.Dense(1024, activation='relu')(x)
    x = layers.Dropout(0.2)(x)
    x = keras.layers.Dense(512, activation='relu')(x)
    x = keras.layers.GlobalMaxPool2D()

    return x
</code>```

GRU Model

I build the time part of the network with a GRU layer

```<code>def action_model(shape=(15, 600, 600, 3), nbout=15):
    # Create our convnet with (112, 112, 3) input shape
    convnet = build_convnet(shape[1:]) #[1:]

    # then create our final model
    model = keras.Sequential()
    # add the convnet with (5, 112, 112, 3) shape
    model.add(TimeDistributed(convnet, input_shape=shape))
    # here, you can also use GRU or LSTM
    model.add(GRU(64))
    # and finally, we make a decision network
    model.add(Dense(1024, activation='relu'))
    model.add(Dropout(.5))
    model.add(Dense(512, activation='relu'))
    model.add(Dropout(.5))
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(.5))
    model.add(Dense(64, activation='relu'))
    model.add(Dense(15, activation='softmax'))
    return model
</code>```

Transfer Learning

I retrain a part of the GRU

```<code>convBase = DenseNet121(include_top=False, weights=None, input_shape=(600,600,3), pooling="avg")

for layer in convBase.layers:
  if 'conv5' in layer.name:
    layer.trainable = True
for layer in convBase.layers:
  if 'conv4' in layer.name:
    layer.trainable = True
</code>```

Model Compile

Model compilation ( image size= 600x600x3)

```<code>INSHAPE=(15, 600, 600, 3) # (5, 112, 112, 3)
model = action_model(INSHAPE, 1)
optimizer = keras.optimizers.Adam(0.001)

model.compile(
    optimizer,
    'categorical_crossentropy',
    metrics='accuracy'
)
</code>```

Model Fit

Here I manually batch my data. I turn an array (60, 600, 600, 3) into a (4,15,600,600) array. Meaning 4 batches each one containing a 15-map long sequence.

```<code>
epochs = 10

for value in range(0, epochs):

    train_x, train_y = sequence_x(train_ds), sequence_y(train_ds)
    val_x, val_y = sequence_x(validation_ds), sequence_y(validation_ds)

    for i in range(0,278): #

        x = next(train_x, "none")
        y = next(train_y, "none")

        if (x!="none" or y!="none"):

            if (np.any(x) and np.any(y)):

                x_stack = np.stack((x[:15], x[15:30], x[30:45], x[45:]))
                y_stack = np.stack((y[:15], y[15:30], y[30:45], y[45:]))
                y_stack=y_stack.reshape(4,15)

                model.fit(x=x_stack, y=y_stack,
                            validation_data=None,
                            batch_size=None,
                            shuffle=False
                            )

            else:
                continue
        else:
            continue
</code>```

The idea is to get a model that, when presented with a sequence of images, can categorize each one of them with a 0 or a 1 if they have a Medicane or not.

The model does compile without any errors but the results it provides are horrible:

.

What am I doing incorrectly? Is there a more effective way to write all of this?

Body:
I am trying to write a pretty complicated neural network (at least for me) in keras that needs to combine both a common CNN structure and an LSTM/GRU layer.

Basically, I have a dataset of climatological maps of the Mediterranean sea, each map details the wind, pressure and other parameters. I am studying Medicanes (Mediterranean hurricanes) and my goal is to create a neural network that can classify each map with a label zero if there is no trace of such hurricanes or one if the map contains one.

In order to achieve that I need a network with two parts:

feature extractor (normal CNN).

temporal layer (LSTM/GRU).

The main cause of this is that each map is correlated with the previous one because the formation and life cycle of a Medicane can take several days to complete.

Important note: the dataset is too big to be uploaded all at once so I have to work one batch at a time.

I am working with Keras and I found it pretty challenging to adapt its standard framework to my needs so I have come up with some peculiar flow to feed my data into the network.

In particular, I found it hard to pass both my batch size and my time-step parameter to the GRU layer using a more standard alternative.

This is what I tried:

I am positively sure I have overcomplicated the task, but, as I said I am not very proficient with Keras and TensorFlow.

The main problem was that I could not find a way to import the data both in a batch (for RAM reasons) and in a sequence of 10-15 pictures (to be used as the time steps in the GRU layer).

I solved this problem by importing batches of 120 maps in order (no shuffle) and I created a way to turn these batches into the sequence of images I needed then I proceeded to re-batch the sequences and feed them to the model manually.

Data Import

batch_size=120

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    "./Figures_1/Train",
    validation_split=None,
    subset=None,
    labels="inferred",
    label_mode="binary",
    color_mode="rgb",
    interpolation='bilinear',
    batch_size=batch_size,
    image_size=(600, 600),
    shuffle=False,
    seed=123
)

Get a sequence of Images

Here, I break down the 120 map batches into sequences of 60 observations, and I return each sequence one at a time.

sequence_lengh=60

def sequence_x(train_dataset):

    x_numpy = np.asarray(list(map(lambda x: x[0], tfds.as_numpy(train_dataset))),dtype=object)

    for element in range(0,x_numpy.shape[0]):
        for i in range(0, x_numpy.shape[0],sequence_lengh):
            x_seq = x_numpy[element][i:i+sequence_lengh]
            yield x_seq

def sequence_y(train_dataset):

    y_numpy = np.asarray(list(map(lambda x: x[1], tfds.as_numpy(train_dataset))),dtype=object)

    for element in range(0,y_numpy.shape[0]):
        for i in range(0, y_numpy.shape[0],sequence_lengh):
            y_seq = y_numpy[element][i:i+sequence_lengh]
            yield y_seq

CNN Model

I build the CNN model based on a pre-trained DenseNet

from keras.layers import TimeDistributed, GRU

def build_convnet(shape=(600, 600, 3)):

    inputs = keras.Input(shape = shape)
    x = inputs

    # preprocessing
    x = keras.applications.densenet.preprocess_input(x)

    #Convbase
    x = convBase(x)
    x = layers.Flatten()(x)

    # Fine tuning
    x = keras.layers.Dense(1024, activation='relu')(x)
    x = layers.Dropout(0.2)(x)
    x = keras.layers.Dense(512, activation='relu')(x)
    x = keras.layers.GlobalMaxPool2D()

    return x

GRU Model

I build the time part of the network with a GRU layer

def action_model(shape=(15, 600, 600, 3), nbout=15):
    # Create our convnet with (112, 112, 3) input shape
    convnet = build_convnet(shape[1:]) #[1:]

    # then create our final model
    model = keras.Sequential()
    # add the convnet with (5, 112, 112, 3) shape
    model.add(TimeDistributed(convnet, input_shape=shape))
    # here, you can also use GRU or LSTM
    model.add(GRU(64))
    # and finally, we make a decision network
    model.add(Dense(1024, activation='relu'))
    model.add(Dropout(.5))
    model.add(Dense(512, activation='relu'))
    model.add(Dropout(.5))
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(.5))
    model.add(Dense(64, activation='relu'))
    model.add(Dense(15, activation='softmax'))
    return model

Transfer Learning

I retrain a part of the GRU

convBase = DenseNet121(include_top=False, weights=None, input_shape=(600,600,3), pooling="avg")

for layer in convBase.layers:
  if 'conv5' in layer.name:
    layer.trainable = True
for layer in convBase.layers:
  if 'conv4' in layer.name:
    layer.trainable = True

Model Compile

Model compilation ( image size= 600x600x3)

INSHAPE=(15, 600, 600, 3) # (5, 112, 112, 3)
model = action_model(INSHAPE, 1)
optimizer = keras.optimizers.Adam(0.001)

model.compile(
    optimizer,
    'categorical_crossentropy',
    metrics='accuracy'
)

Model Fit

Here I manually batch my data. I turn an array (60, 600, 600, 3) into a (4,15,600,600) array. Meaning 4 batches each one containing a 15-map long sequence.

epochs = 10

for value in range(0, epochs):

    train_x, train_y = sequence_x(train_ds), sequence_y(train_ds)
    val_x, val_y = sequence_x(validation_ds), sequence_y(validation_ds)

    for i in range(0,278): #

        x = next(train_x, "none")
        y = next(train_y, "none")

        if (x!="none" or y!="none"):

            if (np.any(x) and np.any(y)):

                x_stack = np.stack((x[:15], x[15:30], x[30:45], x[45:]))
                y_stack = np.stack((y[:15], y[15:30], y[30:45], y[45:]))
                y_stack=y_stack.reshape(4,15)

                model.fit(x=x_stack, y=y_stack,
                            validation_data=None,
                            batch_size=None,
                            shuffle=False
                            )

            else:
                continue
        else:
            continue

The idea is to get a model that, when presented with a sequence of images, can categorize each one of them with a 0 or a 1 if they have a Medicane or not.

The model does compile without any errors but the results it provides are horrible:

.

What am I doing incorrectly? Is there a more effective way to write all of this?


问:
I am using @react-pdf/render in my react js application want to render it as HTML in pdf
I am using @react-pdf render for my react application.

it generated the component in pdf, the problem now is at the level of display of the data coming from my api which are saved in html tags. it displays like this:

My Title

or I would like it to display without the tags. there is also no way to use dangerouslySetInnerHTML
I got this as a result :

```<code><PDFViewer style={styles.viewer}>
      {/* Start of the document*/}
      <Document>
        {/*render a single page*/}
        <Page size="A4" style={styles.page}>
          <View style={styles.section}>
            <Image
              src={`http://127.0.0.1:8000/storage/settings/${setting.logo}`}
              alt="Logo"
              style={styles.logo}
            />
            <Text>N/Réf. : {data.numero_ref}</Text>
            <Text style={styles.concerne}>Concerne. : {data.motif}</Text>

            {/* content of letters*/}
            <Text style={styles.text}>{data.content}</Text>
          </View>
        </Page>
      </Document>
    </PDFViewer>
  );
</code>```

I got this as a result

I would like it to display content without the tags.

Body:
I am using @react-pdf render for my react application.

it generated the component in pdf, the problem now is at the level of display of the data coming from my api which are saved in html tags. it displays like this:

My Title

or I would like it to display without the tags. there is also no way to use dangerouslySetInnerHTML
I got this as a result :

<PDFViewer style={styles.viewer}>
      {/* Start of the document*/}
      <Document>
        {/*render a single page*/}
        <Page size="A4" style={styles.page}>
          <View style={styles.section}>
            <Image
              src={`http://127.0.0.1:8000/storage/settings/${setting.logo}`}
              alt="Logo"
              style={styles.logo}
            />
            <Text>N/Réf. : {data.numero_ref}</Text>
            <Text style={styles.concerne}>Concerne. : {data.motif}</Text>

            {/* content of letters*/}
            <Text style={styles.text}>{data.content}</Text>
          </View>
        </Page>
      </Document>
    </PDFViewer>
  );

I got this as a result

I would like it to display content without the tags.


问:
Python3 SSL: SSLV3_ALERT_HANDSHAKE_FAILURE
Pretty straight forward. I'm trying to do some SSL Handshake and get the endpoint certificate from sslsocket documentation: do_handshake. Instead, I greeted with this specific error:

```<code>  File "/usr/lib/python3.10/ssl.py", line 1342, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)
</code>```

The certificate will be used to extract any SubjectName or CommonName. Been looking around with 100 chrome tabs, busting my memory only for browsing. I have tried many steps:

```<code># Monkey Patch to use Unverified Context
ssl._create_default_https_context = ssl._create_unverified_context

# Disable SSL Verification
sslContext.check_hostname = False
sslContext.verify_mode = ssl.CERT_NONE

# Using Custom Ciphers
cipher = (':ECDHE-RSA-AES128-GCM-SHA256:DES-CBC3-SHA:AES256-SHA:AES128-SHA:AES128-SHA256:AES256-GCM-SHA384:AES256-SHA256:ECDHE-RSA-DES-CBC3:EDH-RSA-DES-CBC3:EECDH+AESGCM:EDH-RSA-DES-CBC3-SHA:EDH-AESGCM:AES256+EECDH:ECHDE-RSA-AES256-GCM-SHA384:ECHDE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECHDE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-A$:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK')
sslContext.set_ciphers(cipher)

# Using Custom OpenSSL Config

openssl_conf = openssl_init

[openssl_init]
ssl_conf = ssl_sect

[ssl_sect]
system_default = system_default_sect

[system_default_sect]
Options = UnsafeLegacyRenegotiation
</code>```

None of them that able to fix the issue. Here's my current modified script based on sslsocket documentation

```<code>import socket
import ssl
import platform
import time

cipher = (':ECDHE-RSA-AES128-GCM-SHA256:DES-CBC3-SHA:AES256-SHA:AES128-SHA:AES128-SHA256:AES256-GCM-SHA384:AES256-SHA256:ECDHE-RSA-DES-CBC3:EDH-RSA-DES-CBC3:EECDH+AESGCM:EDH-RSA-DES-CBC3-SHA:EDH-AESGCM:AES256+EECDH:ECHDE-RSA-AES256-GCM-SHA384:ECHDE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECHDE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-A$:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK')
ssl._create_default_https_context = ssl._create_unverified_context

sslContext = ssl.create_default_context()
sslContext.check_hostname = False
sslContext.set_ciphers(cipher)
sslContext.verify_mode = ssl.CERT_NONE

clientSocket = socket.socket()
secureClientSocket = sslContext.wrap_socket(clientSocket, do_handshake_on_connect=False)

t1 = time.time()
retval = secureClientSocket.connect(("example.com", 443))
print("Time taken to establish the connection:%2.3f"%(time.time() - t1))

t3 = time.time()
secureClientSocket.do_handshake()
print("Time taken for SSL handshake:%2.3f"%(time.time() - t3))

serverCertificate = secureClientSocket.getpeercert()
print("Certificate obtained from the server:")
print(serverCertificate)
</code>```

My Setup

```<code>openssl version
OpenSSL 3.0.7 1 Nov 2022 (Library: OpenSSL 3.0.7 1 Nov 2022)

python3 --version
Python 3.10.8
</code>```

I'm in desperate situation, anyhelp is highly appreciated.

Body:
Pretty straight forward. I'm trying to do some SSL Handshake and get the endpoint certificate from sslsocket documentation: do_handshake. Instead, I greeted with this specific error:

  File "/usr/lib/python3.10/ssl.py", line 1342, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)

The certificate will be used to extract any SubjectName or CommonName. Been looking around with 100 chrome tabs, busting my memory only for browsing. I have tried many steps:

# Monkey Patch to use Unverified Context
ssl._create_default_https_context = ssl._create_unverified_context

# Disable SSL Verification
sslContext.check_hostname = False
sslContext.verify_mode = ssl.CERT_NONE

# Using Custom Ciphers
cipher = (':ECDHE-RSA-AES128-GCM-SHA256:DES-CBC3-SHA:AES256-SHA:AES128-SHA:AES128-SHA256:AES256-GCM-SHA384:AES256-SHA256:ECDHE-RSA-DES-CBC3:EDH-RSA-DES-CBC3:EECDH+AESGCM:EDH-RSA-DES-CBC3-SHA:EDH-AESGCM:AES256+EECDH:ECHDE-RSA-AES256-GCM-SHA384:ECHDE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECHDE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-A$:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK')
sslContext.set_ciphers(cipher)

# Using Custom OpenSSL Config

openssl_conf = openssl_init

[openssl_init]
ssl_conf = ssl_sect

[ssl_sect]
system_default = system_default_sect

[system_default_sect]
Options = UnsafeLegacyRenegotiation

None of them that able to fix the issue. Here's my current modified script based on sslsocket documentation

import socket
import ssl
import platform
import time

cipher = (':ECDHE-RSA-AES128-GCM-SHA256:DES-CBC3-SHA:AES256-SHA:AES128-SHA:AES128-SHA256:AES256-GCM-SHA384:AES256-SHA256:ECDHE-RSA-DES-CBC3:EDH-RSA-DES-CBC3:EECDH+AESGCM:EDH-RSA-DES-CBC3-SHA:EDH-AESGCM:AES256+EECDH:ECHDE-RSA-AES256-GCM-SHA384:ECHDE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECHDE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-A$:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK')
ssl._create_default_https_context = ssl._create_unverified_context

sslContext = ssl.create_default_context()
sslContext.check_hostname = False
sslContext.set_ciphers(cipher)
sslContext.verify_mode = ssl.CERT_NONE

clientSocket = socket.socket()
secureClientSocket = sslContext.wrap_socket(clientSocket, do_handshake_on_connect=False)

t1 = time.time()
retval = secureClientSocket.connect(("example.com", 443))
print("Time taken to establish the connection:%2.3f"%(time.time() - t1))

t3 = time.time()
secureClientSocket.do_handshake()
print("Time taken for SSL handshake:%2.3f"%(time.time() - t3))

serverCertificate = secureClientSocket.getpeercert()
print("Certificate obtained from the server:")
print(serverCertificate)

My Setup

openssl version
OpenSSL 3.0.7 1 Nov 2022 (Library: OpenSSL 3.0.7 1 Nov 2022)

python3 --version
Python 3.10.8

I'm in desperate situation, anyhelp is highly appreciated.


问:
Create Teams meeting by Microsoft Graph or other means
I'd like to create MS Teams meetings from another application.
The Teams application is running on the computer, outlook is not used though.
How would I accomplish this the best / easiest way without (much) user interaction?

As far as I can see, the best option would be to use the REST API to create a meeting using the api-URL https://graph.microsoft.com/v1.0/me/events.
If I can also create a meeting commandline or by COM objects or something else, I could do that, too.

So here would be what I did for research with graph so far:
I can log on to https://developer.microsoft.com/en-us/graph/graph-explorer and use my user to create meetings and get the response. To do that, I modified the permission to read / read-write the calendar. If I copy the access token and use it with a powershell Invoke-RestMethod, it also does what I want. I can do the same with Connect-Graph -Scopes "Calendars.ReadWrite". But it would show this big browser windows about the login as X.

I read about apps, but if I use the apps ID and so on to log in silently, it seems like I am not in the current user scope but in a process scope and that's different. At least I set the API permissions up to also have access to Calendars.ReadWrite via Microsoft Graph, but I get an Access denied error if I try to run the same New-MgUserEvent to create a meeting for the current user (that is running the local powershell).

If use the token with Connect-MgGraph, it displays the client and tenantID and the ContextScope is process, not current user, so that would fit.

If I understand it correctly, I could use the token to get another one for a user... (reference is this: https://learn.microsoft.com/en-us/graph/auth-v2-user )
If I use the Connect-Graph -ForceRefresh parameter (which I guess would do the same, the popup tells me I'm logged in as the current user (not process).

This is a bit odd, so before I try to use the rest api and fumble a bit around:
Can I use the example from the link to refresh the token to get a user token that has the rights that I defined (and be able to access the calendar)?
Or is there some misunderstanding on my part?

Would it be a better idea to just use something like powershell, have the user log in once per day and leave the process in the background and create the new entries from there?
Do you have to refresh a token when you use connect-graph? Or could that be done better by Rest web api, if I can export the token?

The idea of having an app that would have access to all calendars would seem like a bigger security risk and I'd kind of want to avoid that. If I could configure the apps to have access to only one specific calendar, that would be cool, too. But I did not find it when looking around.

Thanks and best regards to all that took their time to read and consider to help.


问:
Pentaho mondrian cube main sql query
I had a problem while programming a schema in mondrian. The thing is that I want to filter the main query inside the  tag of the cube so that it can only access the dimensions taking into account the logged in user. Is there any way to get that value dynamically and add it to the query?

```<code>    <Cube>
        <Annotations>
        </Annotations>
        <View>
            <SQL dialect="generic">
                <
                select a.*
                  from xxxxx a where (here is where i want to obtain the username value)
                >
            </SQL>
        </View>
</code>```

I tried to search in several webpages but I didn't find anything

Title: Pentaho mondrian cube main sql query

Body:
I had a problem while programming a schema in mondrian. The thing is that I want to filter the main query inside the  tag of the cube so that it can only access the dimensions taking into account the logged in user. Is there any way to get that value dynamically and add it to the query?

    <Cube>
        <Annotations>
        </Annotations>
        <View>
            <SQL dialect="generic">
                <
                select a.*
                  from xxxxx a where (here is where i want to obtain the username value)
                >
            </SQL>
        </View>

I tried to search in several webpages but I didn't find anything


问:
Efficient way to compare if items in a list exist in a list of lists
I have 2 lists:

```<code>list_1 = ['Denver Broncos',
 'Carolina Panthers',
 "Levi's Stadium in the San Francisco Bay Area at Santa Clara, California",
 'Carolina Panthers',
 'gold']

list_2 = [['Denver Broncos', 'Denver Broncos', 'Denver Broncos'],
 ['Carolina Panthers', 'Carolina Panthers', 'Carolina Panthers'],
 ['Santa Clara, California',
  "Levi's Stadium",
  "Levi's Stadium in the San Francisco Bay Area at Santa Clara, California."],
 ['Denver Broncos', 'Denver Broncos', 'Denver Broncos'],
 ['gold', 'gold', 'gold']]
</code>```

Is there an efficient way to compare whether each item from list_1 appears in the corresponding (based on its index) of list_2?

Currently I have it as a for loop:

```<code>score = 0
for i in range(len(list_1)):
    if list_1[i] in list_2[i]:
        score+=1

average_score = score/len(predicted_answers)
</code>```

but my lists are huge and I run this multiple times with multiple lists. I was hoping there's a more efficient way (I have access to a GPU if it help)

Body:
I have 2 lists:

list_1 = ['Denver Broncos',
 'Carolina Panthers',
 "Levi's Stadium in the San Francisco Bay Area at Santa Clara, California",
 'Carolina Panthers',
 'gold']

list_2 = [['Denver Broncos', 'Denver Broncos', 'Denver Broncos'],
 ['Carolina Panthers', 'Carolina Panthers', 'Carolina Panthers'],
 ['Santa Clara, California',
  "Levi's Stadium",
  "Levi's Stadium in the San Francisco Bay Area at Santa Clara, California."],
 ['Denver Broncos', 'Denver Broncos', 'Denver Broncos'],
 ['gold', 'gold', 'gold']]

Is there an efficient way to compare whether each item from list_1 appears in the corresponding (based on its index) of list_2?

Currently I have it as a for loop:

score = 0
for i in range(len(list_1)):
    if list_1[i] in list_2[i]:
        score+=1

average_score = score/len(predicted_answers)

but my lists are huge and I run this multiple times with multiple lists. I was hoping there's a more efficient way (I have access to a GPU if it help)


问:
Order by stock by new WP_Query - Woocommerce - Wordpress
I am making a new WP_Query to search for a product.

This shows me the wp_post information but not the stock information.

How can I order the stock results on top and the non-stock ones last in the search.

This is my current code.

```<code>$args = array(
'post_type' => 'product',
'post_status'           => 'publish',
'ignore_sticky_posts'   => 1,
's' => $filter_name,
'tax_query' => $tax_query,
'posts_per_page'=> $limit
);

$list = new WP_Query( $args );
</code>```

Try this code but it doesn't work

```<code>$args = array(
'post_type' => 'product',
'post_status'           => 'publish',
'ignore_sticky_posts'   => 1,
's' => $filter_name,
'tax_query' => $tax_query,
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_key' => '_stock',
'posts_per_page'=> $limit
);

$list = new WP_Query( $args );
</code>```

Body:
I am making a new WP_Query to search for a product.

This shows me the wp_post information but not the stock information.

How can I order the stock results on top and the non-stock ones last in the search.

This is my current code.

$args = array(
'post_type' => 'product',
'post_status'           => 'publish',
'ignore_sticky_posts'   => 1,
's' => $filter_name,
'tax_query' => $tax_query,
'posts_per_page'=> $limit
);

$list = new WP_Query( $args );

Try this code but it doesn't work

$args = array(
'post_type' => 'product',
'post_status'           => 'publish',
'ignore_sticky_posts'   => 1,
's' => $filter_name,
'tax_query' => $tax_query,
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_key' => '_stock',
'posts_per_page'=> $limit
);

$list = new WP_Query( $args );


问:
Slack Channel ID not working but channel name is working fine
Current channel name has been changed. So, every time when we face this then we need to change the name in template too. So, I am planning to provide channel ID instead of channel name but template fails with channel ID. What possibly could be the reason? Below is my code:

---

- name:  Sending slack notification
  hosts: localhost
  gather_facts: false
  become: false
  tasks:
    - slack:
        channel: "{{SLACK_CHANNEL}}"
        token: "{{SLACK_TOKEN}}"
        username: "Ansible - Bot"
        icon_url: "https://docs.ansible.com/favicon.ico"
        msg: "@here xyz"`
```

Below is the way how I am providing Slack channel ID via ansible template:

SLACK_CHANNEL: "abc123"

I have checked slack documentation and couldn't find out the reason. As template is working with channel name so hard to figure out.

Body:
Current channel name has been changed. So, every time when we face this then we need to change the name in template too. So, I am planning to provide channel ID instead of channel name but template fails with channel ID. What possibly could be the reason? Below is my code:

---

- name:  Sending slack notification
  hosts: localhost
  gather_facts: false
  become: false
  tasks:
    - slack:
        channel: "{{SLACK_CHANNEL}}"
        token: "{{SLACK_TOKEN}}"
        username: "Ansible - Bot"
        icon_url: "https://docs.ansible.com/favicon.ico"
        msg: "@here xyz"`

Below is the way how I am providing Slack channel ID via ansible template:

SLACK_CHANNEL: "abc123"

I have checked slack documentation and couldn't find out the reason. As template is working with channel name so hard to figure out.


问:
Appinventor with Googlesheets
I have a spreadsheet and I need to do a search on it, scanning it and finding what I need. I have an input box that accepts anything, I just really need to find it in the spreadsheet. But I can't, can someone help me?
how to find values in spreadsheet using a input box?

I used condition to access what was researched in the spreadsheet, however, it was not a responsive code and I would have to test it cell by cell, which would not be worth it.

Title: Appinventor with Googlesheets