问:
I have some problem with Hashmaps in my Spigot Plugin
I am making a plugin that when you run a command your Helmet will get saved in a Hashmap and in an other Hashmaps gets saved that you are now wearing that item then your head slot will get replaced with an item, but when I run the command I get a lot of error messages that don't help me, the only thing I know is that any of the Hashmaps is Null.

This is the code:

```<code>package de.polarbaerhd.gewei.Commands;

import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.HashMap;

public class GeweiCommand implements CommandExecutor {

    public HashMap<Player, ItemStack> playershelmet = new HashMap<>();
    public HashMap<Player, Boolean> hasgewei = new HashMap<>();

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        Player player = (Player) sender;

        if (hasgewei.get(player) == true) {
            player.getInventory().setHelmet(playershelmet.get(player));
            hasgewei.put(player, false);
        }

        ItemStack gewei = new ItemStack(Material.CARROT);
        ItemMeta meti = gewei.getItemMeta();
        ArrayList<String> lore = new ArrayList<String>();
        lore.add(" ");
        lore.add("§aDas Gestänge von dem Rentier.");
        lore.add(" ");
        meti.setLore(lore);
        meti.setDisplayName("Gestänge");

        ItemStack spielerhelm = new ItemStack(player.getInventory().getHelmet().getType());
        spielerhelm.setItemMeta(player.getInventory().getHelmet().getItemMeta());
        gewei.setItemMeta(meti);
        playershelmet.put(player, spielerhelm);
        hasgewei.put(player, true);
        player.getInventory().setHelmet(gewei);

        return false;
    }

}

</code>```

and that's the error message:

```<code>[23:19:14 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'gewei' in plugin Gewei v1.0-SNAPSHOT
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:47) ~[paper-api-1.19.2-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:155) ~[paper-api-1.19.2-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.craftbukkit.v1_19_R1.CraftServer.dispatchCommand(CraftServer.java:916) ~[paper-1.19.2.jar:git-Paper-232]
        at org.bukkit.craftbukkit.v1_19_R1.command.BukkitCommandWrapper.run(BukkitCommandWrapper.java:64) ~[paper-1.19.2.jar:git-Paper-232]
        at com.mojang.brigadier.CommandDispatcher.execute(CommandDispatcher.java:264) ~[paper-1.19.2.jar:?]
        at net.minecraft.commands.Commands.performCommand(Commands.java:305) ~[?:?]
        at net.minecraft.commands.Commands.performCommand(Commands.java:289) ~[?:?]
        at net.minecraft.server.network.ServerGamePacketListenerImpl.performChatCommand(ServerGamePacketListenerImpl.java:2294) ~[?:?]
        at net.minecraft.server.network.ServerGamePacketListenerImpl.lambda$handleChatCommand$20(ServerGamePacketListenerImpl.java:2248) ~[?:?]
        at net.minecraft.util.thread.BlockableEventLoop.lambda$submitAsync$0(BlockableEventLoop.java:59) ~[?:?]
        at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1768) ~[?:?]
        at net.minecraft.server.TickTask.run(TickTask.java:18) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.util.thread.BlockableEventLoop.doRunTask(BlockableEventLoop.java:153) ~[?:?]
        at net.minecraft.util.thread.ReentrantBlockableEventLoop.doRunTask(ReentrantBlockableEventLoop.java:24) ~[?:?]
        at net.minecraft.server.MinecraftServer.doRunTask(MinecraftServer.java:1341) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.server.MinecraftServer.d(MinecraftServer.java:185) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.util.thread.BlockableEventLoop.pollTask(BlockableEventLoop.java:126) ~[?:?]
        at net.minecraft.server.MinecraftServer.pollTaskInternal(MinecraftServer.java:1318) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.server.MinecraftServer.pollTask(MinecraftServer.java:1311) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.util.thread.BlockableEventLoop.managedBlock(BlockableEventLoop.java:136) ~[?:?]
        at net.minecraft.server.MinecraftServer.tickServer(MinecraftServer.java:1389) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1173) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:305) ~[paper-1.19.2.jar:git-Paper-232]
        at java.lang.Thread.run(Thread.java:833) ~[?:?]
Caused by: java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "java.util.HashMap.get(Object)" is null
        at de.polarbaerhd.gewei.Commands.GeweiCommand.onCommand(GeweiCommand.java:25) ~[gewei-1.0-SNAPSHOT.jar:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:45) ~[paper-api-1.19.2-R0.1-SNAPSHOT.jar:?]
        ... 23 more
</code>```

I thought with another Hashmap it could work but the same Errors show up.

Body:
I am making a plugin that when you run a command your Helmet will get saved in a Hashmap and in an other Hashmaps gets saved that you are now wearing that item then your head slot will get replaced with an item, but when I run the command I get a lot of error messages that don't help me, the only thing I know is that any of the Hashmaps is Null.

This is the code:

package de.polarbaerhd.gewei.Commands;

import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.HashMap;

public class GeweiCommand implements CommandExecutor {

    public HashMap<Player, ItemStack> playershelmet = new HashMap<>();
    public HashMap<Player, Boolean> hasgewei = new HashMap<>();

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        Player player = (Player) sender;

        if (hasgewei.get(player) == true) {
            player.getInventory().setHelmet(playershelmet.get(player));
            hasgewei.put(player, false);
        }

        ItemStack gewei = new ItemStack(Material.CARROT);
        ItemMeta meti = gewei.getItemMeta();
        ArrayList<String> lore = new ArrayList<String>();
        lore.add(" ");
        lore.add("§aDas Gestänge von dem Rentier.");
        lore.add(" ");
        meti.setLore(lore);
        meti.setDisplayName("Gestänge");

        ItemStack spielerhelm = new ItemStack(player.getInventory().getHelmet().getType());
        spielerhelm.setItemMeta(player.getInventory().getHelmet().getItemMeta());
        gewei.setItemMeta(meti);
        playershelmet.put(player, spielerhelm);
        hasgewei.put(player, true);
        player.getInventory().setHelmet(gewei);

        return false;
    }

}

and that's the error message:

[23:19:14 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'gewei' in plugin Gewei v1.0-SNAPSHOT
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:47) ~[paper-api-1.19.2-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:155) ~[paper-api-1.19.2-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.craftbukkit.v1_19_R1.CraftServer.dispatchCommand(CraftServer.java:916) ~[paper-1.19.2.jar:git-Paper-232]
        at org.bukkit.craftbukkit.v1_19_R1.command.BukkitCommandWrapper.run(BukkitCommandWrapper.java:64) ~[paper-1.19.2.jar:git-Paper-232]
        at com.mojang.brigadier.CommandDispatcher.execute(CommandDispatcher.java:264) ~[paper-1.19.2.jar:?]
        at net.minecraft.commands.Commands.performCommand(Commands.java:305) ~[?:?]
        at net.minecraft.commands.Commands.performCommand(Commands.java:289) ~[?:?]
        at net.minecraft.server.network.ServerGamePacketListenerImpl.performChatCommand(ServerGamePacketListenerImpl.java:2294) ~[?:?]
        at net.minecraft.server.network.ServerGamePacketListenerImpl.lambda$handleChatCommand$20(ServerGamePacketListenerImpl.java:2248) ~[?:?]
        at net.minecraft.util.thread.BlockableEventLoop.lambda$submitAsync$0(BlockableEventLoop.java:59) ~[?:?]
        at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1768) ~[?:?]
        at net.minecraft.server.TickTask.run(TickTask.java:18) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.util.thread.BlockableEventLoop.doRunTask(BlockableEventLoop.java:153) ~[?:?]
        at net.minecraft.util.thread.ReentrantBlockableEventLoop.doRunTask(ReentrantBlockableEventLoop.java:24) ~[?:?]
        at net.minecraft.server.MinecraftServer.doRunTask(MinecraftServer.java:1341) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.server.MinecraftServer.d(MinecraftServer.java:185) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.util.thread.BlockableEventLoop.pollTask(BlockableEventLoop.java:126) ~[?:?]
        at net.minecraft.server.MinecraftServer.pollTaskInternal(MinecraftServer.java:1318) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.server.MinecraftServer.pollTask(MinecraftServer.java:1311) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.util.thread.BlockableEventLoop.managedBlock(BlockableEventLoop.java:136) ~[?:?]
        at net.minecraft.server.MinecraftServer.tickServer(MinecraftServer.java:1389) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1173) ~[paper-1.19.2.jar:git-Paper-232]
        at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:305) ~[paper-1.19.2.jar:git-Paper-232]
        at java.lang.Thread.run(Thread.java:833) ~[?:?]
Caused by: java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "java.util.HashMap.get(Object)" is null
        at de.polarbaerhd.gewei.Commands.GeweiCommand.onCommand(GeweiCommand.java:25) ~[gewei-1.0-SNAPSHOT.jar:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:45) ~[paper-api-1.19.2-R0.1-SNAPSHOT.jar:?]
        ... 23 more

I thought with another Hashmap it could work but the same Errors show up.


来源: stackexchange

问:
deployed mern heroku app not hitting endpoint
I deployed my MERN app on heroku. However, I am only able to hit the login endpoint, the other api ednpoints are not working. I have tried changing the proxy address from my local server   "http://127.0.0.1:1000" to my heroku's "https://carer-visit.herokuapp.com/". But they are not responding.

Here is the LOGIN endpoint that is working when deployed

```<code>export function login(userdata) {
  return async (dispatch) => {
    try {

      const loggedInUser = await axios.post(`/api/v1/carers/login`, userdata);

      let { data } = loggedInUser;

      localStorage.setItem('Authtoken', data.token);
      dispatch(setCurrentUser(data.user));
    } catch (error) {
      console.log(error.response.data);
      localStorage.removeItem('Authtoken');
      dispatch(setCurrentUserFailure());
    }
  };
}
</code>```

HERE is an example of another endpoint that is not working when deployed

```<code>export function fetchCarers() {
  return async (dispatch) => {
    dispatch(getCarers());

    try {
      const carerData = await axios.get('/api/v1/carers');

      let {
        data: {
          data: { users },
        },
      } = carerData;

      dispatch(setCarer(users));
    } catch (error) {
      dispatch(getCarerFailure());
    }
  };
}
</code>```

The problem was from here.

```<code> if (process.env.NODE_ENV === 'production') {
      app.use(express.static('client/build'));

      app.get('*', (req, res) => {
        let filePath = path.resolve(__dirname, 'client/build', 'index.html');

        res.sendFile(filePath);
      });
    }
</code>```

I removed the '*' and changed it to this '/'. It started working

```<code> if (process.env.NODE_ENV === 'production') {
          app.use(express.static('client/build'));

          app.get('/', (req, res) => {
            let filePath = path.resolve(__dirname, 'client/build', 'index.html');

            res.sendFile(filePath);
          });
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I deployed my MERN app on heroku. However, I am only able to hit the login endpoint, the other api ednpoints are not working. I have tried changing the proxy address from my local server   "http://127.0.0.1:1000" to my heroku's "https://carer-visit.herokuapp.com/". But they are not responding.

Here is the LOGIN endpoint that is working when deployed

export function login(userdata) {
  return async (dispatch) => {
    try {

      const loggedInUser = await axios.post(`/api/v1/carers/login`, userdata);

      let { data } = loggedInUser;

      localStorage.setItem('Authtoken', data.token);
      dispatch(setCurrentUser(data.user));
    } catch (error) {
      console.log(error.response.data);
      localStorage.removeItem('Authtoken');
      dispatch(setCurrentUserFailure());
    }
  };
}

HERE is an example of another endpoint that is not working when deployed

export function fetchCarers() {
  return async (dispatch) => {
    dispatch(getCarers());

    try {
      const carerData = await axios.get('/api/v1/carers');

      let {
        data: {
          data: { users },
        },
      } = carerData;

      dispatch(setCarer(users));
    } catch (error) {
      dispatch(getCarerFailure());
    }
  };
}

The problem was from here.

 if (process.env.NODE_ENV === 'production') {
      app.use(express.static('client/build'));

      app.get('*', (req, res) => {
        let filePath = path.resolve(__dirname, 'client/build', 'index.html');

        res.sendFile(filePath);
      });
    }

I removed the '*' and changed it to this '/'. It started working

 if (process.env.NODE_ENV === 'production') {
          app.use(express.static('client/build'));

          app.get('/', (req, res) => {
            let filePath = path.resolve(__dirname, 'client/build', 'index.html');

            res.sendFile(filePath);
          });
        }


问:
Getting this error: This solver needs samples of at least 2 classes in the data, but the data contains only one class: '2'
I have a code that is supposed to do these things:

Load already trained model

Load an unseen dataset

Create a pipeline which takes Bert encoder  (SentenceTransformer('all-mpnet-base-v2')) and my trained model.

Then randomly choose a row from dataset, encode it, and predict it

Then ask if the prediction is correct. If not, then ask for the  correct prediction and retrain the model with the right prediction

I have this following code:

```<code>random_row = full_df.sample(1)
X = random_row[['mmgid', 'body','preprocessedBody']]  # select specific columns
article = np.random.choice(X['preprocessedBody'])
encoded_text = bert_model.encode([article])

prediction = multi_model.predict(encoded_text)[0]
print(X['body'])
print(f"Prediction: {prediction}")

# Ask the user if the prediction is correct
response = input("Is this prediction correct? (yes/no)")
# If the prediction is incorrect, ask the user for the correct classification
if response.lower() == 'no':
    correct_classification = input("What is the correct classification for this article?")

    # Retrain the model using the original article and the correct classification
    multi_model.fit([encoded_text2], [correct_classification])

    # Test the updated model by classifying the same article again
    updated_prediction = multi_model.predict([article])

    # Display the new prediction to the user
    print(f"The updated model predicts that this article belongs to the '{updated_prediction}' category.")
</code>```

But I am getting this error:

```<code>-> 1183     raise ValueError(
   1184         "This solver needs samples of at least 2 classes"
   1185         " in the data, but the data contains only one"
   1186         " class: %r"
   1187         % classes_[0]
   1188     )
   1190 if len(self.classes_) == 2:
   1191     n_classes = 1

ValueError: This solver needs samples of at least 2 classes in the data, but the data contains only one class: '2'
</code>```

How can I resolve this issue?

Thanks

Body:
I have a code that is supposed to do these things:

Load already trained model

Load an unseen dataset

Create a pipeline which takes Bert encoder  (SentenceTransformer('all-mpnet-base-v2')) and my trained model.

Then randomly choose a row from dataset, encode it, and predict it

Then ask if the prediction is correct. If not, then ask for the  correct prediction and retrain the model with the right prediction

I have this following code:

random_row = full_df.sample(1)
X = random_row[['mmgid', 'body','preprocessedBody']]  # select specific columns
article = np.random.choice(X['preprocessedBody'])
encoded_text = bert_model.encode([article])

prediction = multi_model.predict(encoded_text)[0]
print(X['body'])
print(f"Prediction: {prediction}")

# Ask the user if the prediction is correct
response = input("Is this prediction correct? (yes/no)")
# If the prediction is incorrect, ask the user for the correct classification
if response.lower() == 'no':
    correct_classification = input("What is the correct classification for this article?")

    # Retrain the model using the original article and the correct classification
    multi_model.fit([encoded_text2], [correct_classification])

    # Test the updated model by classifying the same article again
    updated_prediction = multi_model.predict([article])

    # Display the new prediction to the user
    print(f"The updated model predicts that this article belongs to the '{updated_prediction}' category.")

But I am getting this error:

-> 1183     raise ValueError(
   1184         "This solver needs samples of at least 2 classes"
   1185         " in the data, but the data contains only one"
   1186         " class: %r"
   1187         % classes_[0]
   1188     )
   1190 if len(self.classes_) == 2:
   1191     n_classes = 1

ValueError: This solver needs samples of at least 2 classes in the data, but the data contains only one class: '2'

How can I resolve this issue?

Thanks


问:
Pyo: best way to trigger samples at specific BPM?
I am trying to use Pyo (python module for sound synthesis) to create a track however I am having a hard time understanding how samples are triggered. If, for example, I wish to play a specific sample at 120 bpm, in sync with other synthesizers is the best option to use triggers or a soundtable?

I have tried triggering the samples using time difference but I dont understand how to sync the timing of various tracks throughout one song


问:
CSRF Token with the “SameSite” attribute value “Lax” or “Strict” was omitted because of a cross-site redirect
I am using Kratos in my local environment just fine, works great and does what I want it to do, however the main issue I am facing is when I moved my ory kratos location to a droplet and my frontend to my vercel. On the droplet I have setup kratos as show here with nginx. After setting it up I tested my login flow and got these error's when I requested /self-service/registration/flows?id=${flowId}

Thinking I setup my config incorrectly I set it up as seen here.

version: v0.10.1

dsn: postgres://kratos:MYPASSWORD/kratos?sslmode=disable&max_conns=20&max_idle_conns=4

serve:
  public:
    base_url: http://127.0.0.1:4433/
    host: 127.0.0.1
    cors:
      allow_credentials: true
      allowed_origins:
        - https://frontend.example.com
      allowed_methods:
        - POST
        - GET
        - PUT
        - PATCH
        - DELETE
      allowed_headers:
        - Authorization
        - Cookie
        - Content-Type
      exposed_headers:
        - Content-Type
        - Set-Cookie
      enabled: true
  admin:
    base_url: http://kratos:4434/
    host: 127.0.0.1

selfservice:
  default_browser_return_url: https://frontend.example.com
  allowed_return_urls:
    - https://frontend.example.com
  methods:
    password:
      enabled: true
    oidc:
      enabled: false
  flows:
    error:
      ui_url: https://frontend.example.comerror

    settings:
      ui_url: https://frontend.example.comsettings
      privileged_session_max_age: 15m

    recovery:
      enabled: true
      ui_url: https://frontend.example.comrecovery

    verification:
      enabled: true
      ui_url: https://frontend.example.comverification
      after:
        default_browser_return_url: https://frontend.example.com/

    logout:
      after:
        default_browser_return_url: https://frontend.example.com/

    login:
      ui_url: https://frontend.example.com/login
      lifespan: 10m

    registration:
      lifespan: 10m
      ui_url: https://frontend.example.com/registration
      after:
        password:
          hooks:
            - hook: session
        oidc:
          hooks:
             - hook: session

log:
  leak_sensitive_values: false

# set in SECRETS_COOKIE and SECRETS_DEFAULT env variables
secrets:
  default:
    - 795135465767325463454 #fake
  cookie:
    - 223108c7839f6324242342 #fake

cookies:
  domain: frontend.example.com
  path: /
  same_site: Lax

session:
  lifespan: 72h
  cookie:
    domain: frontend.example.com
    path: /
    same_site: Lax

hashers:
  argon2:
    parallelism: 1
    memory: 128MB
    iterations: 2
    salt_length: 16
    key_length: 16

identity:
  default_schema_id: default
  schemas:
    - id: default
      url: file:///root/kratos/config/identity.schema.json

courier:
  smtp:
    connection_uri: smtps://test:test@mailslurper:1025/?skip_ssl_verify=true
```
<p>The issue still persisted so I checked my code</p>
```const req: any = await fetch(`https://frontend.example.com/self-service/${flow}/flows?id=${flowId}`, {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',

      },
      credentials: 'include',
    }).catch((err) => {
      throw err;
    }); //error
```

everything seems fine, I have credentials and my Content-Type was correct, Then doing some research I found this https://github.com/ory/kratos/issues/662 I was wondering, would this effect me in my situation (I have my frontend domain https://frontend.example.com and my kratos droplet https://kratos.example.com are examples), and if so how I could go about fixing it(could I use the ory-proxy to get cookies to my application safely?)? My idea was that I could simply setup ory hydra has the oauth provider for my platform but I am not sure.

Also,

Thanks in advance!

Body:
I am using Kratos in my local environment just fine, works great and does what I want it to do, however the main issue I am facing is when I moved my ory kratos location to a droplet and my frontend to my vercel. On the droplet I have setup kratos as show here with nginx. After setting it up I tested my login flow and got these error's when I requested /self-service/registration/flows?id=${flowId}

Thinking I setup my config incorrectly I set it up as seen here.

version: v0.10.1

dsn: postgres://kratos:MYPASSWORD/kratos?sslmode=disable&max_conns=20&max_idle_conns=4

serve:
  public:
    base_url: http://127.0.0.1:4433/
    host: 127.0.0.1
    cors:
      allow_credentials: true
      allowed_origins:
        - https://frontend.example.com
      allowed_methods:
        - POST
        - GET
        - PUT
        - PATCH
        - DELETE
      allowed_headers:
        - Authorization
        - Cookie
        - Content-Type
      exposed_headers:
        - Content-Type
        - Set-Cookie
      enabled: true
  admin:
    base_url: http://kratos:4434/
    host: 127.0.0.1

selfservice:
  default_browser_return_url: https://frontend.example.com
  allowed_return_urls:
    - https://frontend.example.com
  methods:
    password:
      enabled: true
    oidc:
      enabled: false
  flows:
    error:
      ui_url: https://frontend.example.comerror

    settings:
      ui_url: https://frontend.example.comsettings
      privileged_session_max_age: 15m

    recovery:
      enabled: true
      ui_url: https://frontend.example.comrecovery

    verification:
      enabled: true
      ui_url: https://frontend.example.comverification
      after:
        default_browser_return_url: https://frontend.example.com/

    logout:
      after:
        default_browser_return_url: https://frontend.example.com/

    login:
      ui_url: https://frontend.example.com/login
      lifespan: 10m

    registration:
      lifespan: 10m
      ui_url: https://frontend.example.com/registration
      after:
        password:
          hooks:
            - hook: session
        oidc:
          hooks:
             - hook: session

log:
  leak_sensitive_values: false

# set in SECRETS_COOKIE and SECRETS_DEFAULT env variables
secrets:
  default:
    - 795135465767325463454 #fake
  cookie:
    - 223108c7839f6324242342 #fake

cookies:
  domain: frontend.example.com
  path: /
  same_site: Lax

session:
  lifespan: 72h
  cookie:
    domain: frontend.example.com
    path: /
    same_site: Lax

hashers:
  argon2:
    parallelism: 1
    memory: 128MB
    iterations: 2
    salt_length: 16
    key_length: 16

identity:
  default_schema_id: default
  schemas:
    - id: default
      url: file:///root/kratos/config/identity.schema.json

courier:
  smtp:
    connection_uri: smtps://test:test@mailslurper:1025/?skip_ssl_verify=true

The issue still persisted so I checked my code

const req: any = await fetch(`https://frontend.example.com/self-service/${flow}/flows?id=${flowId}`, {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',

      },
      credentials: 'include',
    }).catch((err) => {
      throw err;
    }); //error

everything seems fine, I have credentials and my Content-Type was correct, Then doing some research I found this https://github.com/ory/kratos/issues/662 I was wondering, would this effect me in my situation (I have my frontend domain https://frontend.example.com and my kratos droplet https://kratos.example.com are examples), and if so how I could go about fixing it(could I use the ory-proxy to get cookies to my application safely?)? My idea was that I could simply setup ory hydra has the oauth provider for my platform but I am not sure.

Also,

Thanks in advance!


问:
Power BI Capacity failed to refresh dataset even after capacity size increased
I have a power bi dataset with aprox. 300MB in pbix file size and 1.2GB RAM memory size (according to Vertipaq analyser in dax studio).

I've always been able to refresh dataset directly from power bi website using its own servers without using premium capacity ( and still can update the same dataset)

Most of the dataset inputs comes from Athena AWS as input mode, not direct query and we dont have any incremental refresh so far.

I's been a few months that we started to deploy some reports using Power BI Capacities. Most of our reports are not heavy ram/cpu usage and we use a A1 capacity without problems.

The issue starts when we try to refresh our dataset that is deployed by the capacity in times where our users are requesting data from it. We trigger the refresh from microsoft API. At first, we started to get some memory errors so we changed our script to first change capacity from A1 to A3 or A4, wait 60 seconds to be sure that new memory is available ( is this really necessary?) and then trigger the dataset refresh.

Even with A4 capacity, i'm unable to refresh the dataset with the following error after some minutes (usually takes 20mins to refresh, errors appears around 10-15 minutes running):

"This operation was canceled because there wasn’t enough memory to finish running it. Either increase the memory of the Premium capacity where this dataset is hosted or reduce the memory footprint of your dataset by doing things like limiting the amount of imported data. More details: consumed memory 1764 MB, memory limit 1764 MB, database size before command execution 1307 MB. Learn more, see https://go.microsoft.com/fwlink/?linkid=2159753."

What sees strange is the total memory description in the error, aprox. 3GB that would be the A1 capacity, but i'm 100% sure that i've changed the capacity to A4 before the refresh started using microsoft API and even double checked on Azure website.

Also, it's worth mentioning that I'm able to refresh this dataset using the same strategy when we first turn the capacity on (its early in the day about 06:30am and no one is actually consuming resources from capacity).

I'm aware that capacity needs twice the size of aprox. ram memory size + incoming querys when the dataset refresh is requested. But in my calculations, that would be 1.2GB * 2 = 2.4GB + incoming querys. Since A1 capacity can run perfect to users demand, I can't understand why i'm having trouble updating a dataset with A4 capacity (25gb ram available).

Am I doing something wrong changing the capacity before trying to update? It seems like it has no effects on the total RAM available to refresh.

In the scenario that a incoming query is using GBs of ram and reaching the 25gb ram ( i dont thing this is the case), how can I be sure that this is not happening or find out who is requesting such query?

This is my first time writting a question here, I apologize in advance for any mistakes and would be very glad for any help.

Tried to refresh dataset that is served by Power BI Capacity after upgrading capacity to A4. I expected to refresh the dataset without problemns and even without needing to upgrade to A4 (this sounds to me really unnecessary). The problem appears after some minutes only when the same capacity is receiving query from users reports.


问:
FLutter Android Plugin, onDestroy function is not attached to the plugin class
i am creating a plugin with the onAttachedToEngine function that i use to assign context and mediaPlayer session to variables, exactly like the docs say so nothing special is being done. The problem is that when my plugin throws an error and it's time for the onDestroy function to be called, the onDestroy function doesn't seem to see the variables i set during the usage of the current object.

so if i set a variable X to "hello" in the onAttachedToEngine, onDestroy will keep seeing it as null and creates nullPointer exceptions which crashes my plugin and app.

here is a sample code i am using :

```<code>public class flutterPlugin extends MediaBrowserService implements FlutterPlugin, MethodCallHandler {
  private String randomString = "lowercase";

 private void initInstance(BinaryMessenger binaryMessenger, Context context) {
    this.channel = new MethodChannel(binaryMessenger, ID);
    this.channel.setMethodCallHandler(this);
    am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    mContext=context;
    mNotificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    setupBroadcastReceiver();
    startSession(mContext);
    this.randomStirng = "UPPERCASE";

  }

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
    this.initInstance(binding.getBinaryMessenger(), binding.getApplicationContext());
  }

  @Override
  public void onDestroy() {

  this.randomStirng // here the random string i initialized is equal to "lowercase"
  // and the same goes for all the variables initialized in initInstance, they are alll treated an null
  (...)
  }

(...)
}
</code>```

what could the issue be ? is onDestroy being called from a child process ? when getting the parent of super it returns the same class name as the plugin

Body:
i am creating a plugin with the onAttachedToEngine function that i use to assign context and mediaPlayer session to variables, exactly like the docs say so nothing special is being done. The problem is that when my plugin throws an error and it's time for the onDestroy function to be called, the onDestroy function doesn't seem to see the variables i set during the usage of the current object.

so if i set a variable X to "hello" in the onAttachedToEngine, onDestroy will keep seeing it as null and creates nullPointer exceptions which crashes my plugin and app.

here is a sample code i am using :

public class flutterPlugin extends MediaBrowserService implements FlutterPlugin, MethodCallHandler {
  private String randomString = "lowercase";

 private void initInstance(BinaryMessenger binaryMessenger, Context context) {
    this.channel = new MethodChannel(binaryMessenger, ID);
    this.channel.setMethodCallHandler(this);
    am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    mContext=context;
    mNotificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    setupBroadcastReceiver();
    startSession(mContext);
    this.randomStirng = "UPPERCASE";

  }

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
    this.initInstance(binding.getBinaryMessenger(), binding.getApplicationContext());
  }

  @Override
  public void onDestroy() {

  this.randomStirng // here the random string i initialized is equal to "lowercase"
  // and the same goes for all the variables initialized in initInstance, they are alll treated an null
  (...)
  }

(...)
}

what could the issue be ? is onDestroy being called from a child process ? when getting the parent of super it returns the same class name as the plugin


问:
Why do some flex items not shrink as expected?
I have two sets of code, the first is a simple one which has an expected result, the second is unexpected.

In the simple code, I have a fixed height child .fixed. I also have flex child .scrollable.

When I shrink the screen, the .scrollable div first shrinks until its minimum height. Then the .fixed div shrinks, to accommodate the 50vh that is assigned to .parent. Only when these two components are fully shrunk do they eventually overflow the .parent div. Even though .fixed has an assigned height, it does not have an assigned minimum height, so it makes sense that .fixed shrinks.

https://codepen.io/Sean713/pen/xxJZLeo

.parent {
  display: flex;
  flex-direction: column;
  height: 50vh;
  border: 3px solid black;
  width: 200px;
}

.fixed {
  height: 40px;
  border: 3px solid red;
}

.scrollable {
  overflow-y: scroll;
  flex: 1;
  min-height: 90px;
  border: 3px solid orange;
}

p {
  margin: 0;
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="fixed">
    I have fixed height
  </div>
  <div class="scrollable">
    <p>I am scrollable</p>
    <p>I am scrollable</p>
    <p>I am scrollable</p>
    <p>I am scrollable</p>
    <p>I am scrollable</p>
    <p>I am scrollable</p>
  </div>
</div></code>```

However, in a more complex example, I expect the same pattern to occur but it does not.

In this code, my understanding is as follows:

We start to shrink the screen, .blue and .green flex. Inside .blue, .orange shrinks, as .white is fixed. Once .orange reaches its minimum height, I would expect .white to start shrinking as a minimum-height has not been assigned, but it does not. I do not understand why as this seems similar to the first code example.

Similarly, .black never shrinks as well, I do not understand why.

https://codepen.io/Sean713/pen/PoBZKbP

.root {
  height: 70vh;
  display: flex;
  flex-direction: column;
}

.blue {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.white {
  height: 50px;
}

.orange {
  flex: 1;
  min-height: 30px;
}

.purple {
  flex: 1;
}

.green {
  height: 95%;
  display: flex;
  flex-direction: column;
}

.black {
  height: 40px;
}

.red {
  overflow-y: scroll;
  flex: 1;
  min-height: 20px;
}

/* ________________STYLING_______________ */

.root {
  width: 300px;
  border: 3px solid red;
}

.blue {
  border: 5px solid blue;
}

.white {
  background-color: grey;
  border: 3px solid white;
}

.orange {
  background-color: lightgrey;
  border: 3px solid orange;
}

.purple {
  border: 3px solid purple;
}

.green {
  border: 3px solid green;
}

.black {
  border: 3px solid black;
}

.red {
  border: 3px solid red;
}

p {
  margin: 0;
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="root">
  <div class="blue">
    <div class="white">
      I have fixed height (panel)
    </div>
    <div class="orange">I don't (cube)</div>
  </div>
  <div class="purple">
    <div class="green">
      <div class="black">
        <p>I am a fixed height header</p>
      </div>
      <div class="red">
        <p>I can scroll</p>
        <p>I can scroll</p>
        <p>I can scroll</p>
        <p>I can scroll</p>
        <!--         <p>I can scroll</p>
        <p>I can scroll</p>
        <p>I can scroll</p>
        <p>I can scroll</p>
        <p>I can scroll</p>
        <p>I can scroll</p>
        <p>I can scroll</p>
        <p>I can scroll</p> -->
      </div>
    </div>
  </div>
</div>

``````

I have tried research both this forum and elsewhere but have not been able to understand why.

Body:
I have two sets of code, the first is a simple one which has an expected result, the second is unexpected.

In the simple code, I have a fixed height child .fixed. I also have flex child .scrollable.

When I shrink the screen, the .scrollable div first shrinks until its minimum height. Then the .fixed div shrinks, to accommodate the 50vh that is assigned to .parent. Only when these two components are fully shrunk do they eventually overflow the .parent div. Even though .fixed has an assigned height, it does not have an assigned minimum height, so it makes sense that .fixed shrinks.

https://codepen.io/Sean713/pen/xxJZLeo

.parent {
  display: flex;
  flex-direction: column;
  height: 50vh;
  border: 3px solid black;
  width: 200px;
}

.fixed {
  height: 40px;
  border: 3px solid red;
}

.scrollable {
  overflow-y: scroll;
  flex: 1;
  min-height: 90px;
  border: 3px solid orange;
}

p {
  margin: 0;
  padding: 0;
}

    I have fixed height

I am scrollable

I am scrollable

I am scrollable

I am scrollable

I am scrollable

I am scrollable

However, in a more complex example, I expect the same pattern to occur but it does not.

In this code, my understanding is as follows:

We start to shrink the screen, .blue and .green flex. Inside .blue, .orange shrinks, as .white is fixed. Once .orange reaches its minimum height, I would expect .white to start shrinking as a minimum-height has not been assigned, but it does not. I do not understand why as this seems similar to the first code example.

Similarly, .black never shrinks as well, I do not understand why.

https://codepen.io/Sean713/pen/PoBZKbP

.root {
  height: 70vh;
  display: flex;
  flex-direction: column;
}

.blue {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.white {
  height: 50px;
}

.orange {
  flex: 1;
  min-height: 30px;
}

.purple {
  flex: 1;
}

.green {
  height: 95%;
  display: flex;
  flex-direction: column;
}

.black {
  height: 40px;
}

.red {
  overflow-y: scroll;
  flex: 1;
  min-height: 20px;
}

/* ________________STYLING_______________ */

.root {
  width: 300px;
  border: 3px solid red;
}

.blue {
  border: 5px solid blue;
}

.white {
  background-color: grey;
  border: 3px solid white;
}

.orange {
  background-color: lightgrey;
  border: 3px solid orange;
}

.purple {
  border: 3px solid purple;
}

.green {
  border: 3px solid green;
}

.black {
  border: 3px solid black;
}

.red {
  border: 3px solid red;
}

p {
  margin: 0;
  padding: 0;
}

      I have fixed height (panel)

I don't (cube)

I am a fixed height header

I can scroll

I can scroll

I can scroll

I can scroll

```

I have tried research both this forum and elsewhere but have not been able to understand why.


问:
Chrome Browser with localhost
Testing an e-commerce website, it's MERN stack when I run npm run develop chrome opens the page on localhost but I'm unable to click anything on it.

I open Microsoft Edge go in the localhost the application works properly, can add to cart, go into payment, everything works.

Was there an update on Chrome and how I fix this issue

Works on Microsoft Edge not on Chrome

Title: Chrome Browser with localhost


问:
How to recreate photomath photoscaner in react native?
I'm trying to recreate photomath photoscaner in react native, and I cant find any simple solution that can "select" part of an image and crop it while using camera, and solution that can be resized at the same time. Do you have any suggestion on how to implement this?

Here is how it looks like:


问:
SyntaxError: 'await' outside function - Error in local script, works in Jupyter Notebooks
This works in Jupyter notebooks but gives a SyntaxError: 'await' outside function in a local python script.  I've imported all of the same python modules in the Jupiter notebook.

```<code>async def download(url, filename):
    response = await pyfetch(url)
    if response.status == 200:
        with open(filename, "wb") as f: # write binary mode
            f.write(await response.bytes())

path='https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%204/data/Cust_Segmentation.csv'

# download(path, "Cust_Segmentation.csv") # Produces this error: RuntimeWarning: coroutine 'download' was never awaited
await download(path, "Cust_Segmentation.csv")
</code>```

and got this error

```<code>    await download(path, "Cust_Segmentation.csv")
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function
</code>```

Any idea what's going on?  Remember, this works in Jupyter notebooks and NOT in

Solutions Attempted

I tried removing the await before calling the function and got this error: RuntimeWarning: coroutine 'download' was never awaited.

The following links do not appear to be relevant.

%time await main() throws SyntaxError: 'await' outside function in jupyter

discord.py SyntaxError: 'await' outside function

This may have some relevance, but I've tried removing the await and it still throws a different error: RuntimeWarning: coroutine 'download' was never awaited or UnboundLocalError: local variable '_jsfetch' referenced before assignment

'await' outside function error given when running program

Specific error with asyncio.run(download(URL, "Cust_Segmentation.csv")) is the following:

```<code>tail example.py

filename ="Cust_Segmentation.csv"

async def download(url, filename):
    response = await pyfetch(url)
    if response.status == 200:
        with open(filename, "wb") as f: # write binary mode
            f.write(await response.bytes())

asyncio.run(download(URL, "Cust_Segmentation.csv"))
</code>```

Produces:

```<code>python3 example.py
/data/XXX/miniconda/envs/devel/lib/python3.10/site-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.23.1
  warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}"
Traceback (most recent call last):
  File "/mnt/d/DEMO/MachineLearning/k-means_clustering/example.py", line 33, in <module>
    asyncio.run(download(URL, "Cust_Segmentation.csv"))
  File "/data/XXX/miniconda/envs/devel/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/data/XXX/miniconda/envs/devel/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
    return future.result()
  File "/mnt/d/DEMO/MachineLearning/k-means_clustering/example.py", line 28, in download
    response = await pyfetch(url)
  File "/data/XXX/miniconda/envs/devel/lib/python3.10/site-packages/pyodide/http.py", line 234, in pyfetch
    url, await _jsfetch(url, to_js(kwargs, dict_converter=Object.fromEntries))
UnboundLocalError: local variable '_jsfetch' referenced before assignment
</code>```

Body:
This works in Jupyter notebooks but gives a SyntaxError: 'await' outside function in a local python script.  I've imported all of the same python modules in the Jupiter notebook.

async def download(url, filename):
    response = await pyfetch(url)
    if response.status == 200:
        with open(filename, "wb") as f: # write binary mode
            f.write(await response.bytes())

path='https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%204/data/Cust_Segmentation.csv'

# download(path, "Cust_Segmentation.csv") # Produces this error: RuntimeWarning: coroutine 'download' was never awaited
await download(path, "Cust_Segmentation.csv")

and got this error

    await download(path, "Cust_Segmentation.csv")
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function

Any idea what's going on?  Remember, this works in Jupyter notebooks and NOT in

Solutions Attempted

I tried removing the await before calling the function and got this error: RuntimeWarning: coroutine 'download' was never awaited.

The following links do not appear to be relevant.

%time await main() throws SyntaxError: 'await' outside function in jupyter

discord.py SyntaxError: 'await' outside function

This may have some relevance, but I've tried removing the await and it still throws a different error: RuntimeWarning: coroutine 'download' was never awaited or UnboundLocalError: local variable '_jsfetch' referenced before assignment

'await' outside function error given when running program

Specific error with asyncio.run(download(URL, "Cust_Segmentation.csv")) is the following:

tail example.py

filename ="Cust_Segmentation.csv"

async def download(url, filename):
    response = await pyfetch(url)
    if response.status == 200:
        with open(filename, "wb") as f: # write binary mode
            f.write(await response.bytes())

asyncio.run(download(URL, "Cust_Segmentation.csv"))

Produces:

python3 example.py
/data/XXX/miniconda/envs/devel/lib/python3.10/site-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.23.1
  warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}"
Traceback (most recent call last):
  File "/mnt/d/DEMO/MachineLearning/k-means_clustering/example.py", line 33, in <module>
    asyncio.run(download(URL, "Cust_Segmentation.csv"))
  File "/data/XXX/miniconda/envs/devel/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/data/XXX/miniconda/envs/devel/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
    return future.result()
  File "/mnt/d/DEMO/MachineLearning/k-means_clustering/example.py", line 28, in download
    response = await pyfetch(url)
  File "/data/XXX/miniconda/envs/devel/lib/python3.10/site-packages/pyodide/http.py", line 234, in pyfetch
    url, await _jsfetch(url, to_js(kwargs, dict_converter=Object.fromEntries))
UnboundLocalError: local variable '_jsfetch' referenced before assignment


问:
Salesforce XSLT AccountContactRole ==> AccountContactRelations
Pretty new to XSLT...  trying to convert an existing one based on SF Classic's "AccountContactRole" table to the newer "AccountContactRelations".. here's the snippit of the original I'm trying to convert to use the new "AccountContactRelations" table :

```<code>`    <xsl:template match="*:AccountContactRole">
        <row>
            <SUBMITTER></SUBMITTER>
            <SORT_ORDER>
                <xsl:choose>
                    <xsl:when test="*:role='Billing Contact'">1</xsl:when>
                    <xsl:when test="*:role='Order Contact'">2</xsl:when>
                    <xsl:otherwise>3</xsl:otherwise>
                </xsl:choose>
            </SORT_ORDER>
            <ROLE><xsl:value-of select="*:Role" /></ROLE>

        </row>
    </xsl:template>`

</code>```

Of course, now the contacts are compressed to a single entry.. e.g., "Billing Contact;Order Contact;Sandwich Contact;SomeOther Contact" .. and.. they could be in any order, so I will need to iterate over this string until it is empty?

Thanks for any ideas / suggestions... perhaps someone has struggled with the same requirement before when migrating to AccountContactRelations?

~Pete

Body:
Pretty new to XSLT...  trying to convert an existing one based on SF Classic's "AccountContactRole" table to the newer "AccountContactRelations".. here's the snippit of the original I'm trying to convert to use the new "AccountContactRelations" table :

`    <xsl:template match="*:AccountContactRole">
        <row>
            <SUBMITTER></SUBMITTER>
            <SORT_ORDER>
                <xsl:choose>
                    <xsl:when test="*:role='Billing Contact'">1</xsl:when>
                    <xsl:when test="*:role='Order Contact'">2</xsl:when>
                    <xsl:otherwise>3</xsl:otherwise>
                </xsl:choose>
            </SORT_ORDER>
            <ROLE><xsl:value-of select="*:Role" /></ROLE>

        </row>
    </xsl:template>`

Of course, now the contacts are compressed to a single entry.. e.g., "Billing Contact;Order Contact;Sandwich Contact;SomeOther Contact" .. and.. they could be in any order, so I will need to iterate over this string until it is empty?

Thanks for any ideas / suggestions... perhaps someone has struggled with the same requirement before when migrating to AccountContactRelations?

~Pete


问:
Is it possible to get a list of games someone owns on xbox via their gamertag?
Given a gamertag that has public privacy settings, is it possible for me to programatically access the games they purchased?

I'm trying to build an "import your xbox games" features so someone can just type in their gamertag and I can get all of their games for their collection.


问:
What to do in case of "Compilation error: braces around scalar initializer for type 'int'"
I just got my first Arduino, and I'm trying to extend beyond the tutorial and I want to try to make a song with coherent tempos, although the tutorial doesn't explain it :)

this is just one part of the code, and I'm using a passive buzzer btw

```<code>#include "pitches.h" // these help to just put the notes and not the hertz
#include "npm.h"     // these ones to control the Notes Per Minute

// notes in the melody:
int melody1[] = {{NOTE_E2, NOTE_HALF},
                 {NOTE_E2, NOTE_HALF},
                 {NOTE_F2, NOTE_HALF},
                 {NOTE_FS2, NOTE_WHOLE},
                 {NOTE_A2},
                 {NOTE_FS2},
                 {NOTE_A2},
                 {NOTE_FS2},
                 {NOTE_F2},
                 {NOTE_E2},
                 {NOTE_B2},
                 {NOTE_E2},
                 {NOTE_E2}};
                          ↑ that's the brace that is complicating everything ☠

</code>```

when ever I put it the error in the tittle pops out, but if I erase it another error appears:

```<code>Compilation error: expected '}' before ';' token
</code>```

it's contradicting itself, idk what to do :|

*don't worry about the note_half and whole, it is not finished cuz i just wanted to check the tempo before i finished so i wouldn't make it all over again, but the error appeared :|

Body:
I just got my first Arduino, and I'm trying to extend beyond the tutorial and I want to try to make a song with coherent tempos, although the tutorial doesn't explain it :)

this is just one part of the code, and I'm using a passive buzzer btw

#include "pitches.h" // these help to just put the notes and not the hertz
#include "npm.h"     // these ones to control the Notes Per Minute

// notes in the melody:
int melody1[] = {{NOTE_E2, NOTE_HALF},
                 {NOTE_E2, NOTE_HALF},
                 {NOTE_F2, NOTE_HALF},
                 {NOTE_FS2, NOTE_WHOLE},
                 {NOTE_A2},
                 {NOTE_FS2},
                 {NOTE_A2},
                 {NOTE_FS2},
                 {NOTE_F2},
                 {NOTE_E2},
                 {NOTE_B2},
                 {NOTE_E2},
                 {NOTE_E2}};
                          ↑ that's the brace that is complicating everything ☠

when ever I put it the error in the tittle pops out, but if I erase it another error appears:

Compilation error: expected '}' before ';' token

it's contradicting itself, idk what to do :|

*don't worry about the note_half and whole, it is not finished cuz i just wanted to check the tempo before i finished so i wouldn't make it all over again, but the error appeared :|


问:
Running spark job from AWS Lambda
I would like to get data from IceBerg table using AWS Lambda. I was able to create all the code and containers only to discover that AWS Lambda doesn't allow process substitution that spark uses here:
https://github.com/apache/spark/blob/121f9338cefbb1c800fabfea5152899a58176b00/bin/spark-class#L92

The error is:

```<code>/usr/local/lib/python3.10/dist-packages/pyspark/bin/spark-class: line 92: /dev/fd/63: No such file or directory
</code>```

Do you maybe have some idea how this can be solved?

Title: Running spark job from AWS Lambda

Body:
I would like to get data from IceBerg table using AWS Lambda. I was able to create all the code and containers only to discover that AWS Lambda doesn't allow process substitution that spark uses here:
https://github.com/apache/spark/blob/121f9338cefbb1c800fabfea5152899a58176b00/bin/spark-class#L92

The error is:

/usr/local/lib/python3.10/dist-packages/pyspark/bin/spark-class: line 92: /dev/fd/63: No such file or directory

Do you maybe have some idea how this can be solved?


问:
snowflake get sum of value for grouped data based on max date with one to many relations
I have two tables with data as stated below, I want to group table SRC_DATA and get the records which matching only max of date. On the filtered dataset join with REF_DATA(which has one to many relation) and flatten the sum of quantity based on code. I have tried this as given below, But I wanted know if this can be achieved in any efficient way.

Group by PTR_ID,MTR_ID on SRC_DATA and get the latest REF_ID associated. Latest should be max of TXN_DATE on SRC_DATA. There could be dataset on the grouped items fall under less than max of date and those should be kipped.

```<code>with SRC_DATA as
(
select
    COLUMN1::string as PTR_ID
    ,COLUMN2::string as MTR_ID
    ,COLUMN3::string as REF_ID
    ,COLUMN4::date   as TXN_DATE
from (values
    ('P001', 'A1', 'xyz123nfl','2022-11-03')
    ,('P001', 'B1', 'abc123fsd','2022-11-03')
    ,('P001', 'C1', 'dcnjs46fs','2022-11-03')
    ,('P001', 'A1', 'skjd54ksf','2022-10-25')
    ,('P001', 'C1', 'lskdjgt56','2022-09-15')
    ,('P002', 'A1', 'dhoe6439d','2022-11-03')
    ,('P002', 'B1', 'ksjfirt29','2022-11-03')
    ,('P002', 'C1', 'lsdirmg20','2022-10-05')
    ,('P002', 'D1', 'bnkgl90wf','2022-10-25')
    ,('P002', 'A1', 'bnjdlt34m','2022-05-07')
    ,('P002', 'B1', 'kopdg879k','2022-07-10')
     )
),
REF_DATA AS (
select
    COLUMN1::string as REF_ID
    ,COLUMN2::string as QTY_CODE
    ,COLUMN3::int as QTY_VALUE
from (values
('xyz123nfl','QCS',318)
,('xyz123nfl','QOO',315)
,('xyz123nfl','QIT',0)
,('xyz123nfl','QIH',3)
,('abc123fsd','QCS',78)
,('abc123fsd','QOO',0)
,('abc123fsd','QIT',0)
,('abc123fsd','QIH',120)
,('dcnjs46fs','QCS',2)
,('dcnjs46fs','QOO',0)
,('dcnjs46fs','QIT',0)
,('dcnjs46fs','QIH',30)
,('skjd54ksf','QCS',4)
,('skjd54ksf','QOO',0)
,('skjd54ksf','QIT',0)
,('skjd54ksf','QIH',6)
,('lskdjgt56','QCS',515)
,('lskdjgt56','QOO',0)
,('lskdjgt56','QIT',0)
,('lskdjgt56','QIH',0)
,('dhoe6439d','QCS',152)
,('dhoe6439d','QOO',150)
,('dhoe6439d','QIT',0)
,('dhoe6439d','QIH',0)
,('ksjfirt29','QCS',550)
,('ksjfirt29','QOO',560)
,('ksjfirt29','QIT',0)
,('ksjfirt29','QIH',0)
,('lsdirmg20','QCS',9)
,('lsdirmg20','QOO',0)
,('lsdirmg20','QIT',0)
,('lsdirmg20','QIH',0)
,('bnkgl90wf','QCS',1)
,('bnkgl90wf','QOO',1)
,('bnkgl90wf','QIT',0)
,('bnkgl90wf','QIH',0)
,('bnjdlt34m','QCS',2)
,('bnjdlt34m','QOO',2)
,('bnjdlt34m','QIT',0)
,('bnjdlt34m','QIH',0)
,('kopdg879k','QCS',0)
,('kopdg879k','QOO',0)
,('kopdg879k','QIT',0)
,('kopdg879k','QIH',0)
)
)
select DISTINCT
    SRC.PTR_ID
    ,SRC.MTR_ID
    ,SRC.TXN_DATE
    ,sum(case when REF_DATA.QTY_CODE = 'QCS' then REF_DATA.QTY_VALUE else 0 end) over (partition by SRC.PTR_ID,SRC.MTR_ID,SRC.REF_ID) as QTY_COMMIT_SALES
    ,sum(case when REF_DATA.QTY_CODE = 'QOO' then REF_DATA.QTY_VALUE else 0 end) over (partition by SRC.PTR_ID,SRC.MTR_ID,SRC.REF_ID) as QTY_ON_ORDER
    ,sum(case when REF_DATA.QTY_CODE = 'QIT' then REF_DATA.QTY_VALUE else 0 end) over (partition by SRC.PTR_ID,SRC.MTR_ID,SRC.REF_ID) as QTY_IN_TRANSIT
    ,sum(case when REF_DATA.QTY_CODE = 'QIH' then REF_DATA.QTY_VALUE else 0 end) over (partition by SRC.PTR_ID,SRC.MTR_ID,SRC.REF_ID) as QTY_IN_HAND

from (select PTR_ID,MTR_ID,REF_ID,TXN_DATE from SRC_DATA where TXN_DATE = (select max(TXN_DATE) from SRC_DATA)) SRC
INNER JOIN REF_DATA ON SRC.REF_ID = REF_DATA.REF_ID
;
</code>```

Body:
I have two tables with data as stated below, I want to group table SRC_DATA and get the records which matching only max of date. On the filtered dataset join with REF_DATA(which has one to many relation) and flatten the sum of quantity based on code. I have tried this as given below, But I wanted know if this can be achieved in any efficient way.

Group by PTR_ID,MTR_ID on SRC_DATA and get the latest REF_ID associated. Latest should be max of TXN_DATE on SRC_DATA. There could be dataset on the grouped items fall under less than max of date and those should be kipped.

with SRC_DATA as
(
select
    COLUMN1::string as PTR_ID
    ,COLUMN2::string as MTR_ID
    ,COLUMN3::string as REF_ID
    ,COLUMN4::date   as TXN_DATE
from (values
    ('P001', 'A1', 'xyz123nfl','2022-11-03')
    ,('P001', 'B1', 'abc123fsd','2022-11-03')
    ,('P001', 'C1', 'dcnjs46fs','2022-11-03')
    ,('P001', 'A1', 'skjd54ksf','2022-10-25')
    ,('P001', 'C1', 'lskdjgt56','2022-09-15')
    ,('P002', 'A1', 'dhoe6439d','2022-11-03')
    ,('P002', 'B1', 'ksjfirt29','2022-11-03')
    ,('P002', 'C1', 'lsdirmg20','2022-10-05')
    ,('P002', 'D1', 'bnkgl90wf','2022-10-25')
    ,('P002', 'A1', 'bnjdlt34m','2022-05-07')
    ,('P002', 'B1', 'kopdg879k','2022-07-10')
     )
),
REF_DATA AS (
select
    COLUMN1::string as REF_ID
    ,COLUMN2::string as QTY_CODE
    ,COLUMN3::int as QTY_VALUE
from (values
('xyz123nfl','QCS',318)
,('xyz123nfl','QOO',315)
,('xyz123nfl','QIT',0)
,('xyz123nfl','QIH',3)
,('abc123fsd','QCS',78)
,('abc123fsd','QOO',0)
,('abc123fsd','QIT',0)
,('abc123fsd','QIH',120)
,('dcnjs46fs','QCS',2)
,('dcnjs46fs','QOO',0)
,('dcnjs46fs','QIT',0)
,('dcnjs46fs','QIH',30)
,('skjd54ksf','QCS',4)
,('skjd54ksf','QOO',0)
,('skjd54ksf','QIT',0)
,('skjd54ksf','QIH',6)
,('lskdjgt56','QCS',515)
,('lskdjgt56','QOO',0)
,('lskdjgt56','QIT',0)
,('lskdjgt56','QIH',0)
,('dhoe6439d','QCS',152)
,('dhoe6439d','QOO',150)
,('dhoe6439d','QIT',0)
,('dhoe6439d','QIH',0)
,('ksjfirt29','QCS',550)
,('ksjfirt29','QOO',560)
,('ksjfirt29','QIT',0)
,('ksjfirt29','QIH',0)
,('lsdirmg20','QCS',9)
,('lsdirmg20','QOO',0)
,('lsdirmg20','QIT',0)
,('lsdirmg20','QIH',0)
,('bnkgl90wf','QCS',1)
,('bnkgl90wf','QOO',1)
,('bnkgl90wf','QIT',0)
,('bnkgl90wf','QIH',0)
,('bnjdlt34m','QCS',2)
,('bnjdlt34m','QOO',2)
,('bnjdlt34m','QIT',0)
,('bnjdlt34m','QIH',0)
,('kopdg879k','QCS',0)
,('kopdg879k','QOO',0)
,('kopdg879k','QIT',0)
,('kopdg879k','QIH',0)
)
)
select DISTINCT
    SRC.PTR_ID
    ,SRC.MTR_ID
    ,SRC.TXN_DATE
    ,sum(case when REF_DATA.QTY_CODE = 'QCS' then REF_DATA.QTY_VALUE else 0 end) over (partition by SRC.PTR_ID,SRC.MTR_ID,SRC.REF_ID) as QTY_COMMIT_SALES
    ,sum(case when REF_DATA.QTY_CODE = 'QOO' then REF_DATA.QTY_VALUE else 0 end) over (partition by SRC.PTR_ID,SRC.MTR_ID,SRC.REF_ID) as QTY_ON_ORDER
    ,sum(case when REF_DATA.QTY_CODE = 'QIT' then REF_DATA.QTY_VALUE else 0 end) over (partition by SRC.PTR_ID,SRC.MTR_ID,SRC.REF_ID) as QTY_IN_TRANSIT
    ,sum(case when REF_DATA.QTY_CODE = 'QIH' then REF_DATA.QTY_VALUE else 0 end) over (partition by SRC.PTR_ID,SRC.MTR_ID,SRC.REF_ID) as QTY_IN_HAND

from (select PTR_ID,MTR_ID,REF_ID,TXN_DATE from SRC_DATA where TXN_DATE = (select max(TXN_DATE) from SRC_DATA)) SRC
INNER JOIN REF_DATA ON SRC.REF_ID = REF_DATA.REF_ID
;


问:
Remove shadow of the UIDragPreview while item dragging
I have a UICollectionView based component, when user dragging some cells, shadows appears and I want to hide it.

I tried many solutions like this => https://stackoverflow.com/a/62046863/1705700
but no result. Here is my code;

```<code>func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        let item = self.itemList[indexPath.row]
        var dragItem: UIDragItem!
        if let path = item.icon {
            let itemProvider = NSItemProvider(object: path as NSString)
            dragItem = UIDragItem(itemProvider: itemProvider)
            dragItem.localObject = item

            dragItem.previewProvider  = { () -> UIDragPreview? in
                let previewImageView = UIImageView(image: UIImage(named: "test"))
                previewImageView.frame =  CGRect(x: 0, y: 0, width: 90, height: 90)

                let dragPreview = UIDragPreview(view: previewImageView)
                return dragPreview
            }
        }

        return [dragItem]
    }

func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
        let previewParameters = UIDragPreviewParameters()
        previewParameters.backgroundColor = .clear
        if #available(iOS 14.0, *) {
            previewParameters.shadowPath = UIBezierPath(rect: .zero)
        }

        return previewParameters
    }
</code>```

I solved the problem. If I use UIDragPreviewParameters as a parameter of UIDragPreview, background and shadow are disappear.

```<code>func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        let mood = self.moodList[indexPath.row]
        var dragItem: UIDragItem!
        if let path = mood.icon {
            let itemProvider = NSItemProvider(object: path as NSString)
            dragItem = UIDragItem(itemProvider: itemProvider)
            dragItem.localObject = mood

            guard let cell = collectionView.cellForItem(at: indexPath) else {return [dragItem]}
            let cellInsetContents = cell.contentView.bounds.insetBy(dx: 0, dy: 0)

            dragItem.previewProvider  = { () -> UIDragPreview? in
                let previewImageView = UIImageView(image: UIImage(named: "test"))
                previewImageView.frame =  CGRect(x: 0, y: 0, width: 90, height: 90)

                let dragPreviewParams = UIDragPreviewParameters()
                dragPreviewParams.backgroundColor = .clear
                if #available(iOS 14.0, *) {
                    dragPreviewParams.shadowPath = UIBezierPath(rect: .zero)
                } else {
                    // Fallback on earlier versions
                }

                dragPreviewParams.visiblePath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 90, height: 90), cornerRadius: 0)

                let dragPreview = UIDragPreview(view: previewImageView, parameters: dragPreviewParams)
                return dragPreview
            }
        }

        return [dragItem]
    }
</code>```

Body:
I have a UICollectionView based component, when user dragging some cells, shadows appears and I want to hide it.

I tried many solutions like this => https://stackoverflow.com/a/62046863/1705700
but no result. Here is my code;

func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        let item = self.itemList[indexPath.row]
        var dragItem: UIDragItem!
        if let path = item.icon {
            let itemProvider = NSItemProvider(object: path as NSString)
            dragItem = UIDragItem(itemProvider: itemProvider)
            dragItem.localObject = item

            dragItem.previewProvider  = { () -> UIDragPreview? in
                let previewImageView = UIImageView(image: UIImage(named: "test"))
                previewImageView.frame =  CGRect(x: 0, y: 0, width: 90, height: 90)

                let dragPreview = UIDragPreview(view: previewImageView)
                return dragPreview
            }
        }

        return [dragItem]
    }

func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
        let previewParameters = UIDragPreviewParameters()
        previewParameters.backgroundColor = .clear
        if #available(iOS 14.0, *) {
            previewParameters.shadowPath = UIBezierPath(rect: .zero)
        }

        return previewParameters
    }

I solved the problem. If I use UIDragPreviewParameters as a parameter of UIDragPreview, background and shadow are disappear.

func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        let mood = self.moodList[indexPath.row]
        var dragItem: UIDragItem!
        if let path = mood.icon {
            let itemProvider = NSItemProvider(object: path as NSString)
            dragItem = UIDragItem(itemProvider: itemProvider)
            dragItem.localObject = mood

            guard let cell = collectionView.cellForItem(at: indexPath) else {return [dragItem]}
            let cellInsetContents = cell.contentView.bounds.insetBy(dx: 0, dy: 0)

            dragItem.previewProvider  = { () -> UIDragPreview? in
                let previewImageView = UIImageView(image: UIImage(named: "test"))
                previewImageView.frame =  CGRect(x: 0, y: 0, width: 90, height: 90)

                let dragPreviewParams = UIDragPreviewParameters()
                dragPreviewParams.backgroundColor = .clear
                if #available(iOS 14.0, *) {
                    dragPreviewParams.shadowPath = UIBezierPath(rect: .zero)
                } else {
                    // Fallback on earlier versions
                }

                dragPreviewParams.visiblePath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 90, height: 90), cornerRadius: 0)

                let dragPreview = UIDragPreview(view: previewImageView, parameters: dragPreviewParams)
                return dragPreview
            }
        }

        return [dragItem]
    }


问:
Talkback is not saying rtl text with Flutter Semantics
I am trying to make my app support TalkBack as a lot of the users are blind. I am facing a very weird behaviour where TalkBack is saying some things and completely ignoring others.

Here is the code:

```<code>Semantics(
    label: "هذا كتاب بعنوان كيف تقرا كتابا",
    excludeSemantics: true,
    textDirection: TextDirection.rtl,
    child: const Text("كيف تقرا كتابا"),
)
</code>```

Here are my observations

It reads any English text inside "label" all the time

It reads Arabic (rtl language) sometimes depending on what is written. For example, it reads: "هذا الكتاب" but it does not read: "الإعدادات"

Can someone help me with what I should do?

Body:
I am trying to make my app support TalkBack as a lot of the users are blind. I am facing a very weird behaviour where TalkBack is saying some things and completely ignoring others.

Here is the code:

Semantics(
    label: "هذا كتاب بعنوان كيف تقرا كتابا",
    excludeSemantics: true,
    textDirection: TextDirection.rtl,
    child: const Text("كيف تقرا كتابا"),
)

Here are my observations

It reads any English text inside "label" all the time

It reads Arabic (rtl language) sometimes depending on what is written. For example, it reads: "هذا الكتاب" but it does not read: "الإعدادات"

Can someone help me with what I should do?


问:
is it possible to define jobs completely in stage instead of declaring just its name in bamboo yaml specs?
I need to define jobs of stage completely in defining stage block instead of declaring its name in that block and define that in bamboo.yaml
but when I do this it says " Element is of wrong type. Expected StringNode, found MapNode. "this is my bamboo.yml
this is ci-snapshot-stages.yml which stages are defined in

i tried this
and i got "Element is of wrong type. Expected StringNode, found MapNode"


问:
Spreading props in react as attributes?
I've read up on the es6 object spread operator and I've come across it being used in a react tutorial to spread props into a component. I can't understand how this is working though, for instance

```<code>const obj1 = { foo: 'bar', x: 42 };

const clonedObj = { ...obj1 };
</code>```

I understand the properties of obj1 are just copied into a cloned object now but they are still in the form of object properties. So why when an object is spread in JSX do they change their form from object properties to key/value attributes? for instance if obj1 was spread in the below component it would be the same as separate attributes:

```<code><Component {...obj1} >
<Component foo="bar" x={42}>
</code>```

I can't find a reason for this, only some explanations that this is what React does. Is there a deeper reason to understand than just that. So specifically I'm wondering why the format changes from object properties to key value attributes? is it something that the React library is doing to convert? Otherwise I would expect object spreading format to be consistent wherever you use it i.e. staying in the form of object properties.

Title: Spreading props in react as attributes?

Body:
I've read up on the es6 object spread operator and I've come across it being used in a react tutorial to spread props into a component. I can't understand how this is working though, for instance

const obj1 = { foo: 'bar', x: 42 };

const clonedObj = { ...obj1 };

I understand the properties of obj1 are just copied into a cloned object now but they are still in the form of object properties. So why when an object is spread in JSX do they change their form from object properties to key/value attributes? for instance if obj1 was spread in the below component it would be the same as separate attributes:

<Component {...obj1} >
<Component foo="bar" x={42}>

I can't find a reason for this, only some explanations that this is what React does. Is there a deeper reason to understand than just that. So specifically I'm wondering why the format changes from object properties to key value attributes? is it something that the React library is doing to convert? Otherwise I would expect object spreading format to be consistent wherever you use it i.e. staying in the form of object properties.


问:
Error: Route.post() requires a callback function but got a [object Undefined]
Error: Route.post() requires a callback function but got a [object Undefined] how to overcome with this problem

router

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

const {auth} =require("../middleware/auth")
const { addBd } = require("../controllers/birthdayController");

router.route("/addNewBd").post(auth,addBd);
module.exports = router;
</code>```

auth.js

```<code>const jwt = require("jsonwebtoken");
const User=require("../models/Users")
module.exports = async function (req, res, next) {
  let token;

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    // Set token from Bearer token in header
    token = req.headers.authorization.split(" ")[1];
    // Set token from cookie
  } else if (req.cookies.token) {
    token = req.cookies.token;
  }
  if (!token) {
    return res.status(401).send("you are not logged in");
  }

  try {
    // Verify token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    req.user = await User.findById(decoded.user.id);

    next();
  } catch (err) {
    return res.status(401).send("you are not logged in");
  }
};
</code>```

I am getting this problem how to sort out this one

Body:
Error: Route.post() requires a callback function but got a [object Undefined] how to overcome with this problem

router

const express=require("express")
const router = express.Router();

const {auth} =require("../middleware/auth")
const { addBd } = require("../controllers/birthdayController");

router.route("/addNewBd").post(auth,addBd);
module.exports = router;

auth.js

const jwt = require("jsonwebtoken");
const User=require("../models/Users")
module.exports = async function (req, res, next) {
  let token;

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    // Set token from Bearer token in header
    token = req.headers.authorization.split(" ")[1];
    // Set token from cookie
  } else if (req.cookies.token) {
    token = req.cookies.token;
  }
  if (!token) {
    return res.status(401).send("you are not logged in");
  }

  try {
    // Verify token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    req.user = await User.findById(decoded.user.id);

    next();
  } catch (err) {
    return res.status(401).send("you are not logged in");
  }
};

I am getting this problem how to sort out this one


问:
How to get the list of features along side their schema and stats using TFX
Let's say that I have the following, very straightforward pipeline:

import os
from tfx import v1 as tfx

_dataset_folder = './tfrecords/train/*'
_pipeline_data_folder = './pipeline_data'
_serving_model_dir = os.path.join(_pipeline_data_folder, 'serving_model')

example_gen = tfx.components.ImportExampleGen(input_base=_dataset_folder)
statistics_gen = tfx.components.StatisticsGen(examples=example_gen.outputs['examples'])
schema_gen = tfx.components.SchemaGen(
    statistics=statistics_gen.outputs['statistics'],
    infer_feature_shape=True)
example_validator = tfx.components.ExampleValidator(
    statistics=statistics_gen.outputs['statistics'],
    schema=schema_gen.outputs['schema'])

_transform_module_file = 'preprocessing_fn.py'
transform = tfx.components.Transform(
    examples=example_gen.outputs['examples'],
    schema=schema_gen.outputs['schema'],
    module_file=os.path.abspath(_transform_module_file),
    custom_config={'statistics_gen': statistics_gen.outputs['statistics'],
                   'schema_gen': schema_gen.outputs['schema']})

_trainer_module_file = 'run_fn.py'
trainer = tfx.components.Trainer(
    module_file=os.path.abspath(_trainer_module_file),
    examples=transform.outputs['transformed_examples'],
    transform_graph=transform.outputs['transform_graph'],
    schema=schema_gen.outputs['schema'],
    train_args=tfx.proto.TrainArgs(num_steps=10),
    eval_args=tfx.proto.EvalArgs(num_steps=6))

pusher = tfx.components.Pusher(
  model=trainer.outputs['model'],
  push_destination=tfx.proto.PushDestination(
    filesystem=tfx.proto.PushDestination.Filesystem(
        base_directory=_serving_model_dir)))

components = [
    example_gen,
    statistics_gen,
    schema_gen,
    example_validator,
    transform,
    trainer,
    pusher,
]

pipeline = tfx.dsl.Pipeline(
    pipeline_name='straightforward_pipeline',
    pipeline_root=_pipeline_data_folder,
    metadata_connection_config=tfx.orchestration.metadata.sqlite_metadata_connection_config(
        f'{_pipeline_data_folder}/metadata.db'),
    components=components)

tfx.orchestration.LocalDagRunner().run(pipeline)
```
<p>The only part a bit out of ordinary in the snippet code above is the fact that I'm passing <code>statistics_gen</code> and <code>schema_gen</code> to the transform step of the pipeline in the <code>custom_config</code> argument. What I'm hoping to achieve here is iterating over the list of features in the Dataset, in order to transform them.</p>
<p>This is what I need for that:</p>
<ol>
<li>The list of features in the dataset (I don't want to hardcode/assume this list, I want my code to come up with it automatically)</li>
<li>Each feature's type (again, I don't want to hardcode/assume them)</li>
<li>Each feature's statistical attributes (like min, max) and again, I don't want to hardcode/assume them!!!</li>
</ol>
<p>My question is, how can I do this in my <code>preprocessing_fn.py</code> function?</p>
<p>BTW, I know how to do this if I have access to the CSV version of the dataset:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow_data_validation as tfdv

dataset_stats = tfdv.generate_statistics_from_csv(examples_file)
feature_1_stats = tfdv.get_feature_stats(dataset_stats.datasets[0],
                                         tfdv.FeaturePath(['feature_1']))
</code>```

But there is a problem. It is extracting all the info from the dataset while in my code, I believe, they are already extracted by the pipeline steps statistics_gen and schema_gen. And I don't want to redo the whole process. I just need to learn how to use the mentioned two steps to get the info I need.

Body:
Let's say that I have the following, very straightforward pipeline:

import os
from tfx import v1 as tfx

_dataset_folder = './tfrecords/train/*'
_pipeline_data_folder = './pipeline_data'
_serving_model_dir = os.path.join(_pipeline_data_folder, 'serving_model')

example_gen = tfx.components.ImportExampleGen(input_base=_dataset_folder)
statistics_gen = tfx.components.StatisticsGen(examples=example_gen.outputs['examples'])
schema_gen = tfx.components.SchemaGen(
    statistics=statistics_gen.outputs['statistics'],
    infer_feature_shape=True)
example_validator = tfx.components.ExampleValidator(
    statistics=statistics_gen.outputs['statistics'],
    schema=schema_gen.outputs['schema'])

_transform_module_file = 'preprocessing_fn.py'
transform = tfx.components.Transform(
    examples=example_gen.outputs['examples'],
    schema=schema_gen.outputs['schema'],
    module_file=os.path.abspath(_transform_module_file),
    custom_config={'statistics_gen': statistics_gen.outputs['statistics'],
                   'schema_gen': schema_gen.outputs['schema']})

_trainer_module_file = 'run_fn.py'
trainer = tfx.components.Trainer(
    module_file=os.path.abspath(_trainer_module_file),
    examples=transform.outputs['transformed_examples'],
    transform_graph=transform.outputs['transform_graph'],
    schema=schema_gen.outputs['schema'],
    train_args=tfx.proto.TrainArgs(num_steps=10),
    eval_args=tfx.proto.EvalArgs(num_steps=6))

pusher = tfx.components.Pusher(
  model=trainer.outputs['model'],
  push_destination=tfx.proto.PushDestination(
    filesystem=tfx.proto.PushDestination.Filesystem(
        base_directory=_serving_model_dir)))

components = [
    example_gen,
    statistics_gen,
    schema_gen,
    example_validator,
    transform,
    trainer,
    pusher,
]

pipeline = tfx.dsl.Pipeline(
    pipeline_name='straightforward_pipeline',
    pipeline_root=_pipeline_data_folder,
    metadata_connection_config=tfx.orchestration.metadata.sqlite_metadata_connection_config(
        f'{_pipeline_data_folder}/metadata.db'),
    components=components)

tfx.orchestration.LocalDagRunner().run(pipeline)

The only part a bit out of ordinary in the snippet code above is the fact that I'm passing statistics_gen and schema_gen to the transform step of the pipeline in the custom_config argument. What I'm hoping to achieve here is iterating over the list of features in the Dataset, in order to transform them.

This is what I need for that:

The list of features in the dataset (I don't want to hardcode/assume this list, I want my code to come up with it automatically)

Each feature's type (again, I don't want to hardcode/assume them)

Each feature's statistical attributes (like min, max) and again, I don't want to hardcode/assume them!!!

My question is, how can I do this in my preprocessing_fn.py function?

BTW, I know how to do this if I have access to the CSV version of the dataset:

import tensorflow_data_validation as tfdv

dataset_stats = tfdv.generate_statistics_from_csv(examples_file)
feature_1_stats = tfdv.get_feature_stats(dataset_stats.datasets[0],
                                         tfdv.FeaturePath(['feature_1']))

But there is a problem. It is extracting all the info from the dataset while in my code, I believe, they are already extracted by the pipeline steps statistics_gen and schema_gen. And I don't want to redo the whole process. I just need to learn how to use the mentioned two steps to get the info I need.


问:
How to execute groupby with streaming partitions in pyspark?
I'm trying to do a groupby over a streaming partition. When I'm using a sliding window and the partition id the grouped data are empty.

For example:

df = (spark_session.readStream\
                   .format("kafka")\
                   .option("kafka.bootstrap.servers", kafka)\
                   .option("subscribe", input_topic)\
                   .load().selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)",
                                      "CAST(partition as INT)"))
# Expand value to get tm_ms then
df = df.withColumn("ts", from_unixtime(col("ts_ms"), format="yyyy-MM-dd HH:mm:ss.SSS"))\
                 .withColumn("ts", col("ts").cast(TimestampType()))

df = df.withColumn("value", struct("*"))
       .withWatermark("ts", "1 hour")\
       .groupBy(window("ts", "1 second"), "partition")\
       .agg(collect_list("value").alias("value"))
...

df = df.select("partition", "key",
               to_json(struct([c for c in health_tags.columns
                               if c not in {"partition", 'key'}])).alias("value"))\
       .withColumn("partition", col("partition").cast("integer"))

df = df.writeStream \
       .format("kafka")\
       .outputMode("update")\
       .option("kafka.bootstrap.servers", kafka)\
       .option("topic", output_topic)\
       .start()
```

When I'm removing the sliding window -window("ts", "1 second")-, pyspark is able to groupby, but I believe it keeps the state and continuously expands the size of the group as new data arrive.

Is my understanding correct? If yes, how can I use the sliding window along with the partition number to groupby?

Thank you

My expectation is that I will be able to group the data per partition with a sliding window. In addition I want to avoid any shuffling between spark executors.

Body:
I'm trying to do a groupby over a streaming partition. When I'm using a sliding window and the partition id the grouped data are empty.

For example:

df = (spark_session.readStream\
                   .format("kafka")\
                   .option("kafka.bootstrap.servers", kafka)\
                   .option("subscribe", input_topic)\
                   .load().selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)",
                                      "CAST(partition as INT)"))
# Expand value to get tm_ms then
df = df.withColumn("ts", from_unixtime(col("ts_ms"), format="yyyy-MM-dd HH:mm:ss.SSS"))\
                 .withColumn("ts", col("ts").cast(TimestampType()))

df = df.withColumn("value", struct("*"))
       .withWatermark("ts", "1 hour")\
       .groupBy(window("ts", "1 second"), "partition")\
       .agg(collect_list("value").alias("value"))
...

df = df.select("partition", "key",
               to_json(struct([c for c in health_tags.columns
                               if c not in {"partition", 'key'}])).alias("value"))\
       .withColumn("partition", col("partition").cast("integer"))

df = df.writeStream \
       .format("kafka")\
       .outputMode("update")\
       .option("kafka.bootstrap.servers", kafka)\
       .option("topic", output_topic)\
       .start()

When I'm removing the sliding window -window("ts", "1 second")-, pyspark is able to groupby, but I believe it keeps the state and continuously expands the size of the group as new data arrive.

Is my understanding correct? If yes, how can I use the sliding window along with the partition number to groupby?

Thank you

My expectation is that I will be able to group the data per partition with a sliding window. In addition I want to avoid any shuffling between spark executors.


问:
Why does intellisense not provide declared variables and "this" when using less than (<) in Visual Studio?
I have this code:

```<code>class Foo
{
    public void Baz()
    {
        int x = 0;
        var list = new List<int>();

        while (list.Count < ) // start right after "<"
    }
}
</code>```

If I type x or this right after < as indicated, intellisense does not show me either of them, in fact it's really difficult to get it to let me use them because it is determined to force me to use whatever suggestion it does have:

If I use <= instead of < it works as expected:

It even works for > just not <.  What am I missing??

Body:
I have this code:

class Foo
{
    public void Baz()
    {
        int x = 0;
        var list = new List<int>();

        while (list.Count < ) // start right after "<"
    }
}

If I type x or this right after < as indicated, intellisense does not show me either of them, in fact it's really difficult to get it to let me use them because it is determined to force me to use whatever suggestion it does have:

If I use <= instead of < it works as expected:

It even works for > just not <.  What am I missing??


问:
Lombok getter/setter references not showing correctly in VSCode
I'm using Lombok 1.18.24 for a personal project added as a dependency with Apache Maven 3.8.6, using OpenJDK19 in VSCode 1.74.2, and everything works fine, but I've noticed that the Lombok annotations say 0 references even though i use the generated getters and setters in many places.

This happens when I add the @Getter and @Setter annotations in some fields (no matter the field type or access modifier) instead of adding them to the whole class (in some cases I don't need a getter and/or a setter for every class field).

Here are some screenshots with examples to see what i'm talking about:

No matter if I use the generated getter or setter for the field inside or outside its class, or if I use the field directly in its class, the 0 references doesn't change for one or the other.

If I add the annotations to the whole class, those references don't show up, logically.

I tried to add the annotations in other parts, access/modify the fields via the generated getters/setters, access those fields directly inside their classes without using the generated methods, but it won't change.

Am I missing any VSCode configuration or extension for this to work correctly? Could it be a VSCode bug?

Thanks in advance!


问:
Force system to register WINKEY modifier shortcut?
The data OS writes into LNK file for hotkey seems fairly straightforward:

https://github.com/libyal/liblnk/blob/main/documentation/Windows%20Shortcut%20File%20(LNK)%20format.asciidoc

https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey?redirectedfrom=MSDN

Although it does not allow to assign WINKEY by default, because apparently it is """against Windows Experience Guidelines""", you can write down LNK manually. The value for WINKEY+W would be 0x0857, however, it does not seem to register it.
Anything can be done about it?


问:
Whitespace being added at beginning of string when pasting into Eureka form | Swift
I have a Eureka form that displays a TextAreaRow. When the user attempts to "Paste" something from the UIPasteboard into this field, it adds a space to the front of the string (Example: "Homework" becomes " Homework" - notice the space at the front). How can I stop this from happening?</p>
```<code>import UIKit
import Eureka

class MyViewController: FormViewController {
   func setupEurekaForm() {
      form
      +++ Section("TEXTFIELDS")
      <<< TextAreaRow() {
         $0.value = "Test text"
         // here I need to somehow tell the field to disable smartInsertDeleteType
      }
   }
}
</code>```

Body:
I have a Eureka form that displays a TextAreaRow. When the user attempts to "Paste" something from the UIPasteboard into this field, it adds a space to the front of the string (Example: "Homework" becomes " Homework" - notice the space at the front). How can I stop this from happening?

import UIKit
import Eureka

class MyViewController: FormViewController {
   func setupEurekaForm() {
      form
      +++ Section("TEXTFIELDS")
      <<< TextAreaRow() {
         $0.value = "Test text"
         // here I need to somehow tell the field to disable smartInsertDeleteType
      }
   }
}


问:
InvalidArgumentError: Graph execution error:
when running this script, I get an error when calling the model.fit(dataset, epochs=5) method when I want to train the model and I get the error InvalidArgumentError: Graph executes error:

`

```<code>import nltk
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('stopwords')
nltk.download('omw-1.4')

def preprocess_data(data):
  # Tokenize as sentences
  data = [nltk.word_tokenize(sent) for sent in data]

  # Remove stopwords
  stopwords = nltk.corpus.stopwords.words('portuguese')
  data = [[word for word in sent if word not in stopwords] for sent in data]

  # Perform lemmatization
  lemmatizer = nltk.stem.WordNetLemmatizer()
  data = [[lemmatizer.lemmatize(word) for word in sent] for sent in data]

  return data

# Example usage
data = [  "oi tudo bem?", "sim, eu estou com fome e voce?", "eu estou, quero uma pizza", "vou pedir duas pizzas", "Gosto de livros", "quais livros voce gosta de ler?", "oi tudo bem?",     "sim, eu estou com fome e voce?",     "eu estou, quero uma pizza",     "vou pedir duas pizzas",     "Gosto de livros",     "quais livros voce gosta de ler?",    "eu gosto de ler thrillers e ficção científica",     "e você, o que mais gosta de ler?",    "eu também gosto de ler romances e livros de autoajuda",     "qual é o seu livro favorito?",    "um dos meus livros favoritos é o 'O Alquimista' de Paulo Coelho",     "eu também gosto muito desse livro! Qual é o seu gênero literário favorito?",    "eu gosto de todos os gêneros, mas talvez meu favorito seja a ficção científica",     "eu também adoro ficção científica. Qual é o seu livro de ficção científica favorito?",    "meu livro de ficção científica favorito é 'Dune' de Frank Herbert",     "que legal, eu também gosto muito de 'Dune'! Já leu algum outro livro do Frank Herbert?",    "sim, eu também gostei muito de 'O Imperador-Deus de Dune' e 'Herejia de Dune'"]
processed_data = preprocess_data(data)
print(processed_data)

import tensorflow as tf

# Define the input and output sequences
input_sequences = processed_data[:-1]
output_sequences = processed_data[1:]

def flatten(l):
    return [item for sublist in l for item in sublist]

# Create a vocabulary of unique words
vocab = sorted(set(flatten(input_sequences + output_sequences)))

# Create word-to-index and index-to-word mappings
word_to_index = {word: i for i, word in enumerate(vocab)}
index_to_word = {i: word for i, word in enumerate(vocab)}

# Convert the input and output sequences to integers
input_sequences = [[word_to_index[word] for word in seq] for seq in input_sequences]
output_sequences = [[word_to_index[word] for word in seq] for seq in output_sequences]

# Find the maximum sequence length
max_seq_len = max(len(seq) for seq in input_sequences + output_sequences)

# Pad the sequences with zeros to the maximum sequence length
input_sequences = tf.keras.preprocessing.sequence.pad_sequences(
    input_sequences, maxlen=max_seq_len, padding='post')
output_sequences = tf.keras.preprocessing.sequence.pad_sequences(
    output_sequences, maxlen=max_seq_len, padding='post')

# Create a dataset from the padded sequences
batch_size = 32  # Replace 32 with the desired batch size
dataset = tf.data.Dataset.from_tensor_slices(
    (input_sequences, output_sequences)).batch(batch_size)

# Define the RNN model
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(len(vocab), 64, input_length=max_seq_len),
    tf.keras.layers.LSTM(64),
    tf.keras.layers.Dense(len(vocab), activation='softmax')
])

# Compile the model
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Treinar o modelo
model.fit(dataset, epochs=5)
</code>```

`

I hope to be able to train the network, but the error returned is InvalidArgumentError: Graph execution error:

Body:
when running this script, I get an error when calling the model.fit(dataset, epochs=5) method when I want to train the model and I get the error InvalidArgumentError: Graph executes error:

`

import nltk
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('stopwords')
nltk.download('omw-1.4')

def preprocess_data(data):
  # Tokenize as sentences
  data = [nltk.word_tokenize(sent) for sent in data]

  # Remove stopwords
  stopwords = nltk.corpus.stopwords.words('portuguese')
  data = [[word for word in sent if word not in stopwords] for sent in data]

  # Perform lemmatization
  lemmatizer = nltk.stem.WordNetLemmatizer()
  data = [[lemmatizer.lemmatize(word) for word in sent] for sent in data]

  return data

# Example usage
data = [  "oi tudo bem?", "sim, eu estou com fome e voce?", "eu estou, quero uma pizza", "vou pedir duas pizzas", "Gosto de livros", "quais livros voce gosta de ler?", "oi tudo bem?",     "sim, eu estou com fome e voce?",     "eu estou, quero uma pizza",     "vou pedir duas pizzas",     "Gosto de livros",     "quais livros voce gosta de ler?",    "eu gosto de ler thrillers e ficção científica",     "e você, o que mais gosta de ler?",    "eu também gosto de ler romances e livros de autoajuda",     "qual é o seu livro favorito?",    "um dos meus livros favoritos é o 'O Alquimista' de Paulo Coelho",     "eu também gosto muito desse livro! Qual é o seu gênero literário favorito?",    "eu gosto de todos os gêneros, mas talvez meu favorito seja a ficção científica",     "eu também adoro ficção científica. Qual é o seu livro de ficção científica favorito?",    "meu livro de ficção científica favorito é 'Dune' de Frank Herbert",     "que legal, eu também gosto muito de 'Dune'! Já leu algum outro livro do Frank Herbert?",    "sim, eu também gostei muito de 'O Imperador-Deus de Dune' e 'Herejia de Dune'"]
processed_data = preprocess_data(data)
print(processed_data)

import tensorflow as tf

# Define the input and output sequences
input_sequences = processed_data[:-1]
output_sequences = processed_data[1:]

def flatten(l):
    return [item for sublist in l for item in sublist]

# Create a vocabulary of unique words
vocab = sorted(set(flatten(input_sequences + output_sequences)))

# Create word-to-index and index-to-word mappings
word_to_index = {word: i for i, word in enumerate(vocab)}
index_to_word = {i: word for i, word in enumerate(vocab)}

# Convert the input and output sequences to integers
input_sequences = [[word_to_index[word] for word in seq] for seq in input_sequences]
output_sequences = [[word_to_index[word] for word in seq] for seq in output_sequences]

# Find the maximum sequence length
max_seq_len = max(len(seq) for seq in input_sequences + output_sequences)

# Pad the sequences with zeros to the maximum sequence length
input_sequences = tf.keras.preprocessing.sequence.pad_sequences(
    input_sequences, maxlen=max_seq_len, padding='post')
output_sequences = tf.keras.preprocessing.sequence.pad_sequences(
    output_sequences, maxlen=max_seq_len, padding='post')

# Create a dataset from the padded sequences
batch_size = 32  # Replace 32 with the desired batch size
dataset = tf.data.Dataset.from_tensor_slices(
    (input_sequences, output_sequences)).batch(batch_size)

# Define the RNN model
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(len(vocab), 64, input_length=max_seq_len),
    tf.keras.layers.LSTM(64),
    tf.keras.layers.Dense(len(vocab), activation='softmax')
])

# Compile the model
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Treinar o modelo
model.fit(dataset, epochs=5)

`

I hope to be able to train the network, but the error returned is InvalidArgumentError: Graph execution error:


问:
Python http server Prometheus error: expected timestamp or new record, got "MNAME"
Trying to write an endpoint with 2 metrics from a python http server which does not work. For whatever reason, the prometheus parser does not know how to parse html like a br linebreak in between, which is really bad..

If I use a single metric like line 1 only, it works.

I also tried \n, but that works also only for the first metric. Since there will be no linebreak in the html post, the second metric is not recognized as metric??!

```<code>self.wfile.write(bytes(f'sensor1{{type="mylabel1"}} 77', "utf-8"))
self.wfile.write(bytes(f' <br>', "utf-8"))
self.wfile.write(bytes(f'sensor2{{type="mylabel2"}} 78', "utf-8"))
</code>```

My Html Page post looks like in this answer
Prometheus monitoring error "expected value after metric, got \"MNAME\"" for target endpoint

```<code>sensor1{type="mylabel1"} 77
sensor2{type="mylabel2"} 78
</code>```

Any idea what kind of linebreak is expected by the parser? Code is python.

Body:
Trying to write an endpoint with 2 metrics from a python http server which does not work. For whatever reason, the prometheus parser does not know how to parse html like a br linebreak in between, which is really bad..

If I use a single metric like line 1 only, it works.

I also tried \n, but that works also only for the first metric. Since there will be no linebreak in the html post, the second metric is not recognized as metric??!

self.wfile.write(bytes(f'sensor1{{type="mylabel1"}} 77', "utf-8"))
self.wfile.write(bytes(f'
', "utf-8"))
self.wfile.write(bytes(f'sensor2{{type="mylabel2"}} 78', "utf-8"))

My Html Page post looks like in this answer
Prometheus monitoring error "expected value after metric, got \"MNAME\"" for target endpoint

sensor1{type="mylabel1"} 77
sensor2{type="mylabel2"} 78

Any idea what kind of linebreak is expected by the parser? Code is python.


问:
Profile the go build process
Is there a way to profile the go build process? We notice that our build process is taking up a lot of cpu and memory.  While it could be that our code indeed needs the amount of resources, we want to profile the build process and see where all the usage is going.
Thanks

We tried adding more logs with -x options and tried to correlate the output with resource usage but it produced inconsistent results as in our system.  The -gcflags with -m and memprofilerate  etc seem to be only for the resulting process and not for the build process itself.

Title: Profile the go build process


问:
QTableWidget truncate beginning of long cell instead of end
I am creating a GUI in pyqt and I use QTableWidget  to show some list of files.

When the string in a cell is too long, the end is truncated and replaced by "...".
Like in this photo

Is it possible to hide the beginning instead? something like
.../pana/someverylongblablabla.ext

Thanks