Question:
Is there a melt command in Snowflake?

Is there a Snowflake command that will transform a table like this:
```
a,b,c
1,10,0.1
2,11,0.12
3,12,0.13
```
to a table like this:
```
key,value
a,1
a,2
a,3
b,10
b,11
b,13
c,0.1
c,0.12
c,0.13
```
?

This operation is often called melt in other tabular systems, but the basic idea is to convert the table into a list of key value pairs.

There is an UNPIVOT in SnowSQL, but as I understand it UNPIVOT requires to manually specify every single column. This doesn't seem practical for a large number of columns.

Explanation: The desired behavior looks like some kind of table transformation. We should try to find some operation to make a two-dimensional table flat.

Snowflake's SQL is powerful enough to perform such operation without help of
third-party tools or other extensions.

Data prep:

    CREATE OR REPLACE TABLE t(a INT, b INT, c DECIMAL(10,2))
    AS
    SELECT 1,10,0.1
    UNION SELECT 2,11,0.12
    UNION SELECT 3,12,0.13;

[ ![enter image description here](https://i.sstatic.net/o3qiS.png)
](https://i.sstatic.net/o3qiS.png)

Query(aka "dynamic" UNPIVOT):

    SELECT f.KEY, f.VALUE
    FROM (SELECT OBJECT_CONSTRUCT_KEEP_NULL(*) AS j FROM t) AS s
    ,TABLE(FLATTEN(input => s.j)) f
    ORDER BY f.KEY;

Output:

[ ![enter image description here](https://i.sstatic.net/HGmXI.png)
](https://i.sstatic.net/HGmXI.png)

* * *

How does it work?

  1. Transform row into JSON(row 1 becomes ` { "A": 1,"B": 10,"C": 0.1 } ` )
  2. Parse the JSON into key-value pairs using FLATTEN


Question:
Python split a column value into multiple columns and keep remaining column same

The task is to split the values of column A to into different columns and have values of corresponding column2 values and need column3 to contain the corresponding value of the group.

```
Column1 Column2 Column3
Group1  Value1  V1
Group1  Value2  V2
Group1  Value3  V3
Group1  Value4  V4
Group2  Value1  x1
Group2  Value2  x2
Group2  Value3  x3
Group2  Value4  x4
Group3  Value1  y1
Group3  Value2  y2
```

to a table like this:

```
Group1 Group2 Group3 Column3.Group1 Column3.Group2 Column3.Group3
Value1 Value1 Value1  v1             x1                y1
Value2 Value2 Value2  v2             x2                y1
Value3 Value3 NaN     v3             x3                NaN
Value4 Value4 NaN     v4             x4                NaN
```

Any way to achieve this output in python?

Explanation: The desired behavior looks like some kind of table transformation. We should try to find some operation to make column 1's values to become head values of new table and let the original column 2's value to become the values of the new table. Then rearrange the column 3's values into new columns to correspond to the new table's values. If there is no corresponding value, set the value into NaN.

tmp = df.assign(cc=df.groupby('Column1').cumcount())
    out = pd.concat(
        [tmp.pivot(index='cc', columns='Column1', values='Column2'),
         tmp.pivot(index='cc', columns='Column1', values='Column3').add_prefix('Column3.')
        ], axis=1).rename_axis(index=None, columns=None)

out:

       Group1  Group2  Group3 Column3.Group1 Column3.Group2 Column3.Group3
    0  Value1  Value1  Value1             V1             x1             y1
    1  Value2  Value2  Value2             V2             x2             y2
    2  Value3  Value3     NaN             V3             x3            NaN
    3  Value4  Value4     NaN             V4             x4            NaN


Question:
Python type hints: what should I use for a variable that can be any iterable sequence?

```
def mysum(x)->int:
    s = 0
    for i in x:
        s += i
    return s
```

The argument x can be list[int] or set[int], it can also be d.keys() where d is a dict, it can be range(10), as well as possibly many other sequences, where the item is of type int. What is the correct type-hint for x?

Explanation: Programmers want to indicate the type of Python function parameters, but can only indicate the base type (such as int, float, etc.). If they want to indicate that the type of the parameter is any iterable sequence, they need to import an additional library.

You can use [ ` typing.Iterable `
](https://docs.python.org/library/typing.html#typing.Iterable) :

    from typing import Iterable

    def mysum(x: Iterable[int]) -> int:
        s = 0
        for i in x:
            s += i
        return s

* * *

Edit: ` typing.Iterable ` is an alias for [ ` collections.abc.Iterable `
](https://docs.python.org/library/collections.abc.html#collections.abc.Iterable)
, so you should use that instead, as suggested in the comments.


Question:
I have below scenario where list str columns need to be merged with the dataframe.

```
columns = ["server", "ip"]

dataframes = [
        df1,
        df2,
        df3,
        df4,
]

df_res = pd.merge(dataframes, columns )
```

df1 name , server , df1,df2,df3 and df4 contains column "server" and "ip" and other columns too.

So, i want to merge all the columns with server and ip in the df_res.

But i am getting issue as below:

Can only merge Series or DataFrame objects, a <class 'list'> was passed. Please help.

Explanation: The programmer wants to extract specific columns from the given dataframe and form a new table.

Use ` concat ` instead of ` merge ` to stack datframes vertically.

    df_res = pd.concat([df[columns] for df in dataframes],ignore_index = True)

This will create a new dataframe df_res with columns =['server', 'ip'] by
stacking all rows vertically. It also replaces the original index with new
index.


Question:
I have a custom PyTorch model that bottlenecks my application due to how it is currently used.

The application is a web server built in Flask that receives job submissions for the PyTorch model to process. Due to the processing time of each job, I use Celery to handle the computation, where Flask queues the tasks for Celery to execute.

Each job consists of loading the PyTorch model from the disk, moving the model and data to a GPU, and making a prediction on the data submitted. However, loading the model takes around 6 seconds. In many instances, that is a magnitude or two larger than prediction time.

Thus, is it possible to load the model and move it to a GPU on server startup (specifically when the Celery worker starts), avoiding the time needed to load the model and copy it to the GPU every job? Ideally, I'd want to load the model and copy it to every available GPU on server startup, leaving each Celery job to choose an available GPU and copy the data over. Currently, I only have one GPU, so a multi-GPU solution is not a requirement at the moment, but I'm planning ahead.

Further, the memory constraints of the model and data allow for only one job per GPU at a time, so I have a single Celery worker that processes jobs sequentially. This could reduce the complexity of the solution due to avoiding multiple jobs attempting to use the model in shared memory at the same time, so I figured I'd mention it.

How can I deal with it?

Explanation: The application is a Flask-based web server that receives job submissions for the PyTorch model to process. Each job involves loading the model, moving it to a GPU, and making predictions on the submitted data. However, the model loading process takes around 6 seconds, which is significantly longer than the prediction time. Therefore, a method is needed that can load the model and move it to a GPU during server startup is needed.

Yes, there are ways to share a PyTorch model across multiple processes without
creating copies.

**torch.multiprocessing** and **model.share_memory_()** :

This method utilizes the **torch.multiprocessing** module from PyTorch. You
can call **model.share_memory_()** on your model to allocate shared memory for
its parameters. This allows all processes to access the same model parameters
in shared memory, avoiding redundant copies. This approach is efficient for
training a model in parallel across multiple CPU cores.

Some resources for further exploration: [
https://www.geeksforgeeks.org/getting-started-with-pytorch/
](https://www.geeksforgeeks.org/getting-started-with-pytorch/)


Question:
Dropping elements from lists in a nested Polars column

How do I get this behaviour:

```
pl.Series(['abc_remove_def', 'remove_abc_def', 'abc_def_remove']).str.split('_').map_elements(lambda x: [y for y in x if y != 'remove']).list.join('_')
```

Without using the slower map_elements? I have tried using .list.eval and pl.element() but I can't find anything that actually excludes elements from a list by name (i.e. by the word 'remove' in this case)

Explanation: Use the fastest method to remove elements from the given list.

[ ` list.eval ` ](https://docs.pola.rs/py-
polars/html/reference/series/api/polars.Series.list.eval.html) , in
combination with [ ` filter ` ](https://docs.pola.rs/py-
polars/html/reference/expressions/api/polars.Expr.filter.html) would work as
following:

    # list_eval
    (pl
       .Series(['abc_remove_def', 'remove_abc_def', 'abc_def_remove']).str.split('_')
       .list.eval(pl.element().filter(pl.element() != 'remove'))
    )

That said, [ ` list.set_difference ` ](https://docs.pola.rs/py-
polars/html/reference/series/api/polars.Series.list.set_difference.html) as
suggested by @jqurious is the most straightforward and fastest:

    # list_set_difference
    (pl
       .Series(['abc_remove_def', 'remove_abc_def', 'abc_def_remove']).str.split('_')
       .list.set_difference(['remove'])
    )

Output:

    shape: (3,)
    Series: '' [list[str]]
    [
        ["abc", "def"]
        ["abc", "def"]
        ["abc", "def"]
    ]

#####  Timings and differences

lists of 3 items [ ![polars timing comparison remove item
list](https://i.sstatic.net/gWbsB.png) ](https://i.sstatic.net/gWbsB.png)

lists of 100 items with many duplicates [ ![polars timing comparison remove
item list](https://i.sstatic.net/LnYJ6.png) ](https://i.sstatic.net/LnYJ6.png)

lists of 100 items without duplicates [ ![polars timing comparison remove item
list](https://i.sstatic.net/qpe3L.png) ](https://i.sstatic.net/qpe3L.png)

_NB. the timings exclude the creation of the Series._

Additionally, it is important to note that ` list.set_difference ` would also
remove duplicated values.

For instance on:

    s = pl.Series(['abc_remove_abc_def', 'remove_abc_def']).str.split('_')

    # output after set_difference
    shape: (2,)
    Series: '' [list[str]]
    [
        ["abc", "def"]
        ["def", "abc"]
    ]

    # output for the other approaches
    shape: (2,)
    Series: '' [list[str]]
    [
        ["abc", "abc", "def"]
        ["abc", "def"]
    ]


Question:
I'm trying to write an LLM class as below:

```
from langchain_openai import ChatOpenAI

class LLM:
    def __init__(self,model_name):
        super().__init__(model_name=model_name)
        self.model_name = model_name

class OpenAILLM(LLM,ChatOpenAI):
    def __init__(self,model_name):
        super().__init__(model_name=model_name)
        self.model_name = model_name
```
which works fine but when I try to add another variable in __init__ of OpenAILLM class as below

```
from langchain_openai import ChatOpenAI

class LLM:
    def __init__(self,model_name):
        super().__init__(model_name=model_name)
        self.model_name = model_name

class OpenAILLM(LLM,ChatOpenAI):
    def __init__(self,model_name):
        super().__init__(model_name=model_name)
        self.model_name = model_name
        self.var = 'var'
```

The object creation for OpenAILLM fails and gives ValueError: "OpenAILLM" object has no field "var"

Can anyone help me how I can add more variables?

Another thing I tried is the get_var function define below works but the set_var function defined below gives same error as above

```
from langchain_openai import ChatOpenAI

class LLM():
    var = 1
    def __init__(self,model_name):
        super().__init__(model_name=model_name)
        self.model_name = model_name

class OpenAILLM(LLM,ChatOpenAI):
    def __init__(self,model_name):
        super().__init__(model_name=model_name)
        self.model_name = model_name
    def get_var(self):
        return self.var
    def set_var(self, var):
        print('self var',self.var)
        self.var = var
        return True
```

The mro of OpenAILLM is as below

```
(__main__.OpenAILLM,
 __main__.LLM,
 langchain_openai.chat_models.base.ChatOpenAI,
 langchain_core.language_models.chat_models.BaseChatModel,
 langchain_core.language_models.base.BaseLanguageModel,
 langchain_core.runnables.base.RunnableSerializable,
 langchain_core.load.serializable.Serializable,
 pydantic.v1.main.BaseModel,
 pydantic.v1.utils.Representation,
 langchain_core.runnables.base.Runnable,
 typing.Generic,
 abc.ABC,
 object)
```

I think this has to do something with pydantic, but I'm not sure. And I don't know how to resolve it. Please help.

Explanation: When trying to add another variable in the __init__ method of the OpenAILLM class, a ValueError is raised and states that the "OpenAILLM" object has no field "var". When defining `get_var` and `set_var` functions in the OpenAILLM class, the same error is encountered. OpenAILLM might not allow programmers to add new members in its syntax criteria.

There is a ` __slots__ ` attribute defined on the class ` OpenAILLM ` (by
Pydantic, which I'm not familiar with).

Refer to [ https://docs.python.org/3/reference/datamodel.html#slots
](https://docs.python.org/3/reference/datamodel.html#slots) to see how `
__slots__ ` works.

Simply said, if a ` __slots__ ` is defined on a class, its members are set in
stone and you may not add additional members to its **direct** instances. And
I believe that ` ChatOpenAI ` is not meant to be subclassed, so just avoid
that usage.


Question:
Create a New Column Based on the Value of two Columns in Pandas with conditionals

I have a dataframe with two different columns i need to use to calculate a score:
```
id        Pos        Player        GW        VP        Final        Drop        TournamentPoints
0        1        1        Alessio Bianchi        2        7.0        5.0        NaN
1        2        2        Gianluca Bianco        2        7.0        0.0        NaN
2        3        2        Sara Rossi        1        5.0        0.0        NaN
3        4        2        Gabriele Verdi        1        4.5        0.0        NaN
4        5        2        Luca Gialli        1        3.0        0.0        NaN
```

Tournament points is calculated from GW and VP with a formula:
```
df['TournamentPoints'] = ((number_of_players / 10) * (df["VP"] + 1)) + (df['GW'] * x)
```
where number_of_players and X are calculated previously.

However i need another step:
1. add 50 to the row with the highest value in "Final" columns (in this case Alessio Bianchi)
2. if two rows have the same value in "Final" and it's the highest, only the row with the lowest "Pos" must receive the 50 boost

Explanation: The last column's values is the result of the combination of previous 2 column. It depends on the maximum value of one of 2. If meeting 2 same maximum values. One is chosen depending on another value of 2nd column.

Assuming Pos is already sorted, you can use [ ` idxmax `
](https://pandas.pydata.org/pandas-
docs/stable/reference/api/pandas.Series.idxmax.html) , this will select the
first row that has the maximum value:

    df['TournamentPoints'] = ((number_of_players / 10) * (df["VP"] + 1)) + (df['GW'] * x)

    df.loc[df['Final'].idxmax(), 'TournamentPoints'] += 50

If Pos is not sorted:

    df.loc[df.sort_values(by='Pos')['Final'].idxmax(), 'TournamentPoints'] += 50


Question:
I set up a local simple http server in python on windows.

I set up an HTML file with javascript that uses setInterval() to request a JSON in the local directory every second. (Then updates the webpage with json content.)

Great, this works. Until after 15-60 seconds, the browser stops making requests, based on the server log in the terminal. The response 304 always precedes the break.

How can I avoid this and force the server always serve the json file every second?

Very new to this attempt and had to do tricks to make the browser even make the requests for local jsons or so due to security protocols. In part why the server is necessary, as via file:/// it can't be done.

My thought is change something in the server so if it wants to respond with 304, it will give a 200. I hope if it's always 200, the browser won't pause requests.

My other thought is ensure the json is always changing, hopefully avoiding the idea of it cached.

Explanation: The issue is about caching. The browser always fetch the JSON file from the cache. The browser is receiving a 304 response from the server, indicating that the content has not been modified since the last request, since it uses the cached version. Therefore, it should avoid using cache.

It seems like your issue is related to caching. The browser is receiving a 304
response from the server, indicating that the content has not been modified
since the last request, so it's using the cached version instead of making a
new request.

To force the browser to always fetch the JSON file from the server instead of
using the cache, you can try to disable caching on the server side. You can
modify your Python HTTP server to include headers that prevent caching. You
can do this by setting the [ Cache-Control ](https://developer.mozilla.org/en-
US/docs/Web/HTTP/Headers/Cache-Control) headers to no-cache.

    import sys
    from http.server import HTTPServer, SimpleHTTPRequestHandler, test

    class CORSRequestHandler(SimpleHTTPRequestHandler):
        def end_headers(self):
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Cache-Control', 'no-cache')
            SimpleHTTPRequestHandler.end_headers(self)

    if __name__ == '__main__':
        test(CORSRequestHandler, HTTPServer, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000)

In my understanding it looks something like this: **main.py**

    import os
    import sys
    from http.server import HTTPServer, SimpleHTTPRequestHandler

    class CORSRequestHandler(SimpleHTTPRequestHandler):
        def end_headers(self):
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Cache-Control', 'no-cache')
            super().end_headers()

        def do_GET(self):
            if self.path == '/data.json':
                self.send_response(200)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                with open(os.path.join(os.getcwd(), 'data.json'), 'rb') as file:
                    self.wfile.write(file.read())
            else:
                super().do_GET()

    def run_server(port):
        server_address = ('', port)
        httpd = HTTPServer(server_address, CORSRequestHandler)
        print(f"Server running on port {port}")
        httpd.serve_forever()

    if __name__ == '__main__':
        port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
        run_server(port)

**index.html**

    <!DOCTYPE html>

        <meta charset="UTF-8">
        <title>JSON</title>

JSON


Question:
I have a dataframe with people and the food they like:

```
df_class = pl.DataFrame(
    {
        'people': ['alan', 'bob', 'charlie'],
        'food': [['orange', 'apple'], ['banana', 'cherry'], ['banana', 'grape']]
    }
)
print(df_class)

shape: (3, 2)
┌──────┬─────┐
│ people    ┆ food      │
│ ---           ┆ ---          │
│ str           ┆ list[str]   │
╞═════╪═════════════╡
│ alan     ┆ ["orange", "apple"]   │
│ bob      ┆ ["banana", "cherry"] │
│ charlie ┆ ["banana", "grape"]  │
└─────┴─────────────┘
```

And, I have a data structure with animals and the things they like to eat:

```
animals = [
    ('squirrel', ('acorn', 'almond')),
    ('parrot', ('cracker', 'grape', 'guava')),
    ('dog', ('chicken', 'bone')),
    ('monkey', ('banana', 'plants'))
]
```

I want to add a new column pets in df_class, such that pets is a list of the animals that have at least one food in common with the corresponding person:

```
df_class.with_columns(pets=???)   # <-- not sure what to do here

shape: (3, 3)
┌─────────┬─────────────┬──────────┐
│ people            ┆ fruits                          ┆ pets                 │
│ ---                   ┆ ---                               ┆ ---                     │
│ str                  ┆ list[str]                         ┆ list[str]              │
╞═════════╪══════════════╪══════════╡
│ alan               ┆ ["orange", "apple"]      ┆ []                       │
│ bob                ┆ ["banana", "cherry"]    ┆ ["monkey"]        │
│ charlie           ┆ ["banana", "grape"]      ┆ ["monkey", "parrot"] │
└─────────┴──────────────┴─────────────┘
```

1. I have some flexibility in the data structure for animals, in case for e.g. this is easier to do with some sort of set intersection
2. the order of pets is unimportant
3. pets should contain unique values
4. I'm looking for a single expression that would achieve the desired result, so as to fit within a larger framework of a list of expressions that perform transformations on other columns of my actual dataset

Side note: my title seems kind of clunky and I'm open to suggestions to reword so that it's easier to find by others that might be trying to solve a similar problem.

Explanation: The programmer wants to add a new column of data (such as the data structure is like, name: information) to the original table, and this set of data will be related to each column in the original table. For example, if the second column has the same information with new piece of data, a new corresponding name can be added to the new column.

It looks like a ` join ` on the exploded lists.

It can be kept as a "single expression" by putting it inside [ `
.map_batches() `
](https://docs.pola.rs/docs/python/dev/reference/expressions/api/polars.map_batches.html#polars-
map-batches)

    df_class.with_columns(pets =
       pl.col("food").map_batches(lambda col:
          pl.LazyFrame(col)
            .with_row_index()
            .explode("food")
            .join(
               pl.LazyFrame(animals, schema=["pets", "food"]).explode("food"),
               on = "food",
               how = "left"
            )
            .group_by("index", maintain_order=True)
            .agg(
               pl.col("pets").unique().drop_nulls()
            )
            .collect()
            .get_column("pets")
       )
    )

    shape: (3, 3)
    ┌─────────┬──────────────────────┬──────────────────────┐
    │ people  ┆ food                 ┆ pets                 │
    │ ---     ┆ ---                  ┆ ---                  │
    │ str     ┆ list[str]            ┆ list[str]            │
    ╞═════════╪══════════════════════╪══════════════════════╡
    │ alan    ┆ ["orange", "apple"]  ┆ []                   │
    │ bob     ┆ ["banana", "cherry"] ┆ ["monkey"]           │
    │ charlie ┆ ["banana", "grape"]  ┆ ["monkey", "parrot"] │
    └─────────┴──────────────────────┴──────────────────────┘

###  Explanation

We add a row index to the "left" frame and [ explode
](https://docs.pola.rs/docs/python/dev/reference/dataframe/api/polars.DataFrame.explode.html#polars.DataFrame.explode)
the lists.

(The row index will allow us to rebuild the rows later on.)

    df_class_long = df_class.with_row_index().explode("food")

    # shape: (6, 3)
    # ┌───────┬─────────┬────────┐
    # │ index ┆ people  ┆ food   │
    # │ ---   ┆ ---     ┆ ---    │
    # │ u32   ┆ str     ┆ str    │
    # ╞═══════╪═════════╪════════╡
    # │ 0     ┆ alan    ┆ orange │
    # │ 0     ┆ alan    ┆ apple  │
    # │ 1     ┆ bob     ┆ banana │
    # │ 1     ┆ bob     ┆ cherry │
    # │ 2     ┆ charlie ┆ banana │
    # │ 2     ┆ charlie ┆ grape  │
    # └───────┴─────────┴────────┘

    df_pets_long = pl.DataFrame(animals, schema=["pets", "food"]).explode("food")

    # shape: (9, 2)
    # ┌──────────┬─────────┐
    # │ pets     ┆ food    │
    # │ ---      ┆ ---     │
    # │ str      ┆ str     │
    # ╞══════════╪═════════╡
    # │ squirrel ┆ acorn   │
    # │ squirrel ┆ almond  │
    # │ parrot   ┆ cracker │
    # │ parrot   ┆ grape   │
    # │ parrot   ┆ guava   │
    # │ dog      ┆ chicken │
    # │ dog      ┆ bone    │
    # │ monkey   ┆ banana  │
    # │ monkey   ┆ plants  │
    # └──────────┴─────────┘

We then use a [ Left Join ](https://docs.pola.rs/user-
guide/transformations/joins/#left-join) to find the "intersections" (whilst
keeping all the rows from the left side).

    df_class_long.join(df_pets_long, on="food", how="left")

    # shape: (6, 4)
    # ┌───────┬─────────┬────────┬────────┐
    # │ index ┆ people  ┆ food   ┆ pets   │
    # │ ---   ┆ ---     ┆ ---    ┆ ---    │
    # │ u32   ┆ str     ┆ str    ┆ str    │
    # ╞═══════╪═════════╪════════╪════════╡
    # │ 0     ┆ alan    ┆ orange ┆ null   │
    # │ 0     ┆ alan    ┆ apple  ┆ null   │
    # │ 1     ┆ bob     ┆ banana ┆ monkey │
    # │ 1     ┆ bob     ┆ cherry ┆ null   │
    # │ 2     ┆ charlie ┆ banana ┆ monkey │
    # │ 2     ┆ charlie ┆ grape  ┆ parrot │
    # └───────┴─────────┴────────┴────────┘

We can then rebuild the "rows" with [ ` .group_by() `
](https://docs.pola.rs/docs/python/dev/reference/dataframe/api/polars.DataFrame.group_by.html#polars.DataFrame.group_by)

  * You stated you want [ ` .unique() ` ](https://docs.pola.rs/docs/python/dev/reference/expressions/api/polars.Expr.unique.html#polars.Expr.unique) pets only.
  * We also [ drop nulls. ](https://docs.pola.rs/docs/python/dev/reference/expressions/api/polars.Expr.drop_nulls.html#polars.Expr.drop_nulls)

    (df_class_long.join(df_pets_long, on="food", how="left")
      .group_by("index", maintain_order=True) # we need to retain row order
      .agg(pl.col("pets").unique().drop_nulls())
    )

    # shape: (3, 2)
    # ┌───────┬──────────────────────┐
    # │ index ┆ pets                 │
    # │ ---   ┆ ---                  │
    # │ u32   ┆ list[str]            │
    # ╞═══════╪══════════════════════╡
    # │ 0     ┆ []                   │
    # │ 1     ┆ ["monkey"]           │
    # │ 2     ┆ ["monkey", "parrot"] │
    # └───────┴──────────────────────┘


Question:
I´ve got the following DataFrame:

                        value
A   B
111 2024-03-22 00:00:00 1
111 2024-03-22 01:00:00 2
111 2024-03-22 02:00:00 3
222 2024-03-22 00:00:00 4
222 2024-03-22 01:00:00 5
222 2024-03-22 02:00:00 6
Now I want to resample and sum index B to days and would expect the following result:

                        value
A   B
111 2024-03-22 00:00:00 6
222 2024-03-22 00:00:00 15
How can I achieve something like that?

Another Example would be the following:

                        value
A   B
111 2024-03-22 00:00:00 1
111 2024-03-22 01:00:00 2
111 2024-03-22 02:00:00 3
222 2024-03-22 00:00:00 4
222 2024-03-22 01:00:00 5
222 2024-03-22 02:00:00 6
333 2024-03-22 05:00:00 7
Of which I want the following result with resampling by 1h:

                        value
A   B
111 2024-03-22 00:00:00 1
111 2024-03-22 01:00:00 2
111 2024-03-22 02:00:00 3
111 2024-03-22 03:00:00 0
111 2024-03-22 04:00:00 0
111 2024-03-22 05:00:00 0
222 2024-03-22 00:00:00 4
222 2024-03-22 01:00:00 5
222 2024-03-22 02:00:00 6
222 2024-03-22 03:00:00 0
222 2024-03-22 04:00:00 0
222 2024-03-22 05:00:00 0
333 2024-03-22 00:00:00 0
333 2024-03-22 01:00:00 0
333 2024-03-22 02:00:00 0
333 2024-03-22 03:00:00 0
333 2024-03-22 04:00:00 0
333 2024-03-22 05:00:00 7
Pandas Version: 2.0.1

I tried using level on resample but that way I lose Index A.

I have the same issue when I have two timestamps in the index and want one to be resampled to days and the other to hours.

I´ve looked at other answers of related questions here but couldn´t find a way to get them working for me.

Explanation: Programmers want to merge or expand the rows of a table based on the characteristics of a particular column.


Question:
My dataframe looks like

```
data = {
    "ReportName": ["Sample cycle", 'Message',  "ID", "m1", "Uncertainty m1", "Message", "Sample cycle", 'Message', "ID", "m0", "Uncertainty m0", "Message", "ID", "m1", "Uncertainty m1", "Message"],
    "Values": [ "1","NO", "II", None, None, "NO", "1", "NO", "ID1", "1.8", "0.43", "NO", "ID2", "1.5", "0.41", "NO"],
}

df = pd.DataFrame(data)
```

I I created a new "ID" column with this function

```
def extract_id(row):
    if row['ReportName'] == 'ID':
        return row['Values']
    return None
```

Now I want fill Na with ID from ReportName == 'Sample cycle' to next 'Sample cycle'.

Desired output
```
        ReportName Values    ID
0     Sample cycle      1  None
1          Message     NO    II
2               ID     II    II
3               m1   None    II
4   Uncertainty m1   None    II
5          Message     NO    II
6     Sample cycle      1  None
7          Message     NO   ID1
8               ID    ID1   ID1
9               m0    1.8   ID1
10  Uncertainty m0   0.43   ID1
11         Message     NO   ID1
12              ID    ID2   ID2
13              m1    1.5   ID2
14  Uncertainty m1   0.41   ID2
15         Message     NO   ID2
```

Explanation: The programmer wants to add a column and fill it with the value when "sample cycle" appears in the first column until the next "sample cycle" is encountered. The value of the new column will be filled with the value of the ID of the sample cycle.

You can use [ ` groupby.transform ` ](https://pandas.pydata.org/pandas-
docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html#pandas.core.groupby.DataFrameGroupBy.transform)
with masks:

    # identify rows with ID
    m1 = df['ReportName'].eq('ID')
    # identify rows with "Sample cycle"
    # this is used both to form groups
    # and to mask the output
    m2 = df['ReportName'].eq('Sample cycle')

    df.loc[~m2, 'ID'] = (df['Values'].where(m1).groupby(m2.cumsum())
                         .transform(lambda x: x.ffill().bfill())
                        )

Output:

            ReportName Values   ID
    0     Sample cycle      1  NaN
    1          Message     NO   II
    2               ID     II   II
    3               m1   None   II
    4   Uncertainty m1   None   II
    5          Message     NO   II
    6     Sample cycle      1  NaN
    7          Message     NO  ID1
    8               ID    ID1  ID1
    9               m0    1.8  ID1
    10  Uncertainty m0   0.43  ID1
    11         Message     NO  ID1
    12              ID    ID2  ID2
    13              m1    1.5  ID2
    14  Uncertainty m1   0.41  ID2
    15         Message     NO  ID2


Question:
I wrote a bot that change name of the telegram channel every N minutes But, when name of the channel is changed telegram automaticly send message, that channel name has been changed

i tried bot.delete_message command, but could't figure out how to delete that exact message

Explanation: The programmer want to delete the automatic message sent by Telegram when he changed the name of the telegram every N mintues. He needs a decorator to intercept and delete the messages.

To delete the message that Telegram sends automatically when the channel name
is changed, you can use the **channel_post_handler** decorator provided by the
Telebot library to intercept and delete these messages.

Example: **bot.py**

    import telebot

    bot = telebot.TeleBot('BOT_TOKEN')

    @bot.channel_post_handler(content_types=['new_chat_title'])
    def channel_name_changed(message):
        try:
            bot.delete_message(message.chat.id, message.message_id)
        except Exception as e:
            print("Error deleting message:", e)

    if __name__ == '__main__':
        bot.polling()

**changer.py**

    import random
    from time import sleep

    import telebot

    bot = telebot.TeleBot('BOT_TOKEN')

    def change_channel_name():
        new_name = random.choice(["Channel 1", "Channel 2", "Channel 3", "Channel 4", "Channel 5"])
        try:
            bot.set_chat_title(
                "@CHAT",
                new_name
            )
        except Exception as e:
            print("Error changing channel name:", e)

    def main():
        while True:
            change_channel_name()
            sleep(10)

    if __name__ == '__main__':
        main()


Question:
I am working on a huge denormalized table on a SQL server (10 columns x 130m rows). Take this as data example :

```
import pandas as pd
import numpy as np
data = pd.DataFrame({
    'status' :  ['pending', 'pending','pending', 'canceled','canceled','canceled', 'confirmed', 'confirmed','confirmed'],
    'clientId' : ['A', 'B', 'C', 'A', 'D', 'C', 'A', 'B','C'],
    'partner' :  ['A', np.nan,'C', 'A',np.nan,'C', 'A', np.nan,'C'],
    'product' : ['afiliates', 'pre-paid', 'giftcard','afiliates', 'pre-paid', 'giftcard','afiliates', 'pre-paid', 'giftcard'],
    'brand' : ['brand_1', 'brand_2', 'brand_3','brand_1', 'brand_2', 'brand_3','brand_1', 'brand_3', 'brand_3'],
    'gmv' : [100,100,100,100,100,100,100,100,100]})

data = data.astype({'partner':'category','status':'category','product':'category', 'brand':'category'})
```

As you can see, many of it columns are categories/strings that could be factorize (replaced by a small int identification to another x.1 join).

My question is if there is a easy way to extract another "dataframe" from each category columns and factory factorize the main table, so the bytes transmitted over a single query could be faster! Is there any easy library for it?

I would expect to get this output:

```
    data = pd.DataFrame({
        'status' :  ['1', '1','1', '2','2','2', '3', '3','3'],
        'clientId' : ['1', '2', '3', '1', '4', '3', '1', '2','3'],
        'partner' :  ['A', np.nan,'C', 'A',np.nan,'C', 'A', np.nan,'C'],
        'product' : ['afiliates', 'pre-paid', 'giftcard','afiliates', 'pre-paid', 'giftcard','afiliates', 'pre-paid', 'giftcard'],
        'brand' : ['brand_1', 'brand_2', 'brand_3','brand_1', 'brand_2', 'brand_3','brand_1', 'brand_3', 'brand_3'],
        'gmv' : [100,100,100,100,100,100,100,100,100]})

status_df = {1 : 'pending', 2:'canceled', 3:'confirmed'}
clientid = {1 : 'A', 2:'B', 3:'C', 4:'D'}
```

Explanation: The goal is to factorize columns with different categories to optimize data transfer efficiency on SQL servers, which can improve query performance by replacing category columns with small integer identifiers.

You can use [ ` factorize ` ](https://pandas.pydata.org/pandas-
docs/stable/reference/api/pandas.factorize.html) to do this. For example:

    codes, uniques = pd.factorize(data['status'])
    data['status'] = codes
    status_df = pd.DataFrame(uniques)

Output (data):

       status clientId partner    product    brand  gmv
    0       0        A       A  afiliates  brand_1  100
    1       0        B     NaN   pre-paid  brand_2  100
    2       0        C       C   giftcard  brand_3  100
    3       1        A       A  afiliates  brand_1  100
    4       1        D     NaN   pre-paid  brand_2  100
    5       1        C       C   giftcard  brand_3  100
    6       2        A       A  afiliates  brand_1  100
    7       2        B     NaN   pre-paid  brand_3  100
    8       2        C       C   giftcard  brand_3  100

Output (status_df):

               0
    0    pending
    1   canceled
    2  confirmed

For columns like ` partner ` , where there are ` NaN ` values, you can choose
to have them replaced with ` -1 ` (the default behaviour), or to have ` NaN `
included in ` partner_df ` (along with its own index) by specifying `
use_na_sentinel=False ` .


Question:
Is any supertype and also a subtype of all types in TypeScript?

I am teaching a class on TypeScript fundamentals and I am trying to really understand the relationships between basic TS types. In all articles I saw, they put the any type very close to the top of the type hierarchy. Either

+---------+
| unknown |
+---------+
     |
     v
  +-----+
  | any |
  +-----+
     |
     v
all other types
Or maybe

+--------------+
| any, unknown |
+--------------+
     |
     v
all other types
But I do not see it that way. You can assign value of all other types to an unknown variable but you cannot assign unknown value to anything. That puts it on top. But with any, you can assign all values of all types to any and also assign an any value to variables of all types. So it behaves as uknown and never at the same time. From this I would argue, that any stands completely aside of the type hierarchy tree not fitting anywhere in it. I would say any sidesteps the type system completely and in essence means "turn off typechecking"

Am I wrong?

Explanation: The questioner wants to confirm whether their understanding of relationships between basic TS types (unknown, any, all other types) is correct, and hopes that there is a literature or a definition to support their understanding.

From the [ docs ](https://www.typescriptlang.org/docs/handbook/basic-
types.html#any) :

> The any type is a powerful way to work with existing JavaScript, allowing
> you to gradually opt-in and opt-out of type checking during compilation.

So i guess your understanding is correct. ` any ` is a way to opt out of type
checking.

But it (and also, unknown) are top types as all types are assignable to them.

From [ wiki definition
](https://en.wikipedia.org/wiki/Top_type#:%7E:text=The%20top%20type%20is%20sometimes,object%20of%20the%20type%20system.)
of top types:

> The top type is sometimes called also universal type, or universal supertype
> as all other types in the type system of interest are subtypes of it, and in
> most cases, it contains every possible object of the type system.

It seems that all that is required from a top type is all other types to be
assignable to it, which is true of both ` unknown ` and ` any ` .


Question:
Better option than pandas iterrows

I have following table in pandas. the table contains time and the price of the product.

For analysis purposes, I want to have 2 columns which would contain the next time when the product is more than $100 price change & less than $100 price change.

e.g. if I am at cell 09:19 cell the next price more than $100 would be 14:02 & less than $100 would be 11:39 so 14:02 & 11:39 should come in 09:19 row in respective columns.

Same way against cell 09:56, next price more than $100 would be 14:02 & less than $100 would be 12:18 so these 2 values would come in against the row of 09:56.

```
Table
Time        Price    Up_Time   Down_Time
09:19:00    3252.25
09:24:00    3259.9
09:56:00    3199.4
10:17:00    3222.5
10:43:00    3191.25
11:39:00    3143
12:18:00    2991.7
13:20:00    3196.35
13:26:00    3176.1
13:34:00    3198.85
13:37:00    3260.75
14:00:00    3160.85
14:02:00    3450
14:19:00    3060.5
14:30:00    2968.7
14:31:00    2895.8
14:52:00    2880.7
14:53:00    2901.55
14:55:00    2885.55
14:57:00    2839.05
14:58:00    2871.5
15:00:00    2718.95
```

I am using following code, which works but takes 15-20 mins for 1 dataset.

```
for i, row in df.iterrows():
    time_up = np.nan
    time_down = np.nan

    for j in range(i+1, len(df)):
        diff = df.iloc[j]['Price'] - row['Price']
        if diff > 100:
            time_up = df.iloc[j]['Time']
        elif diff < -100:
            time_down = df.iloc[j]['Time']

        if not pd.isna(time_up) or not pd.isna(time_down):
            break

    df.at[i, 'Up_Time'] = time_up
    df.at[i, 'Down_Time'] = time_down
```

Is there any efficient ways to do it?

Explanation: Programmers are maintaining a fluctuating dollar schedule. He/She wants to add two new columns to the table, recording the time when there is a price difference greater than or equal to +100 USD compared to the current time, and the time when the price difference is greater than or equal to -100 USD. He wants to know a more efficient function to improve processing speed.


Question:
Trying to interact with a contract using is function selector, how do i get the block hash?

I have the below code in a index.js file, but when i run it i get an error message: The method eth_sendTransaction does not exist/is not available. Please can anyone help?

```
require('dotenv').config();
require('events').EventEmitter.defaultMaxListeners = 0

const { ethers } = require('ethers');

// Provider and contract address
const provider = new ethers.providers.JsonRpcProvider('https://polygon-mumbai.infura.io/v3/7d803b173d114ba8a1bffafff7ff541a');
const wallet = new ethers.Wallet(process.env.KEY, provider)
//const signer = wallet.provider.getSigner(wallet.address);
const contractAddress = '0x57C98f1f2BC34A0054CBc1257fcc9333c1b6730c';

// Function selector
const functionSelector = '0x838ad0ee';

// Call the contract
const send = async () => {
  try {
    const result = await wallet.call({
        to: contractAddress,
        data: functionSelector
    });
    console.log("Result:", result);
} catch (error) {
    console.error("Error:", error);
}
}

send()
```

Explanation: The desired behavior is to record the transaction. However, the Mumbai TestNet explorer does not work. Therefore, if the behavior of sending a read-write transaction that will be stored on the chain is required, another method should be used.

const result = await wallet.call({
        to: contractAddress,
        data: functionSelector
    });

> _The code produces and output but it does not record the transaction on the
> Mumbai TestNet explorer_

Calls are read-only actions that are not recorded on the chain. This way, you
can retrieve data from the chain without paying transaction fees, but you
can't modify any state with a call.

If you want to send a (read-write) transaction that will be stored on the
chain, one of the ways to do it is to invoke the [ wallet.sendTransaction()
](https://docs.ethers.org/v6/api/providers/#Signer-sendTransaction) method _(`
Wallet ` type inherits from the ` Signer ` type) _ .


Question:
Selenium Python how to run an XPath error handling exception on loop with multiple def?

is it possible to schedule my code by running it with schedule.every(10).seconds.do(example) or similar? I'm trying to schedule the Error Handling part in my code (XPath) which works with a While loop although because its in a While loop it refuses to run the other def functions, I want the XPath/error handling part to run in a loop with my Selenium window but detect and not interfere with the other def functions. it should just detect the XPath being there or not being there then run an exception if it doesn't detect.. Does anyone have a solution?

```
def example():
    options = Options()
    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),
                              options=options)

    driver.get("example.com")
    driver.set_window_position(0, 0)
    driver.set_window_size(750, 512)

    while True:
        e = driver.find_elements(By.XPATH,"/html/body/div/div/div/div/div[2]/div/div/div[2]/div[2]/div[1]/span/button/span")
        if not e:
            print("Element not found")
            pyautogui.moveTo(89, 56)
            time.sleep(1)
            pyautogui.click()

        time.sleep(10)

def example2():
    options = Options()
    options.add_experimental_option("detach", True)

    driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()))

    driver.get("example.com")
    driver.set_window_position(750, 0)
    driver.set_window_size(750, 512)

    while True:
        e = driver.find_elements(By.XPATH,"/html/body/div/div/div/div/div[2]/div/div/div[2]/div[2]/div[1]/span/button/span")
        if not e:
            print("Element not found")
            pyautogui.moveTo(850, 57)
            time.sleep(1)
            pyautogui.click()

schedule.every().day.at("22:59").do(example)
schedule.every().day.at("22:59").do(example2)

while True:
    schedule.run_pending()
    time.sleep(1)
```

Explanation: Try to schedule the Error Handling part in the code while the Selenium window is still working. The while loop will refuse to run the other def functions. Python is single-threaded, another function should be imported to solve.

Your current approach tries to use a blocking while True loop inside your example and example2 functions, which continuously checks for the presence of an element by its XPath. This will indeed block any other code execution including scheduled tasks, as Python's default execution model is single-threaded. If one part of the code is in an infinite loop or a long-running operation, it effectively freezes everything else.

My suggestion is that you should use Python's threading library to run your blocking loops in separate threads. This allows your main program to continue running and executing other scheduled tasks without being blocked by the infinite loops in example and example2.

import threading
import schedule
import time
# Import other necessary modules like Selenium, pyautogui, etc.

def example():
    # Your existing code for example function

def example2():
    # Your existing code for example2 function

# Schedule tasks as before
schedule.every().day.at("22:59").do(example)
schedule.every().day.at("22:59").do(example2)

# Run the example functions in their threads
example_thread = threading.Thread(target=example)
example2_thread = threading.Thread(target=example2)

example_thread.start()
example2_thread.start()

# Run the scheduler in the main thread
while True:
    schedule.run_pending()
    time.sleep(1)
There is another approach that you can use.Instead of using a while True loop within your example and example2 functions, consider restructuring your code to check for the element at scheduled intervals. This can be done directly with the schedule library by scheduling the check itself, instead of putting it in an infinite loop.

For instance, you could create a function dedicated to checking the element's presence and then schedule this function to run every 10 seconds or so, alongside your other tasks. This avoids the need for a blocking loop and allows the scheduler to manage when the checks occur.

For handling exceptions such as an element not being found (which seems to be your primary concern), make sure to wrap the relevant part of your code in a try-except block. This will catch exceptions related to the element not being present and allow your code to react accordingly (e.g., clicking somewhere else on the page).

Please be cautious about accessing shared resources from multiple threads simultaneously, as this can lead to race conditions. Use threading locks if necessary to avoid such issues.

Hope it helps. Thanks


Question:
How to create an image from a string in python

I'm currently having trouble creating an image from a binary string of data in my Python program. I receive the binary data via a socket but when I try the methods I read about in Imaging Library Handbook like this:

···
buff = StringIO.StringIO() #buffer where image is stored
#Then I concatenate data by doing a
buff.write(data) #the data from the socket
im = Image.open(buff)
···
I get an exception to the effect of "image type not recognized". I know that I am receiving the data correctly because if I write the image to a file and then open a file it works:

···
buff = StringIO.StringIO() #buffer where image is stored
buff.write(data) #data is from the socket
output = open("tmp.jpg", 'wb')
output.write(buff)
output.close()
im = Image.open("tmp.jpg")
im.show()
···
I figure I am probably doing something wrong in using the StringIO class but I'm not sure

Explanation: The programmer tries to create an image form a string. However, the data is received and the content is correct. The possible reason is wrong use of StringIO functions.

I suspect that you're not ` seek ` -ing back to the beginning of the buffer
before you pass the StringIO object to PIL. Here's some code the demonstrates
the problem and solution:

    >>> buff = StringIO.StringIO()
    >>> buff.write(open('map.png', 'rb').read())
    >>>
    >>> #seek back to the beginning so the whole thing will be read by PIL
    >>> buff.seek(0)
    >>>
    >>> Image.open(buff)
    <PngImagePlugin.PngImageFile instance at 0x00BD7DC8>
    >>>
    >>> #that worked.. but if we try again:
    >>> Image.open(buff)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "c:\python25\lib\site-packages\pil-1.1.6-py2.5-win32.egg\Image.py", line 1916, in open
        raise IOError("cannot identify image file")
    IOError: cannot identify image file

Make sure you call ` buff.seek(0) ` before reading any StringIO objects.
Otherwise you'll be reading from the end of the buffer, which will look like
an empty file and is likely causing the error you're seeing.


Question:
Retrieve bounded time periods as a step function where beginning of period returns 1, end of period returns 0

I have a table in Microsoft SQL Server called Downtime that looks like this (I have omitted some irrelevant columns and many entries):

```
ID        StartTime                                        EndTime
5        2024-03-27 09:07:20.653        2024-03-27 09:09:07.690
17        2024-03-27 09:59:50.557        2024-03-27 10:59:50.137
24        2024-03-27 11:04:07.497        2024-03-27 11:07:02.657
```

I need to write a query that turns the above data into this format:

```
t_stamp                                   CurrentlyDown
2024-03-27 09:07:20.653        1
2024-03-27 09:09:07.690        0
2024-03-27 09:59:50.557        1
2024-03-27 10:59:50.137        0
2024-03-27 11:04:07.497        1
2024-03-27 11:07:02.657        0
```

In words, this query should split each original entry into two entries (one t_stamp for StartTime and one t_stamp for EndTime) and return a value (CurrentlyDown) of 1 (if t_stamp is from the StartTime column) or 0 (if t_stamp is from the EndTime column).

I can think to try two things:

A self join around the ID field with a CASE statement checking the timestamp fields
Two CTE's (one focused on grabbing StartTimes and the other focused on EndTimes) with a final query to join these two CTE's together around the ID column. Maybe just one CTE is needed here?

I am concerned with performance so I want to do this as efficiently as possible. I am far from a SQL expert, so I don't really know which path is best to take (if either).

Explanation: This is a SQL table issue where the author wants the original entries to be split into two entries by rearranging the StartTime and EndTime that were originally in each row into columns. The StartTime is then represented by a 1 and the EndTime by a 0. The author would like to have very efficient ways of dealing with this that could be different from what he has proposed for larger tables.


Question:
Why does JavaScript return different results for RegExp test() method with empty object?

I recently came across a code snippet (a joke) where the test() method of JavaScript's RegExp object was used with an empty object as an argument. Here's the code:

```
console.log(new RegExp({}).test('mom')); // true
console.log(new RegExp({}).test('dad')); // false
```

Can someone explain why is it happens?

Explanation: It is not clear to the questioner why RegExp's test() function returns different results, and he/she does not seem to have a deep understanding of RegExp's constructor.

This is a curious fact. [ RegExp constructor
](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) accepts a string as
its first argument. Since you are passing ` {} ` it gets coerced to string,
and the coercion of an object is the literal string ` [object Object] ` .

By a fortuitous coincidence, the square brackets have a precise meaning in a
regular expression, and it means "one of these characters of the set".

Thus, the regular expression is equal to ` [objectO ] ` . In other words, your
code is equal to:

    console.log(new RegExp('[object Object]').test('mom'));

which is equal to:

    console.log(new RegExp('[objectO ]').test('mom'));

which means: tests ` true ` if any of these characters is present: o, b, j, e,
c, t, O, space. ` mom ` satisfies this condition, while ` dad ` doesn't.


Question:
Problem generating causal sentences with js [closed]

I am creating a sentence translation app, but I have a problem with the generation of causal sentences. I have to generate the sentences with an external url, but in my code instead of generating me a whole sentence, it only generates one character. Can you help me understand where I am going wrong?

```
<main>
  <section class="panel translation">
    <div class="translation-flag"></div>
    <button class="favorites">⭐</button>
    <div class="translation-result">
      <p class="translation-text">Traduzione</p>
    </div>
  </section>

  <section class="panel controls">
    <input class="text-input" type="text" placeholder="inserisci il testo da tradurre">

    <button class="lang-button" data-lang="en">🇬🇧</button>
    <button class="lang-button" data-lang="fr">🇫🇷</button>
    <button class="lang-button" data-lang="es">🇪🇸</button>
    <button class="reset-button">❌</button>
    <button class="random-button">
      <i class="fa-solid fa-dice icon-dice"></i>
    </button>
  </section>

  <div class="panel translate">
    <h1>Le tue parole preferite</h1>
   <ul class="translate-favorites">

   </ul>

    </p>
  </div>
</main>

 const langButtons = document.querySelectorAll('.lang-button');
const textInput = document.querySelector('.text-input');
const translationText = document.querySelector('.translation-text');
const translationFlag = document.querySelector('.translation-flag');
const resetButton = document.querySelector('.reset-button');
const randomButton = document.querySelector('.random-button');

//Funzione per aggiornare la lista delle traduzioni preferite
function updateFavoriteList(translation) {
  const translateFavorite = document.querySelector('.translate-favorites');
  translateFavorite.innerHTML = '';
    translation.forEach(function(translateTexts) {
      const li = document.createElement('li');
      li.textContent = translateTexts;
      translateFavorite.appendChild(li);
    });
}

async function translate(text, lang, flag) {
  const url = `https://api.mymemory.translated.net/get?q=${text}&langpair=it|${lang}`;
  const response = await fetch(url);
  const jsonData = await response.json();
  const result = jsonData.responseData.translatedText;
  console.log(result);

  translationText.innerText = result;
  translationFlag.innerText = flag;
}

langButtons.forEach(function(langButton) {
  langButton.addEventListener('click', function() {

    // recupero il testo dal campo di input e rimuovo eventuali spazi extra
    // all'inizio e alla fine della stringa inserita con il metodo .trim()
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim
    const text = textInput.value.trim();

    // recupero il codice lingua dal data-attribute del pulsante
    const lang = langButton.dataset.lang;
    // recupero la bandierina dalla testo del pulsante
    const flag = langButton.innerText;

    // se il campo di input ha effettvamente del testo
    // invoco la funzione e faccio partire la chiamata alle API
    if(text.length > 0) {
      translate(text, lang, flag);
    }
  });
});

randomButton.addEventListener('click', function() {
  const randomUrls = 'https://random-word-api.herokuapp.com/word?length=5';
  const randomIndex = Math.floor(Math.random() * randomUrls.length);
  const randomWork = randomUrls[randomIndex];
  console.log(randomWork);
  textInput.value = randomWork;
});

resetButton.addEventListener('click', reset);
```

The new code for the my question is:
```
async function randomString() {
  const response = await fetch('https://random-word-api.herokuapp.com/word?lang=it');
  const work = await response.json();
  console.log(work);
  textInput.value = work;
}

randomButton.addEventListener('click', function() {
  randomString();
});
```

Explanation: The programmer is creating a sentence translation app, the app also uses an external url to generate the causal sentence. However, the generation only contains one character. It seems that he should use another function to solve.

[ Stack Overflow  ](https://stackoverflow.com)

  1. [ About ](https://stackoverflow.co/)
  2. Products
  3. [ OverflowAI ](https://stackoverflow.co/teams/ai/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav-bar&utm_content=overflowai)

  1. [ Stack Overflow for Teams  Where developers & technologists share private knowledge with coworkers  ](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-for-teams)
  2. [ Advertising & Talent  Reach devs & technologists worldwide about your product, service or employer brand  ](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-advertising)
  3. [ OverflowAI  GenAI features for Teams  ](https://stackoverflow.co/teams/ai/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=overflow-ai)
  4. [ OverflowAPI  Train & fine-tune LLMs  ](https://stackoverflow.co/api-solutions/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=overflow-api)
  5. [ Labs  The future of collective knowledge sharing  ](https://stackoverflow.co/labs/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=labs)
  6. [ About the company ](https://stackoverflow.co/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=about-the-company) [ Visit the blog ](https://stackoverflow.blog/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=blog)

Loading…

  1. ###  [ current community ](https://stackoverflow.com)

     * [ Stack Overflow  ](https://stackoverflow.com)

[ help ](https://stackoverflow.com/help) [ chat
](https://chat.stackoverflow.com/?tab=site&host=stackoverflow.com)

     * [ Meta Stack Overflow  ](https://meta.stackoverflow.com)

###  your communities

[ Sign up
](https://stackoverflow.com/users/signup?ssrc=site_switcher&returnurl=https%3a%2f%2fstackoverflow.com%2fquestions%2f78232924%2fproblem-
generating-causal-sentences-with-js) or [ log in
](https://stackoverflow.com/users/login?ssrc=site_switcher&returnurl=https%3a%2f%2fstackoverflow.com%2fquestions%2f78232924%2fproblem-
generating-causal-sentences-with-js) to customize your list.

###  [ more stack exchange communities ](https://stackexchange.com/sites)

[ company blog ](https://stackoverflow.blog)

  2.   3. [ Log in ](https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2fquestions%2f78232924%2fproblem-generating-causal-sentences-with-js)
  4. [ Sign up ](https://stackoverflow.com/users/signup?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2fquestions%2f78232924%2fproblem-generating-causal-sentences-with-js)

  1.     1. [ Home  ](/)
    2. [ Questions  ](/questions)
    3. [ Tags  ](/tags)
    4.     5. [ Users  ](/users)
    6. [ Companies  ](https://stackoverflow.com/jobs/companies?so_medium=stackoverflow&so_source=SiteNav)
    7. [ Labs  ](javascript:void\(0\))
    8. [ Jobs  ](/jobs?source=so-left-nav)
    9. [ Discussions  ](/beta/discussions)
    10. [ Collectives  ](javascript:void\(0\))

    11. Communities for your favorite technologies. [ Explore all Collectives ](/collectives-all)

  2. Teams

Now available on Stack Overflow for Teams!  AI features where you work:
search, IDE, and chat.

[ Learn more
](https://stackoverflow.co/teams/ai/?utm_medium=referral&utm_source=stackoverflow-
community&utm_campaign=side-bar&utm_content=overflowai-learn-more) [ Explore
Teams
](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-
community&utm_campaign=side-bar&utm_content=explore-teams)

  3. [ Teams  ](javascript:void\(0\))
  4. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. [ Explore Teams ](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact)

#####  Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you
use most.

[ Learn more about Collectives ](/collectives)

**Teams**

Q&A for work

Connect and share knowledge within a single location that is structured and
easy to search.

[ Learn more about Teams ](https://stackoverflow.co/teams/)

Get early access and see previews of new features.

[ Learn more about Labs ](https://stackoverflow.co/labs/)

#  Page not found

This question was  removed from Stack Overflow for reasons of moderation  .
Please refer to the help center for [ possible explanations why a question
might be removed ](/help/deleted-questions) .

Here are some similar questions that might be relevant:

  * [ Setting "checked" for a checkbox with jQuery ](/questions/426258/setting-checked-for-a-checkbox-with-jquery)
  * [ Generating random whole numbers in JavaScript in a specific range ](/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range)
  * [ Get the current URL with JavaScript? ](/questions/1034621/get-the-current-url-with-javascript)
  * [ How can I change an element's class with JavaScript? ](/questions/195951/how-can-i-change-an-elements-class-with-javascript)
  * [ Using async/await with a forEach loop ](/questions/37576685/using-async-await-with-a-foreach-loop)
  * [ How can I upload files asynchronously with jQuery? ](/questions/166221/how-can-i-upload-files-asynchronously-with-jquery)
  * [ Compare two dates with JavaScript ](/questions/492994/compare-two-dates-with-javascript)
  * [ Scroll to an element with jQuery ](/questions/6677035/scroll-to-an-element-with-jquery)
  * [ How to format a number with commas as thousands separators? ](/questions/2901102/how-to-format-a-number-with-commas-as-thousands-separators)
  * [ Disable/enable an input with jQuery? ](/questions/1414365/disable-enable-an-input-with-jquery)

Try a [ Google Search
](http://www.google.com/search?q=site:stackoverflow.com/questions+problem+generating+causal+sentences+with+js)

Try [ searching for similar questions
](/search?q=problem%20generating%20causal%20sentences%20with%20js)

Browse our [ recent questions ](/questions)

Browse our [ popular tags ](/tags)

If you feel something is missing that should be here, [ contact us ](/contact)
.


Question:
CannotDeliverBroadcastException On Samsung devices running Android 13 (API 33)

We got lot of crash reports from Firebase regarding this crash.

```
Fatal Exception: android.app.RemoteServiceException$CannotDeliverBroadcastException: can't deliver broadcast
       at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:2219)
       at android.app.ActivityThread.-$$Nest$mthrowRemoteServiceException()
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2508)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:226)
       at android.os.Looper.loop(Looper.java:313)
       at android.app.ActivityThread.main(ActivityThread.java:8762)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)
```

Crash happens only on Samsung devices running android 13 (API 33)

We followed this post CannotDeliverBroadcastException only on Pixel devices running Android 12

The thing is - we can't just silence/absorb this crash, as some of our app functionality is build on the broadcast (BroadcastReceiver, registered in Manifest).

We need to actually prevent this crash (somehow :))

We checked also this one on google issue tracker but it seems there is no solution https://issuetracker.google.com/issues/245258072

Any of you found a solution for this? Thanks

Explanation: The programmer got a crash report related to broadcast on Samung devices running android 13. He/she has checked a relevant solution which is about solving BroadcastException on Pixel devices running Android 12. Maybe the real crash is not broadcase but something else.

This may not be a broadcast bug at all, but a knock-on error caused by memory
fragmentation (OOM).

Profile your app while it is running and make sure it is not running out of
its allocated memory.

Here are some very [ good suggestions
](https://developer.android.com/topic/performance/memory) to try. Bouncing the
service (kill/relaunch) on a timer might prevent this behavior too.


Question:
How to control Argo(helm) flow with Script output

I have a script defined in Argo WorkflowTemplate as follows. This may either print status:true or status:false (I have simplified this)

```
- name:util-script
    script:
      image: python3
      command: ["python3"]
      script |
         print(status:true)
```

Is there a way to control dag flow based on the above script output? I know helm provides flow control like Helm Doc - Flow control

Following is what I tried so far, but this always jumps to else condition. anything Im doing wrong? Appreciate any input on this

```
{{- if contains "status:true" `tasks.util-script.outputs.result` }}
  # even result is `status:true`, does not reach here
{{ else }}
  # always reach here
{{ end }}
```

I have verified tasks.util-script.outputs.result indeed returns the expected result.

Explanation: The programmer has defined a script in the Argo WorkflowTemplate that prints either `status:true` or `status:false`. The programmer wants to control the workflow based on the script's output but is unable to correctly evaluate the output. They have used the `contains` function to check if the output contains `status:true`, but it always goes to the else condition. The programmer has verified that `tasks.util-script.outputs.result` indeed returns the expected result. Another conditional script should be used.

Helm executes before the workflow runs. That's why you'd end up in the else
block.

  1. Your task is not evaluated
  2. When template is rendered,

        `tasks.util-script.outputs.result`

creates a literal string, which doesn't contain status text

You need to use a ` when ` conditional, as shown in the documentation - [
https://argo-workflows.readthedocs.io/en/stable/walk-through/conditionals/
](https://argo-workflows.readthedocs.io/en/stable/walk-through/conditionals/)

    - name: next
      template: next
      when: {{`{{tasks.util-script.outputs.result}}`}} == "status:true"


Question:
How can I convert a PredictResponse to JSON?

I have a VertexAI project I want to access. I'm currently trying two approaches, via a React frontend and via a Python backend, which I would then connect to the FE. I posted a question about making requests to VertexAI from Node here.

In the python approach, I'm able to make the request and receive the correct response. However, in order for it to be accessible by the FE, I would need to convert it to JSON. I'm struggling with how to do that.

Here's the code I'm using:

```
# The AI Platform services require regional API endpoints.
client_options = {"api_endpoint": api_endpoint}
# Initialize client that will be used to create and send requests.
# This client only needs to be created once, and can be reused for multiple requests.
client = PredictionServiceClient(
    client_options=client_options, credentials=credentials
)
instance = schema.predict.instance.TextClassificationPredictionInstance(
    content=content,
).to_value()
instances = [instance]
parameters_dict = {}
parameters = json_format.ParseDict(parameters_dict, Value())
endpoint = client.endpoint_path(
    project=project_id, location=compute_region, endpoint=endpoint_id
)
response = client.predict(
    endpoint=endpoint, instances=instances, parameters=parameters
)
response_dict = [dict(prediction) for prediction in response.predictions]
```

`response_dict` is printable, but I can't convert `response` to json using `json.dumps` because:

```
TypeError: Object of type PredictResponse is not JSON serializable
```
This is the error that has been plaguing me in every attempt. DuetAI simply tells me to use `json.dumps`.

EDIT
Here's the working code using the accepted response:
```
    ...
    response = client.predict(
        endpoint=endpoint, instances=instances, parameters=parameters
    )

    predictions = MessageToDict(response._pb)
    predictions = predictions["predictions"][0]
```

Explanation: The programmer wants to access a project through Python. Although he can make the request and receive the correct response, he does not how to convert it into JSON, which is a necessary step for being accessed by FE. It seems that he/she does not notice the transmission format for each function related to json.

Since ` json.dumps ` requires serialization of your response/s, I believe it's
better to use [ ` json_format.MessageToDict `
](https://stackoverflow.com/questions/73588294/unable-to-convert-protobuf-
binary-file-to-json-in-python-bytes-object-has-no?rq=3) instead of `
json_format.ParseDict ` .

They work quite the opposite:

  * ` ParseDict ` takes a JSON dictionary representation and merges it into a pre-existing Protobuf message object. It parses the JSON data and populates the corresponding fields in the Protobuf message.

  * ` MessageToDict ` takes a Protobuf message object and converts it into a Python dictionary representation which can then be easily serialized to JSON using ` json.dumps ` .

I found some online resources which discuss the ` MessageToDict ` function of
the protobuf library. Please check them out for more information.

  * [ Unable to convert protobuf binary file to json in python - bytes' object has no attribute 'DESCRIPTOR' ](https://stackoverflow.com/questions/73588294/unable-to-convert-protobuf-binary-file-to-json-in-python-bytes-object-has-no?rq=3)

  * [ JSON to Protobuf in Python ](https://stackoverflow.com/questions/60345426/json-to-protobuf-in-python?rq=3)

  * [ Unable to parse Vertex job responses lack ](https://cloud.google.com/knowledge/kb/unable-to-parse-vertex-job-responses-lack-000004947)


Question:
How can I initialise a constexpr array with values using std::generate

For example, if I wanted a constexpr std::array<int,100> initialised with all the multiples of 3 from 1-300 at compile time how can I do this?

My first thought was to use std::generate, something like:

```
constexpr std::array<int,100> a { std::generate(a.begin(), a.end(), [n=0]()mutable{ return n+=3; });
```

I get an error such as `<source>:9:52: error: void value not ignored as it ought to be`.

and I can't use std::generate after this because of course, it's read only at that point.

Explanation: An attempt was made to initialize a constexpr array using std::generate and a lambda expression to generate multiples of 3 between 1 and 300. However, an error was encountered in the code: <source>:9:52: error: void value not ignored as it ought to be. Additionally, since the array is read-only after initialization, it is not possible to use std::generate after that point. A helper alias template is needed to overcome these challenges.

You can use ` index_sequence ` :

    template <size_t ... Indices>
    constexpr auto gen(std::index_sequence<Indices...>) {
        return std::array<int,100>{ (Indices * 3)... };
    }

    int main() {
        constexpr std::array<int,100> a = gen(std::make_index_sequence<100>());
    }


Question:
django add filtes in template is not work expectedly

I am a Django and Python beginner, and I encountered a problem while using Django. I hope to use a filter in the template to get the string I need, but the result below is not what I expected.

```
# filter definition

@register.filter
def to_class_name(obj):
    return obj.__class__.__name__
```

```
# HTML template for UpdateView (This template will be used by multiple models.)
# object = Order()

{{ object|to_class_name }} #reulst: Order

{{ 'wms'|add:object|to_class_name }} #result: str, expect: object

```

I roughly understand that the issue lies with the order, but it seems I can't add parentheses to modify it.

```
{{ 'wms'|add:(object|to_class_name) }} #cause SyntaxError
```

Is there any way to solve this problem? Or is there a better way to determine the page data I need to output based on the model class when multiple models share one template? Thank you all.

Explanation: The programmer encountered an issue while using Django. The aim is to use a filter in the template to retrieve the desired string, but the resulting output does not match the expectations. He/she wants another syntax, which is a better approach to determine the page data to output based on the model class when multiple models share one template.

> I roughly understand that the issue lies with the order, but it seems I
> can't add parentheses to modify it.

You can use variables. [ link
](https://docs.djangoproject.com/en/5.0/ref/templates/builtins/#with)

One way is to use ` with ` tag.

> it caches a complex variable under a simpler name. The variable is available
> until the ` {% endwith %} ` tag appears.

eg.

    {% with firstname="Tobias" %}

Hello {{ firstname }}, how are you?

    {% endwith %}

In your case, something like this

    {% with class_name=object|to_class_name %}
       {{ 'wms'|add:class_name }}
    {% endwith %}

Another approach is to use ` firstof ` tag. [ link
](https://docs.djangoproject.com/en/5.0/ref/templates/builtins/#firstof)

    {% firstof object|to_class_name as class_name %}
    {{ 'wms'|add:class_name }}


Question:
Saving a scipy.sparse matrix directly as a regular txt file

I have a scipy.sparse matrix (csr_matrix()). But I need to save it to a file not in the .npz format but as a regular .txt or .csv file. My problem is that I don't have enough memory to convert the sparse matrix into a regular np.array() and then save it to a file. Is there a way to have the data as a sparse matrix in memory but save it directly as a regular matrix to the disk? Or is there a way to "unzip" a .npz file without loading it into memory inside Python?

Explanation: Due to memory constraints, converting the sparse matrix into a regular np.array() and subsequently saving it becomes problematic. The challenge is to find a solution that allows the data to remain as a sparse matrix in memory while directly saving it as a regular matrix to the disk.

Answer to new question:

    import numpy as np
    from scipy import sparse, io
    A = sparse.eye(5, format='csr') * np.pi
    np.set_printoptions(precision=16, linewidth=1000)
    with open('matrix.txt', 'a') as f:
        for row in A:
            f.write(str(row.toarray()[0]))
            f.write('\n')

    # [3.141592653589793 0.                0.                0.                0.               ]
    # [0.                3.141592653589793 0.                0.                0.               ]
    # [0.                0.                3.141592653589793 0.                0.               ]
    # [0.                0.                0.                3.141592653589793 0.               ]
    # [0.                0.                0.                0.                3.141592653589793]

And with begin/end brackets:

    import numpy as np
    from scipy import sparse, io
    A = sparse.eye(5, format='csr') * np.pi
    np.set_printoptions(precision=16, linewidth=1000)
    with open('matrix.txt', 'a') as f:
        for i, row in enumerate(A):
            f.write('[' if (i == 0) else ' ')
            f.write(str(row.toarray()[0]))
            f.write(']' if (i == A.shape[0] - 1) else '\n')

    # [[3.141592653589793 0.                0.                0.                0.               ]
    #  [0.                3.141592653589793 0.                0.                0.               ]
    #  [0.                0.                3.141592653589793 0.                0.               ]
    #  [0.                0.                0.                3.141592653589793 0.               ]
    #  [0.                0.                0.                0.                3.141592653589793]]

You may have to fiddle with ` set_printoptions ` depending on your data.

* * *

Answer to original question, which did not require that the matrix be written
as dense.

[ Harwell-Boeing format
](https://docs.scipy.org/doc/scipy/reference/io.html#harwell-boeing-files) is
plain text:

    import numpy as np
    from scipy import sparse, io
    A = sparse.eye(3, format='csr') * np.pi

    # Default title                                                           0
    #              3             1             1             1
    # RUA                        3             3             3             0
    # (40I2)          (40I2)          (3E25.16)
    #  1 2 3 4
    #  1 2 3
    #   3.1415926535897931E+00  3.1415926535897931E+00  3.1415926535897931E+00

    io.hb_write('matrix.txt', A)  # saves as matrix.txt
    A2 = io.hb_read('matrix.txt')
    assert not (A2 != A).nnz  # efficient check for equality

So is [ Matrix Market
](https://docs.scipy.org/doc/scipy/reference/io.html#matrix-market-files) :

    io.mmwrite('matrix', A)  # saves as matrix.mtx

    # %%MatrixMarket matrix coordinate real symmetric
    # %
    # 3 3 3
    # 1 1 3.141592653589793e+00
    # 2 2 3.141592653589793e+00
    # 3 3 3.141592653589793e+00

    A2 = io.mmread('matrix')
    assert not (A2 != A).nnz

* * *

If you want an even simpler _format_ , although it involves more code:

    import numpy as np
    from scipy import sparse
    A = sparse.eye(10, format='csr')*np.pi

    np.savetxt('data.txt', A.data)
    np.savetxt('indices.txt', A.indices, fmt='%i')
    np.savetxt('indptr.txt', A.indptr, fmt='%i')

To load:

    data = np.loadtxt('data.txt')
    indices = np.loadtxt('indices.txt', dtype=np.int32)
    indptr = np.loadtxt('indptr.txt', dtype=np.int32)

    A2 = sparse.csr_matrix((data, indices, indptr))
    assert not (A2 != A).nnz

But the important idea is that all you need to save are the ` data ` , `
indices ` , and ` indptr ` attributes of the ` csr_matrix ` .


Question:
dbms_random.value() in Snowflake - Oracle to snowflake conversion

Below is the oracle sql query that I got to convert to snowflake. In here, i am blocked in creating dbms_random.value() in snowflake

```
select emp_id, emp_name, emp_mob,
(case when dbms_random.value() >= 0.85 then 'Y' else 'N' end) as tag
from eds_dwg.employee_data
```

Can someone help me on this?

Thanks

Explanation: Trying to convert a piece of oracle sql code to a snowflake version. But the author doesn't know how to mimic dbms_random.value() with snowflake's function.

You can use Snowflake Data generation functions: [
https://docs.snowflake.com/en/sql-reference/functions-data-generation.html
](https://docs.snowflake.com/en/sql-reference/functions-data-generation.html)

NORMAL() returns a floating point number with a specified mean and standard
deviation. Something like this with correct adaptions of the parameters could
to the trick: [ https://docs.snowflake.com/en/sql-
reference/functions/normal.html ](https://docs.snowflake.com/en/sql-
reference/functions/normal.html)

An alternative can be using UNIFORM(): [ https://docs.snowflake.com/en/sql-
reference/functions/uniform.html ](https://docs.snowflake.com/en/sql-
reference/functions/uniform.html)

Example from docs to generate a value between 0 and 1:

    select uniform(0::float, 1::float, random()) from table(generator(rowcount => 5));


Question:
Inconsistent delay when using RegisterHotkey and PeekMessagew In Go

I'm trying to write a simple Go program that will listen for global windows hotkeys while in the background and send API calls when specific ones have been pressed. This is my first time learning how to work with Windows messages so this is probably just me not understanding how they work.

My calls to PeekMessageW often return 0 even though hotkeys are being pressed, and then after a minute or so suddenly returns them all at once. Is this just expected behaviour?

I'm doing everything on the same goroutine. First I create a new window and save the HWND like this:

```
func createWindow(
    user32 *syscall.DLL,
    dwExStyle uint32,
    lpClassName, lpWindowName *uint16,
    dwStyle uint32,
    x, y, nWidth, nHeight int,
    hWndParent, hMenu, hInstance uintptr,
    lpParam unsafe.Pointer,
) uintptr {
    procCreateWindowEx := user32.MustFindProc("CreateWindowExW")

    ret, _, _ := procCreateWindowEx.Call(
        uintptr(dwExStyle),
        uintptr(unsafe.Pointer(lpClassName)),
        uintptr(unsafe.Pointer(lpWindowName)),
        uintptr(dwStyle),
        uintptr(x),
        uintptr(y),
        uintptr(nWidth),
        uintptr(nHeight),
        hWndParent,
        hMenu,
        hInstance,
        uintptr(lpParam),
    )
    return ret
}

func GiveSimpleWindowPls(user32 *syscall.DLL) uintptr {
    var hwnd uintptr
    className, _ := syscall.UTF16PtrFromString("STATIC")
    windowName, _ := syscall.UTF16PtrFromString("Simple Window")

    hwnd = createWindow(
        user32,
        0,
        className,
        windowName,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        nil,
    )

    if hwnd != 0 {
        fmt.Println("HWND:", hwnd)
    } else {
        fmt.Println("Could not create window")
    }
    return hwnd
}
```

I then register my hotkeys:

```
func Register(user32 *syscall.DLL, hwnd uintptr) (map[int]*Hotkey, error) {
    reghotkey := user32.MustFindProc("RegisterHotKey")

    // Hotkeys to listen to:
    // (hardcoded for now)
    keys := map[int]*Hotkey{
        6:  {6, ModAlt + ModCtrl + ModShift, '6'},
        7:  {7, ModAlt + ModCtrl + ModShift, '7'},
        8:  {8, ModAlt + ModCtrl + ModShift, '8'},
        9:  {9, ModAlt + ModCtrl + ModShift, '9'},
        10: {10, ModAlt + ModCtrl + ModShift, '0'},
    }

    // Register hotkeys:
    for _, v := range keys {
        r1, _, err := reghotkey.Call(hwnd, uintptr(v.Id), uintptr(v.Modifiers), uintptr(v.KeyCode))
        if r1 != 1 {
            return nil, fmt.Errorf("error registering hotkey %#v: %w", v, err)
        }
    }
    return keys, nil
}
```

And finally call PeekMessageW in a loop:

```
const WM_HOTKEY = 0x0312

func Listen(keys map[int]*Hotkey, switcher Switcher, hwnd uintptr) {
    peekmsg := user32.MustFindProc("PeekMessageW")

    for {
        var msg = &MSG{}
        a, _, _ := peekmsg.Call(uintptr(unsafe.Pointer(msg)), hwnd, WM_HOTKEY, WM_HOTKEY, 1)
        fmt.Printf("%#v %d \n", msg, a)

        if a == 0 {
            time.Sleep(time.Millisecond * 50)
            continue
        }

        if key, ok := keys[int(msg.WPARAM)]; ok {
            fmt.Println("Hotkey was pressed:", key)

            switcher.Switch(key.Id) // for now this just does nothing and returns
        }
    }
}
```

And at first this seems to work perfectly, but every minute or so PeekMessageW starts to only return 0 even though I am pressing my hotkeys. Then after a while, it returns all the messages one after the other, as if the queue had congested for a while and finally gets released.

Am I wrong in expecting to be able to peek WM_HOTKEY messages immediately (or at least within a couple seconds) after the hotkey is pressed? The program sometimes stops receiving these messages for up to a minute at a time, and then suddenly processes them all at once. Is the queue being blocked by some other process I have running that Windows gives priority?

This is my first time trying to figure out how this works, but I've spent hours searching for a solution online and can't see where I'm going wrong.

Explanation: The issue involves writing a Go program that listens for global Windows hotkeys in the background and sends API calls when specific hotkeys are pressed. However, there are inconsistencies with the delay when using RegisterHotkey and PeekMessageW. The PeekMessageW function sometimes returns 0 even when hotkeys are pressed, and after a minute or so, it suddenly returns all the messages at once. The question is whether this behavior is expected or if there is an error in the code. Maybe another function needs to be used here.

After several red herrings I finally found the solution to the problem. I
needed to call runtime.LockOsThread() before everything to lock my goroutine
to the current system thread, as the hotkey messages are thread specific.


Question:
Command-line to reverse byte order/change endianess

I'm hacking around in some scripts trying to parse some data written by Javas `DataOutputStream#writeLong(...)`. Since java always seems to write big endian, I have a problem feeding the bytes to `od`. This is due to the fact that `od` always assumes that the endianess matches the endianess of the arch that you are currently on, and I'm on a little endian machine.

I'm looking for an easy one-liner to reverse the byte order. Let's say that you know that the last 8 bytes of a file is a long written by the aforementioned `writeLong(...)` method. My current best attempt to print this long is

```
tail -c 8 file | tac | od -t d8
```

, but `tac` only seems to work on text (fair enough). I've found some references to `dd conv=swab`, but this only swaps bytes in pairs, and cannot reverse these eight bytes.

Does anyone know a good one-liner for this?

Explanation: A better easy one-liner to reverse the byte order is required. That can be used in data returned by DataOutputStream#writeLong(...), where Java always seems to write big endian.

You could use objcopy:

    $ objcopy -I binary -O binary --reverse-bytes=num inputfile.bin outputfile.bin

where num is either 2 or 4.


Question:
How to disable Swagger ui documentation in Fastapi for production server?

How to disable Swagger ui documentation in Fastapi for production server? i need disable fastapi documentation

Explanation: The programmer wants to disable fastapi documentation.

[ Construct your app with ` docs_url=None ` and ` redoc_url=None `
](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls) and FastAPI won't
mount those endpoints.

    app = FastAPI(docs_url=None, redoc_url=None)


Question:
Django-Forms with json fields

I am looking to accept json data in a form field and than validate it using some database operations. The data will mostly consist of an array of integers. So can you please help me as to how can i do so.

I have tried to google this but didn't get any decent answer. Please help.

Explanation: A validation using some database operations is required on a json data in a form field. The json data mostly consist of an array of integers.

You need to take it as text input using ` CharField ` . And in the clean
method of this field, you can validate it as per your requirement to check if
input is valid.

Something like:

    class myForm(forms.Form):
         jsonfield = forms.CharField(max_length=1024)

        def clean_jsonfield(self):
             jdata = self.cleaned_data['jsonfield']
             try:
                 json_data = json.loads(jdata) #loads string as json
                 #validate json_data
             except:
                 raise forms.ValidationError("Invalid data in jsonfield")
             #if json data not valid:
                #raise forms.ValidationError("Invalid data in jsonfield")
             return jdata

You may also find a custom field for JSON data input.


Question:
Vectorization with multiple rows and columns of dataframe instead of one

Currently working on building a csv file that include historical stock info, while not only includes historical prices, but momentum indicators. I've successfully added indicators by looping through an entire dataframe (w/ > 25,000,000 rows), but it takes too long (30 - 36 h).

What I'm trying to accomplish: I'd like start with the the 3 day high:

```
high = stock_df.loc[x+1:x+4, "High"].max(axis=0)
```

and divide that by the day 0 low:
```
low =  stock_df.loc[x, "Low"]
```

without iterating through entire loop like as shown below:
```
stock_ticker_list = df.Symbol.unique()
for ticker in stock_ticker_list:
    #return dataframe thats historical infor for one stock
    print(ticker)
    stock_df = df.loc[df.Symbol == ticker]
    start = stock_df.index[stock_df['Symbol'] == ticker][0]
    for x in range(start, start + len(stock_df) - 2):
        try:
            high = stock_df.loc[x+1:x+4, "High"].max(axis=0)
            low =  stock_df.loc[x, "Low"]
            df2.loc[x,"H/L"] = high/low
        except:
            df2.loc[x,"H/L"] = pd.NA
```

I've look through the documentation and found methods like pandas.Series.pct_change and pandas.Series.div but it does not appear as though these functions will work without me also creating a column for the 3 day high. I tried to create a column for the three day high

```
s = stock_df["High"]
stock_df['Three_day_high'] = max([s.diff(-1),s.diff(-2),s.diff(-3)]) + s
```

but got a ValueError (`ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().`)

Explanation: By looping through an entire dataframe with greater than 25,000,000 rows, adding indicators takes 30 to 36 hours. Now, the programmer wants to start with the 3 day high and divide that by the day 0 low. It is desired to find a vectorised method to efficiently calculate the required ratio without using loop and to improve computational performance.

Consider windowing operations: [ https://pandas.pydata.org/pandas-
docs/stable/user_guide/window.html ](https://pandas.pydata.org/pandas-
docs/stable/user_guide/window.html)

    import pandas as pd
    import numpy as np

    # for testing, have generated a 50 million row dataframe with random numbers in the range 500 to 1500
    l1 = np.round(500 + 1000 * np.random.rand(5000000,1), 0)
    df = pd.DataFrame(l1, columns = ["Val"])

    # rolling window applied to the Val column
    %timeit df["Val"].rolling(window=3).max() / df["Val"]  # optional timing function
    df["H"] = df["Val"].rolling(window=3, closed = 'left').max() # optional to show 3 day high
    df["HL"] = df["Val"].rolling(window=3, closed = 'left').max() / df["Val"]
    df[:7]

1.07 s ± 10.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) [ ![enter
image description here](https://i.sstatic.net/n3863.png)
](https://i.sstatic.net/n3863.png)


Question:
What effect does the `virtual` modifier have on an interface member?

Say I have an interface like interface IThing { virtual string A => "A"; }. What effect does the virtual keyword have on implementing types here? Surprisingly, I couldn't find anything regarding this on either SO, dotnet GitHub pages and discussions, nor on learn.microsoft.com, possibly buried under all the unrelated content where the words interface and virtual appear in any combination. From my quick testing it doesn't appear to have any sensible effect. My intuition tells me to expect from the implementing classes' hierarchy to have been introduced the given virtual members, as if the base implementing class has declared them itself, but it's not the case.

For example:
```
class Thing: IThing
{
}

class Thing2: Thing
{
    override public string A => "!"; // ERROR: No suitable method found to override.
}
```

If I declare the A property on Thing, but do not declare it explicitly as virtual, it still won't compile. I also have the freedom apparently to just define them w/o the modifier despite it being present in the interface and it compiles. And code using IThing only sees the default implementation of A regardless of what I do unless the class implements the interface directly and not through inheritance in this setup.

Can somebody clarify the use of the virtual modifier on interface members? I use the latest stable language version of C#.

Explanation: The programmer want to know clearly about the use of the virtual modifier on interface members, and he/she uses the latest stable language version of C#.

The following:

    interface IThing { virtual string A => "A"; }

Is the so called [ default interface method ](https://learn.microsoft.com/en-
us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-
methods) and virtual as far as I can see actually does nothing because:

> The ` virtual ` modifier may be used on a function member that would
> otherwise be implicitly ` virtual `

I.e. it just an explicit declaration of the fact that **interface** method is
virtual since the language team decided to not restrict such things.

See also the [ Virtual Modifier vs Sealed Modifier
](https://learn.microsoft.com/en-us/dotnet/csharp/language-
reference/proposals/csharp-8.0/default-interface-methods#virtual-modifier-vs-
sealed-modifier) part of the spec:

> Decisions: Made in the LDM 2017-04-05:
>
>   * non- ` virtual ` should be explicitly expressed through ` sealed ` or `
> private ` .
>   * ` sealed ` is the keyword to make interface instance members with bodies
> non- ` virtual `
>   * We want to allow all modifiers in interfaces
>   * ...
>

Note that default implemented ` IThing.A ` is not part of the ` Thing ` ,
hence you can't do ` new Thing().A ` , you need to cast to the interface
first.

If you want to override the ` IThing.A ` in the ` Thing2 ` then you can
implement the interface directly:

    class Thing2 : Thing, IThing
    {
         public string A => "!";
    }

    Console.WriteLine(((IThing)new Thing()).A); // Prints "A"
    Console.WriteLine(((IThing)new Thing2()).A); // Prints "!"

Another way would be declaring ` public virtual string A ` in the ` Thing ` so
your current code for ` Thing2 ` works:

    class Thing : IThing
    {
        public virtual string A => "A";
    }

    class Thing2 : Thing
    {
        public override string A => "!";
    }

To understand meaning of ` sealed ` / ` virtual ` identifiers in interfaces
you can create a second interface:

    interface IThing {  string A => "A"; }
    interface IThing2 : IThing {  string IThing.A => "B"; }
    class Thing : IThing2 {}

    Console.WriteLine(((IThing)new Thing()).A); // Prints "B"

While if you declare ` IThing.A ` as ` sealed ` then ` IThing2 ` will not
compile:

    interface IThing { sealed string A => "A"; }

    interface IThing2 : IThing
    {
        // Does not compile:
        // string IThing.A => "B";
    }

    class AntoherThing : IThing
    {
        // Does not compile too:
        string IThing.A => "B";
    }

Also check out the [ why virtual is allowed while implementing the interface
methods? ](https://stackoverflow.com/q/4470446/2501279) linked by [ wohlstad
](https://stackoverflow.com/users/18519921/wohlstad) in the comments.


Question:
Child component not re-rendering after parent component gets updated

I have 1 parent(Container) and 2 (List, SelectedItem) child components, Initially I render all data to Container and send all data to list and first item as selectedItem to selected Item component. So ar so good

When a user clicks an item in the List component, it updates the selected item of the Parent through a function, the parent is able to update state, But it is not re-rendering selected item component.

List Component:
```
 import "./SelectedImage.css"

function ListSection({items, updateSelectedItem}) {
  return (
    <div className="list-section">
      <ul>
        {
          (items).map((item) => {
            return <li key={item.id} onClick={() => updateSelectedItem(item.id)}>{item.name}</li>
          })
        }
      </ul>
    </div>
  );
}

export default ListSection;
```

Container Component
```
import LeftSection from './LeftSection';
import logo from './logo.svg';
import RightSection from './RightSection ';
import SelectedItem from './SelectedItem';
import "./App.css";
import ListSection from './ListSection';
import { Component, useState } from 'react';

const products = [
  {id: 1, name: "Lime", size: ["large", "medium", "small"], category: "Juice", image: "lime-juice.jpg"},
  {id: 2, name: "Orange", size: ["large", "medium", "small"], category: "Juice", image: "orange-juice.jpg"},
  {id: 3, name: "Mango", size: ["large", "medium", "small"], category: "Juice", image: "mango-juice.jpg"},
]

function Container() {
  let [selectItem, setSelectItem] = useState(products[0]);

  function chooseSelectedItem(id) {
    let item = products.filter((value) => {
      console.log(value.id);
      return (value.id == id)
    })
    setSelectItem(item[0]);
    console.log(item[0]);
  }

  return (
    <div className="Container">
      <ListSection items={products} updateSelectedItem={chooseSelectedItem}/>
      <SelectedItem CurrentSelectedItem={selectItem}/>
    </div>
  );
}

export default Container;
```

SelectedItemComponent

```
import QuantityBar from "./QuantityBar";
import "./SelectedImage.css"
import { useState } from "react";

function SelectedItem({CurrentSelectedItem}) {
  let [item, setItem] = useState(CurrentSelectedItem);

  return (
    <div className="selected-item">
      {/* <img src={item.image} className="selected-image" /> */}
      {item.name}
      {/* <QuantityBar itemCount={0} /> */}
    </div>
  );
}

export default SelectedItem;
```

Explanation: The state of the parent (Container) can be updated through a function, however the selected item component is not re-rendered. Another function is needed to solve the update of selected item component.

Since you're initializing the state using ` useState ` with the prop `
CurrentSelectedItem ` , any changes to ` CurrentSelectedItem ` won't be
reflected in the state of the component.

You can use the ` useEffect ` hook to update the state of ` SelectedItem `
whenever ` CurrentSelectedItem ` changes:

    function SelectedItem({ CurrentSelectedItem }) {
      const [item, setItem] = useState(CurrentSelectedItem);

      useEffect(() => {
        setItem(CurrentSelectedItem);
      }, [CurrentSelectedItem]);

      ...
    }

Or if ` SelectedItem ` is solely dependent on ` CurrentSelectedItem ` , you
can remove the local state in ` SelectedItem ` and directly use `
CurrentSelectedItem ` as a prop, like

    function SelectedItem({ CurrentSelectedItem }) {
      return (

          {/*  */}
          {CurrentSelectedItem.name}
          {/* <QuantityBar itemCount={0} /> */}

      );
    }