问:
Unable to create a div with 100% height and make the overflow scrollable
I'm creating a page and I need the side menu to have a scroll.

And have the maximum size possible between the Header and the Footer.

Currently the code does not respect overflow-y with height: auto or height 100% in the BoxDates div.

However, if you set height: 300px (see image), the scroll appears in the correct place, but obviously I don't want that.

How could I do this?

```<code>import styled from "styled-components";

export const LineServiceDetails = styled.div`
    display: flex;
    flex-direction: column;
    height: 100%;
`;

export const TxtActualService = styled.p`
    font-size: 25px;
    color: #444;
    margin-left: 5px;
`;

export const BoxBackZone = styled.div`
    display: flex;
    align-items: center;
`;

export const MainContainer = styled.div`
    padding: 20px;
    display: flex;
    height: 100%;
    flex-direction: column;
`;

export const Container = styled.div`
    position: absolute;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    user-select: none;
`;

export const BtnBack = styled.div`
    cursor: pointer;
`;

export const BoxTopMonth = styled.div`
    display: flex;
    width: 100%;
    height: fit-content;
    margin-top: 3px;
    gap: 10px;
`;

export const BoxChangeMonth = styled.div`
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f2f2f2;
    border-radius: 3px;
    width: 25px;
    height: 25px;
    &:hover{
        cursor: pointer;
    }
`;

export const BoxAtualMonth = styled.div`
    background: #f2f2f2;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 3px;
`;

export const TxtMonth = styled.p`
    color: #1f61cf;
`;

export const BoxDates = styled.div`
    overflow-y: auto;
    width: 300px;
    margin-top: 10px;
`;

export const BoxDate = styled.div`
    display: flex;
    flex-direction: column;
    gap: 10px;
    &:not(:first-child){
        margin-top: 10px;
    }
`;

export const TxtDate = styled.p`
    color: #444;
`;

export const BoxMealTime = styled.div`
    background: #f2f2f2;
    height: 35px;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    &:hover{
        cursor: pointer;
    }
`;

export const MealTimeTxt = styled.p`
    color: #1f61cf;
`;
</code>```

```<code>import { useNavigate } from "react-router-dom";

import {
    BtnBack,
    Container,
    MainContainer,
    BoxBackZone,
    TxtActualService,
    LineServiceDetails,
    BoxTopMonth,
    BoxChangeMonth,
    BoxAtualMonth,
    TxtMonth,
    BoxDates,
    BoxDate,
    TxtDate,
    BoxMealTime,
    MealTimeTxt
} from "./style";

import Footer from "../Components/Footer";
import Header from "../Components/Header";

import { IoArrowBackCircleOutline } from "react-icons/io5";
import { IoIosArrowBack, IoIosArrowForward } from "react-icons/io";

export default function Requests(){

    const navigate = useNavigate();

    return (
        <Container>
            <Header />
            <MainContainer>
                <BoxBackZone>
                    <BtnBack onClick={() => { navigate('/kiosk/menu') }}>
                        <IoArrowBackCircleOutline size={50} color="#444" />
                    </BtnBack>
                    <TxtActualService>Adquirir</TxtActualService>
                </BoxBackZone>
                <LineServiceDetails>
                    <BoxTopMonth>
                        <BoxChangeMonth>
                            <IoIosArrowBack size="20" color="#1f61cf" />
                        </BoxChangeMonth>
                        <BoxAtualMonth>
                            <TxtMonth>Agosto 2022</TxtMonth>
                        </BoxAtualMonth>
                        <BoxChangeMonth>
                            <IoIosArrowForward size="20" color="#1f61cf" />
                        </BoxChangeMonth>
                    </BoxTopMonth>
                    <BoxDates>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                    </BoxDates>
                </LineServiceDetails>
            </MainContainer>
            <Footer />
        </Container>
    );
}
</code>```

Body:
I'm creating a page and I need the side menu to have a scroll.

And have the maximum size possible between the Header and the Footer.

Currently the code does not respect overflow-y with height: auto or height 100% in the BoxDates div.

However, if you set height: 300px (see image), the scroll appears in the correct place, but obviously I don't want that.

How could I do this?

import styled from "styled-components";

export const LineServiceDetails = styled.div`
    display: flex;
    flex-direction: column;
    height: 100%;
`;

export const TxtActualService = styled.p`
    font-size: 25px;
    color: #444;
    margin-left: 5px;
`;

export const BoxBackZone = styled.div`
    display: flex;
    align-items: center;
`;

export const MainContainer = styled.div`
    padding: 20px;
    display: flex;
    height: 100%;
    flex-direction: column;
`;

export const Container = styled.div`
    position: absolute;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    user-select: none;
`;

export const BtnBack = styled.div`
    cursor: pointer;
`;

export const BoxTopMonth = styled.div`
    display: flex;
    width: 100%;
    height: fit-content;
    margin-top: 3px;
    gap: 10px;
`;

export const BoxChangeMonth = styled.div`
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f2f2f2;
    border-radius: 3px;
    width: 25px;
    height: 25px;
    &:hover{
        cursor: pointer;
    }
`;

export const BoxAtualMonth = styled.div`
    background: #f2f2f2;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 3px;
`;

export const TxtMonth = styled.p`
    color: #1f61cf;
`;

export const BoxDates = styled.div`
    overflow-y: auto;
    width: 300px;
    margin-top: 10px;
`;

export const BoxDate = styled.div`
    display: flex;
    flex-direction: column;
    gap: 10px;
    &:not(:first-child){
        margin-top: 10px;
    }
`;

export const TxtDate = styled.p`
    color: #444;
`;

export const BoxMealTime = styled.div`
    background: #f2f2f2;
    height: 35px;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    &:hover{
        cursor: pointer;
    }
`;

export const MealTimeTxt = styled.p`
    color: #1f61cf;
`;

import { useNavigate } from "react-router-dom";

import {
    BtnBack,
    Container,
    MainContainer,
    BoxBackZone,
    TxtActualService,
    LineServiceDetails,
    BoxTopMonth,
    BoxChangeMonth,
    BoxAtualMonth,
    TxtMonth,
    BoxDates,
    BoxDate,
    TxtDate,
    BoxMealTime,
    MealTimeTxt
} from "./style";

import Footer from "../Components/Footer";
import Header from "../Components/Header";

import { IoArrowBackCircleOutline } from "react-icons/io5";
import { IoIosArrowBack, IoIosArrowForward } from "react-icons/io";

export default function Requests(){

    const navigate = useNavigate();

    return (
        <Container>

            <MainContainer>
                <BoxBackZone>
                    <BtnBack onClick={() => { navigate('/kiosk/menu') }}>
                        <IoArrowBackCircleOutline size={50} color="#444" />
                    </BtnBack>
                    <TxtActualService>Adquirir</TxtActualService>
                </BoxBackZone>
                <LineServiceDetails>
                    <BoxTopMonth>
                        <BoxChangeMonth>
                            <IoIosArrowBack size="20" color="#1f61cf" />
                        </BoxChangeMonth>
                        <BoxAtualMonth>
                            <TxtMonth>Agosto 2022</TxtMonth>
                        </BoxAtualMonth>
                        <BoxChangeMonth>
                            <IoIosArrowForward size="20" color="#1f61cf" />
                        </BoxChangeMonth>
                    </BoxTopMonth>
                    <BoxDates>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                        <BoxDate>
                            <TxtDate>1 de Agosto de 2022</TxtDate>
                            <BoxMealTime>
                                <MealTimeTxt>Almoço</MealTimeTxt>
                            </BoxMealTime>
                            <BoxMealTime>
                                <MealTimeTxt>Jantar</MealTimeTxt>
                            </BoxMealTime>
                        </BoxDate>
                    </BoxDates>
                </LineServiceDetails>
            </MainContainer>

        </Container>
    );
}


来源: stackexchange

问:
why in laravel mutators i can't access to the model properties?
i'm in laravel 9, basically the code is:

class Body extends Model
{
    use HasFactory;

    [...]

    public function __construct()
    {
        $this->myvar = Cookie::get('myvar');
    }

    protected function manageEncryptedAttribute() : Attribute
    {
        echo "my output: ".$this->myvar;

        return Attribute::make(
            get: fn ($value) => $value,
            set: fn ($value) => $value,
        );
    }

    protected function height(): Attribute
    {
        return $this->manageEncryptedAttribute();
    }

    protected function weight(): Attribute
    {
        return $this->manageEncryptedAttribute();
    }
}
```

here where you see echo "my output: "..., the proprerties $this->myvar is empty. But if i try to print itself on the __construct the variable has his value correct. any clue on how to solve this?

I have tried a lot of changing on the code, but without any success.

ContentLicense: CC BY-SA 4.0

Body:
i'm in laravel 9, basically the code is:

class Body extends Model
{
    use HasFactory;

    [...]

    public function __construct()
    {
        $this->myvar = Cookie::get('myvar');
    }

    protected function manageEncryptedAttribute() : Attribute
    {
        echo "my output: ".$this->myvar;

        return Attribute::make(
            get: fn ($value) => $value,
            set: fn ($value) => $value,
        );
    }

    protected function height(): Attribute
    {
        return $this->manageEncryptedAttribute();
    }

    protected function weight(): Attribute
    {
        return $this->manageEncryptedAttribute();
    }
}

here where you see echo "my output: "..., the proprerties $this->myvar is empty. But if i try to print itself on the __construct the variable has his value correct. any clue on how to solve this?

I have tried a lot of changing on the code, but without any success.


问:
Have button fall inline after using dangerouslySetInnerHTML
I'm trying to make a show more/less product description in React using dangerouslySetInnerHTML. I'm able to get it to work, but I would like the button to be displayed inline with the rest of the content.

I can't use a pseudo element like :after because I need it to have an onClick event.

I also tried adding markup to the dangerouslySetInnerHTML by doing something like below, but again I run into issues with the onClick.

```<code>dangerouslySetInnerHTML={{__html: content + `<button onClick={toggleReadMore}>
                {isTruncatedText ? readMore : readLess}
              </button>`
</code>```

I thought by wrapping each piece of content in spans I could make them be inline, but that doesn't work either.

```<code>import {useState} from 'react'

interface IProductDescription {
  content: string
  readMore: string
  readLess: string
}
export function ProductDescription({
  content,
  readMore,
  readLess,
}: IProductDescription) {
  const [isTruncatedText, setIsTruncatedText] = useState(true)
  const toggleReadMore = () => setIsTruncatedText(!isTruncatedText)

  return (
    <>
      <div>
        <span
          dangerouslySetInnerHTML={{__html: content}}
          className={`transition-all text-body  text-clip ${
            isTruncatedText ? 'line-clamp-5' : ''
          }`}
        ></span>
        <span>
          <button onClick={toggleReadMore}>
            {isTruncatedText ? readMore : readLess}
          </button>
        </span>
      </div>
    </>
  )
}
</code>```

Body:
I'm trying to make a show more/less product description in React using dangerouslySetInnerHTML. I'm able to get it to work, but I would like the button to be displayed inline with the rest of the content.

I can't use a pseudo element like :after because I need it to have an onClick event.

I also tried adding markup to the dangerouslySetInnerHTML by doing something like below, but again I run into issues with the onClick.

dangerouslySetInnerHTML={{__html: content + `<button onClick={toggleReadMore}>
                {isTruncatedText ? readMore : readLess}
              </button>`

I thought by wrapping each piece of content in spans I could make them be inline, but that doesn't work either.

import {useState} from 'react'

interface IProductDescription {
  content: string
  readMore: string
  readLess: string
}
export function ProductDescription({
  content,
  readMore,
  readLess,
}: IProductDescription) {
  const [isTruncatedText, setIsTruncatedText] = useState(true)
  const toggleReadMore = () => setIsTruncatedText(!isTruncatedText)

  return (
    <>

          <button onClick={toggleReadMore}>
            {isTruncatedText ? readMore : readLess}
          </button>

    </>
  )
}


问:
What is the original of typing.d.ts?
I understand this is a Typescript definition file, but what's the file's origin?
I watched a guy doing a coding video create a type in this file, which then made it available everywhere without importing it (the type).

Does one have to use the filename typings.d.ts for this, or does Typescript autodetect any *.d.ts file?

There's little documentation available on it and I'm having trouble understanding when I can use the file.

Title: What is the original of typing.d.ts?


问:
Linking tpop with wix, automatic dropshipping
I have been designing a webshop, where whenever a customer buys something, address and stuff will be transmitted, but where i have to put it all in manually.
Wordpress has this thing called velo, a javascript frameworks which works with the service.
Is there anyone who had the same or a simular problem and came with a solution for it?

any help would be appreciated.


问:
How to evaluate JavaScript rendering outcome within Python environment?
I have some JavaScript and HTML code as can be seen below. When I view this code in the browser it neatly shows 155.248.238.2:3128, however, I can't get the 3128 part translated into my Python script. I have tried to use the js2py library with the eval_js function but can't get it to work in any way.

```<code><script type="text/javascript">h8q7=8546;v2b2=9534;z6l2=1976;w3s9=7278;j0f6=9654;k1o5=9732;n4k1=5329;r8e5=2801;c3h8=2013;d4n4=4497;c3c3d4=0^h8q7;g7a1p6=1^v2b2;t0l2c3=2^z6l2;b2z6t0=3^w3s9;o5v2j0=4^j0f6;m3w3r8=5^k1o5;x4t0h8=6^n4k1;p6i9x4=7^r8e5;j0u1v2=8^c3h8;z6b2m3=9^d4n4;</script>

<font class="spy14">155.248.238.2<script type="text/javascript">document.write("<font class=spy2>:<\/font>"+(b2z6t0^w3s9)+(g7a1p6^v2b2)+(t0l2c3^z6l2)+(j0u1v2^c3h8))</script></font>
</code>```

Example of tried solution:

```<code>import js2py

js = '\nh8q7=8546;v2b2=9534;z6l2=1976;w3s9=7278;j0f6=9654;k1o5=9732;n4k1=5329;r8e5=2801;c3h8=2013;d4n4=4497;c3c3d4=0^h8q7;g7a1p6=1^v2b2;t0l2c3=2^z6l2;b2z6t0=3^w3s9;o5v2j0=4^j0f6;m3w3r8=5^k1o5;x4t0h8=6^n4k1;p6i9x4=7^r8e5;j0u1v2=8^c3h8;z6b2m3=9^d4n4;\n    }\n}\ndocument.write("<font class=spy2>:<\\/font>"+(b2z6t0^w3s9)+(g7a1p6^v2b2)+(t0l2c3^z6l2)+(j0u1v2^c3h8))'

context = js2py.EvalJs()
context.execute(js)
print(context.output)
KeyError                                  Traceback (most recent call last)
File ~/scraper/lib/python3.9/site-packages/js2py/evaljs.py:193, in EvalJs.execute(self, js, use_compilation_plan)
    192 try:
--> 193     compiled = cache[hashkey]
IndexError: list index out of range
</code>```

Body:
I have some JavaScript and HTML code as can be seen below. When I view this code in the browser it neatly shows 155.248.238.2:3128, however, I can't get the 3128 part translated into my Python script. I have tried to use the js2py library with the eval_js function but can't get it to work in any way.

155.248.238.2

Example of tried solution:

import js2py

js = '\nh8q7=8546;v2b2=9534;z6l2=1976;w3s9=7278;j0f6=9654;k1o5=9732;n4k1=5329;r8e5=2801;c3h8=2013;d4n4=4497;c3c3d4=0^h8q7;g7a1p6=1^v2b2;t0l2c3=2^z6l2;b2z6t0=3^w3s9;o5v2j0=4^j0f6;m3w3r8=5^k1o5;x4t0h8=6^n4k1;p6i9x4=7^r8e5;j0u1v2=8^c3h8;z6b2m3=9^d4n4;\n    }\n}\ndocument.write(":<\\/font>"+(b2z6t0^w3s9)+(g7a1p6^v2b2)+(t0l2c3^z6l2)+(j0u1v2^c3h8))'

context = js2py.EvalJs()
context.execute(js)
print(context.output)
KeyError                                  Traceback (most recent call last)
File ~/scraper/lib/python3.9/site-packages/js2py/evaljs.py:193, in EvalJs.execute(self, js, use_compilation_plan)
    192 try:
--> 193     compiled = cache[hashkey]
IndexError: list index out of range


问:
dynamically interpret job ids and run specific python files given a environment variable
I have a project that contains many automation-like scripts in a "jobs/" folder. The jobs can run on either a trigger or on a CRON like basis. Each job is separated in a python script in the "jobs/" folder. Each python script has a unique JOB_ID set as a variable. There can be many, many, jobs in the  "jobs/" folder.

What I want to do is create a driver script which checks each file in the jobs folder for its job id, compares them against an environment variable which indicates which job(s) to run, and execute them in order. I want to achieve this without creating a hardcoded map in the driver script:

#example job file in the "/jobs" folder:

JOB_ID = 2
JOBCONFIG = json.loads(os.environ.get(
    "GITLAB_JOB_CONFIG", "{}")).get(JOB_ID, {})

if __name__ == "__main__":
  #execution stuffs

```
<pre class="lang-py prettyprint-override"><code>#Driver File:

if __name__ == "__main__":
    jobs = json.loads(os.environ.get(
    "GITLAB_JOB_CONFIG", "{}"))
    if not jobs:
        sys.exit(1)
    for key in jobs:
        os.system("#run the corresponding job")
</code>```

Is there a way to infer the job ids from the python scripts in the "jobs/" folder without importing/mapping? All the jobs will always be in that folder and will always have a job id in the file.

Body:
I have a project that contains many automation-like scripts in a "jobs/" folder. The jobs can run on either a trigger or on a CRON like basis. Each job is separated in a python script in the "jobs/" folder. Each python script has a unique JOB_ID set as a variable. There can be many, many, jobs in the  "jobs/" folder.

What I want to do is create a driver script which checks each file in the jobs folder for its job id, compares them against an environment variable which indicates which job(s) to run, and execute them in order. I want to achieve this without creating a hardcoded map in the driver script:

#example job file in the "/jobs" folder:

JOB_ID = 2
JOBCONFIG = json.loads(os.environ.get(
    "GITLAB_JOB_CONFIG", "{}")).get(JOB_ID, {})

if __name__ == "__main__":
  #execution stuffs

#Driver File:

if __name__ == "__main__":
    jobs = json.loads(os.environ.get(
    "GITLAB_JOB_CONFIG", "{}"))
    if not jobs:
        sys.exit(1)
    for key in jobs:
        os.system("#run the corresponding job")

Is there a way to infer the job ids from the python scripts in the "jobs/" folder without importing/mapping? All the jobs will always be in that folder and will always have a job id in the file.


问:
Plot grouped barplots of averages of 2 columns for each category
I have a .CSV that has 1 column with categorical data and 2 columns with numerical data. I want to create a barplot that has the average of column 2 and the average of column 3 plotted side by side for each category in column 1.

Example data:

```<code>data = [
    ['Bananas', 1, 5],
    ['Apple', 4, 2],
    ['Bananas', 2, 5],
    ['Oranges', 3, 6],
    ['Apple', 4, 2],
    ['Apple', 2, 5],
    ['Oranges', 1, 2],
    ['Apple', 5, 5],
    ['Oranges', 6, 1]
]

df = pd.DataFrame(data, columns=['Column1', 'Column2', 'Column3'])
df.Column2.astype(float)
df.Column3.astype(float)
df
</code>```

I am able to do a single bar plots just fine and swap out Column2 and Column3.

```<code>df = df.sort_values(by='Column1')
plt.figure(figsize=(30,16))
p = sns.barplot(x="Column1", y="Column2", data=df, errorbar=('ci', False), palette="tab20")
plt.xticks(fontsize=14)
plt.yticks(fontsize=20)
plt.bar_label(p.containers[0],size=18,fmt="%.2f")
</code>```

However, I'm having trouble plotting both Column2 and Column3 on the same graph. I tried the same as above, but subbing in " y1="Column2", y2="Column3" " but get a "Horizontal orientation requires numeric x variable." TypeError.
I've also tried using hue

```<code>df = df.sort_values(by='Column1')
plt.figure(figsize=(30,16))
p = sns.barplot(x="Column1", y="Column2", hue="Column3", data=df, errorbar=('ci', False), palette="tab20")
plt.xticks(fontsize=14)
plt.yticks(fontsize=20)
plt.bar_label(p.containers[0],size=18,fmt="%.2f")
</code>```

but the barplot is very messed up, the averages aren't calculated right and the bar labels only show up on one bar.

I've recreated what I was looking for in Excel with the sample data. Ideally, I'd want both bars to be the same color for each fruit too.

Update:
I've got it plotted correctly now

```<code>dfm = df.melt(id_vars=["Column1"], var_name="Test1", value_name="Test2")
plt.figure(figsize=(30,16))
p=sns.barplot(data=dfm, x="Column1", y="Test2", hue="Test1", palette="tab20", errorbar=('ci', False))
plt.xticks(fontsize=14)
plt.yticks(fontsize=20)
plt.legend([],[], frameon=False)
for p in p.containers:
    plt.bar_label(p, fmt='%.2f', label_type='edge', padding=1, fontsize=20)
</code>```

However, I'm still struggling to get each category a unique color while keeping the grouped bars the same color.

Body:
I have a .CSV that has 1 column with categorical data and 2 columns with numerical data. I want to create a barplot that has the average of column 2 and the average of column 3 plotted side by side for each category in column 1.

Example data:

data = [
    ['Bananas', 1, 5],
    ['Apple', 4, 2],
    ['Bananas', 2, 5],
    ['Oranges', 3, 6],
    ['Apple', 4, 2],
    ['Apple', 2, 5],
    ['Oranges', 1, 2],
    ['Apple', 5, 5],
    ['Oranges', 6, 1]
]

df = pd.DataFrame(data, columns=['Column1', 'Column2', 'Column3'])
df.Column2.astype(float)
df.Column3.astype(float)
df

I am able to do a single bar plots just fine and swap out Column2 and Column3.

df = df.sort_values(by='Column1')
plt.figure(figsize=(30,16))
p = sns.barplot(x="Column1", y="Column2", data=df, errorbar=('ci', False), palette="tab20")
plt.xticks(fontsize=14)
plt.yticks(fontsize=20)
plt.bar_label(p.containers[0],size=18,fmt="%.2f")

However, I'm having trouble plotting both Column2 and Column3 on the same graph. I tried the same as above, but subbing in " y1="Column2", y2="Column3" " but get a "Horizontal orientation requires numeric x variable." TypeError.
I've also tried using hue

df = df.sort_values(by='Column1')
plt.figure(figsize=(30,16))
p = sns.barplot(x="Column1", y="Column2", hue="Column3", data=df, errorbar=('ci', False), palette="tab20")
plt.xticks(fontsize=14)
plt.yticks(fontsize=20)
plt.bar_label(p.containers[0],size=18,fmt="%.2f")

but the barplot is very messed up, the averages aren't calculated right and the bar labels only show up on one bar.

I've recreated what I was looking for in Excel with the sample data. Ideally, I'd want both bars to be the same color for each fruit too.

Update:
I've got it plotted correctly now

dfm = df.melt(id_vars=["Column1"], var_name="Test1", value_name="Test2")
plt.figure(figsize=(30,16))
p=sns.barplot(data=dfm, x="Column1", y="Test2", hue="Test1", palette="tab20", errorbar=('ci', False))
plt.xticks(fontsize=14)
plt.yticks(fontsize=20)
plt.legend([],[], frameon=False)
for p in p.containers:
    plt.bar_label(p, fmt='%.2f', label_type='edge', padding=1, fontsize=20)

However, I'm still struggling to get each category a unique color while keeping the grouped bars the same color.


问:
How to update state in React to equal an array
https://stackblitz.com/edit/react-kgbnnd?file=src/App.js

I've created a demo of my problem above.

I'm trying to update state based on an array that changes when user clicks check-boxes. I'm trying to filter the products shown on an online store page.

The array is updating correctly, but as I try to update state it doesn't work - the array always holds one value only.

If I dont use setCategories(selectedCategories) the issue does not occur. Any idea how I can successfully update my state?

```<code>import React, {useState} from "react";
import "./style.css";

export default function App() {
  const [categories, setCategories] = useState([])
  let selectedCategories = []

  const data = [{
    id: 1,
    value: 1,
    title: "Shoes",
  },
  {
    id: 2,
    value: 2,
    title: "Hats",
  },
  {
    id: 3,
    value: 3,
    title: "Pants",
  },
  {
    id: 4,
    value: 4,
    title: "Shirts",
  },]

  const removeCategory = (arr, value) => {
    let index = arr.indexOf(value)
    if (index > -1) {
      arr.splice(index, 1)
    }
    return arr
  }

  const handleChange = (e) => {
    const value = e.target.value
    const isChecked = e.target.checked

    isChecked
      ? selectedCategories.push(value)
      : removeCategory(selectedCategories, value)

    setCategories(selectedCategories)
  }

  return (
    <div>
       <h2>Categories</h2>
          {data?.map((item) => (
            <div className="inputItem" key={item.id}>
              <input
                type="checkbox"
                id={item.id}
                value={item.id}
                onChange={handleChange}
              />
              <label htmlFor={item.id}>{item.title}</label>
            </div>
          ))}
    </div>
  );
}
</code>```

Body:
https://stackblitz.com/edit/react-kgbnnd?file=src/App.js

I've created a demo of my problem above.

I'm trying to update state based on an array that changes when user clicks check-boxes. I'm trying to filter the products shown on an online store page.

The array is updating correctly, but as I try to update state it doesn't work - the array always holds one value only.

If I dont use setCategories(selectedCategories) the issue does not occur. Any idea how I can successfully update my state?

import React, {useState} from "react";
import "./style.css";

export default function App() {
  const [categories, setCategories] = useState([])
  let selectedCategories = []

  const data = [{
    id: 1,
    value: 1,
    title: "Shoes",
  },
  {
    id: 2,
    value: 2,
    title: "Hats",
  },
  {
    id: 3,
    value: 3,
    title: "Pants",
  },
  {
    id: 4,
    value: 4,
    title: "Shirts",
  },]

  const removeCategory = (arr, value) => {
    let index = arr.indexOf(value)
    if (index > -1) {
      arr.splice(index, 1)
    }
    return arr
  }

  const handleChange = (e) => {
    const value = e.target.value
    const isChecked = e.target.checked

    isChecked
      ? selectedCategories.push(value)
      : removeCategory(selectedCategories, value)

    setCategories(selectedCategories)
  }

  return (

Categories

          {data?.map((item) => (

              <input
                type="checkbox"
                id={item.id}
                value={item.id}
                onChange={handleChange}
              />
              {item.title}

          ))}

  );
}


问:
Track mouse movements only on X axis for a certain number of pixels (right direction)
I want to be able to have my computer detect when I highlight text on my screen (or I guess when I move the mouse a certain distance in the x axis).

I also want my computer to know that I'm holding down a key, this way I do not misfire a bunch of times moving the cursor around.

I'm trying to put this all to an if statement.

I tried to make the mouse move but im unsure how to tell Python to only focus on the x axis and a certain amount of pixels going right before the if statement triggers another action! Please see the ("Do first action"), ("Do second action") , etc

```<code>savedpos = (pyautogui.position())
while(True):

    curpos = (pyautogui.position())
    if savedpos != curpos:
        savedpos = curpos
</code>```

I want to do something like:

```<code>my_switch=0
global my_switch
my_switch = my_switch % 3
if savedpos != curpos and my_switch == 0:
    print("Do first action")
    my_switch += 1

elif (event.char) == '3' and my_switch == 1:
     print("Do second action")
     my_switch += 1

elif (event.char) == '3' and my_switch == 2:
    print("Do third action")
    my_switch += 1
</code>```

I want python to know when I move my mouse right or left in a straight line on x axis if: 1# did the mouse move right a certain number of pixels #2 was something copied to the clipboard?

I tried to make the mouse move but im unsure how to tell Python to only focus on the x axis and a certain amount of pixels going right before the if statement triggers another action! Please see the ("Do first action"), ("Do second action") , etc

Body:
I want to be able to have my computer detect when I highlight text on my screen (or I guess when I move the mouse a certain distance in the x axis).

I also want my computer to know that I'm holding down a key, this way I do not misfire a bunch of times moving the cursor around.

I'm trying to put this all to an if statement.

I tried to make the mouse move but im unsure how to tell Python to only focus on the x axis and a certain amount of pixels going right before the if statement triggers another action! Please see the ("Do first action"), ("Do second action") , etc

savedpos = (pyautogui.position())
while(True):

    curpos = (pyautogui.position())
    if savedpos != curpos:
        savedpos = curpos

I want to do something like:

my_switch=0
global my_switch
my_switch = my_switch % 3
if savedpos != curpos and my_switch == 0:
    print("Do first action")
    my_switch += 1

elif (event.char) == '3' and my_switch == 1:
     print("Do second action")
     my_switch += 1

elif (event.char) == '3' and my_switch == 2:
    print("Do third action")
    my_switch += 1

I want python to know when I move my mouse right or left in a straight line on x axis if: 1# did the mouse move right a certain number of pixels #2 was something copied to the clipboard?

I tried to make the mouse move but im unsure how to tell Python to only focus on the x axis and a certain amount of pixels going right before the if statement triggers another action! Please see the ("Do first action"), ("Do second action") , etc


问:
Query and {JSON]

While using BigQuery's Console, we were instructed to input some data.

The following example was used for guidance

```<code>SELECT * FROM `bigquery-public-data.new_york_citibike.citibike_trips`
</code>```

Afterward, I ran the query as instructed and removed the LIMIT clause.

The [JSON] results produced this information ...

```<code>[{
    "tripduration": "2083",
    "starttime": "2016-04-18T13:02:24",
    "stoptime": "2016-04-18T13:37:08",
    "start_station_id": "417",
    "start_station_name": "Barclay St \\u0026 Church St",
    "start_station_latitude": "40.71291224",
    "start_station_longitude": "-74.01020234",
    "end_station_id": "309",
    "end_station_name": "Murray St \\u0026 West St",
    "end_station_latitude": "40.7149787",
    "end_station_longitude": "-74.013012",
    "bikeid": "23641",
    "usertype": "Subscriber",
    "birth_year": "1945",
    "gender": "male",
    "customer_plan": ""
},]
</code>```

Some of the results were deleted (TRIM).

I attempted to locate the longest ride on the citibikes and the shortest ride as well. (In terms of distance).

I didn't calibrate the information correctly. Therefore, I didn't receive any response for this calculation.

[JSON] is a query result-based language, will it create the same response each time it's used for public datasets?

Title: Query and {JSON]

Body:
While using BigQuery's Console, we were instructed to input some data.

The following example was used for guidance

SELECT * FROM `bigquery-public-data.new_york_citibike.citibike_trips`

Afterward, I ran the query as instructed and removed the LIMIT clause.

The [JSON] results produced this information ...

[{
    "tripduration": "2083",
    "starttime": "2016-04-18T13:02:24",
    "stoptime": "2016-04-18T13:37:08",
    "start_station_id": "417",
    "start_station_name": "Barclay St \\u0026 Church St",
    "start_station_latitude": "40.71291224",
    "start_station_longitude": "-74.01020234",
    "end_station_id": "309",
    "end_station_name": "Murray St \\u0026 West St",
    "end_station_latitude": "40.7149787",
    "end_station_longitude": "-74.013012",
    "bikeid": "23641",
    "usertype": "Subscriber",
    "birth_year": "1945",
    "gender": "male",
    "customer_plan": ""
},]

Some of the results were deleted (TRIM).

I attempted to locate the longest ride on the citibikes and the shortest ride as well. (In terms of distance).

I didn't calibrate the information correctly. Therefore, I didn't receive any response for this calculation.

[JSON] is a query result-based language, will it create the same response each time it's used for public datasets?


问:
Inconsistent behaviour of GregorianCalendar when created from ZonedDateTime
I'm writing some integration of legacy code that expects date/time as a GregorianCalendar.

So, I'm creating the GregorianCalendar using from(ZonedDateTime) method.

However, the result is showing some inconsistent behaviour when the GregorianCalendar is created from the ZonedDateTime versus when the GregorianCalendar is created, let's say, from a string parsing or even from epoch millis. For example, when setting the Calendar day_of_week. To demonstrate this (https://onecompiler.com/java/3yssz4q86):

```<code>import java.util.*;
import java.time.*;

public class Main {
  public static void main(String[] args) {
    final GregorianCalendar calendarPure = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
    printInfo(calendarPure);

    ZoneId zone = ZoneId.of("America/Los_Angeles");
    final ZonedDateTime zdtNow = ZonedDateTime.now(zone);

    final GregorianCalendar calendarFromZdt = GregorianCalendar.from(zdtNow);
    printInfo(calendarFromZdt);

    final GregorianCalendar calendarFromZdtEpoch = new GregorianCalendar();
    calendarFromZdtEpoch.setTimeInMillis(zdtNow.toInstant().toEpochMilli());

    printInfo(calendarFromZdtEpoch);
  }

  private static void printInfo(GregorianCalendar cal) {
    System.out.printf("Now: %tc%n", cal);
    System.out.printf("Last Sunday: %tc%n", getLastSunday(cal));
    System.out.printf("Week of Year: %d%n", cal.get(Calendar.WEEK_OF_YEAR));
    System.out.printf("Time in Millis: %d%n", cal.getTimeInMillis());
    System.out.printf("toString(): %s%n", cal);
    System.out.println();
  }

  public static GregorianCalendar getLastSunday(GregorianCalendar referenceDate) {
    final GregorianCalendar lastSundayMidNight = (GregorianCalendar)referenceDate.clone();
    lastSundayMidNight.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    return lastSundayMidNight;
  }

}
</code>```

The output is:

```<code>Now: Wed Dec 28 16:45:36 PST 2022
Last Sunday: Sun Dec 25 16:45:36 PST 2022
Week of Year: 53
Time in Millis: 1672274736631
toString(): java.util.GregorianCalendar[time=1672274736631,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=11,WEEK_OF_YEAR=53,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=362,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=45,SECOND=36,MILLISECOND=631,ZONE_OFFSET=-28800000,DST_OFFSET=0]

Now: Wed Dec 28 16:45:36 PST 2022
Last Sunday: Sun Jan 01 16:45:36 PST 2023
Week of Year: 52
Time in Millis: 1672274736668
toString(): java.util.GregorianCalendar[time=1672274736668,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2022,MONTH=11,WEEK_OF_YEAR=52,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=362,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=45,SECOND=36,MILLISECOND=668,ZONE_OFFSET=-28800000,DST_OFFSET=0]

Now: Thu Dec 29 00:45:36 UTC 2022
Last Sunday: Sun Dec 25 00:45:36 UTC 2022
Week of Year: 53
Time in Millis: 1672274736668
toString(): java.util.GregorianCalendar[time=1672274736668,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Etc/UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=11,WEEK_OF_YEAR=53,WEEK_OF_MONTH=5,DAY_OF_MONTH=29,DAY_OF_YEAR=363,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=5,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=45,SECOND=36,MILLISECOND=668,ZONE_OFFSET=0,DST_OFFSET=0]
</code>```

I noticed that, from GregorianCalendar.toString() that prints the internal fields a different in firstDayOfWeek and minimalDaysInFirstWeek. That could be the cause for the divergence in the after results. I wonder where the GregorianCalendar is getting these values from. Maybe there is a way to set something on ZonedDateTime object that will ensure the results will be the same? Couldn't find anything on javadocs.

Note: Please, don't tell me not to use GregorianCalendar. I know, I know. I'm just writing an integration for two pieces of code that I'm not allowed to modify, one uses GregorianCalendar (sigh), the other uses ZonedDateTime.

Body:
I'm writing some integration of legacy code that expects date/time as a GregorianCalendar.

So, I'm creating the GregorianCalendar using from(ZonedDateTime) method.

However, the result is showing some inconsistent behaviour when the GregorianCalendar is created from the ZonedDateTime versus when the GregorianCalendar is created, let's say, from a string parsing or even from epoch millis. For example, when setting the Calendar day_of_week. To demonstrate this (https://onecompiler.com/java/3yssz4q86):

import java.util.*;
import java.time.*;

public class Main {
  public static void main(String[] args) {
    final GregorianCalendar calendarPure = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
    printInfo(calendarPure);

    ZoneId zone = ZoneId.of("America/Los_Angeles");
    final ZonedDateTime zdtNow = ZonedDateTime.now(zone);

    final GregorianCalendar calendarFromZdt = GregorianCalendar.from(zdtNow);
    printInfo(calendarFromZdt);

    final GregorianCalendar calendarFromZdtEpoch = new GregorianCalendar();
    calendarFromZdtEpoch.setTimeInMillis(zdtNow.toInstant().toEpochMilli());

    printInfo(calendarFromZdtEpoch);
  }

  private static void printInfo(GregorianCalendar cal) {
    System.out.printf("Now: %tc%n", cal);
    System.out.printf("Last Sunday: %tc%n", getLastSunday(cal));
    System.out.printf("Week of Year: %d%n", cal.get(Calendar.WEEK_OF_YEAR));
    System.out.printf("Time in Millis: %d%n", cal.getTimeInMillis());
    System.out.printf("toString(): %s%n", cal);
    System.out.println();
  }

  public static GregorianCalendar getLastSunday(GregorianCalendar referenceDate) {
    final GregorianCalendar lastSundayMidNight = (GregorianCalendar)referenceDate.clone();
    lastSundayMidNight.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    return lastSundayMidNight;
  }

}

The output is:

Now: Wed Dec 28 16:45:36 PST 2022
Last Sunday: Sun Dec 25 16:45:36 PST 2022
Week of Year: 53
Time in Millis: 1672274736631
toString(): java.util.GregorianCalendar[time=1672274736631,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=11,WEEK_OF_YEAR=53,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=362,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=45,SECOND=36,MILLISECOND=631,ZONE_OFFSET=-28800000,DST_OFFSET=0]

Now: Wed Dec 28 16:45:36 PST 2022
Last Sunday: Sun Jan 01 16:45:36 PST 2023
Week of Year: 52
Time in Millis: 1672274736668
toString(): java.util.GregorianCalendar[time=1672274736668,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2022,MONTH=11,WEEK_OF_YEAR=52,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=362,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=45,SECOND=36,MILLISECOND=668,ZONE_OFFSET=-28800000,DST_OFFSET=0]

Now: Thu Dec 29 00:45:36 UTC 2022
Last Sunday: Sun Dec 25 00:45:36 UTC 2022
Week of Year: 53
Time in Millis: 1672274736668
toString(): java.util.GregorianCalendar[time=1672274736668,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Etc/UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=11,WEEK_OF_YEAR=53,WEEK_OF_MONTH=5,DAY_OF_MONTH=29,DAY_OF_YEAR=363,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=5,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=45,SECOND=36,MILLISECOND=668,ZONE_OFFSET=0,DST_OFFSET=0]

I noticed that, from GregorianCalendar.toString() that prints the internal fields a different in firstDayOfWeek and minimalDaysInFirstWeek. That could be the cause for the divergence in the after results. I wonder where the GregorianCalendar is getting these values from. Maybe there is a way to set something on ZonedDateTime object that will ensure the results will be the same? Couldn't find anything on javadocs.

Note: Please, don't tell me not to use GregorianCalendar. I know, I know. I'm just writing an integration for two pieces of code that I'm not allowed to modify, one uses GregorianCalendar (sigh), the other uses ZonedDateTime.


问:
Django pic app code explanation, not sure why this works
so i was trying to follow along dr Chuck's Django course. In the pics app

```<code>def post(self, request, pk=None):
    form = CreateForm(request.POST, request.FILES or None)

pic = form.save(commit=False)

</code>```
```<code>def save(self, commit=True):
    instance = super(CreateForm, self).save(commit=False)

    # We only need to adjust picture if it is a freshly uploaded file
    f = instance.picture  # Make a copy
    if isinstance(f, InMemoryUploadedFile):  # Extract data from the form to the model
        bytearr = f.read()
        instance.content_type = f.content_type
        instance.picture = bytearr
</code>```

So my confusion is, instance is a model object and picture attribute in model is a binaryfiled, but in form its a FileField. So for new entry f = instance.picture, should always return null, as there is nothing in database yet. I get that 'subject' and 'text' will be retrieved when i call super as these are similar for both model and form, but instance should not have picture yet. And if it does, than this must always be true "if isinstance(f, InMemoryUploadedFile)". I know this code works perfectly, i just don't understand how.

I appreciate any help.

Form.py

```<code>class CreateForm(forms.ModelForm):
    max_upload_limit = 2 * 1024 * 1024
    max_upload_limit_text = naturalsize(max_upload_limit)

    # Call this 'picture' so it gets copied from the form to the in-memory model
    # It will not be the "bytes", it will be the "InMemoryUploadedFile"
    # because we need to pull out things like content_type
    picture = forms.FileField(required=False, label='File to Upload <= ' + max_upload_limit_text)
    upload_field_name = 'picture'

    # Hint: this will need to be changed for use in the ads application :)
    class Meta:
        model = article
        fields = ['subject', 'text', 'picture']
</code>```

Models.py

```<code>picture = models.BinaryField(null=True, blank=True, editable=True)
content_type = models.CharField(max_length=256, null=True, blank=True, help_text='The MIMEType of the file')
</code>```

I tried using f = request.FILES['picture'], but this did not work, but i just want to understand why code in course worked

Body:
so i was trying to follow along dr Chuck's Django course. In the pics app

def post(self, request, pk=None):
    form = CreateForm(request.POST, request.FILES or None)

pic = form.save(commit=False)

def save(self, commit=True):
    instance = super(CreateForm, self).save(commit=False)

    # We only need to adjust picture if it is a freshly uploaded file
    f = instance.picture  # Make a copy
    if isinstance(f, InMemoryUploadedFile):  # Extract data from the form to the model
        bytearr = f.read()
        instance.content_type = f.content_type
        instance.picture = bytearr

So my confusion is, instance is a model object and picture attribute in model is a binaryfiled, but in form its a FileField. So for new entry f = instance.picture, should always return null, as there is nothing in database yet. I get that 'subject' and 'text' will be retrieved when i call super as these are similar for both model and form, but instance should not have picture yet. And if it does, than this must always be true "if isinstance(f, InMemoryUploadedFile)". I know this code works perfectly, i just don't understand how.

I appreciate any help.

Form.py

class CreateForm(forms.ModelForm):
    max_upload_limit = 2 * 1024 * 1024
    max_upload_limit_text = naturalsize(max_upload_limit)

    # Call this 'picture' so it gets copied from the form to the in-memory model
    # It will not be the "bytes", it will be the "InMemoryUploadedFile"
    # because we need to pull out things like content_type
    picture = forms.FileField(required=False, label='File to Upload <= ' + max_upload_limit_text)
    upload_field_name = 'picture'

    # Hint: this will need to be changed for use in the ads application :)
    class Meta:
        model = article
        fields = ['subject', 'text', 'picture']

Models.py

picture = models.BinaryField(null=True, blank=True, editable=True)
content_type = models.CharField(max_length=256, null=True, blank=True, help_text='The MIMEType of the file')

I tried using f = request.FILES['picture'], but this did not work, but i just want to understand why code in course worked


问:
Problem accessing a route that has no parameter in Laravel 8
I have a problem accessing my route, I have a "pedidos" view where it contains some information, features and links. In one of these links I have a href with the route "pedidos.imports", every time I click on this link the route gives me an error. The route has already been created, the view too and I have the function in my controller. The only solution I found was to change the order of the routes, but that doesn't seem like the best thing to do. It could be a trivial error, but I can't solve it, even though I've already worked with several errors throughout my project.

Here's the error:

```<code>App\Http\Controllers\ReserveController::show(): Argument #1 ($id) must be of type int, string given, called in
C:\xampp\htdocs\ApLabRequest\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54
</code>```

Link:

```<code><a style="font-size: 20px;" href="{{route('pedidos.imports')}}" class="btn btn-info form-control">
 <i class="fas fa-upload"></i>
 Importar
</a>
</code>```

Route:

```<code>Route::resource('pedidos', ReserveController::class)->middleware('auth');
Route::get('pedidos/imports', [ReserveController::class, 'imports'])->name('pedidos.imports')->middleware('auth');
</code>```

Controller:

```<code>public function imports()
{
    $deeps = Deep::get();
    $clients = Client::with('properties')->orderBy('name')->get();
    $kinds = Kind::get();
    $materials = Material::get();
    $cultures = Culture::get();
    $paymentMethods = PaymentMethod::get();
    return view('reserves.imports', compact('deeps', 'clients', 'kinds', 'materials', 'cultures', 'paymentMethods'));
}
</code>```

"Solution" I found:

```<code>Route::get('pedidos/imports', [ReserveController::class, 'imports'])->name('pedidos.imports')->middleware('auth');
Route::resource('pedidos', ReserveController::class)->middleware('auth');
</code>```

One thing I realized is that all the routes I created so far had some parameter, but in this new route I don't need a parameter and it doesn't even make sense to have it (for me). Summarizing what I'm trying to implement, this route returns a view where I will import an excel file and save these values in the database.

Body:
I have a problem accessing my route, I have a "pedidos" view where it contains some information, features and links. In one of these links I have a href with the route "pedidos.imports", every time I click on this link the route gives me an error. The route has already been created, the view too and I have the function in my controller. The only solution I found was to change the order of the routes, but that doesn't seem like the best thing to do. It could be a trivial error, but I can't solve it, even though I've already worked with several errors throughout my project.

Here's the error:

App\Http\Controllers\ReserveController::show(): Argument #1 ($id) must be of type int, string given, called in
C:\xampp\htdocs\ApLabRequest\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54

Link:

 Importar

Route:

Route::resource('pedidos', ReserveController::class)->middleware('auth');
Route::get('pedidos/imports', [ReserveController::class, 'imports'])->name('pedidos.imports')->middleware('auth');

Controller:

public function imports()
{
    $deeps = Deep::get();
    $clients = Client::with('properties')->orderBy('name')->get();
    $kinds = Kind::get();
    $materials = Material::get();
    $cultures = Culture::get();
    $paymentMethods = PaymentMethod::get();
    return view('reserves.imports', compact('deeps', 'clients', 'kinds', 'materials', 'cultures', 'paymentMethods'));
}

"Solution" I found:

Route::get('pedidos/imports', [ReserveController::class, 'imports'])->name('pedidos.imports')->middleware('auth');
Route::resource('pedidos', ReserveController::class)->middleware('auth');

One thing I realized is that all the routes I created so far had some parameter, but in this new route I don't need a parameter and it doesn't even make sense to have it (for me). Summarizing what I'm trying to implement, this route returns a view where I will import an excel file and save these values in the database.


问:
uncaught exit normal && crash affecting parent process Elixir
As a result of the GraphQL request, some DB operations are being done within the Phoenix application, and during those operations, I started a gen server this way,

```<code>  def start_fingerprint_fraud_check(customer_identity) do
    id = process_name("customer_identity-" <> "#{customer_identity.id}")

    General.Supervisor.start_child(NectarineCredit.Risk.IdentityCheck, %{
      id: id,
      ref: nil,
      type: :worker
    })
    |> case do
      {:ok, _pid} ->
        GenServer.call(id, {:validate_customer_identity_fraud, customer_identity})

      {:error, {:already_started, _pid}} ->
        Logger.debug(
          "Identity fraud check is already running for this customer: #{
            customer_identity.customer_id
          }"
        )

        GenServer.call(id, {:validate_customer_identity_fraud, customer_identity})
    end
  end
</code>```

and In gen server.

```<code>defmodule NectarineCredit.Risk.IdentityCheck do
  @moduledoc false

  use GenServer, restart: :temporary

  require Logger

  def start_link(opts) do
    GenServer.start_link(__MODULE__, opts, name: opts.id)
  end

  def init(opts) do
    {:ok, opts}
  end

  def handle_call(
        {:validate_customer_identity_fraud, _customer_identity},
        _from,
        %{ref: ref} = state
      )
      when is_reference(ref) do
    {:reply, :ok, state}
  end

  def handle_call(
        {:validate_customer_identity_fraud, customer_identity},
        _from,
        %{ref: nil} = state
      ) do
    task =
      Task.Supervisor.async_nolink(NectarineCredit.TaskSupervisor, fn ->
        #stuff
      end)

    # We return :ok and the server will continue running
    {:reply, :ok, %{state | ref: task.ref}}
  end

  # The task completed successfully
  def handle_info({ref, answer}, %{ref: ref} = state) do
    Process.demonitor(ref, [:flush])
    {:stop, :normal, %{state | ref: nil}}
  end

  # The task failed
  def handle_info({:DOWN, ref, :process, _pid, reason}, %{ref: ref} = state) do
    {:stop, :shutdown, %{state | ref: nil}}
  end

  def terminate(exit_state, _state) do
    Logger.debug("Process went down as #{exit_state}")
  end
end
</code>```

Problems:

when the task Task.Supervisor.async_nolink done all the work and gen server went down as normal, I am getting this error,

Uncaught exit - {:normal, {GenServer, :call, [:"customer_identity-dbdd5d5c-a827-4b75-91cd-dade07b39c8e", {:validate_customer_identity_fraud, %NectarineCredit.Identities{somedata}}, 5000]}}

This process should be isolated, no matter if it fails It should not disturb another process, but when this Uncaught exit happens, it gives 500 status to the GrapQL call as well in which its happening. To my understanding, it should be isolated and run/crash in its own space.

any help would be great.

Body:
As a result of the GraphQL request, some DB operations are being done within the Phoenix application, and during those operations, I started a gen server this way,

  def start_fingerprint_fraud_check(customer_identity) do
    id = process_name("customer_identity-" <> "#{customer_identity.id}")

    General.Supervisor.start_child(NectarineCredit.Risk.IdentityCheck, %{
      id: id,
      ref: nil,
      type: :worker
    })
    |> case do
      {:ok, _pid} ->
        GenServer.call(id, {:validate_customer_identity_fraud, customer_identity})

      {:error, {:already_started, _pid}} ->
        Logger.debug(
          "Identity fraud check is already running for this customer: #{
            customer_identity.customer_id
          }"
        )

        GenServer.call(id, {:validate_customer_identity_fraud, customer_identity})
    end
  end

and In gen server.

defmodule NectarineCredit.Risk.IdentityCheck do
  @moduledoc false

  use GenServer, restart: :temporary

  require Logger

  def start_link(opts) do
    GenServer.start_link(__MODULE__, opts, name: opts.id)
  end

  def init(opts) do
    {:ok, opts}
  end

  def handle_call(
        {:validate_customer_identity_fraud, _customer_identity},
        _from,
        %{ref: ref} = state
      )
      when is_reference(ref) do
    {:reply, :ok, state}
  end

  def handle_call(
        {:validate_customer_identity_fraud, customer_identity},
        _from,
        %{ref: nil} = state
      ) do
    task =
      Task.Supervisor.async_nolink(NectarineCredit.TaskSupervisor, fn ->
        #stuff
      end)

    # We return :ok and the server will continue running
    {:reply, :ok, %{state | ref: task.ref}}
  end

  # The task completed successfully
  def handle_info({ref, answer}, %{ref: ref} = state) do
    Process.demonitor(ref, [:flush])
    {:stop, :normal, %{state | ref: nil}}
  end

  # The task failed
  def handle_info({:DOWN, ref, :process, _pid, reason}, %{ref: ref} = state) do
    {:stop, :shutdown, %{state | ref: nil}}
  end

  def terminate(exit_state, _state) do
    Logger.debug("Process went down as #{exit_state}")
  end
end

Problems:

when the task Task.Supervisor.async_nolink done all the work and gen server went down as normal, I am getting this error,

Uncaught exit - {:normal, {GenServer, :call, [:"customer_identity-dbdd5d5c-a827-4b75-91cd-dade07b39c8e", {:validate_customer_identity_fraud, %NectarineCredit.Identities{somedata}}, 5000]}}

This process should be isolated, no matter if it fails It should not disturb another process, but when this Uncaught exit happens, it gives 500 status to the GrapQL call as well in which its happening. To my understanding, it should be isolated and run/crash in its own space.

any help would be great.


问:
Dynamic title with Vue + Laravel
I am struggling to add the forum post as the title for when someone clicks on the forum post. It appears I need to add it to the blade file rather than Vue. So in summary need to pass from Vue to the blade which displays everything.

Using Laravel Jetstream

app.blade.php

<title inertia>{{ config('app.name', 'Laravel') }}</title>

In source:

```<code><title inertia>Daily Forum Post</title>
</code>```

App.vue

```<code><Head :title="title" />

export default {
    props: {
        title: String,
</code>```

Shows correct title, but not in source.

Tried passing the variable with no luck, also tried using vue meta with no luck

Title: Dynamic title with Vue + Laravel

Body:
I am struggling to add the forum post as the title for when someone clicks on the forum post. It appears I need to add it to the blade file rather than Vue. So in summary need to pass from Vue to the blade which displays everything.

Using Laravel Jetstream

app.blade.php

<title inertia>{{ config('app.name', 'Laravel') }}</title>

In source:

<title inertia>Daily Forum Post</title>

App.vue

export default {
    props: {
        title: String,

Shows correct title, but not in source.

Tried passing the variable with no luck, also tried using vue meta with no luck


问:
jq: read value of a key using arguments (variable key name) from json
I have a json like this:

myfile.json

```<code>{
    "kind": "Configuration",
    "data": {
        "foo.xml": "\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cconf\u003e\n \u003c/conf\u003e\n",
        "bar.xml": "\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cConfiguration\u003e\n \u003c/Configuration\u003e\n",
        "abc.properties": "transaction=true"
    }
}
</code>```

and I'm trying to get the value of the key "bar.xml"

This command does the job and I'm getting the expected output:

```<code>$ jq -r  '.data."bar.xml"' myfile.json
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
 </Configuration>

</code>```

However, the key name could change. So I will have the key name in a variable

export KEY_NAME=bar.xml

Trying to use this variable in jq command and haven't been able to figure out the right way.

Tried below commands but working

```<code>$ jq --arg a $KEY_NAME -r  '.data."$a"' myfile.json
null

$ jq --arg a $KEY_NAME -r  '.data.$a' myfile.json
jq: error: syntax error, unexpected '$', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.data.$a
jq: 1 compile error

$ jq --arg a $KEY_NAME -r  '.data.[$a]' myfile.json
jq: error: syntax error, unexpected '[', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.data.[$a]
jq: 1 compile error

$ jq --arg a "$KEY_NAME" -r  '.data.$a' myfile.json
jq: error: syntax error, unexpected '$', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.data.$a
jq: 1 compile error

</code>```

Could you please help me with a right command?

Body:
I have a json like this:

myfile.json

{
    "kind": "Configuration",
    "data": {
        "foo.xml": "\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cconf\u003e\n \u003c/conf\u003e\n",
        "bar.xml": "\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cConfiguration\u003e\n \u003c/Configuration\u003e\n",
        "abc.properties": "transaction=true"
    }
}

and I'm trying to get the value of the key "bar.xml"

This command does the job and I'm getting the expected output:

$ jq -r  '.data."bar.xml"' myfile.json
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
 </Configuration>

However, the key name could change. So I will have the key name in a variable

export KEY_NAME=bar.xml

Trying to use this variable in jq command and haven't been able to figure out the right way.

Tried below commands but working

$ jq --arg a $KEY_NAME -r  '.data."$a"' myfile.json
null

$ jq --arg a $KEY_NAME -r  '.data.$a' myfile.json
jq: error: syntax error, unexpected '$', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.data.$a
jq: 1 compile error

$ jq --arg a $KEY_NAME -r  '.data.[$a]' myfile.json
jq: error: syntax error, unexpected '[', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.data.[$a]
jq: 1 compile error

$ jq --arg a "$KEY_NAME" -r  '.data.$a' myfile.json
jq: error: syntax error, unexpected '$', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.data.$a
jq: 1 compile error

Could you please help me with a right command?


问:
Video choppy on slower devices
I have noticed how youtube can play videos on old smartphones with no lag. I have a 3 seconds long video that acts as an animation on my website, I have compressed the file size down to less than a megabyte and have waited for the "canplaythrough" eventlistener before playing the video, but the video still lags like crazy on my laptop. I made a system that loads videos that match the user's resolution that looks like this

```<code> var resulution_list = [1280, 1408, 1536, 1664, 1792, 1920, 2560];

 var resulution_dict = {
   1280: "videos/render_animation_1280.mp4",
   1408: "videos/render_animation_1408.mp4",
   1536: "videos/render_animation_1536.mp4",
   1664: "videos/render_animation_1664.mp4",
   1792: "videos/render_animation_1792.mp4",
   1920: "videos/render_animation_1920.mp4",
   2560: "videos/render_animation_2560.mp4",
 };

 var resulution_goal = window.innerWidth;

 var closest_resulution = resulution_list.reduce(function (prev, curr) {
   return Math.abs(curr - resulution_goal) < Math.abs(prev - resulution_goal)
     ? curr
     : prev;
 });

 const video_url = resulution_dict[closest_resulution];

 var source = document.createElement("source");

 source.setAttribute("src", video_url);
 source.setAttribute("type", "video/mp4");

 document.getElementsByTagName("video")[0].appendChild(source);

</code>```

But that did not seem to help at all.
My video tag looks like this:

<video id="animation-video" class="video_first" style="opacity: 0;" controls preload>

It is really important that the video plays without any lag.
Any help would be appreciated.

Title: Video choppy on slower devices

Body:
I have noticed how youtube can play videos on old smartphones with no lag. I have a 3 seconds long video that acts as an animation on my website, I have compressed the file size down to less than a megabyte and have waited for the "canplaythrough" eventlistener before playing the video, but the video still lags like crazy on my laptop. I made a system that loads videos that match the user's resolution that looks like this

 var resulution_list = [1280, 1408, 1536, 1664, 1792, 1920, 2560];

 var resulution_dict = {
   1280: "videos/render_animation_1280.mp4",
   1408: "videos/render_animation_1408.mp4",
   1536: "videos/render_animation_1536.mp4",
   1664: "videos/render_animation_1664.mp4",
   1792: "videos/render_animation_1792.mp4",
   1920: "videos/render_animation_1920.mp4",
   2560: "videos/render_animation_2560.mp4",
 };

 var resulution_goal = window.innerWidth;

 var closest_resulution = resulution_list.reduce(function (prev, curr) {
   return Math.abs(curr - resulution_goal) < Math.abs(prev - resulution_goal)
     ? curr
     : prev;
 });

 const video_url = resulution_dict[closest_resulution];

 var source = document.createElement("source");

 source.setAttribute("src", video_url);
 source.setAttribute("type", "video/mp4");

 document.getElementsByTagName("video")[0].appendChild(source);

But that did not seem to help at all.
My video tag looks like this:

<video id="animation-video" class="video_first" style="opacity: 0;" controls preload>

It is really important that the video plays without any lag.
Any help would be appreciated.


问:
How to use opentelemetry logs in javascript(nodejs)
I am trying to understand how to use and send logs using opentelemetry but find it is confusing. Suppose I am developing an application(preferable using javascript) and want to log things in the app and send the logs to a backend(e.g. azure monitor), what is the best way to do it?
For traces and metrics, opentelemetry provides api/sdk to either direct exports traces/metrics to backend or through collector. However, my understanding of how logs work are so different. It looks to me opentelemetry does provide some api/sdk, but I am not sure if I should use it as an application developer. I see in the opentelemetry logging overview, it mentioned two things below:

OpenTelemetry defines an API for emitting LogRecords. Application developers are NOT encouraged to call this API directly. It is provided for library authors to build Appenders, which use the API to bridge between existing logging libraries and the OpenTelemetry log data model. Existing logging libraries generally provide a much richer set of features than what is defined in OpenTelemetry. It is NOT a goal of OpenTelemetry to ship a feature-rich logging library.

OpenTelemetry defines an API for emitting Events. The API consists of convenience methods which delegate to the API for emitting LogRecords. Application developers are encouraged to call this API directly.

How do I know if this api/sdk in javascript should be used by application developer or library authors to build Appenders? It seems this api/sdk has both emit event and emit LogRecords.

I understand opentelemetry log architecture aim to make sure both logs that we do not have control and controllable logs(like in terms of formats) to have correlation and context information, so one approach(called Via File or Stdout Logs) is to save the logs to some intermediary medium and then send to collector(My understanding this is more of the case of uncontrollable logs). The second approach(called Direct to Collector) is to send logs direct to collector. In the doc of the second way, it mentions "The most convenient way to achieve this is to provide addons or extensions to the commonly used logging libraries.", what does it mean? Does the addons or extensions refers to the Appenders mentioned above? I would appreciate some code examples of these two approaches in javascript especially the 2nd approach.


问:
How to use tf.image.resize_with_pad but pad with ones instead of zeros?
According to Tensorflow documentation, the padding is always with zeros instead of ones.

Is there there a way to change the padding to ones?

If not, what is the best alternative for a tensorflow dataset?

Here is my code example:

```<code>def resize_with_pad(image, label):

    image = tf.image.resize_with_pad(image=image,
                                     target_height=resized_wh,
                                     target_width=resized_wh,
                                     method=ResizeMethod.BILINEAR,
                                     antialias=False)
    return image, label

def create_tf_dataset_pipeline(tf_dataset):

    tf_dataset = tf_dataset.map(load_image, num_parallel_calls=AUTOTUNE)
    tf_dataset = tf_dataset.map(normalize, num_parallel_calls=AUTOTUNE)
    tf_dataset = tf_dataset.map(resize_with_pad, num_parallel_calls=AUTOTUNE)
    tf_dataset = tf_dataset.batch(batch_size)
    tf_dataset = tf_dataset.prefetch(AUTOTUNE)

    return tf_dataset

train_data = tf.data.Dataset.from_tensor_slices((x_train_filepaths, y_train_class))
train_data = create_tf_dataset_pipeline(train_data)

</code>```

I tried resizing and padding the images and saving it in a directory (i.e. frontloading the processing), but that is very inflexible as I need to create a new dataset every time I want to train a model on a different size. It would be much better if I could do it dynamically with tensor flow.

Body:
According to Tensorflow documentation, the padding is always with zeros instead of ones.

Is there there a way to change the padding to ones?

If not, what is the best alternative for a tensorflow dataset?

Here is my code example:

def resize_with_pad(image, label):

    image = tf.image.resize_with_pad(image=image,
                                     target_height=resized_wh,
                                     target_width=resized_wh,
                                     method=ResizeMethod.BILINEAR,
                                     antialias=False)
    return image, label

def create_tf_dataset_pipeline(tf_dataset):

    tf_dataset = tf_dataset.map(load_image, num_parallel_calls=AUTOTUNE)
    tf_dataset = tf_dataset.map(normalize, num_parallel_calls=AUTOTUNE)
    tf_dataset = tf_dataset.map(resize_with_pad, num_parallel_calls=AUTOTUNE)
    tf_dataset = tf_dataset.batch(batch_size)
    tf_dataset = tf_dataset.prefetch(AUTOTUNE)

    return tf_dataset

train_data = tf.data.Dataset.from_tensor_slices((x_train_filepaths, y_train_class))
train_data = create_tf_dataset_pipeline(train_data)

I tried resizing and padding the images and saving it in a directory (i.e. frontloading the processing), but that is very inflexible as I need to create a new dataset every time I want to train a model on a different size. It would be much better if I could do it dynamically with tensor flow.


问:
how to automatically drop index levels that only have single value?
I have a dataframe that has A to M columns for example. Then I did:

```<code>groups = df.groupby(['E', 'D', 'B', 'G', 'I'])
stats = pd.concat(
   [
        groups['N'].mean().rename("N_mean"),
        groups['H'].median().rename('H_median')
   ]
)
stats = stats[stats['N']>0]
</code>```

now if I print stats, the index is ('E', 'D', 'B', 'G', 'I'). However, many of them only contain single value which means they are insignificant. I knew I can determine which level is insignificant then stats.index.droplevel(...). But I wonder is there already builtin method to automatically do this?

Body:
I have a dataframe that has A to M columns for example. Then I did:

groups = df.groupby(['E', 'D', 'B', 'G', 'I'])
stats = pd.concat(
   [
        groups['N'].mean().rename("N_mean"),
        groups['H'].median().rename('H_median')
   ]
)
stats = stats[stats['N']>0]

now if I print stats, the index is ('E', 'D', 'B', 'G', 'I'). However, many of them only contain single value which means they are insignificant. I knew I can determine which level is insignificant then stats.index.droplevel(...). But I wonder is there already builtin method to automatically do this?


问:
DataGrid: Filtering the contents of a DataGridComboBoxColumn based on the row
I am struggling with DataGridComboBoxColumn filtering. I am using a DataGrid with a DataGridComboBoxColumn. I am able to bind to a Dictionary of values using CollectionViewSource. (Not sure this is the right way but it works.)

What I need is for the user to be able to select a value in the combobox and for the data to be filtered based on the data record in the row.

For example:

Rows in the data grid:

Person (text), State (combobox)

Person 1, the combobox valid values are CA and WI

Person 2, the combobox valid values are WI and MN

Person 3, the combobox valid values are WI

I can populate the combobox but I am unable to get filtering to work.


问:
call google vision Api from Flutter
I want to make a Flutter app where I detect text and number from an image using Google Cloud vision API.

I see the API of Google Cloud Vision is here.

I know that from Flutter, I need to create a json file, with content is an image.
Then, sending that json file to Google Cloud vision endpoint, and get the result back.

However, how can I implement it in Flutter. Is there any example using this.

Title: call google vision Api from Flutter


问:
Why I cannot get all contributors of a GitHub Repository using GitHub API
Following is my code and every time it only returns 60 contributors:

```<code>base_url = "https://api.github.com"

owner = "http4s"
repo = "http4s"

# Set the headers for the request
headers = {
    "Accept": "application/vnd.github+json",
    "Authorization":"token xxxxxx"
}

url = f"{base_url}/repos/{owner}/{repo}/contributors?per_page=100"

more_pages = True

# Initialize a set to store the contributors
contributors = set()

while more_pages:
    # Send the request to the API endpoint
    response = requests.get(url, headers=headers)

    # Check the status code of the response
    if response.status_code == 200:
        # If the request is successful, add the list of contributors to the `contributors` set
        contributors.update([contributor["login"] for contributor in response.json()])

        # Check the `Link` header in the response to see if there are more pages to fetch
        link_header = response.headers.get("Link")
        if link_header:
            # The `Link` header has the format `<url>; rel="name"`, so we split it on `;` to get the URL
            next_url = link_header.split(";")[0][1:-1]

            # Check if the `rel` parameter is "next" to determine if there are more pages to fetch
            if "rel=\"next\"" in link_header:
                url = next_url
            else:
                more_pages = False
        else:
            more_pages = False
    else:
        # If the request is not successful, print the status code and the error message
        print(f"Failed to get contributors: {response.status_code} {response.text}")
        more_pages = False

</code>```

Can someone tell me how can I optimize my code?

I have tried many ways to fetch more contributors, but every time it only returns 60 different contributors. I want to get the full list of contributors.

Body:
Following is my code and every time it only returns 60 contributors:

base_url = "https://api.github.com"

owner = "http4s"
repo = "http4s"

# Set the headers for the request
headers = {
    "Accept": "application/vnd.github+json",
    "Authorization":"token xxxxxx"
}

url = f"{base_url}/repos/{owner}/{repo}/contributors?per_page=100"

more_pages = True

# Initialize a set to store the contributors
contributors = set()

while more_pages:
    # Send the request to the API endpoint
    response = requests.get(url, headers=headers)

    # Check the status code of the response
    if response.status_code == 200:
        # If the request is successful, add the list of contributors to the `contributors` set
        contributors.update([contributor["login"] for contributor in response.json()])

        # Check the `Link` header in the response to see if there are more pages to fetch
        link_header = response.headers.get("Link")
        if link_header:
            # The `Link` header has the format `<url>; rel="name"`, so we split it on `;` to get the URL
            next_url = link_header.split(";")[0][1:-1]

            # Check if the `rel` parameter is "next" to determine if there are more pages to fetch
            if "rel=\"next\"" in link_header:
                url = next_url
            else:
                more_pages = False
        else:
            more_pages = False
    else:
        # If the request is not successful, print the status code and the error message
        print(f"Failed to get contributors: {response.status_code} {response.text}")
        more_pages = False

Can someone tell me how can I optimize my code?

I have tried many ways to fetch more contributors, but every time it only returns 60 different contributors. I want to get the full list of contributors.


问:
AWS SAM: MinimumCompressionSize property doesn't work on Lambda responses for AWS::Serverless::Api
According to the AWS SAM Template Documentation, you can specify a MinimumCompressedSize attribute for AWS::Serverless::API resources which should compress response bodies which exceed a given threshold, yet in local testing this doesn't work.

Take for instance a slightly modified node v16 "Hello-World" project generated using sam init:

template.yaml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app

  Sample SAM Template for sam-app
  Globals:
  Function:
    Timeout: 3
    MemorySize: 128
Resources:
  CompressedApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: "Prod"
      MinimumCompressionSize: 0
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs16.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get
            RestApiId: !Ref CompressedApi

```
<p>And the corresponding node code for app.lambdaHandler:</p>
<pre class="lang-js prettyprint-override"><code>exports.lambdaHandler = async (event, context) => {
    try {
        // const ret = await axios(url);
        response = {
            'statusCode': 200,
            'body': JSON.stringify({
                message: 'hello world',
                // location: ret.data.trim()
            })
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};
</code>```

After running sam local start-api and opening 127.0.0.1:3000/hello I should expect (if my browser sends an Accept-Encoding header with gzip, deflate, or identity compression) to see a compressed response, even for a small payload of 25 bytes since my MinimumCompressionSize is set to zero.

Instead I get a uncompressed response:

Why doesn't the lambda function response get compressed?  Did I make some mistake in composing this template.yaml?

Note: I'm aware it's possible to setup gzip compression using an HttpApi resource (instead of the Api type used here) by having the lambda function itself compress the response body using a process like the one described in this blog post, but my understanding is that this type of Api resource should support this out-of-the-box and there's some mistake I'm making in setting up my application.

Body:
According to the AWS SAM Template Documentation, you can specify a MinimumCompressedSize attribute for AWS::Serverless::API resources which should compress response bodies which exceed a given threshold, yet in local testing this doesn't work.

Take for instance a slightly modified node v16 "Hello-World" project generated using sam init:

template.yaml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app

  Sample SAM Template for sam-app
  Globals:
  Function:
    Timeout: 3
    MemorySize: 128
Resources:
  CompressedApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: "Prod"
      MinimumCompressionSize: 0
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs16.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get
            RestApiId: !Ref CompressedApi

And the corresponding node code for app.lambdaHandler:

exports.lambdaHandler = async (event, context) => {
    try {
        // const ret = await axios(url);
        response = {
            'statusCode': 200,
            'body': JSON.stringify({
                message: 'hello world',
                // location: ret.data.trim()
            })
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};

After running sam local start-api and opening 127.0.0.1:3000/hello I should expect (if my browser sends an Accept-Encoding header with gzip, deflate, or identity compression) to see a compressed response, even for a small payload of 25 bytes since my MinimumCompressionSize is set to zero.

Instead I get a uncompressed response:

Why doesn't the lambda function response get compressed?  Did I make some mistake in composing this template.yaml?

Note: I'm aware it's possible to setup gzip compression using an HttpApi resource (instead of the Api type used here) by having the lambda function itself compress the response body using a process like the one described in this blog post, but my understanding is that this type of Api resource should support this out-of-the-box and there's some mistake I'm making in setting up my application.


问:
Odoo Style Toolbar will cause container style clear
When I try to change Style from the inline text toolbar (image 1), it will clear the parent container style.

image 1 inline text toolbar with a mark of problem tool

Below is the screen capture to describe the issue

video capture to describe the issue

I have try to look trough the code and find the toolbar is defind in OdooEditor.js
(addons\web_editor\static\lib\odoo-editor\src\OdooEditor.js), but not found anything relate to solve this issue.

Anyone use odoo 15 face the same issue? Any clue?


问:
How to build docker image in gitlab-runner and push to local registry? And why --insecure-registry command make --tls=false not working
I'm trying to construct gitlab CI/CD with docker.
The goal is building docker image on runner and push to local insecure registry, but docker build keep throwing this error.

```<code>error during connect: Post "http://docker:2375/v1.24/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&shmsize=0&t=test_project&target=&ulimits=null&version=1": dial tcp: lookup docker on xxx.xxx.xxx.xxx:53: no such host
</code>```

This is my gitlab-ci file.

...

package:
  image: docker:latest
  stage: package
  variables:
    DOCKER_HOST: tcp://docker:2375
    DOCKER_DRIVER: overlay2
    DOCKER_TLS_CERTDIR: ""
  services:
    - name: docker:20-dind
      alias: docker
      command: ["--tls=false", "--insecure-registry=$DOCKER_REGISTRY_IP:$DOCKER_REGISTRY_PORT"] # OPTIONS
  script:
    - docker build -t $DOCKER_IMAGE_NAME . # Error occurred
    - docker tag $DOCKER_IMAGE_NAME $DOCKER_REGISTRY_IP:$DOCKER_REGISTRY_PORT/$DOCKER_IMAGE_NAME
    - docker push $DOCKER_REGISTRY_IP:$DOCKER_REGISTRY_PORT/$DOCKER_IMAGE_NAME
  cache:
    key: "$DOCKER_IMAGE_NAME"
    policy: pull
    paths:
      - build

...
```
<p>I set priviliged=true to solve first error.</p>
```[[runners]]
  name = "docker-runner"
  url = "http://192.165.100.2/"
  id = 10
  token = "47e5LRRhgBPcnhfYdDxB"
  token_obtained_at = 2022-12-28T06:50:33Z
  token_expires_at = 0001-01-01T00:00:00Z
  executor = "docker"
  [runners.custom_build_dir]
  [runners.cache]
    MaxUploadedArchiveSize = 0
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]
  [runners.docker]
    tls_verify = false
    image = "alpine:latest"
    privileged = true                #set to true
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    disable_cache = false
    volumes = ["/cache"]
    shm_size = 0
```
<p>Then first error as solved, but second error has occurred.</p>
```Cannot connect to the Docker daemon at tcp://docker:2375. Is the docker daemon running?
```
<p>To solve second error, I added "--tls=false" command to docker:dind service according to this link.</p>
```services:
    - name: docker:20-dind
      alias: docker
      command: ["--tls=false"]
```
<p>Then <code>no such host</code> error has solved, But third error has occurred.</p>
```Get "https://xxx.xxx.xxx.xxx:5000/v2/": http: server gave HTTP response to HTTPS client
```
<p>To solve third error, I added <code>insecure-registry</code> command according to this link.</p>
```services:
    - name: docker:20-dind
      alias: docker
      command: ["--tls=false", "--insecure-registry=$DOCKER_REGISTRY_IP:$DOCKER_REGISTRY_PORT"]
```
<p>I expected to solve https problem, but error went back to the beginning.</p>
```error during connect: Post "http://docker:2375/v1.24/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&shmsize=0&t=test_project&target=&ulimits=null&version=1": dial tcp: lookup docker on xxx.xxx.xxx.xxx:53: no such host
```

Why --insecure-registry command make --tls=false not working?

How to build docker image in gitlab-runner and push to local registry?

Thanks.

Body:
I'm trying to construct gitlab CI/CD with docker.
The goal is building docker image on runner and push to local insecure registry, but docker build keep throwing this error.

error during connect: Post "http://docker:2375/v1.24/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&shmsize=0&t=test_project&target=&ulimits=null&version=1": dial tcp: lookup docker on xxx.xxx.xxx.xxx:53: no such host

This is my gitlab-ci file.

...

package:
  image: docker:latest
  stage: package
  variables:
    DOCKER_HOST: tcp://docker:2375
    DOCKER_DRIVER: overlay2
    DOCKER_TLS_CERTDIR: ""
  services:
    - name: docker:20-dind
      alias: docker
      command: ["--tls=false", "--insecure-registry=$DOCKER_REGISTRY_IP:$DOCKER_REGISTRY_PORT"] # OPTIONS
  script:
    - docker build -t $DOCKER_IMAGE_NAME . # Error occurred
    - docker tag $DOCKER_IMAGE_NAME $DOCKER_REGISTRY_IP:$DOCKER_REGISTRY_PORT/$DOCKER_IMAGE_NAME
    - docker push $DOCKER_REGISTRY_IP:$DOCKER_REGISTRY_PORT/$DOCKER_IMAGE_NAME
  cache:
    key: "$DOCKER_IMAGE_NAME"
    policy: pull
    paths:
      - build

...

I set priviliged=true to solve first error.

[[runners]]
  name = "docker-runner"
  url = "http://192.165.100.2/"
  id = 10
  token = "47e5LRRhgBPcnhfYdDxB"
  token_obtained_at = 2022-12-28T06:50:33Z
  token_expires_at = 0001-01-01T00:00:00Z
  executor = "docker"
  [runners.custom_build_dir]
  [runners.cache]
    MaxUploadedArchiveSize = 0
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]
  [runners.docker]
    tls_verify = false
    image = "alpine:latest"
    privileged = true                #set to true
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    disable_cache = false
    volumes = ["/cache"]
    shm_size = 0

Then first error as solved, but second error has occurred.

Cannot connect to the Docker daemon at tcp://docker:2375. Is the docker daemon running?

To solve second error, I added "--tls=false" command to docker:dind service according to this link.

services:
    - name: docker:20-dind
      alias: docker
      command: ["--tls=false"]

Then no such host error has solved, But third error has occurred.

Get "https://xxx.xxx.xxx.xxx:5000/v2/": http: server gave HTTP response to HTTPS client

To solve third error, I added insecure-registry command according to this link.

services:
    - name: docker:20-dind
      alias: docker
      command: ["--tls=false", "--insecure-registry=$DOCKER_REGISTRY_IP:$DOCKER_REGISTRY_PORT"]

I expected to solve https problem, but error went back to the beginning.

error during connect: Post "http://docker:2375/v1.24/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&shmsize=0&t=test_project&target=&ulimits=null&version=1": dial tcp: lookup docker on xxx.xxx.xxx.xxx:53: no such host

Why --insecure-registry command make --tls=false not working?

How to build docker image in gitlab-runner and push to local registry?

Thanks.


问:
How to find to see if a set exists in a set of sets
It's relatively hard to explain.

So for example, if I have a set a that is {(0,0,0), (0,1,0), (0, 0, 1)} and set b is {((0,0,0), (0,1,0), (0, 0, 1)), ((0,0,0), (0,1,0), (0, 0, 2), ...), ...}.

What function would allow me to see if set a exists in set b? I also want to make sure that the function returns false when set b has ((0,0,0), (0,1,0), (0, 0, 1), (0,0,2)) and not the exact set((0,0,0), (0,1,0), (0, 0, 1)).

Thank you so much.

I tried the function includes(b.begin(), b.end(), a.begin(), a.end()), but it does not work because it only checks if there is a subset.

Example code that shows this underneath.

```<code>#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <set>
#include <tuple>

using namespace std;

int main() {

  set <tuple<int, int, int>> coord;
  set <tuple<int, int, int>> testcoord0;
  set <tuple<int, int, int>> testcoord1;
  set <tuple<int, int, int>> total_set;
  tuple <int, int, int> tuple0 = make_tuple(0, 0, 0);
  tuple <int, int, int> tuple1 = make_tuple(0, 1, 0);
  tuple <int, int, int> tuple2 = make_tuple(0, 0, 1);
  tuple <int, int, int> tuple3 = make_tuple(0, 0, 2);
  tuple <int, int, int> tuple4 = make_tuple(0, 2, 0);
  tuple <int, int, int> tuple5 = make_tuple(2, 0, 0);

  coord.insert(tuple0);
  coord.insert(tuple1);
  coord.insert(tuple2);
  testcoord0.insert(tuple0);
  testcoord0.insert(tuple1);
  testcoord0.insert(tuple2);
  testcoord0.insert(tuple3);
  total_set.insert(testcoord0.begin(), testcoord0.end());
  testcoord1.insert(tuple3);
  testcoord1.insert(tuple4);
  testcoord1.insert(tuple5);
  total_set.insert(testcoord1.begin(), testcoord1.end());

  if (includes(total_set.begin(), total_set.end(), coord.begin(), coord.end())) {
        cout<< "it does exists" << endl;
    }
    else {
        cout<< "it does not exists" << endl;
    }

}
</code>```

Body:
It's relatively hard to explain.

So for example, if I have a set a that is {(0,0,0), (0,1,0), (0, 0, 1)} and set b is {((0,0,0), (0,1,0), (0, 0, 1)), ((0,0,0), (0,1,0), (0, 0, 2), ...), ...}.

What function would allow me to see if set a exists in set b? I also want to make sure that the function returns false when set b has ((0,0,0), (0,1,0), (0, 0, 1), (0,0,2)) and not the exact set((0,0,0), (0,1,0), (0, 0, 1)).

Thank you so much.

I tried the function includes(b.begin(), b.end(), a.begin(), a.end()), but it does not work because it only checks if there is a subset.

Example code that shows this underneath.

#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <set>
#include <tuple>

using namespace std;

int main() {

  set <tuple<int, int, int>> coord;
  set <tuple<int, int, int>> testcoord0;
  set <tuple<int, int, int>> testcoord1;
  set <tuple<int, int, int>> total_set;
  tuple <int, int, int> tuple0 = make_tuple(0, 0, 0);
  tuple <int, int, int> tuple1 = make_tuple(0, 1, 0);
  tuple <int, int, int> tuple2 = make_tuple(0, 0, 1);
  tuple <int, int, int> tuple3 = make_tuple(0, 0, 2);
  tuple <int, int, int> tuple4 = make_tuple(0, 2, 0);
  tuple <int, int, int> tuple5 = make_tuple(2, 0, 0);

  coord.insert(tuple0);
  coord.insert(tuple1);
  coord.insert(tuple2);
  testcoord0.insert(tuple0);
  testcoord0.insert(tuple1);
  testcoord0.insert(tuple2);
  testcoord0.insert(tuple3);
  total_set.insert(testcoord0.begin(), testcoord0.end());
  testcoord1.insert(tuple3);
  testcoord1.insert(tuple4);
  testcoord1.insert(tuple5);
  total_set.insert(testcoord1.begin(), testcoord1.end());

  if (includes(total_set.begin(), total_set.end(), coord.begin(), coord.end())) {
        cout<< "it does exists" << endl;
    }
    else {
        cout<< "it does not exists" << endl;
    }

}