问:
RolloutWorker problem when try to execute PPOConfig: Exception raised in creation task: The actor died because of an error raised in its creation task
I am trying to follow the steps mentioned on "Getting Started with RLlib" (https://docs.ray.io/en/latest/rllib/rllib-training.html) along with my custom environment.

However my run doesn't work in the first code block show in the guide.
This is actually the script I m trying to run:

```<code>import ray
from ray.rllib.algorithms.ppo import PPOConfig
from ray.tune.logger import pretty_print
from gym_sw_env.envs.Examplev2 import Example_v2 #this is my custom env

ray.init(ignore_reinit_error=True)

algo = (
    PPOConfig()
    .rollouts(num_rollout_workers=1)
    .resources(num_gpus=0)
    .environment(env=Example_v2)
    .build()
)
</code>```

While this is the error I have:

```<code>(RolloutWorker pid=24420) 2022-12-17 11:36:34,235   ERROR worker.py:763 -- Exception raised in creation task: The actor died because of an error raised in its creation task, ray::RolloutWorker.__init__() (pid=24420, ip=127.0.0.1, repr=<ray.rllib.evaluation.rollout_worker.RolloutWorker object at 0x000001693BEB1C10>)
(RolloutWorker pid=24420)   File "python\ray\_raylet.pyx", line 859, in ray._raylet.execute_task
(RolloutWorker pid=24420)   File "python\ray\_raylet.pyx", line 863, in ray._raylet.execute_task
(RolloutWorker pid=24420)   File "python\ray\_raylet.pyx", line 810, in ray._raylet.execute_task.function_executor
(RolloutWorker pid=24420)   File "C:\Users\**MYUSER**\Anaconda3\lib\site-packages\ray\_private\function_manager.py", line 674, in actor_method_executor
(RolloutWorker pid=24420)     return method(__ray_actor, *args, **kwargs)
(RolloutWorker pid=24420)   File "C:\Users\**MYUSER**\Anaconda3\lib\site-packages\ray\util\tracing\tracing_helper.py", line 466, in _resume_span
(RolloutWorker pid=24420)     return method(self, *_args, **_kwargs)
(RolloutWorker pid=24420)   File "C:\Users\**MYUSER**\Anaconda3\lib\site-packages\ray\rllib\evaluation\rollout_worker.py", line 492, in __init__
(RolloutWorker pid=24420)     self.env = env_creator(copy.deepcopy(self.env_context))
(RolloutWorker pid=24420)   File "C:\Users\**MYUSER**\Anaconda3\lib\site-packages\ray\rllib\algorithms\algorithm.py", line 2139, in <lambda>
(RolloutWorker pid=24420)     return env_id, lambda cfg: env_specifier(cfg)
(RolloutWorker pid=24420) TypeError: __init__() takes 1 positional argument but 2 were given
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [3], line 7
      2 from ray.tune.logger import pretty_print
      3 from gym_sw_env.envs.Examplev2 import Example_v2
      6 algo = (
----> 7     PPOConfig()
      8     .rollouts(num_rollout_workers=1)
      9     .resources(num_gpus=0)
     10     .environment(env=Example_v2)
     11     .build()
     12 )

File ~\Anaconda3\lib\site-packages\ray\rllib\algorithms\algorithm_config.py:311, in AlgorithmConfig.build(self, env, logger_creator)
    308 if logger_creator is not None:
    309     self.logger_creator = logger_creator
--> 311 return self.algo_class(
    312     config=self.to_dict(),
    313     env=self.env,
    314     logger_creator=self.logger_creator,
    315 )

File ~\Anaconda3\lib\site-packages\ray\rllib\algorithms\algorithm.py:414, in Algorithm.__init__(self, config, env, logger_creator, **kwargs)
    402 # Initialize common evaluation_metrics to nan, before they become
    403 # available. We want to make sure the metrics are always present
    404 # (although their values may be nan), so that Tune does not complain
    405 # when we use these as stopping criteria.
    406 self.evaluation_metrics = {
    407     "evaluation": {
    408         "episode_reward_max": np.nan,
   (...)
    411     }
    412 }
--> 414 super().__init__(config=config, logger_creator=logger_creator, **kwargs)
    416 # Check, whether `training_iteration` is still a tune.Trainable property
    417 # and has not been overridden by the user in the attempt to implement the
    418 # algos logic (this should be done now inside `training_step`).
    419 try:

File ~\Anaconda3\lib\site-packages\ray\tune\trainable\trainable.py:161, in Trainable.__init__(self, config, logger_creator, remote_checkpoint_dir, custom_syncer, sync_timeout)
    159 start_time = time.time()
    160 self._local_ip = ray.util.get_node_ip_address()
--> 161 self.setup(copy.deepcopy(self.config))
    162 setup_time = time.time() - start_time
    163 if setup_time > SETUP_TIME_THRESHOLD:

File ~\Anaconda3\lib\site-packages\ray\rllib\algorithms\algorithm.py:549, in Algorithm.setup(self, config)
    536 except RayActorError as e:
    537     # In case of an actor (remote worker) init failure, the remote worker
    538     # may still exist and will be accessible, however, e.g. calling
    539     # its `sample.remote()` would result in strange "property not found"
    540     # errors.
    541     if e.actor_init_failed:
    542         # Raise the original error here that the RolloutWorker raised
    543         # during its construction process. This is to enforce transparency
   (...)
    547         # - e.args[0].args[2]: The original Exception (e.g. a ValueError due
    548         # to a config mismatch) thrown inside the actor.
--> 549         raise e.args[0].args[2]
    550     # In any other case, raise the RayActorError as-is.
    551     else:
    552         raise e

File python\ray\_raylet.pyx:852, in ray._raylet.execute_task()

File python\ray\_raylet.pyx:906, in ray._raylet.execute_task()

File python\ray\_raylet.pyx:859, in ray._raylet.execute_task()

File python\ray\_raylet.pyx:863, in ray._raylet.execute_task()

File python\ray\_raylet.pyx:810, in ray._raylet.execute_task.function_executor()

File ~\Anaconda3\lib\site-packages\ray\_private\function_manager.py:674, in actor_method_executor()
    672     return method(*args, **kwargs)
    673 else:
--> 674     return method(__ray_actor, *args, **kwargs)

File ~\Anaconda3\lib\site-packages\ray\util\tracing\tracing_helper.py:466, in _resume_span()
    464 # If tracing feature flag is not on, perform a no-op
    465 if not _is_tracing_enabled() or _ray_trace_ctx is None:
--> 466     return method(self, *_args, **_kwargs)
    468 tracer: _opentelemetry.trace.Tracer = _opentelemetry.trace.get_tracer(
    469     __name__
    470 )
    472 # Retrieves the context from the _ray_trace_ctx dictionary we
    473 # injected.

File ~\Anaconda3\lib\site-packages\ray\rllib\evaluation\rollout_worker.py:492, in __init__()
    485 # Create a (single) env for this worker.
    486 if not (
    487     worker_index == 0
    488     and num_workers > 0
    489     and not policy_config.get("create_env_on_driver")
    490 ):
    491     # Run the `env_creator` function passing the EnvContext.
--> 492     self.env = env_creator(copy.deepcopy(self.env_context))
    494 if self.env is not None:
    495     # Validate environment (general validation function).
    496     if not self._disable_env_checking:

File ~\Anaconda3\lib\site-packages\ray\rllib\algorithms\algorithm.py:2139, in Algorithm._get_env_id_and_creator.<locals>.<lambda>()
   2137         return env_id, lambda cfg: _wrapper.remote(cfg)
   2138     else:
-> 2139         return env_id, lambda cfg: env_specifier(cfg)
   2141 # No env -> Env creator always returns None.
   2142 elif env_specifier is None:

TypeError: __init__() takes 1 positional argument but 2 were given
</code>```

Does anybody know how to resolve it? I am just following the first step of the guide.

I am just try to remove the build() method for PPOConfigure, so I have:

```<code>algo = (
    PPOConfig()
    .rollouts(num_rollout_workers=1)
    .resources(num_gpus=0)
    .environment(env=Example_v2)
)
</code>```

And this doesn't produce any error. So the question may be also: is build() method necessary?

I am trying to search other errors like this, but nothing was found.

Body:
I am trying to follow the steps mentioned on "Getting Started with RLlib" (https://docs.ray.io/en/latest/rllib/rllib-training.html) along with my custom environment.

However my run doesn't work in the first code block show in the guide.
This is actually the script I m trying to run:

import ray
from ray.rllib.algorithms.ppo import PPOConfig
from ray.tune.logger import pretty_print
from gym_sw_env.envs.Examplev2 import Example_v2 #this is my custom env

ray.init(ignore_reinit_error=True)

algo = (
    PPOConfig()
    .rollouts(num_rollout_workers=1)
    .resources(num_gpus=0)
    .environment(env=Example_v2)
    .build()
)

While this is the error I have:

(RolloutWorker pid=24420) 2022-12-17 11:36:34,235   ERROR worker.py:763 -- Exception raised in creation task: The actor died because of an error raised in its creation task, ray::RolloutWorker.__init__() (pid=24420, ip=127.0.0.1, repr=<ray.rllib.evaluation.rollout_worker.RolloutWorker object at 0x000001693BEB1C10>)
(RolloutWorker pid=24420)   File "python\ray\_raylet.pyx", line 859, in ray._raylet.execute_task
(RolloutWorker pid=24420)   File "python\ray\_raylet.pyx", line 863, in ray._raylet.execute_task
(RolloutWorker pid=24420)   File "python\ray\_raylet.pyx", line 810, in ray._raylet.execute_task.function_executor
(RolloutWorker pid=24420)   File "C:\Users\**MYUSER**\Anaconda3\lib\site-packages\ray\_private\function_manager.py", line 674, in actor_method_executor
(RolloutWorker pid=24420)     return method(__ray_actor, *args, **kwargs)
(RolloutWorker pid=24420)   File "C:\Users\**MYUSER**\Anaconda3\lib\site-packages\ray\util\tracing\tracing_helper.py", line 466, in _resume_span
(RolloutWorker pid=24420)     return method(self, *_args, **_kwargs)
(RolloutWorker pid=24420)   File "C:\Users\**MYUSER**\Anaconda3\lib\site-packages\ray\rllib\evaluation\rollout_worker.py", line 492, in __init__
(RolloutWorker pid=24420)     self.env = env_creator(copy.deepcopy(self.env_context))
(RolloutWorker pid=24420)   File "C:\Users\**MYUSER**\Anaconda3\lib\site-packages\ray\rllib\algorithms\algorithm.py", line 2139, in <lambda>
(RolloutWorker pid=24420)     return env_id, lambda cfg: env_specifier(cfg)
(RolloutWorker pid=24420) TypeError: __init__() takes 1 positional argument but 2 were given
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [3], line 7
      2 from ray.tune.logger import pretty_print
      3 from gym_sw_env.envs.Examplev2 import Example_v2
      6 algo = (
----> 7     PPOConfig()
      8     .rollouts(num_rollout_workers=1)
      9     .resources(num_gpus=0)
     10     .environment(env=Example_v2)
     11     .build()
     12 )

File ~\Anaconda3\lib\site-packages\ray\rllib\algorithms\algorithm_config.py:311, in AlgorithmConfig.build(self, env, logger_creator)
    308 if logger_creator is not None:
    309     self.logger_creator = logger_creator
--> 311 return self.algo_class(
    312     config=self.to_dict(),
    313     env=self.env,
    314     logger_creator=self.logger_creator,
    315 )

File ~\Anaconda3\lib\site-packages\ray\rllib\algorithms\algorithm.py:414, in Algorithm.__init__(self, config, env, logger_creator, **kwargs)
    402 # Initialize common evaluation_metrics to nan, before they become
    403 # available. We want to make sure the metrics are always present
    404 # (although their values may be nan), so that Tune does not complain
    405 # when we use these as stopping criteria.
    406 self.evaluation_metrics = {
    407     "evaluation": {
    408         "episode_reward_max": np.nan,
   (...)
    411     }
    412 }
--> 414 super().__init__(config=config, logger_creator=logger_creator, **kwargs)
    416 # Check, whether `training_iteration` is still a tune.Trainable property
    417 # and has not been overridden by the user in the attempt to implement the
    418 # algos logic (this should be done now inside `training_step`).
    419 try:

File ~\Anaconda3\lib\site-packages\ray\tune\trainable\trainable.py:161, in Trainable.__init__(self, config, logger_creator, remote_checkpoint_dir, custom_syncer, sync_timeout)
    159 start_time = time.time()
    160 self._local_ip = ray.util.get_node_ip_address()
--> 161 self.setup(copy.deepcopy(self.config))
    162 setup_time = time.time() - start_time
    163 if setup_time > SETUP_TIME_THRESHOLD:

File ~\Anaconda3\lib\site-packages\ray\rllib\algorithms\algorithm.py:549, in Algorithm.setup(self, config)
    536 except RayActorError as e:
    537     # In case of an actor (remote worker) init failure, the remote worker
    538     # may still exist and will be accessible, however, e.g. calling
    539     # its `sample.remote()` would result in strange "property not found"
    540     # errors.
    541     if e.actor_init_failed:
    542         # Raise the original error here that the RolloutWorker raised
    543         # during its construction process. This is to enforce transparency
   (...)
    547         # - e.args[0].args[2]: The original Exception (e.g. a ValueError due
    548         # to a config mismatch) thrown inside the actor.
--> 549         raise e.args[0].args[2]
    550     # In any other case, raise the RayActorError as-is.
    551     else:
    552         raise e

File python\ray\_raylet.pyx:852, in ray._raylet.execute_task()

File python\ray\_raylet.pyx:906, in ray._raylet.execute_task()

File python\ray\_raylet.pyx:859, in ray._raylet.execute_task()

File python\ray\_raylet.pyx:863, in ray._raylet.execute_task()

File python\ray\_raylet.pyx:810, in ray._raylet.execute_task.function_executor()

File ~\Anaconda3\lib\site-packages\ray\_private\function_manager.py:674, in actor_method_executor()
    672     return method(*args, **kwargs)
    673 else:
--> 674     return method(__ray_actor, *args, **kwargs)

File ~\Anaconda3\lib\site-packages\ray\util\tracing\tracing_helper.py:466, in _resume_span()
    464 # If tracing feature flag is not on, perform a no-op
    465 if not _is_tracing_enabled() or _ray_trace_ctx is None:
--> 466     return method(self, *_args, **_kwargs)
    468 tracer: _opentelemetry.trace.Tracer = _opentelemetry.trace.get_tracer(
    469     __name__
    470 )
    472 # Retrieves the context from the _ray_trace_ctx dictionary we
    473 # injected.

File ~\Anaconda3\lib\site-packages\ray\rllib\evaluation\rollout_worker.py:492, in __init__()
    485 # Create a (single) env for this worker.
    486 if not (
    487     worker_index == 0
    488     and num_workers > 0
    489     and not policy_config.get("create_env_on_driver")
    490 ):
    491     # Run the `env_creator` function passing the EnvContext.
--> 492     self.env = env_creator(copy.deepcopy(self.env_context))
    494 if self.env is not None:
    495     # Validate environment (general validation function).
    496     if not self._disable_env_checking:

File ~\Anaconda3\lib\site-packages\ray\rllib\algorithms\algorithm.py:2139, in Algorithm._get_env_id_and_creator.<locals>.<lambda>()
   2137         return env_id, lambda cfg: _wrapper.remote(cfg)
   2138     else:
-> 2139         return env_id, lambda cfg: env_specifier(cfg)
   2141 # No env -> Env creator always returns None.
   2142 elif env_specifier is None:

TypeError: __init__() takes 1 positional argument but 2 were given

Does anybody know how to resolve it? I am just following the first step of the guide.

I am just try to remove the build() method for PPOConfigure, so I have:

algo = (
    PPOConfig()
    .rollouts(num_rollout_workers=1)
    .resources(num_gpus=0)
    .environment(env=Example_v2)
)

And this doesn't produce any error. So the question may be also: is build() method necessary?

I am trying to search other errors like this, but nothing was found.


来源: stackexchange

问:
Is it possible to embed Wordpress plugin within Razor view?
I see a lot of materials on running Wordpress on .NET Core, but what I try to find is it possible to embed/host Wordpress plugin within Razor view.

Is it possible to accomplish?

ContentLicense: CC BY-SA 4.0


问:
How to fix the expected enum `Result`, found reference error in Rust
I have an interface as follows:

```<code>#[async_trait]
pub trait HttpClient {
    async fn send_request(&self, path: String) -> Result<Response, Error>;
}
</code>```

Then in integration test, I have an implementation for it as follows:

```<code>struct MockClient {
    res_req: HashMap<String, Result<Response, Error>>
}
impl MockClient {
    pub fn mock(res_req: HashMap<String, Result<Response, Error>>) -> Self {
        Self {
            res_req,
        }
    }
}

#[async_trait]
impl HttpClient for MockClient {
    async fn send_request(&self, path: String) -> Result<Response, Error> {
        self.res_req.get(&path).unwrap()
    }
}
</code>```

But his fails compilation with the following error

```<code>error[E0308]: mismatched types
  --> tests/integration_test.rs:22:9
   |
22 |         self.res_req.get(&path).unwrap()
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `Result`, found reference
   |
   = note:   expected enum `Result<Response, reqwest::Error>`
           found reference `&Result<Response, reqwest::Error>`

</code>```

I tried using .clone() to create a copy and returned but that did not work.

My questions are:

Why is the compilation error occuring?

Why did the attempt to use clone() not work?

How do I get this to compile?

Body:
I have an interface as follows:

#[async_trait]
pub trait HttpClient {
    async fn send_request(&self, path: String) -> Result<Response, Error>;
}

Then in integration test, I have an implementation for it as follows:

struct MockClient {
    res_req: HashMap<String, Result<Response, Error>>
}
impl MockClient {
    pub fn mock(res_req: HashMap<String, Result<Response, Error>>) -> Self {
        Self {
            res_req,
        }
    }
}

#[async_trait]
impl HttpClient for MockClient {
    async fn send_request(&self, path: String) -> Result<Response, Error> {
        self.res_req.get(&path).unwrap()
    }
}

But his fails compilation with the following error

error[E0308]: mismatched types
  --> tests/integration_test.rs:22:9
   |
22 |         self.res_req.get(&path).unwrap()
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `Result`, found reference
   |
   = note:   expected enum `Result<Response, reqwest::Error>`
           found reference `&Result<Response, reqwest::Error>`

I tried using .clone() to create a copy and returned but that did not work.

My questions are:

Why is the compilation error occuring?

Why did the attempt to use clone() not work?

How do I get this to compile?


问:
Join these two formulas so that it only gives me an excel result
doing a job on LaLiga santander (Spanish football), I'm creating a code to award the third place in the champions league. The two conditions are that they look for the fourth team with the most points, and if several coincide, that they look for the team with the best goal difference among them. This is the line of code for the first condition:

```<code>=ArrayFormula(TEXTJOIN(",";1;IF($D$43:$AQ$43=LARGE($D$43:$AQ$43;4);$D$3:$AQ$3;"")))
</code>```

And this is the code for the second one:

```<code>=ArrayFormula(TEXTJOIN(",";1;IF(E44:AQ44=LARGE(E44:AQ44;4);$D$3:$AQ$3;"")))
</code>```

I manage to get the results in two different cells, and I wonder if there is a way to combine both formulas in the same one, so that it first looks for the team with the fourth most points, and then between them the team with the best goal difference.

I attach an image with the table for help:
table

I have tried with the AND() function inside the IF() function and with IFS(), but I get nothing. The result should be "Atletico Madrid"

Body:
doing a job on LaLiga santander (Spanish football), I'm creating a code to award the third place in the champions league. The two conditions are that they look for the fourth team with the most points, and if several coincide, that they look for the team with the best goal difference among them. This is the line of code for the first condition:

=ArrayFormula(TEXTJOIN(",";1;IF($D$43:$AQ$43=LARGE($D$43:$AQ$43;4);$D$3:$AQ$3;"")))

And this is the code for the second one:

=ArrayFormula(TEXTJOIN(",";1;IF(E44:AQ44=LARGE(E44:AQ44;4);$D$3:$AQ$3;"")))

I manage to get the results in two different cells, and I wonder if there is a way to combine both formulas in the same one, so that it first looks for the team with the fourth most points, and then between them the team with the best goal difference.

I attach an image with the table for help:
table

I have tried with the AND() function inside the IF() function and with IFS(), but I get nothing. The result should be "Atletico Madrid"


问:
Type hints for Python 3 dictionary containing required and un-determined optional keys
If I have a dictionary which contains required and but also arbitrary optional keys, how should I type this dictionary?

Example:

```<code>Dictionary family:
  father: str,
  mother: str,

  # optional key start
  son1: str,
  daughter1: str,
  son2: str,
  daughter2: str,
  # arbitrary many more sons, daughters, grandparents, ...
</code>```

The family can contain any one of them.

```<code>{father: "Bob", mother: "Alice"}
</code>```

or

```<code>{father: "Bob", mother: "Alice", son1: "Peter"}
</code>```

or

```<code>{father: "Bob", mother: "Alice", daughter1: "Jane"}
</code>```

If I just use Dict[str, str], users cannot know father and mother are required. If I use a TypedDict, no additional keys are allowed; total=False and NotRequired[str] still require to know all keys up-front. How to type this?

In TypeScript on would use

```<code>type family = {
  father: string,
  mother: string,

  [key: string]: string
}
</code>```

to allow arbitrary additional keys of type string.

Does Python have this function?

Body:
If I have a dictionary which contains required and but also arbitrary optional keys, how should I type this dictionary?

Example:

Dictionary family:
  father: str,
  mother: str,

  # optional key start
  son1: str,
  daughter1: str,
  son2: str,
  daughter2: str,
  # arbitrary many more sons, daughters, grandparents, ...

The family can contain any one of them.

{father: "Bob", mother: "Alice"}

or

{father: "Bob", mother: "Alice", son1: "Peter"}

or

{father: "Bob", mother: "Alice", daughter1: "Jane"}

If I just use Dict[str, str], users cannot know father and mother are required. If I use a TypedDict, no additional keys are allowed; total=False and NotRequired[str] still require to know all keys up-front. How to type this?

In TypeScript on would use

type family = {
  father: string,
  mother: string,

  [key: string]: string
}

to allow arbitrary additional keys of type string.

Does Python have this function?


问:
fatal error LNK1118
When I build my dll the "fatal error LNK1118: syntax error in 'ENTRY' statement" occur in definition.def file.So please tell me how to write in the definition.def file.In somwhere I read about dumpbin.exe.Can I use it in this case.

#define ENTRY   _stdcall

typedef LONG  OKERR
these are define in other header file.
The definition.def file like this.

LIBRARY "hello"

EXPORTS

OKERR ENTRY function1

OKERR ENTRY function2

ContentLicense: CC BY-SA 3.0

Title: fatal error LNK1118


问:
htmlspecialchars not allowing url to open
Am using

```<code><form action="<?php echo htmlspecialchars(Uri::getInstance()->toString()); ?>" method="post"
      name="adminForm" id="adminForm">
</code>```

However, theres dynamic link which is generated like on clicking link as

```<code>https://www.mywebsite.com/index.php?option=com_rsform&formId=1&form[car]=Honda&form[Model]=City%20Hybrid%20e%20HEV
</code>```

Due to above code for htmlspecialchars link on clicking is just refresing the page. I understand the purpose of htmlspecialchars for security

Any workaround solution that the dynamic link as generated can be executed.

Body:
Am using

<form action="<?php echo htmlspecialchars(Uri::getInstance()->toString()); ?>" method="post"
      name="adminForm" id="adminForm">

However, theres dynamic link which is generated like on clicking link as

https://www.mywebsite.com/index.php?option=com_rsform&formId=1&form[car]=Honda&form[Model]=City%20Hybrid%20e%20HEV

Due to above code for htmlspecialchars link on clicking is just refresing the page. I understand the purpose of htmlspecialchars for security

Any workaround solution that the dynamic link as generated can be executed.


问:
Longest Repeating Character Replacement - anlyzing big O of my solution
leetcode problem 424. Longest Repeating Character Replacement

"You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations."

I solved it like so:

```<code>var characterReplacement = function (s, k) {
  let l = 0,
    r = 0,
    maxWindow = 0;
  map = new Map();
  while (r < s.length) {
    let freq = (map.get(s[r]) ?? 0) + 1;
    map.set(s[r], freq);
    let maxFreq = Math.max(...map.values());
    if (r + 1 - l - maxFreq <= k) {
      maxWindow = Math.max(r + 1 - l, maxWindow);
    } else {
      map.set(s[l], map.get(s[l]) - 1);
      l++;
    }
    r++;
  }
  return maxWindow;
};
</code>```

I know I can do better by just maintaining a max frequency seen thus far, but I want to understand how to analyze my code above. And anyway if I am not mistaken both solutions will be O(n).  My question is, how do I analyze big O of the worst case of my solution, and is it indeed O(n) as my intuition tells me?

Tried to find a pattern for the cost of the basic operation that resembles some maybe some kind of nown series expansion but could not.

Body:
leetcode problem 424. Longest Repeating Character Replacement

"You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations."

I solved it like so:

var characterReplacement = function (s, k) {
  let l = 0,
    r = 0,
    maxWindow = 0;
  map = new Map();
  while (r < s.length) {
    let freq = (map.get(s[r]) ?? 0) + 1;
    map.set(s[r], freq);
    let maxFreq = Math.max(...map.values());
    if (r + 1 - l - maxFreq <= k) {
      maxWindow = Math.max(r + 1 - l, maxWindow);
    } else {
      map.set(s[l], map.get(s[l]) - 1);
      l++;
    }
    r++;
  }
  return maxWindow;
};

I know I can do better by just maintaining a max frequency seen thus far, but I want to understand how to analyze my code above. And anyway if I am not mistaken both solutions will be O(n).  My question is, how do I analyze big O of the worst case of my solution, and is it indeed O(n) as my intuition tells me?

Tried to find a pattern for the cost of the basic operation that resembles some maybe some kind of nown series expansion but could not.


问:
Matching algorithm to find an suitable place in a grid
I'm trying to solve a task from a programming challenge and it should be really easy with a matching algorithm but I'm pretty lost how it should be transfered in a graph.
It should be probably based on max-min-flow or maximum bipartit matching.
Could anybody give me a little hint on how to solve this or how to transfer the input in a graph? Thanks in advance!


问:
Why we need Mean, median and mode in statistic?
Anyone could explain me why we need mean median and mode in statistic?
How to know which data is in good mean median and mode?

Thank you for help


问:
Can't change color in WordCloud
I am having a problem changing the color in the words in my wordcloud
If i use this code

```<code>#Library
library(wordcloud)
library(stringr)
library(dplyr)

#Data
p = nba$birth_country

#code
wordcloud(p, scale = c(10, 2), min.freq = 1, colors = rainbow(33))
</code>```

words have a different size but their color is always the same (red)
I've tried to change the number in colors and in scale, but nothing changed.
So i've tried to use another color, but also nothing changend
Then i've tried to use random.color, but it gives me this error

Error in -freq : invalid argument to unary operator

Pls help :(

What i want vs What i've got

Title: Can't change color in WordCloud

Body:
I am having a problem changing the color in the words in my wordcloud
If i use this code

#Library
library(wordcloud)
library(stringr)
library(dplyr)

#Data
p = nba$birth_country

#code
wordcloud(p, scale = c(10, 2), min.freq = 1, colors = rainbow(33))

words have a different size but their color is always the same (red)
I've tried to change the number in colors and in scale, but nothing changed.
So i've tried to use another color, but also nothing changend
Then i've tried to use random.color, but it gives me this error

Error in -freq : invalid argument to unary operator

Pls help :(

What i want vs What i've got


问:
How can I get List of one of my Models from Json string?
I've tried searching about my problem found couple of suggestions but couldnt find any working solution. That's why I'm here to explain more detaily.

I've got a table which is stores Json data of a row of any table in database.

```<code>TblStatus - ID, TableName(string), JsonData(nvarcharmax)
</code>```

So I wanted to get 'JsonData' as list of 'TableName' .

Here is the how I'm getting an object from string;

```<code>public static class ObjectExtensions{
    public static object GetTableObject(string tableName){
    PropertyInfo[] properties = typeof(Models.Context).GetProperties();
    var prop = properties.FirstOrDefault(p => p.Name == tableName);

    using (var db = new Models.Context())
    {
        var table = prop?.GetValue(db);
        return table;
    }
  }
}
</code>```

But couldn't use like that;

```<code>var table = ObjectExtensions.GetTableObject('TblHistory'); // it returns object?
List<table> list = new List<table>(); // couldnt use like that
</code>```

Is there any suggestion about that?

Thanks

I've tried searching about my problem found couple of suggestions but couldnt find any working solution. That's why I'm here to explain more detaily.

Body:
I've tried searching about my problem found couple of suggestions but couldnt find any working solution. That's why I'm here to explain more detaily.

I've got a table which is stores Json data of a row of any table in database.

TblStatus - ID, TableName(string), JsonData(nvarcharmax)

So I wanted to get 'JsonData' as list of 'TableName' .

Here is the how I'm getting an object from string;

public static class ObjectExtensions{
    public static object GetTableObject(string tableName){
    PropertyInfo[] properties = typeof(Models.Context).GetProperties();
    var prop = properties.FirstOrDefault(p => p.Name == tableName);

    using (var db = new Models.Context())
    {
        var table = prop?.GetValue(db);
        return table;
    }
  }
}

But couldn't use like that;

var table = ObjectExtensions.GetTableObject('TblHistory'); // it returns object?
List
 list = new List
(); // couldnt use like that

Is there any suggestion about that?

Thanks

I've tried searching about my problem found couple of suggestions but couldnt find any working solution. That's why I'm here to explain more detaily.


问:
Excal vba Run-time error '429' ActiveX component can't create object
Here in this excel vba I'm trying to get local path of excel file saved on OneDrive (instead of url path) and print pdf to same directory. But I'm encountering an error called:

"Run-time error '429' ActiveX component can't create object"

Main Code is as follow:

```<code>Option Explicit
Dim LocalPathExcel$, LocalPathPDF$

Sub SavePDF1()
    LocalPathExcel$ = GetLocalPath(ThisWorkbook.FullName)
    LocalPathPDF$ = Replace(LocalPathExcel$, ".xlsm", ".pdf")

    If Dir(LocalPathPDF$) <> vbNullString Then
        Kill LocalPathPDF$
    End If

    Sheet4.ExportAsFixedFormat Type:=xlTypePDF, fileName:=LocalPathPDF$, _
    Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End Sub
</code>```

Error

Debug

VBAProject references

SupportingFunc

Body:
Here in this excel vba I'm trying to get local path of excel file saved on OneDrive (instead of url path) and print pdf to same directory. But I'm encountering an error called:

"Run-time error '429' ActiveX component can't create object"

Main Code is as follow:

Option Explicit
Dim LocalPathExcel$, LocalPathPDF$

Sub SavePDF1()
    LocalPathExcel$ = GetLocalPath(ThisWorkbook.FullName)
    LocalPathPDF$ = Replace(LocalPathExcel$, ".xlsm", ".pdf")

    If Dir(LocalPathPDF$) <> vbNullString Then
        Kill LocalPathPDF$
    End If

    Sheet4.ExportAsFixedFormat Type:=xlTypePDF, fileName:=LocalPathPDF$, _
    Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End Sub

Error

Debug

VBAProject references

SupportingFunc


问:
Unresolved External Symbol
so I have this code in my Memory.cpp

```<code>template<typename T>
T Memory::ReadMemory(const std::uintptr_t& baseAddress) const {
    T buffer = 0;
    ReadProcessMemory(this->m_pH, (LPCVOID)(baseAddress), &buffer, sizeof(buffer), NULL);
    return buffer;
}
</code>```

And this code in my Base.cpp:

```<code>std::uintptr_t CBase::Get_CurrentIcon() const {
    return ptrMemory->ReadMemory<std::uintptr_t>(0x360);
}

byte CBase::Get_CurrentSlot() const {
    return ptrMemory->ReadMemory<byte>(0x420);
}
</code>```

However that causes an unresolved external symbol error stating public: unsigned __int64 __cdecl Memory::ReadMemory<unsigned __int64>(unsigned __int64 const &)const.

So I was able to fix it with instead of using T, to add a ReadMemory for each used Data Type like this in my Memory.cpp.

```<code>template<>
std::uintptr_t Memory::ReadMemory(const std::uintptr_t& baseAddress) const {
    std::uintptr_t buffer = 0;
    ReadProcessMemory(this->m_pH, (LPCVOID)(baseAddress), &buffer, sizeof(buffer), NULL);
    return buffer;
}

template<>
byte Memory::ReadMemory(const std::uintptr_t& baseAddress) const {
    byte buffer = 0;
    ReadProcessMemory(this->m_pH, (LPCVOID)(baseAddress), &buffer, sizeof(buffer), NULL);
    return buffer;
}
</code>```

However that feels kinda overcomplicated. Is there a better method to fix the issue?

Title: Unresolved External Symbol

Body:
so I have this code in my Memory.cpp

template<typename T>
T Memory::ReadMemory(const std::uintptr_t& baseAddress) const {
    T buffer = 0;
    ReadProcessMemory(this->m_pH, (LPCVOID)(baseAddress), &buffer, sizeof(buffer), NULL);
    return buffer;
}

And this code in my Base.cpp:

std::uintptr_t CBase::Get_CurrentIcon() const {
    return ptrMemory->ReadMemory<std::uintptr_t>(0x360);
}

byte CBase::Get_CurrentSlot() const {
    return ptrMemory->ReadMemory<byte>(0x420);
}

However that causes an unresolved external symbol error stating public: unsigned __int64 __cdecl Memory::ReadMemory<unsigned __int64>(unsigned __int64 const &)const.

So I was able to fix it with instead of using T, to add a ReadMemory for each used Data Type like this in my Memory.cpp.

template<>
std::uintptr_t Memory::ReadMemory(const std::uintptr_t& baseAddress) const {
    std::uintptr_t buffer = 0;
    ReadProcessMemory(this->m_pH, (LPCVOID)(baseAddress), &buffer, sizeof(buffer), NULL);
    return buffer;
}

template<>
byte Memory::ReadMemory(const std::uintptr_t& baseAddress) const {
    byte buffer = 0;
    ReadProcessMemory(this->m_pH, (LPCVOID)(baseAddress), &buffer, sizeof(buffer), NULL);
    return buffer;
}

However that feels kinda overcomplicated. Is there a better method to fix the issue?


问:
How to test the spring boot app in local which is behind AWS Load Balancer
Currently my spring boot app is behind the AWS Load Balancer. Once after successful login, jwt values are being passed and fetching required info from it.

I need to setup the app in local and replicate getting the request through load balancer


问:
Crontab to run git pull as www-data user
I've created cronjob with crontab -u www-data -e and added the following command:

```<code>* * * * * cd /var/www/example.com/wp-content/themes/mytheme && /usr/local/bin/git pull origin dev
</code>```

But it's not pulling in anything. I've also set up custom cron log via rsyslog, but it only shows command, no output. When I run said command as root everything works.

Permissions on dirs and files are setup properly, and owner of said directory is www-data.

Body:
I've created cronjob with crontab -u www-data -e and added the following command:

* * * * * cd /var/www/example.com/wp-content/themes/mytheme && /usr/local/bin/git pull origin dev

But it's not pulling in anything. I've also set up custom cron log via rsyslog, but it only shows command, no output. When I run said command as root everything works.

Permissions on dirs and files are setup properly, and owner of said directory is www-data.


问:
update in codeigniter 3, it's run but database didnt changed
i dont understand with my code. it's run, and work. but when i see in database didnt changed.

here's my controller, function perbarui for get id data, get the data id from model (MMobil).

```<code>public function perbarui($id = NULL){
        $this->load->model('merek');
        $this->load->library('form_validation');
        $data['merk'] = $this->merek->getList();
        $data['detail'] = $this->MMobil->detail($id);
        $submit = $this->input->post('submit');
        print_r($data);
        if ($submit) {
                $nomor_kendaraan = $this->input->post('nomor_kendaraan');
                $nomor_mesin = $this->input->post('nomor_mesin');
                $id_merek = $this->input->post('id_merek');
                $tahun_beli = $this->input->post('tahun_beli');
                $nama_mobil = $this->input->post('nama_mobil');
                $this->form_validation->set_rules('nama_mobil', 'Nama_Mobil', 'required');
                $this->form_validation->set_rules('nomor_kendaraan', 'Nomor_Kendaraan', 'required');

                $data['detik'] = $this->MMobil->setData($nomor_kendaraan, $nomor_mesin, $id_merek, $tahun_beli, $nama_mobil);
            if ($this->form_validation->run() == FALSE) {
                $data['errors'] = TRUE;
            }else{
                $data['detail'] = $this->MMobil->detail($id);
                print_r($data);
            }
            //redirect('Master');
        }
        $this->load->view('master-detail-mobil', $data);
    }
</code>```

here's my models. function setData for storage variable after click submit. function edit get id data and get variable arrayData from function setData

```<code>public function setData($nomor_kendaraan, $nomor_mesin, $id_merek, $tahun_beli, $nama_mobil){
        $this->nomor_kendaraan = $nomor_kendaraan;
        $this->nomor_mesin = $nomor_mesin;
        $this->id_merek = $id_merek;
        $this->tahun_beli = $tahun_beli;
        $this->nama_mobil = $nama_mobil;
    }

public function edit($id){
        $arrayData = array(
            'nomor_kendaraan' => $this->nomor_kendaraan,
            'nomor_mesin' => $this->nomor_mesin,
            'id_merek' => $this->id_merek,
            'tahun_beli' => $this->tahun_beli,
            'nama_mobil' => $this->nama_mobil,
        );
        $this->db->where('nomor_mesin', $id);
        return $this->db->update($this->table,$arrayData);
    }
</code>```

here's my views

```<code><?php $this->load->view('header.php'); ?>
<?php
    echo"<h4>UPDATE DATA</h4>";
?>
    <form class="form-horizontal" role="form" method="post" action="<?php echo site_url()?>/Master/perbarui/">
    <div class="form-group">
        <label class="control-label col-sm-2" for="noken">Nomor Kendaraan :</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" name="nomor_kendaraan" value="<?php
                echo @$detail->nomor_kendaraan;
            ?>">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="nomes">Nomor Mesin :</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" name="nomor_mesin" value="<?php
                echo @$detail->nomor_mesin;
            ?>">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="merk">Merek Mobil :</label>
        <div class="col-sm-10">
            <select class="form-control" name="id_merek">
                <?php foreach ($merk as $mrk) :?>
                    <option value="<?php echo $mrk->id_merek ?>">
                        <?php
                            echo $mrk->nama_merek;
                        ?>
                    </option>
                <?php endforeach?>
            </select>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="thn">Tahun Beli :</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" name="tahun_beli" value="<?php
                echo @$detail->tahun_beli; ?>">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="namo">Nama Mobil :</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" name="nama_mobil" value="<?php
                echo @$detail->nama_mobil; ?>">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="nomes"></label>
        <div class="col-sm-2">
            <input type="submit" class="form-control" name="submit" value="simpan">
        </div>
    </div>
</form>
<?php $this->load->view('footer.php'); ?>
</code>```

and here my pictures before click submit and after click submit. i typed print_r for see the data array. if you see data array detail before click submit, there is data in detail. but after click submit data array detail gone.

enter image description here enter image description here

Body:
i dont understand with my code. it's run, and work. but when i see in database didnt changed.

here's my controller, function perbarui for get id data, get the data id from model (MMobil).

public function perbarui($id = NULL){
        $this->load->model('merek');
        $this->load->library('form_validation');
        $data['merk'] = $this->merek->getList();
        $data['detail'] = $this->MMobil->detail($id);
        $submit = $this->input->post('submit');
        print_r($data);
        if ($submit) {
                $nomor_kendaraan = $this->input->post('nomor_kendaraan');
                $nomor_mesin = $this->input->post('nomor_mesin');
                $id_merek = $this->input->post('id_merek');
                $tahun_beli = $this->input->post('tahun_beli');
                $nama_mobil = $this->input->post('nama_mobil');
                $this->form_validation->set_rules('nama_mobil', 'Nama_Mobil', 'required');
                $this->form_validation->set_rules('nomor_kendaraan', 'Nomor_Kendaraan', 'required');

                $data['detik'] = $this->MMobil->setData($nomor_kendaraan, $nomor_mesin, $id_merek, $tahun_beli, $nama_mobil);
            if ($this->form_validation->run() == FALSE) {
                $data['errors'] = TRUE;
            }else{
                $data['detail'] = $this->MMobil->detail($id);
                print_r($data);
            }
            //redirect('Master');
        }
        $this->load->view('master-detail-mobil', $data);
    }

here's my models. function setData for storage variable after click submit. function edit get id data and get variable arrayData from function setData

public function setData($nomor_kendaraan, $nomor_mesin, $id_merek, $tahun_beli, $nama_mobil){
        $this->nomor_kendaraan = $nomor_kendaraan;
        $this->nomor_mesin = $nomor_mesin;
        $this->id_merek = $id_merek;
        $this->tahun_beli = $tahun_beli;
        $this->nama_mobil = $nama_mobil;
    }

public function edit($id){
        $arrayData = array(
            'nomor_kendaraan' => $this->nomor_kendaraan,
            'nomor_mesin' => $this->nomor_mesin,
            'id_merek' => $this->id_merek,
            'tahun_beli' => $this->tahun_beli,
            'nama_mobil' => $this->nama_mobil,
        );
        $this->db->where('nomor_mesin', $id);
        return $this->db->update($this->table,$arrayData);
    }

here's my views

<?php $this->load->view('header.php'); ?>
<?php
    echo"
UPDATE DATA
";
?>
    <form class="form-horizontal" role="form" method="post" action="<?php echo site_url()?>/Master/perbarui/">

        Nomor Kendaraan :

            <input type="text" class="form-control" name="nomor_kendaraan" value="<?php
                echo @$detail->nomor_kendaraan;
            ?>">

        Nomor Mesin :

            <input type="text" class="form-control" name="nomor_mesin" value="<?php
                echo @$detail->nomor_mesin;
            ?>">

        Merek Mobil :

            <select class="form-control" name="id_merek">
                <?php foreach ($merk as $mrk) :?>
                    <option value="<?php echo $mrk->id_merek ?>">
                        <?php
                            echo $mrk->nama_merek;
                        ?>
                    </option>
                <?php endforeach?>
            </select>

        Tahun Beli :

            <input type="text" class="form-control" name="tahun_beli" value="<?php
                echo @$detail->tahun_beli; ?>">

        Nama Mobil :

            <input type="text" class="form-control" name="nama_mobil" value="<?php
                echo @$detail->nama_mobil; ?>">

            <input type="submit" class="form-control" name="submit" value="simpan">

</form>
<?php $this->load->view('footer.php'); ?>

and here my pictures before click submit and after click submit. i typed print_r for see the data array. if you see data array detail before click submit, there is data in detail. but after click submit data array detail gone.

enter image description here enter image description here


问:
File picker doesnt get the path right
im using the modern way to get user to pick file and then get it using the "registerForActivityResult(ActivityResultContracts.StartActivityForResult())" method, but the path that I get is not correct (after creating File with the given path it says it doesnt exists). Could anyone please help me with this problem? cant find any solution online with the modern way.

```<code>private fun initializeImportResultLauncher() {
    importResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val path = result.data!!.data!!.path ?: return@registerForActivityResult
            val file = File(path)
            val fileExists = file.exists()

            binding.importedFileText.text =
                String.format("selected file: %s", importFile!!.name)
        }
    }
}
</code>```
```<code>private fun initializeImportButton() {
    binding.importButton.setOnClickListener {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "*/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        importResultLauncher.launch(intent)
    }
}
</code>```

in the debugger after selecting existing file it says that fileExists is false.
Path in the debugger is: /document/raw:/storage/emulated/0/Download/importFile.csv.

Or maybe im just not correctly saving files in the phone directory, if the code is correct could I get some help with that.

Tried every other method but just cant get it working

Title: File picker doesnt get the path right

Body:
im using the modern way to get user to pick file and then get it using the "registerForActivityResult(ActivityResultContracts.StartActivityForResult())" method, but the path that I get is not correct (after creating File with the given path it says it doesnt exists). Could anyone please help me with this problem? cant find any solution online with the modern way.

private fun initializeImportResultLauncher() {
    importResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val path = result.data!!.data!!.path ?: return@registerForActivityResult
            val file = File(path)
            val fileExists = file.exists()

            binding.importedFileText.text =
                String.format("selected file: %s", importFile!!.name)
        }
    }
}

private fun initializeImportButton() {
    binding.importButton.setOnClickListener {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "*/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        importResultLauncher.launch(intent)
    }
}

in the debugger after selecting existing file it says that fileExists is false.
Path in the debugger is: /document/raw:/storage/emulated/0/Download/importFile.csv.

Or maybe im just not correctly saving files in the phone directory, if the code is correct could I get some help with that.

Tried every other method but just cant get it working


问:
ERROR - attempt to perform arithmetic on a nil value
I have the following error when opening my garage in fivem,
and also the cars don't show up in my garage.

enter image description here

The error says line 692
status = "$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1))..""

full code

`

```<code>function src.myVehicles(work)
    local source = source
    local user_id = vRP.getUserId(source)
    local myvehicles = {}
    local ipva = ""
    local status = ""
    if user_id then
        if workgarage[work] then
            for k,v in pairs(workgarage) do
                if k == work then
                    for k2,v2 in pairs(v) do
                        status = "<span class=\"green\">"..k.."</span>"
                        ipva = "<span class=\"green\">Pago</span>"
                        table.insert(myvehicles,{ name = v2, name2 = vRP.vehicleName(v2), engine = 100, body = 100, fuel = 100, status = status, ipva = ipva })
                    end
                end
            end
            return myvehicles
        else
            local vehicle = vRP.query("creative/get_vehicle",{ user_id = parseInt(user_id) })
            local address = vRP.query("homes/get_homeuserid",{ user_id = parseInt(user_id) })
            if #address > 0 then
                for k,v in pairs(address) do
                    if v.home == work then
                        for k2,v2 in pairs(vehicle) do
                            if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then
                                status = "<span class=\"red\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>" --0.5
                            elseif vehicle[k2].detido == 1 then
                                status = "<span class=\"orange\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
                            else
                                status = "<span class=\"green\">Gratuita</span>"
                            end

                            if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then
                                ipva = "<span class=\"red\">Atrasado</span>"
                            else
                                ipva = "<span class=\"green\">Pago</span>"
                            end
                            table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva })
                        end
                        return myvehicles
                    else
                        for k2,v2 in pairs(vehicle) do
                            if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then
                                status = "<span class=\"red\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
                            elseif vehicle[k2].detido == 1 then
                                status = "<span class=\"orange\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
                            else
                                status = "<span class=\"green\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.005)).."</span>"
                            end

                            if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then
                                ipva = "<span class=\"red\">Atrasado</span>"
                            else
                                ipva = "<span class=\"green\">Pago</span>"
                            end
                            table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva })
                        end
                        return myvehicles
                    end
                end
             else
                for k2,v2 in pairs(vehicle) do
                    if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then
                        status = "<span class=\"red\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
                    elseif vehicle[k2].detido == 1 then
                        status = "<span class=\"orange\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
                    else
                        status = "<span class=\"green\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>"
                    end

                    if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then
                        ipva = "<span class=\"red\">Atrasado</span>"
                    else
                        ipva = "<span class=\"green\">Pago</span>"
                    end
                    table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva })
                end
                return myvehicles
            end
        end
    end

end
</code>```

`
I tried several things but I couldn't solve it.

in the database I have 2 cars assigned to me, but they still don't appear in my garage.

Body:
I have the following error when opening my garage in fivem,
and also the cars don't show up in my garage.

enter image description here

The error says line 692
status = "$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1))..""

full code

`

function src.myVehicles(work)
    local source = source
    local user_id = vRP.getUserId(source)
    local myvehicles = {}
    local ipva = ""
    local status = ""
    if user_id then
        if workgarage[work] then
            for k,v in pairs(workgarage) do
                if k == work then
                    for k2,v2 in pairs(v) do
                        status = ""..k..""
                        ipva = "Pago"
                        table.insert(myvehicles,{ name = v2, name2 = vRP.vehicleName(v2), engine = 100, body = 100, fuel = 100, status = status, ipva = ipva })
                    end
                end
            end
            return myvehicles
        else
            local vehicle = vRP.query("creative/get_vehicle",{ user_id = parseInt(user_id) })
            local address = vRP.query("homes/get_homeuserid",{ user_id = parseInt(user_id) })
            if #address > 0 then
                for k,v in pairs(address) do
                    if v.home == work then
                        for k2,v2 in pairs(vehicle) do
                            if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then
                                status = "$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."" --0.5
                            elseif vehicle[k2].detido == 1 then
                                status = "$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1))..""
                            else
                                status = "Gratuita"
                            end

                            if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then
                                ipva = "Atrasado"
                            else
                                ipva = "Pago"
                            end
                            table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva })
                        end
                        return myvehicles
                    else
                        for k2,v2 in pairs(vehicle) do
                            if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then
                                status = "$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1))..""
                            elseif vehicle[k2].detido == 1 then
                                status = "$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1))..""
                            else
                                status = "$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.005))..""
                            end

                            if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then
                                ipva = "Atrasado"
                            else
                                ipva = "Pago"
                            end
                            table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva })
                        end
                        return myvehicles
                    end
                end
             else
                for k2,v2 in pairs(vehicle) do
                    if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then
                        status = "$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1))..""
                    elseif vehicle[k2].detido == 1 then
                        status = "$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1))..""
                    else
                        status = "$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1))..""
                    end

                    if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then
                        ipva = "Atrasado"
                    else
                        ipva = "Pago"
                    end
                    table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva })
                end
                return myvehicles
            end
        end
    end

end

`
I tried several things but I couldn't solve it.

in the database I have 2 cars assigned to me, but they still don't appear in my garage.


问:
JS Websocket Dispatch data in application
I currently have a server (an ESP32 for connoisseurs) which regularly sends clients a json via websocket, I am able to receive this data, but I do not know how to process this data efficiently

I have JSON that looks like this:

```<code>  "fruit": [
    { "kiwi fruit": 3,
      "mangoes": 4,
      "apples": null
    },
    { "cart": true },
  ],
  "vegetables":
    { "potatoes": "almond",
      "prickly pear",
      "leeks": false
    }
};
</code>```

And here is my function used when I receive a message

function onMessage(event) {

   var data = JSON.parse(event.data);
   var keys = Object.keys(data);
   for (let i = 0; i < keys. length; i++) {
     const element = keys[i];
     if (element == "fruit")
     {
     }
     if (eleme,t == "vegetables")
     {
     ....
```

I would like some json data to modify the html and others to modify variables in my javascript application

I find my way of doing things totally inefficient, Is there a more efficient way of paresing a Json?

Sincerely Baptiste

Body:
I currently have a server (an ESP32 for connoisseurs) which regularly sends clients a json via websocket, I am able to receive this data, but I do not know how to process this data efficiently

I have JSON that looks like this:

  "fruit": [
    { "kiwi fruit": 3,
      "mangoes": 4,
      "apples": null
    },
    { "cart": true },
  ],
  "vegetables":
    { "potatoes": "almond",
      "prickly pear",
      "leeks": false
    }
};

And here is my function used when I receive a message

function onMessage(event) {

   var data = JSON.parse(event.data);
   var keys = Object.keys(data);
   for (let i = 0; i < keys. length; i++) {
     const element = keys[i];
     if (element == "fruit")
     {
     }
     if (eleme,t == "vegetables")
     {
     ....

I would like some json data to modify the html and others to modify variables in my javascript application

I find my way of doing things totally inefficient, Is there a more efficient way of paresing a Json?

Sincerely Baptiste


问:
add search and paginated in data table flutter
hi how can i add search and paginated in my Datatable2 in flutter
this is my code and data come from server and i have one request for search for exmaple when typing the name of person and send to server response is returned ..how can i This Response(details of person) show in my data table

```<code>class TableSamleNew extends StatefulWidget {
  const TableSamleNew({Key? key}) : super(key: key);

  @override
  State<TableSamleNew> createState() => _TableSamleNewState();
}

class _TableSamleNewState extends State<TableSamleNew> {
  final getListController = Get.put(GetListController());

  late List<ListItem>? listItem =
      getListController.getList!.data!.listItem;
  @override
  Widget build(BuildContext context) {
    var input = Get.rootDelegate.arguments();
    final List my_list_2 = [];
    List mylist_3 = input["headers"];
    azadlist_3.forEach((element) => my_list_2.add(element.name));

    return Scaffold(
      body: Directionality(
        textDirection: TextDirection.rtl,
        child: GetBuilder<GetListController>(
          init: GetListController(),
          initState: (_) {},
          builder: (_) => getListController.isLoading
              ? const Padding(
                  padding: EdgeInsets.only(top: 50),
                  child: Center(child: CircularProgressIndicator()),
                )
              : DataTable2(
                  columnSpacing: 12,
                  horizontalMargin: 12,
                  minWidth: 600,
                  columns: my_list_2
                      .map<DataColumn>((el) => DataColumn(label: Text(el!)))
                      .toList(),
                  rows: listItem!
                      .map<DataRow>((e) => DataRow(cells: [
                            DataCell(Text('${e.itemInfo?.name}'
                                '${e.itemInfo?.paymentDate}')),
                            DataCell(Text('${e.itemInfo!.helpType}')),
                            DataCell(Text('${e.itemInfo!.helpType}')),
                            DataCell(Text('${e.itemInfo!.helpType}')),
                            // DataCell(Text('${e.itemInfo?.clientStoreAddress}')),
                          ]))
                      .toList()),
        ),
      ),
    );
  }
}
</code>```

And Thank You For Your Response

Body:
hi how can i add search and paginated in my Datatable2 in flutter
this is my code and data come from server and i have one request for search for exmaple when typing the name of person and send to server response is returned ..how can i This Response(details of person) show in my data table

class TableSamleNew extends StatefulWidget {
  const TableSamleNew({Key? key}) : super(key: key);

  @override
  State<TableSamleNew> createState() => _TableSamleNewState();
}

class _TableSamleNewState extends State<TableSamleNew> {
  final getListController = Get.put(GetListController());

  late List<ListItem>? listItem =
      getListController.getList!.data!.listItem;
  @override
  Widget build(BuildContext context) {
    var input = Get.rootDelegate.arguments();
    final List my_list_2 = [];
    List mylist_3 = input["headers"];
    azadlist_3.forEach((element) => my_list_2.add(element.name));

    return Scaffold(
      body: Directionality(
        textDirection: TextDirection.rtl,
        child: GetBuilder<GetListController>(
          init: GetListController(),
          initState: (_) {},
          builder: (_) => getListController.isLoading
              ? const Padding(
                  padding: EdgeInsets.only(top: 50),
                  child: Center(child: CircularProgressIndicator()),
                )
              : DataTable2(
                  columnSpacing: 12,
                  horizontalMargin: 12,
                  minWidth: 600,
                  columns: my_list_2
                      .map<DataColumn>((el) => DataColumn(label: Text(el!)))
                      .toList(),
                  rows: listItem!
                      .map<DataRow>((e) => DataRow(cells: [
                            DataCell(Text('${e.itemInfo?.name}'
                                '${e.itemInfo?.paymentDate}')),
                            DataCell(Text('${e.itemInfo!.helpType}')),
                            DataCell(Text('${e.itemInfo!.helpType}')),
                            DataCell(Text('${e.itemInfo!.helpType}')),
                            // DataCell(Text('${e.itemInfo?.clientStoreAddress}')),
                          ]))
                      .toList()),
        ),
      ),
    );
  }
}

And Thank You For Your Response


问:
Tensorboard remove images from logs on the go
I'm using tensorboard on pytorch: https://pytorch.org/docs/stable/tensorboard.html

I save images every epoch with add_image: https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter.add_image

I'm trying to find a way to keep only the last epoch of images because otherwise the tensorboard file becomes huge.

Is there a way to do it? Also if I want also to keep the best epoch j. Is there a way to do this too?

A similar question is also here: Remove image outputs from TensorBoard but it's not defined like this + it ~6 years ago.


问:
Is it possible to add Upload as a field in antd-form-builder?
I use antd-form-builder to create a form. I want to add an upload field to the form how can I do it? I add code here, in this code I've used Form.Item to create Upload field. Is it possible to convert it to an antd-form-builder meta field?</p>
```<code>const columns = 1
  const meta1 = {
    columns,
    fields: [
      {
        key: "gageId",
        label: "ID",
        placeholder: "Gage ID",
        colSpan: 2,
      }
    ],
}
const meta2 = {
    columns,
    fields: [
      {
        key: "textarea",
        label: "Comment",
        widget: "textarea",
        colSpan: 2,
      },
    ],
  }
<Fragment>
          <fieldset className="form-frame">
            <FormBuilder meta={meta1} form={form} />
          </fieldset>
          <fieldset className="form-frame">
            <Form.Item label="Upload">
              <Upload action="/upload.do">
                <Button icon={<UploadOutlined />}>Upload Directory</Button>
              </Upload>
            </Form.Item>
            <FormBuilder meta={meta2} form={form} />
          </fieldset>
</Fragment>
</code>```

Body:
I use antd-form-builder to create a form. I want to add an upload field to the form how can I do it? I add code here, in this code I've used Form.Item to create Upload field. Is it possible to convert it to an antd-form-builder meta field?

const columns = 1
  const meta1 = {
    columns,
    fields: [
      {
        key: "gageId",
        label: "ID",
        placeholder: "Gage ID",
        colSpan: 2,
      }
    ],
}
const meta2 = {
    columns,
    fields: [
      {
        key: "textarea",
        label: "Comment",
        widget: "textarea",
        colSpan: 2,
      },
    ],
  }
<Fragment>
          <fieldset className="form-frame">
            <FormBuilder meta={meta1} form={form} />
          </fieldset>
          <fieldset className="form-frame">
            <Form.Item label="Upload">
              <Upload action="/upload.do">
                <Button icon={<UploadOutlined />}>Upload Directory</Button>
              </Upload>
            </Form.Item>
            <FormBuilder meta={meta2} form={form} />
          </fieldset>
</Fragment>


问:
.NET HttpClientHandler with ServerCertificateCustomValidationCallback , how to add additional information to generated AuthenticationException
I am using a custom server validation callback based on
this example

```<code>private void InitServices(IHostBuilder builder, ...)
{
...
    builder
    .ConfigureServices((context, services) =>
    {
        services.AddHttpClient("myHttpClient", c =>
            {
                c.Timeout = TimeSpan.FromSeconds(httpClientTimeoutSeconds);
            })
            .ConfigurePrimaryHttpMessageHandler(() =>
            {
                 var handler = new HttpClientHandler();
                 var myPemCaCertificateString = File.ReadAllText(myPemCaFilePath);
                 var caRootBytes = Encoding.ASCII.GetBytes(myPemCaCertificateString);
                 myCaRootX509Certificate = new X509Certificate2(caRootBytes);
                 var myRootCertificates = new X509Certificate2Collection(myCaRootX509Certificate);

                 handler.ServerCertificateCustomValidationCallback = CreateCustomRootValidator(myRootCertificates);
         ...
            }
</code>```

The validation method checks the chain.Build result and detects the SslPolicyErrors value and also the ChainElementStatus in case of failure. But the method can return only a bool value if the validation fails.

```<code>        private RemoteCertificateValidationCallback CreateCustomRootRemoteValidator(X509Certificate2Collection trustedRoots, X509Certificate2Collection intermediates = null)
        {
            if (trustedRoots == null)
                throw new ArgumentNullException(nameof(trustedRoots));
            if (trustedRoots.Count == 0)
                throw new ArgumentException("No trusted roots were provided", nameof(trustedRoots));

            X509Certificate2Collection roots = new X509Certificate2Collection(trustedRoots);
            X509Certificate2Collection intermeds = null;

            if (intermediates != null)
            {
                intermeds = new X509Certificate2Collection(intermediates);
            }

            intermediates = null;
            trustedRoots = null;

            return (sender, serverCert, chain, errors) =>
            {
                // Missing cert or the destination hostname wasn't valid for the cert.
                if ((errors & ~SslPolicyErrors.RemoteCertificateChainErrors) != 0)
                {
                    return false;
                }

                for (int i = 1; i < chain.ChainElements.Count; i++)
                {
                    chain.ChainPolicy.ExtraStore.Add(chain.ChainElements[i].Certificate);
                }

                if (intermeds != null)
                {
                    chain.ChainPolicy.ExtraStore.AddRange(intermeds);
                }

                chain.ChainPolicy.CustomTrustStore.Clear();
                chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
                chain.ChainPolicy.CustomTrustStore.AddRange(roots);
                var retChainBuild = chain.Build((X509Certificate2)serverCert);

                // Check if chain.Build returned false, that means ServerCertificateCustomValidation failed
                if (!retChainBuild)
                {
                    var nrChainElements = chain.ChainElements.Count;

                    if (nrChainElements > 0)
                    {
                        // the last element in the chain should be the root ca
                        X509ChainElement chainElement = chain.ChainElements[nrChainElements - 1];

                        foreach (X509ChainStatus status in chainElement.ChainElementStatus)
                        {
                            if (status.Status == X509ChainStatusFlags.PartialChain)
                            {
                            }
                            else if (status.Status == X509ChainStatusFlags.UntrustedRoot)
                            {
                            }
                        }
                    }
                }

                return retChainBuild;
            };
        }
</code>```

If the custom implementation of the ServerCertificateCustomValidationCallback returns false, then the following message is available in the AuthenticationException that is thrown when using the HttpClient:

```<code>The remote certificate was rejected by the provided RemoteCertificateValidationCallback.
</code>```

If the ServerCertificateCustomValidationCallback is not defined for the HttpClientHandler, the original Microsoft implementation returns the following message in the AuthenticationException:

```<code>The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot
</code>```

How can the information about the SslPolicyErrors type and also about the ChainElementStatus be passed to the AuthenticationException, in case of defining a ServerCertificateCustomValidationCallback for the HttpClientHandler?

Body:
I am using a custom server validation callback based on
this example

private void InitServices(IHostBuilder builder, ...)
{
...
    builder
    .ConfigureServices((context, services) =>
    {
        services.AddHttpClient("myHttpClient", c =>
            {
                c.Timeout = TimeSpan.FromSeconds(httpClientTimeoutSeconds);
            })
            .ConfigurePrimaryHttpMessageHandler(() =>
            {
                 var handler = new HttpClientHandler();
                 var myPemCaCertificateString = File.ReadAllText(myPemCaFilePath);
                 var caRootBytes = Encoding.ASCII.GetBytes(myPemCaCertificateString);
                 myCaRootX509Certificate = new X509Certificate2(caRootBytes);
                 var myRootCertificates = new X509Certificate2Collection(myCaRootX509Certificate);

                 handler.ServerCertificateCustomValidationCallback = CreateCustomRootValidator(myRootCertificates);
         ...
            }

The validation method checks the chain.Build result and detects the SslPolicyErrors value and also the ChainElementStatus in case of failure. But the method can return only a bool value if the validation fails.

        private RemoteCertificateValidationCallback CreateCustomRootRemoteValidator(X509Certificate2Collection trustedRoots, X509Certificate2Collection intermediates = null)
        {
            if (trustedRoots == null)
                throw new ArgumentNullException(nameof(trustedRoots));
            if (trustedRoots.Count == 0)
                throw new ArgumentException("No trusted roots were provided", nameof(trustedRoots));

            X509Certificate2Collection roots = new X509Certificate2Collection(trustedRoots);
            X509Certificate2Collection intermeds = null;

            if (intermediates != null)
            {
                intermeds = new X509Certificate2Collection(intermediates);
            }

            intermediates = null;
            trustedRoots = null;

            return (sender, serverCert, chain, errors) =>
            {
                // Missing cert or the destination hostname wasn't valid for the cert.
                if ((errors & ~SslPolicyErrors.RemoteCertificateChainErrors) != 0)
                {
                    return false;
                }

                for (int i = 1; i < chain.ChainElements.Count; i++)
                {
                    chain.ChainPolicy.ExtraStore.Add(chain.ChainElements[i].Certificate);
                }

                if (intermeds != null)
                {
                    chain.ChainPolicy.ExtraStore.AddRange(intermeds);
                }

                chain.ChainPolicy.CustomTrustStore.Clear();
                chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
                chain.ChainPolicy.CustomTrustStore.AddRange(roots);
                var retChainBuild = chain.Build((X509Certificate2)serverCert);

                // Check if chain.Build returned false, that means ServerCertificateCustomValidation failed
                if (!retChainBuild)
                {
                    var nrChainElements = chain.ChainElements.Count;

                    if (nrChainElements > 0)
                    {
                        // the last element in the chain should be the root ca
                        X509ChainElement chainElement = chain.ChainElements[nrChainElements - 1];

                        foreach (X509ChainStatus status in chainElement.ChainElementStatus)
                        {
                            if (status.Status == X509ChainStatusFlags.PartialChain)
                            {
                            }
                            else if (status.Status == X509ChainStatusFlags.UntrustedRoot)
                            {
                            }
                        }
                    }
                }

                return retChainBuild;
            };
        }

If the custom implementation of the ServerCertificateCustomValidationCallback returns false, then the following message is available in the AuthenticationException that is thrown when using the HttpClient:

The remote certificate was rejected by the provided RemoteCertificateValidationCallback.

If the ServerCertificateCustomValidationCallback is not defined for the HttpClientHandler, the original Microsoft implementation returns the following message in the AuthenticationException:

The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot

How can the information about the SslPolicyErrors type and also about the ChainElementStatus be passed to the AuthenticationException, in case of defining a ServerCertificateCustomValidationCallback for the HttpClientHandler?


问:
Is there android api to check which LTE or NR bearers are configured
I would like to monitor when and which data radio bearers my android phone has setup at any given moment e.g. when a VoLTE bearer is setup, when a QCI9 bearer is setup, etc. Is there any support in telephony package for that in android?

I downloaded a few apps and check api documentation but could only find support for things like signal strength or type of cell but not details of bearers.


问:
Is there some way to navigate along side sections in this Scroll Area?
Can some one give me any advice, how can i solve problem with navigation in the scollable area from react drei (https://www.npmjs.com/package/@react-three/drei) tools in front of Canvas 3D background. When i am trying use common navigation between sections with section id="hero" and Banner area. It is working, but scroll area working is scrolling my content with css property translate: translate3d(...). So if i use my  tag with section id. It scrolls to the given id but than i am not able to scroll back to the upper sections.

Here is my code:

I was expectig regular behavior of  tag navigation


问:
How to make API requests after authenticating with django-allauth?
I've integrated Github and GitLab authentication in my Django app using django-allauth. After authentication, how do I get access to the request token to make API calls to Github and GitLab?

I'm using django-allauth v0.51.0 and django v4.1.4.


问:
Unable to return document data from Firestore
I have the following code that is querying Firestore to get the name of a user based on their deviceIdentifier.

  func getUserName(deviceUid: String) -> String {
    var name = ""
    let db = Firestore.firestore()
    db.collection("users").document(deviceUid).getDocument { document, error in
      if let document = document, document.exists {
        let dataDescription = document.data()
        print("dataDescription: \(dataDescription)")
        name = dataDescription?["name"] as! String
      } else {
        print("Document does not exist")
      }
    }
    return name
  }
```

I can see that the data is in Firestore because I get the following in the console logs: dataDescription: Optional(["name": xxx, "deviceUid": xxx-xxx-xxxx-xxxx]) but the method isn't returning the name.

Body:
I have the following code that is querying Firestore to get the name of a user based on their deviceIdentifier.

  func getUserName(deviceUid: String) -> String {
    var name = ""
    let db = Firestore.firestore()
    db.collection("users").document(deviceUid).getDocument { document, error in
      if let document = document, document.exists {
        let dataDescription = document.data()
        print("dataDescription: \(dataDescription)")
        name = dataDescription?["name"] as! String
      } else {
        print("Document does not exist")
      }
    }
    return name
  }

I can see that the data is in Firestore because I get the following in the console logs: dataDescription: Optional(["name": xxx, "deviceUid": xxx-xxx-xxxx-xxxx]) but the method isn't returning the name.


问:
Changing the channel name does not work the second time
I'm doing a bit of testing for a system I want to make soon. I currently have a ticket that opens and then an embed is sent in where there is a close button.
If I close the ticket now everything happens as it should and the ticket is moved to another category and the name is adjusted. Now I can open the ticket again and the ticket is moved back to the old category and the name is changed back. But if I want to close the ticket now, it is only moved to the category but the name doesn't change like at the beginning and I don't understand why this happens or I can't find a solution since 2h.
(A check is already inside with the console log (at the beginning both are sent, at the 2nd time only the first))

Please excuse the German words in my code

I want the ticket to be moved to the category and the name to change as well. I have no idea why this works the first time, but after that it doesn't. I am open for further questions

Edit: I just found out that the same thing happens with the open button too. The button works the same way

Close Button Code:

```<code>if (e.customId === "ticketclose") {
  if (!supportrole) {
    e.reply({
      content: "Du hast keine Berechtigung hier für",
      ephemeral: true
    })
    return
  }

  let channel = e.channel.name
  let ersteller = tstate[e.channel.id].Creator
  let newcategory = e.guild.channels.cache.find(ct => ct.name === "closed tickets" && ct.type === ChannelType.GuildCategory)

  if (!newcategory) {
    await e.guild.channels.create({
      name: `closed tickets`,
      type: ChannelType.GuildCategory,
      permissionOverwrites: [{
          id: e.guild.id,
          deny: [PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ViewChannel],
        },
        {
          id: "816372587809734696",
          allow: [PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ViewChannel]
        },
      ]
    })
  }

  let ch = e.guild.channels.cache.find(ch => ch.id === `${e.channel.id}`)

  let namech = e.channel.name
  namech = namech.replace("closed-", "")
  namech = namech.replace("ticket-", "")

  let embed = {
    title: `Closed Ticket - ${namech}`,
    description: `Ticket von ${e.user}\n\nBeteiligte Personen:\n${tstate[ch.id].Beteiligung}\n\nAnliegen:\n${tstate[ch.id].Anliegen}`,
    color: 0xFFFF00,
    thumbnail: {
      url: client.user.avatarURL(),
    },
    timestamp: new Date(),
    footer: {
      text: footer,
      icon_url: client.user.avatarURL(),
    },
  }

  let row1 = new ActionRowBuilder()
    .addComponents(
      new ButtonBuilder()
      .setCustomId("tickettrans")
      .setLabel("Transkript Speichern")
      .setStyle(ButtonStyle.Primary)
      .setEmoji("")
    )
    .addComponents(
      new ButtonBuilder()
      .setCustomId("ticketopen")
      .setLabel("Ticket Öffnen")
      .setStyle(ButtonStyle.Success)
      .setEmoji("")
    )

  e.update({
    embeds: [embed],
    components: [row1]
  })

  await ch.permissionOverwrites.set([{
      id: e.guild.id,
      deny: [PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ViewChannel],
    },
    /*{
        id: ersteller,
        deny:[PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ViewChannel]
    },*/
    {
      id: "816372587809734696",
      allow: [PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ViewChannel]
    },

  ]).then(ch => {
    ch.setParent(newcategory).then(msg => {
      console.log("1")
      ch.setName(`closed-ticket-${namech}`).then(msg => {
        console.log("2")
      })
    })
  })

  ticketsystem[ersteller].Ticketgeöffnet = 0

  fs.writeFileSync(path.resolve(__dirname, "./ticketsystem.json"), JSON.stringify(ticketsystem, null, 4), err => {
    if (err) {
      console.log(err);
    }
  });
}
</code>```

Body:
I'm doing a bit of testing for a system I want to make soon. I currently have a ticket that opens and then an embed is sent in where there is a close button.
If I close the ticket now everything happens as it should and the ticket is moved to another category and the name is adjusted. Now I can open the ticket again and the ticket is moved back to the old category and the name is changed back. But if I want to close the ticket now, it is only moved to the category but the name doesn't change like at the beginning and I don't understand why this happens or I can't find a solution since 2h.
(A check is already inside with the console log (at the beginning both are sent, at the 2nd time only the first))

Please excuse the German words in my code

I want the ticket to be moved to the category and the name to change as well. I have no idea why this works the first time, but after that it doesn't. I am open for further questions

Edit: I just found out that the same thing happens with the open button too. The button works the same way

Close Button Code:

if (e.customId === "ticketclose") {
  if (!supportrole) {
    e.reply({
      content: "Du hast keine Berechtigung hier für",
      ephemeral: true
    })
    return
  }

  let channel = e.channel.name
  let ersteller = tstate[e.channel.id].Creator
  let newcategory = e.guild.channels.cache.find(ct => ct.name === "closed tickets" && ct.type === ChannelType.GuildCategory)

  if (!newcategory) {
    await e.guild.channels.create({
      name: `closed tickets`,
      type: ChannelType.GuildCategory,
      permissionOverwrites: [{
          id: e.guild.id,
          deny: [PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ViewChannel],
        },
        {
          id: "816372587809734696",
          allow: [PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ViewChannel]
        },
      ]
    })
  }

  let ch = e.guild.channels.cache.find(ch => ch.id === `${e.channel.id}`)

  let namech = e.channel.name
  namech = namech.replace("closed-", "")
  namech = namech.replace("ticket-", "")

  let embed = {
    title: `Closed Ticket - ${namech}`,
    description: `Ticket von ${e.user}\n\nBeteiligte Personen:\n${tstate[ch.id].Beteiligung}\n\nAnliegen:\n${tstate[ch.id].Anliegen}`,
    color: 0xFFFF00,
    thumbnail: {
      url: client.user.avatarURL(),
    },
    timestamp: new Date(),
    footer: {
      text: footer,
      icon_url: client.user.avatarURL(),
    },
  }

  let row1 = new ActionRowBuilder()
    .addComponents(
      new ButtonBuilder()
      .setCustomId("tickettrans")
      .setLabel("Transkript Speichern")
      .setStyle(ButtonStyle.Primary)
      .setEmoji("")
    )
    .addComponents(
      new ButtonBuilder()
      .setCustomId("ticketopen")
      .setLabel("Ticket Öffnen")
      .setStyle(ButtonStyle.Success)
      .setEmoji("")
    )

  e.update({
    embeds: [embed],
    components: [row1]
  })

  await ch.permissionOverwrites.set([{
      id: e.guild.id,
      deny: [PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ViewChannel],
    },
    /*{
        id: ersteller,
        deny:[PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ViewChannel]
    },*/
    {
      id: "816372587809734696",
      allow: [PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ViewChannel]
    },

  ]).then(ch => {
    ch.setParent(newcategory).then(msg => {
      console.log("1")
      ch.setName(`closed-ticket-${namech}`).then(msg => {
        console.log("2")
      })
    })
  })

  ticketsystem[ersteller].Ticketgeöffnet = 0

  fs.writeFileSync(path.resolve(__dirname, "./ticketsystem.json"), JSON.stringify(ticketsystem, null, 4), err => {
    if (err) {
      console.log(err);
    }
  });
}


问:
Nextjs not able to receive data from expressjs API in correct format
ive got a page which i call an api through getserversideprops to basically get all the data from a table. it used to work fine, but suddenly when i runned it today an error occured which i dont know the cause is. this is the response im getting when i console log the response

what i tried on my own and noticed to "help" was reducing the amount of columns that the API was selecting. For the api i used knex and express. this was the original code that used to work but now does not.

```<code> try{
        let data = "";
        await db.transaction(async (t)=>{
            data = await db('sales').transacting(t)
            .join('users','users.id','sales.cashier_id')
            .join('customer','customer.customer_id','sales.customer_id')
            .select('customer.name as customer_name','sales.sales_id','sales.date','sales.payment_type','sales.payment_status','sales.customer_id','sales.transaction_total','sales.total_paid','users.name','sales.shipment_fee','sales.days','sales.sale_type')

        })
        return data
    }catch(e){
        console.log(e);
        throw e;
    }
</code>```

what i tried was reducing the amount of select columns to i think 5 or 6, but definitely if the amount of columsn i use is under a limit it works. like

```<code> try{
        let data = "";
        await db.transaction(async (t)=>{
            data = await db('sales').transacting(t)
            .join('users','users.id','sales.cashier_id')
            .join('customer','customer.customer_id','sales.customer_id')
             .select('customer.name as customer_name','sales.sales_id','sales.transaction_total','sales.date','sales.payment_type')
        })
        return data
    }catch(e){
        console.log(e);
        throw e;
    }
</code>```

these are the attributes of my table

this is the server.js file of my expressjs

```<code>const compression = require('compression');
const express = require("express");
const app = express();
const fs = require('fs');
const http = require('http')
const https =  require('https')
const PORT = process.env.PORT || 8000;
var cors = require('cors')
const mainRoutes = require('./api/v1/routes/index')
const cookieParser = require("cookie-parser");

app.use(compression());
app.use(cors( {origin: 'http://localhost:3000',credentials: true}))
// app.use(cors());
app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

// Main Routes
app.use("/api/v1", mainRoutes,(req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
</code>```

this is how im calling the api from next

```<code>export async function getServerSideProps(context) {
    try{
        const res = await axios.get("/sales/get-all");
        const data = await  res.data
     return { props: { data } }
    }catch(err){
      const data = "error"
      return { props: { data} }
    }

    }
</code>```

where i declared default url of the axios at the app.js file of next

```<code>import '../styles/globals.css'
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:8000/api/v1/"

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp
</code>```

im not quite sure what the problem is so pardon if the title of the question is not according to the problem i have.

EDIT:
i moved the api to a useeffect call, its now working. but why isnt it working in getserversideprops?

Body:
ive got a page which i call an api through getserversideprops to basically get all the data from a table. it used to work fine, but suddenly when i runned it today an error occured which i dont know the cause is. this is the response im getting when i console log the response

what i tried on my own and noticed to "help" was reducing the amount of columns that the API was selecting. For the api i used knex and express. this was the original code that used to work but now does not.

 try{
        let data = "";
        await db.transaction(async (t)=>{
            data = await db('sales').transacting(t)
            .join('users','users.id','sales.cashier_id')
            .join('customer','customer.customer_id','sales.customer_id')
            .select('customer.name as customer_name','sales.sales_id','sales.date','sales.payment_type','sales.payment_status','sales.customer_id','sales.transaction_total','sales.total_paid','users.name','sales.shipment_fee','sales.days','sales.sale_type')

        })
        return data
    }catch(e){
        console.log(e);
        throw e;
    }

what i tried was reducing the amount of select columns to i think 5 or 6, but definitely if the amount of columsn i use is under a limit it works. like

 try{
        let data = "";
        await db.transaction(async (t)=>{
            data = await db('sales').transacting(t)
            .join('users','users.id','sales.cashier_id')
            .join('customer','customer.customer_id','sales.customer_id')
             .select('customer.name as customer_name','sales.sales_id','sales.transaction_total','sales.date','sales.payment_type')
        })
        return data
    }catch(e){
        console.log(e);
        throw e;
    }

these are the attributes of my table

this is the server.js file of my expressjs

const compression = require('compression');
const express = require("express");
const app = express();
const fs = require('fs');
const http = require('http')
const https =  require('https')
const PORT = process.env.PORT || 8000;
var cors = require('cors')
const mainRoutes = require('./api/v1/routes/index')
const cookieParser = require("cookie-parser");

app.use(compression());
app.use(cors( {origin: 'http://localhost:3000',credentials: true}))
// app.use(cors());
app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

// Main Routes
app.use("/api/v1", mainRoutes,(req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

this is how im calling the api from next

export async function getServerSideProps(context) {
    try{
        const res = await axios.get("/sales/get-all");
        const data = await  res.data
     return { props: { data } }
    }catch(err){
      const data = "error"
      return { props: { data} }
    }

    }

where i declared default url of the axios at the app.js file of next

import '../styles/globals.css'
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:8000/api/v1/"

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

im not quite sure what the problem is so pardon if the title of the question is not according to the problem i have.

EDIT:
i moved the api to a useeffect call, its now working. but why isnt it working in getserversideprops?


问:
i18n use json locales file and fetching some from backend
I have project on next.js + spring boot. I want to use i18n and separate getting localization files methods. One part of localization (such as UI text) I would like get from json files in next.js project, and and the other part of locales (some content I want change from admin panel) - from my backend server by 18next-http-backend.

I can only implement one of the methods, but not both at the same time.

```<code>const I18NextHttpBackend = require('i18next-http-backend')

module.exports = {
  i18n: {
    defaultLocale: 'ua',
    locales: ['ua', 'ru', 'en'],

    backend: {
      loadPath: `${process.env.NEXT_PUBLIC_BACKEND_URL}/localization/{{lng}}/{{ns}}`,
    },
  },
  debug: true,
  ns: ['common', 'footer'],
  serializeConfig: false,
  use: [I18NextHttpBackend], // When this setting is enabled, next.js does not see locales.json files in ./public/locales
}

</code>```

Is there a way to get those locales from both methods?

I tried to find a solution on the Internet, but I did not find similar examples where localization files are obtained in two ways at the same time

Body:
I have project on next.js + spring boot. I want to use i18n and separate getting localization files methods. One part of localization (such as UI text) I would like get from json files in next.js project, and and the other part of locales (some content I want change from admin panel) - from my backend server by 18next-http-backend.

I can only implement one of the methods, but not both at the same time.

const I18NextHttpBackend = require('i18next-http-backend')

module.exports = {
  i18n: {
    defaultLocale: 'ua',
    locales: ['ua', 'ru', 'en'],

    backend: {
      loadPath: `${process.env.NEXT_PUBLIC_BACKEND_URL}/localization/{{lng}}/{{ns}}`,
    },
  },
  debug: true,
  ns: ['common', 'footer'],
  serializeConfig: false,
  use: [I18NextHttpBackend], // When this setting is enabled, next.js does not see locales.json files in ./public/locales
}

Is there a way to get those locales from both methods?

I tried to find a solution on the Internet, but I did not find similar examples where localization files are obtained in two ways at the same time