问:
Snap applications not showing in "show applications", Ubuntu 20.04
Yesterday, after Ubuntu (or maybe Dell) installed some updates and I restarted, my snap applications were not showing on my sidebar, nor are they present in "show applications" or a normal search.

They are still installed and snap list still shows them, and they will still run via snap run <application>.

I've tried uninstalling them all (although I did not use --purge when I ran snap remove <application>), followed by uninstalling snap itself, then re-installing everything. They are still present but not showing up.

More searching has brought me to sites referencing the XDG_DATA_DIRS environment variable (explained HERE). If I understand correctly this should link all the folders where applications are stored, and the paths within should be separated by colons, not spaces. Thus I ran echo $XDG_DATA_DIRS and was rewarded with:

/usr/local/share/:/usr/share/:/var/lib/snapd/desktop /var/lib/snapd/desktop /var/lib/snapd/desktop

So I suspect my issue is the facts that the snapd directory is listed three times, and it is separated by spaces.

Does anyone have any ideas how I could fix this? I suspect, but am not certain that this is the issue.

I'm on Ubuntu 20.04, using fish shell.

I've found THIS post showing a possible solution, and upon running sudo ag "XDG_DATA_DIRS=" / 2>/dev/null | grep -v snap (and waiting a while) I got the following output (minus a few auth.log references which I've removed) Apologies for the big, possibly irreverent, "data dump"

```<code>/etc/profile.d/xdg_dirs_desktop_session.sh:4:DEFAULT_XDG_DATA_DIRS='/usr/local/share/:/usr/share/'
/etc/profile.d/xdg_dirs_desktop_session.sh:18:       XDG_DATA_DIRS="$DEFAULT_XDG_DATA_DIRS"
/etc/profile.d/xdg_dirs_desktop_session.sh:21:       XDG_DATA_DIRS=/usr/share/"$DESKTOP_SESSION":"$XDG_DATA_DIRS"
/etc/profile.d/apps-bin-path.sh:12:    export XDG_DATA_DIRS="/usr/local/share:/usr/share"
/etc/X11/Xsession.d/55gnome-session_gnomerc:17:      XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/
/etc/X11/Xsession.d/55gnome-session_gnomerc:19:      XDG_DATA_DIRS=/usr/share/gnome:"$XDG_DATA_DIRS"
/etc/X11/Xsession.d/60x11-common_xdg_path:5:DEFAULT_XDG_DATA_DIRS='/usr/local/share/:/usr/share/'
/etc/X11/Xsession.d/60x11-common_xdg_path:17:       XDG_DATA_DIRS="$DEFAULT_XDG_DATA_DIRS"
/etc/X11/Xsession.d/60x11-common_xdg_path:20:       XDG_DATA_DIRS=/usr/share/"$DESKTOP_SESSION":"$XDG_DATA_DIRS"
/usr/share/doc/gnome-software/README.md:24:$ XDG_DATA_DIRS=install/share:$XDG_DATA_DIRS ./install/bin/gnome-software
</code>```

I'm not certain I have found the correct places to think about updating the environment variable, as none of these referenced /var/lib/snaped/desktop...And this might not be the issue causing the problem at all! Any help would be welcome!

答:
You are running into https://bugs.launchpad.net/ubuntu/+source/snapd/+bug/1957948 which will require a fix in snapd.

Using a different shell as your login shell, and then executing fish once it has started, is the right workaround.

Body:
Yesterday, after Ubuntu (or maybe Dell) installed some updates and I restarted, my snap applications were not showing on my sidebar, nor are they present in "show applications" or a normal search.

They are still installed and snap list still shows them, and they will still run via snap run <application>.

I've tried uninstalling them all (although I did not use --purge when I ran snap remove <application>), followed by uninstalling snap itself, then re-installing everything. They are still present but not showing up.

More searching has brought me to sites referencing the XDG_DATA_DIRS environment variable (explained HERE). If I understand correctly this should link all the folders where applications are stored, and the paths within should be separated by colons, not spaces. Thus I ran echo $XDG_DATA_DIRS and was rewarded with:

/usr/local/share/:/usr/share/:/var/lib/snapd/desktop /var/lib/snapd/desktop /var/lib/snapd/desktop

So I suspect my issue is the facts that the snapd directory is listed three times, and it is separated by spaces.

Does anyone have any ideas how I could fix this? I suspect, but am not certain that this is the issue.

I'm on Ubuntu 20.04, using fish shell.

I've found THIS post showing a possible solution, and upon running sudo ag "XDG_DATA_DIRS=" / 2>/dev/null | grep -v snap (and waiting a while) I got the following output (minus a few auth.log references which I've removed) Apologies for the big, possibly irreverent, "data dump"

/etc/profile.d/xdg_dirs_desktop_session.sh:4:DEFAULT_XDG_DATA_DIRS='/usr/local/share/:/usr/share/'
/etc/profile.d/xdg_dirs_desktop_session.sh:18:       XDG_DATA_DIRS="$DEFAULT_XDG_DATA_DIRS"
/etc/profile.d/xdg_dirs_desktop_session.sh:21:       XDG_DATA_DIRS=/usr/share/"$DESKTOP_SESSION":"$XDG_DATA_DIRS"
/etc/profile.d/apps-bin-path.sh:12:    export XDG_DATA_DIRS="/usr/local/share:/usr/share"
/etc/X11/Xsession.d/55gnome-session_gnomerc:17:      XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/
/etc/X11/Xsession.d/55gnome-session_gnomerc:19:      XDG_DATA_DIRS=/usr/share/gnome:"$XDG_DATA_DIRS"
/etc/X11/Xsession.d/60x11-common_xdg_path:5:DEFAULT_XDG_DATA_DIRS='/usr/local/share/:/usr/share/'
/etc/X11/Xsession.d/60x11-common_xdg_path:17:       XDG_DATA_DIRS="$DEFAULT_XDG_DATA_DIRS"
/etc/X11/Xsession.d/60x11-common_xdg_path:20:       XDG_DATA_DIRS=/usr/share/"$DESKTOP_SESSION":"$XDG_DATA_DIRS"
/usr/share/doc/gnome-software/README.md:24:$ XDG_DATA_DIRS=install/share:$XDG_DATA_DIRS ./install/bin/gnome-software

I'm not certain I have found the correct places to think about updating the environment variable, as none of these referenced /var/lib/snaped/desktop...And this might not be the issue causing the problem at all! Any help would be welcome!


来源: stackexchange

问:
How to run a script in background (linux openwrt)?
I have this script:

```<code>#!/bin/sh
while [ true ] ; do
    urlfile=$( ls /root/wget/wget-download-link.txt | head -n 1 )
    dir=$( cat /root/wget/wget-dir.txt )
    if [ "$urlfile" = "" ] ; then
        sleep 30
        continue
    fi

    url=$( head -n 1 $urlfile )
    if [ "$url" = "" ] ; then
        mv $urlfile $urlfile.invalid
        continue
    fi

    mv $urlfile $urlfile.busy
    wget -b $url -P $dir -o /www/wget.log -c -t 100 -nc
    mv $urlfile.busy $urlfile.done
done
</code>```

The script basically checks for any new URLs at wget-download-link.txt for every 30 seconds and if there's a new URL it'll download it with wget, the problem is that when I try to run this script on Putty like this

```<code>/root/wget/wget_download.sh --daemon
</code>```

it's still running in the foreground, I still can see the terminal output. How do I make it run in the background ?

答:
In another way these code would tried:

```<code>ssh admin@192.168.1.1 "/jffs/your_script.sh &"
</code>```

Simple and without any programs like nohup screen...

(BTW: worked on Asus-Merlin firmware)

ContentLicense: CC BY-SA 3.0

Body:
I have this script:

#!/bin/sh
while [ true ] ; do
    urlfile=$( ls /root/wget/wget-download-link.txt | head -n 1 )
    dir=$( cat /root/wget/wget-dir.txt )
    if [ "$urlfile" = "" ] ; then
        sleep 30
        continue
    fi

    url=$( head -n 1 $urlfile )
    if [ "$url" = "" ] ; then
        mv $urlfile $urlfile.invalid
        continue
    fi

    mv $urlfile $urlfile.busy
    wget -b $url -P $dir -o /www/wget.log -c -t 100 -nc
    mv $urlfile.busy $urlfile.done
done

The script basically checks for any new URLs at wget-download-link.txt for every 30 seconds and if there's a new URL it'll download it with wget, the problem is that when I try to run this script on Putty like this

/root/wget/wget_download.sh --daemon

it's still running in the foreground, I still can see the terminal output. How do I make it run in the background ?

Body:
In another way these code would tried:

ssh admin@192.168.1.1 "/jffs/your_script.sh &"

Simple and without any programs like nohup screen...

(BTW: worked on Asus-Merlin firmware)

ContentLicense: CC BY-SA 4.0


问:
aligning the text in a div to the bottom
I have two divs next to each other, one with float: right and the other with float: left. The one on the left contains an image (200x100px) and the div on the right should contain a text. I would like to have the text of the div on the right to start on the bottom left of the div instead of the top left, is that possible somehow?
Thanks

答:
you can try to add to your div this css:</p>

```<code> #rightDiv{
   display: table;
   vertical-align: bottom;
}
</code>```

Body:
you can try to add to your div this css:

 #rightDiv{
   display: table;
   vertical-align: bottom;
}


问:
structure initialization for xh711 issue
I am building a program for Xh711 on esp32. I have defined a a struct and i am trying to initialize it. I am getting the next error.

could not convert '{GPIO_NUM_18, GPIO_NUM_19, 0, 1, 1, GAIN64, 0, -1,
storm->ad_str_t::smoothed, storm->ad_str_t::sampling,
storm->ad_str_t::timerHandle}' from '' to 'ad_xh711_handle_t'

```<code>void str_init_Xh711(ad_str_t *storm){

    printf("Starting xh711...\n");
    ad_xh711_handle_t xh711={
        .dout= GPIO_NUM_18,
        .scl= GPIO_NUM_19,
        .offset = 0,
        .calibrationFactor = 1,//NULL,
        .conversionFactor=1,
        .gainValue= Gain::GAIN64,
        .rawData =0,//NULL,
        .value = -1,
        .smoothed =storm->smoothed,
        .sampling =storm->sampling,
        .timerHandle = storm->timerHandle
    };

    xh711_init(&xh711,Gain::GAIN64);

}

typedef struct {
    gpio_num_t dout;
    gpio_num_t scl;
    int32_t offset = 0;
    double calibrationFactor;
    double conversionFactor=1;

    Gain gainValue;
    int32_t rawData;
    double value = -1;
    bool smoothed;
    uint8_t sampling;
    esp_timer_handle_t timerHandle;
}ad_xh711_handle_t;
</code>```

答: default values in typedef can not work and have to be removed</p>

Body:
I am building a program for Xh711 on esp32. I have defined a a struct and i am trying to initialize it. I am getting the next error.

could not convert '{GPIO_NUM_18, GPIO_NUM_19, 0, 1, 1, GAIN64, 0, -1,
storm->ad_str_t::smoothed, storm->ad_str_t::sampling,
storm->ad_str_t::timerHandle}' from '' to 'ad_xh711_handle_t'

void str_init_Xh711(ad_str_t *storm){

    printf("Starting xh711...\n");
    ad_xh711_handle_t xh711={
        .dout= GPIO_NUM_18,
        .scl= GPIO_NUM_19,
        .offset = 0,
        .calibrationFactor = 1,//NULL,
        .conversionFactor=1,
        .gainValue= Gain::GAIN64,
        .rawData =0,//NULL,
        .value = -1,
        .smoothed =storm->smoothed,
        .sampling =storm->sampling,
        .timerHandle = storm->timerHandle
    };

    xh711_init(&xh711,Gain::GAIN64);

}

typedef struct {
    gpio_num_t dout;
    gpio_num_t scl;
    int32_t offset = 0;
    double calibrationFactor;
    double conversionFactor=1;

    Gain gainValue;
    int32_t rawData;
    double value = -1;
    bool smoothed;
    uint8_t sampling;
    esp_timer_handle_t timerHandle;
}ad_xh711_handle_t;


问:
Pandas Dataframe datetime condition
I have the following dataframe and would like to create a new column based on a condition. The new column should contain 'Night' for the hours between 20:00 and 06:00, 'Morning' for the time between 06:00 and 14:30 and 'Afternoon' for the time between 14:30 and 20:00. How can I formulate and apply such a condition best way?</p>
```<code>import pandas as pd

df = {'A' : ['test', '2222', '1111', '3333', '1111'],
        'B' : ['aaa', 'aaa', 'bbbb', 'ccccc', 'aaa'],
        'Date' : ['15.07.2018 06:23:56', '15.07.2018 01:23:56', '15.07.2018 06:40:06', '15.07.2018 11:38:27', '15.07.2018 21:38:27'],
        'Defect': [0, 1, 0, 1, 0]
        }

df = pd.DataFrame(df)
df['Date'] = pd.to_datetime(df['Date'])
</code>```

答:
You can create an index of the date field and then use indexer_between_time.

```<code>idx = pd.DatetimeIndex(df["Date"])
conditions = [
    ("20:00", "06:00", "Night"),
    ("06:00", "14:30", "Morning"),
    ("14:30", "20:00", "Afternoon"),
]

for cond in conditions:
    start, end, val = cond
    df.loc[idx.indexer_between_time(start, end, include_end=False), "Time_of_Day"] = val

      A      B                Date  Defect Time_of_Day
0  test    aaa 2018-07-15 06:23:56       0     Morning
1  2222    aaa 2018-07-15 01:23:56       1       Night
2  1111   bbbb 2018-07-15 06:40:06       0     Morning
3  3333  ccccc 2018-07-15 11:38:27       1     Morning
4  1111    aaa 2018-07-15 21:38:27       0       Night
</code>```

Title: Pandas Dataframe datetime condition

Body:
I have the following dataframe and would like to create a new column based on a condition. The new column should contain 'Night' for the hours between 20:00 and 06:00, 'Morning' for the time between 06:00 and 14:30 and 'Afternoon' for the time between 14:30 and 20:00. How can I formulate and apply such a condition best way?

import pandas as pd

df = {'A' : ['test', '2222', '1111', '3333', '1111'],
        'B' : ['aaa', 'aaa', 'bbbb', 'ccccc', 'aaa'],
        'Date' : ['15.07.2018 06:23:56', '15.07.2018 01:23:56', '15.07.2018 06:40:06', '15.07.2018 11:38:27', '15.07.2018 21:38:27'],
        'Defect': [0, 1, 0, 1, 0]
        }

df = pd.DataFrame(df)
df['Date'] = pd.to_datetime(df['Date'])

Body:
You can create an index of the date field and then use indexer_between_time.

idx = pd.DatetimeIndex(df["Date"])
conditions = [
    ("20:00", "06:00", "Night"),
    ("06:00", "14:30", "Morning"),
    ("14:30", "20:00", "Afternoon"),
]

for cond in conditions:
    start, end, val = cond
    df.loc[idx.indexer_between_time(start, end, include_end=False), "Time_of_Day"] = val

      A      B                Date  Defect Time_of_Day
0  test    aaa 2018-07-15 06:23:56       0     Morning
1  2222    aaa 2018-07-15 01:23:56       1       Night
2  1111   bbbb 2018-07-15 06:40:06       0     Morning
3  3333  ccccc 2018-07-15 11:38:27       1     Morning
4  1111    aaa 2018-07-15 21:38:27       0       Night


问:
a2enmod command not found in apache server using cpanel in linux vps
after going to /etc/httpd/conf/httpd.conf  and even after changing

```<code>Allow override none -> Allow override All , and then restarting the server using

service httpd restart
</code>```

and then i type the command

```<code> a2enmod proxy
</code>```

then i get an error :

```<code>bash- a2enmod command not found. .
</code>```

Can you please help me? i am getting an error in the  developer tools console when i am using web-sockets and so for that i need to enable web-sockets proxy.

答: On Debian a2enmod is located at /usr/sbin/a2enmod and sometimes /usr/sbin is not in your PATH.

Body:
after going to /etc/httpd/conf/httpd.conf  and even after changing

Allow override none -> Allow override All , and then restarting the server using

service httpd restart

and then i type the command

 a2enmod proxy

then i get an error :

bash- a2enmod command not found. .

Can you please help me? i am getting an error in the  developer tools console when i am using web-sockets and so for that i need to enable web-sockets proxy.


问:
How do I get the answers on the table using vanilla JS?
I am trying to get the answers in the table and am unsure how to do so using only Javascript. No JQuery
https://jsfiddle.net/4yxz39gk/

```<code>const grid=document.querySelector(".grid")
const smallgrid=document.querySelector(".grid-small")
let num = []
let times= []

function arr(){
    for (let i=0; i<169; i++){
       let small=document.createElement("div")
       grid.appendChild(small)
       num.push(small)

        num[i].classList.add("grid-small")

    }

}

arr()

function time(){
    for(let i=1; i<13; i++){
        for(let j=1; j<13; j++){
            let result = i*j
            times.push(result)

        }
    }
}
time()
console.log(times)
</code>```

How do I add my answers to my table!
Any help is much appreciated.

Thanks

答:
I don't know if this is exactly what you want.</p>
```<code>function time(){
    let index = 0;
    for(let i=1; i<=13; i++){
        for(let j=1; j<=13; j++){
            index++;
            let result = i*j
            times.push(result)
            document.querySelector(`.grid > div:nth-child(${index})`).textContent = result
        }
    }
}
</code>```

Body:
I am trying to get the answers in the table and am unsure how to do so using only Javascript. No JQuery
https://jsfiddle.net/4yxz39gk/

const grid=document.querySelector(".grid")
const smallgrid=document.querySelector(".grid-small")
let num = []
let times= []

function arr(){
    for (let i=0; i<169; i++){
       let small=document.createElement("div")
       grid.appendChild(small)
       num.push(small)

        num[i].classList.add("grid-small")

    }

}

arr()

function time(){
    for(let i=1; i<13; i++){
        for(let j=1; j<13; j++){
            let result = i*j
            times.push(result)

        }
    }
}
time()
console.log(times)

How do I add my answers to my table!
Any help is much appreciated.

Thanks

Body:
I don't know if this is exactly what you want.

function time(){
    let index = 0;
    for(let i=1; i<=13; i++){
        for(let j=1; j<=13; j++){
            index++;
            let result = i*j
            times.push(result)
            document.querySelector(`.grid > div:nth-child(${index})`).textContent = result
        }
    }
}


问:
I want to let my Discord Bot send images/gifs
I've been trying every bit of code I find that might work but either the command doesn't load (it says the bot is typing and then stops) or just the bot itself doesn't work. I'm using Python.</p>

答:
You can use file parameter

await ctx.send("Any text", file=discord.File("NAME.png"))
```
<p><strong>If you get an error with file path:</strong></p>
<pre class="lang-py prettyprint-override"><code>import os

//Not necesarryif the fileis in the same folder!
os.chdir("C:/Users/COMPUTER-NAME/Desktop/Bot-Folder/")

await ctx.send("ANY TEXT", file=discord.File("NAME-OF-THE-IMAGE.png"))
</code>```

If you use embed:

embed.set_image(url="DIRECT IMAGE URL")
```

Body:
You can use file parameter

await ctx.send("Any text", file=discord.File("NAME.png"))

If you get an error with file path:

import os

//Not necesarryif the fileis in the same folder!
os.chdir("C:/Users/COMPUTER-NAME/Desktop/Bot-Folder/")

await ctx.send("ANY TEXT", file=discord.File("NAME-OF-THE-IMAGE.png"))

If you use embed:

embed.set_image(url="DIRECT IMAGE URL")


问:
Dictionary key name from combination of string and variable value
Basically, I am trying to append values from a list as key-value pairs to a new dictionary. I want the key names in a specific format and order.

```<code>#!/usr/bin/env python3
ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for val in range(len(ipv4_list)):
    ipv4_dic[i] = ipv4_list[val]
    i+=1

print(ipv4_dic)
</code>```

Current output:

```<code>{1: '192.168.1.2', 2: '192.168.1.3', 3: '192.168.1.4'}
</code>```

The above is good but I want to change key names to something like IP1, IP2, etc.

How do I make that in the line ipv4_dic[i] = ipv4_list[key]

I tried something like ipv4_dic["IP"+i] but does not work.

```<code>    ipv4_dic["IP"+i] = ipv4_list[val]
TypeError: can only concatenate str (not "int") to str
</code>```

The expected dictionary output as follows:

```<code>{IP1: '192.168.1.2', IP2: '192.168.1.3', IP3: '192.168.1.4'}
</code>```

答:
It does not work because you are trying to concatenate a string with an integer, which is not allowed in Python.

In order to have your code working with the minimum possible amendments is to transform the integer i to a string, via the str() function, i.e. replacing in your code

```<code>ipv4_dic["IP"+i] = ipv4_list[val]
</code>```

with

```<code>ipv4_dic["IP"+str(i)] = ipv4_list[val]
</code>```

However, you can use dict comprehension, i.e. you loop each position of the ipv4_dic you're about to create, placing there a key built from each element of your ipv4_list, in a single line of code.

```<code>ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {f"IP{i+1}": ipv4_list[i] for i in range(len(ipv4_list))}
</code>```

Explanation:
for each i in the range from 0 to len(ipv4_list) we are building the single dictionary key through an f-string, concatenating the string "IP" to the value i+1 (the range starts at 0, but you want your first dict element to be "IP1", that's why i+1). Then, we set the value for this key as ipv4_list[i], which are the single elements contained in your starting list.

The basic  usage is

```<code>l = ['A', 'B', 'C']

d = {i : l[i] for i in range(len(l))}
</code>```

which is pretty similar to your case, without the refinements in the keys creation, since you're incrementing the index (i.e. i) and concatenating it to a string.

Body:
Basically, I am trying to append values from a list as key-value pairs to a new dictionary. I want the key names in a specific format and order.

#!/usr/bin/env python3
ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for val in range(len(ipv4_list)):
    ipv4_dic[i] = ipv4_list[val]
    i+=1

print(ipv4_dic)

Current output:

{1: '192.168.1.2', 2: '192.168.1.3', 3: '192.168.1.4'}

The above is good but I want to change key names to something like IP1, IP2, etc.

How do I make that in the line ipv4_dic[i] = ipv4_list[key]

I tried something like ipv4_dic["IP"+i] but does not work.

    ipv4_dic["IP"+i] = ipv4_list[val]
TypeError: can only concatenate str (not "int") to str

The expected dictionary output as follows:

{IP1: '192.168.1.2', IP2: '192.168.1.3', IP3: '192.168.1.4'}

Body:
It does not work because you are trying to concatenate a string with an integer, which is not allowed in Python.

In order to have your code working with the minimum possible amendments is to transform the integer i to a string, via the str() function, i.e. replacing in your code

ipv4_dic["IP"+i] = ipv4_list[val]

with

ipv4_dic["IP"+str(i)] = ipv4_list[val]

However, you can use dict comprehension, i.e. you loop each position of the ipv4_dic you're about to create, placing there a key built from each element of your ipv4_list, in a single line of code.

ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {f"IP{i+1}": ipv4_list[i] for i in range(len(ipv4_list))}

Explanation:
for each i in the range from 0 to len(ipv4_list) we are building the single dictionary key through an f-string, concatenating the string "IP" to the value i+1 (the range starts at 0, but you want your first dict element to be "IP1", that's why i+1). Then, we set the value for this key as ipv4_list[i], which are the single elements contained in your starting list.

The basic  usage is

l = ['A', 'B', 'C']

d = {i : l[i] for i in range(len(l))}

which is pretty similar to your case, without the refinements in the keys creation, since you're incrementing the index (i.e. i) and concatenating it to a string.


问:
JSF and j_security_check connection
I have an .xhtml page in which I have tried both BalusC's suggestion here and also the following without avoiding the OP's issue

```<code>  <meta http-equiv="refresh" content="#{session.maxInactiveInterval}"/>
</code>```

Basically, I start the application and the form based authentication page is rendered.  I then wait for the session time to expire.  If I try to login after that then the OP's problem occurs.

答:
<meta http-equiv="refresh" content="#{session.maxInactiveInterval}"/>
```

<p>The <code>#{session}</code> is available in Facelets only. That it doesn't work suggests that you are not using Facelets for this particular view, but its legacy predecesor JSP or even plain vanilla HTML.</p>

<p>For JSP you should be using <code>${pageContext.session}</code> to get the session, exactly as demonstrated in my answer on the question which you found yourself.</p>

<pre class="lang-xml prettyprint-override"><code><meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval}"/>
</code>```

Or, much better, get rid of legacy JSP altogether and replace it by its successor Facelets.

Title: JSF and j_security_check connection

Body:
I have an .xhtml page in which I have tried both BalusC's suggestion here and also the following without avoiding the OP's issue

  <meta http-equiv="refresh" content="#{session.maxInactiveInterval}"/>

Basically, I start the application and the form based authentication page is rendered.  I then wait for the session time to expire.  If I try to login after that then the OP's problem occurs.

Body:
<meta http-equiv="refresh" content="#{session.maxInactiveInterval}"/>

The #{session} is available in Facelets only. That it doesn't work suggests that you are not using Facelets for this particular view, but its legacy predecesor JSP or even plain vanilla HTML.

For JSP you should be using ${pageContext.session} to get the session, exactly as demonstrated in my answer on the question which you found yourself.

<meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval}"/>

Or, much better, get rid of legacy JSP altogether and replace it by its successor Facelets.


问:
Writing in the beginning of a text file Java
I need to write something into a text file's beginning. I have a text file with content and i want write something before this content. Say i have;

Good afternoon sir,how are you today?

  I'm fine,how are you?

  Thanks for asking,I'm great

After modifying,I want it to be like this:

Page 1-Scene 59

  25.05.2011

Good afternoon sir,how are you today?

  I'm fine,how are you?

  Thanks for asking,I'm great

Just made up the content :) How can i modify a text file like this way?

答:
I will leave it here just in case anyone need</p>
```<code>    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try (FileInputStream fileInputStream1 = new FileInputStream(fileName1);
         FileInputStream fileInputStream2 = new FileInputStream(fileName2)) {

        while (fileInputStream2.available() > 0) {
            byteArrayOutputStream.write(fileInputStream2.read());
        }
        while (fileInputStream1.available() > 0) {
            byteArrayOutputStream.write(fileInputStream1.read());
        }
    }
    try (FileOutputStream fileOutputStream = new FileOutputStream(fileName1)) {
        byteArrayOutputStream.writeTo(fileOutputStream);
    }
</code>```

Body:
I will leave it here just in case anyone need

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try (FileInputStream fileInputStream1 = new FileInputStream(fileName1);
         FileInputStream fileInputStream2 = new FileInputStream(fileName2)) {

        while (fileInputStream2.available() > 0) {
            byteArrayOutputStream.write(fileInputStream2.read());
        }
        while (fileInputStream1.available() > 0) {
            byteArrayOutputStream.write(fileInputStream1.read());
        }
    }
    try (FileOutputStream fileOutputStream = new FileOutputStream(fileName1)) {
        byteArrayOutputStream.writeTo(fileOutputStream);
    }


答:
Dictionaries work like this:

```<code>thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
</code>```

Try this:

```<code>ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for key in range(len(ipv4_list)):
    auxStr = "IP" + str(i)  #convert i to string, and merging IP
     ipv4_dic[auxStr] = ipv4_list[key]
    i+=1

print(ipv4_dic)
</code>```

This should do it!
Happy coding!!!

Title: Dictionary key name from combination of string and variable value

Body:
Dictionaries work like this:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

Try this:

ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for key in range(len(ipv4_list)):
    auxStr = "IP" + str(i)  #convert i to string, and merging IP
     ipv4_dic[auxStr] = ipv4_list[key]
    i+=1

print(ipv4_dic)

This should do it!
Happy coding!!!


问:
Flutter Error: No named parameter with the name 'displayLarge'
I am working on an app, I posted last update on git 2 days ago and haven't touched the code since. Now, I opened android studio and it was giving me this error when I tried to run it... I tried deleting repository from my computer and then cloning it again but it didn't work. I have also tried searching for similar problems, and found out there was a similar problem with speed-dial package and one comment said something about broken package versions. Anyways, this is the error I am getting after I try running my app:

These are first few lines of the error it's giving me, but there is more than a thousand lines following these.

I also tried running flutter doctor and it gave me the following:

答:
Please follow the below steps to solve the issue.

Open pubspec.yaml file.

Change google_fonts: ^2.2.0 to google_fonts: 2.2.0

Save.


问:
When I try to destructure my state object in react typescript, I get an `Object is possibly 'undefined'` error
When I try to destructure my state object in react typescript, I get an Object is possibly 'undefined' error. If I use optional chaining I got this error const newUser: NewUser | undefined Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.

The error is showing when I am trying to destructure object RegisterUser(newUser?.email, newUser?.password, newUser?.name, navigate)

My Code:

```<code>type NewUser ={
    name: string,
    email: string,
    password: string,
    navigate: string
}

const Register = () => {
    const [newUser, setNewUser] = useState<NewUser>() // single object will return

    const [RegisterUser] = UseFirebase()
    const navigate = useNavigate()

    const handleValues = (e: any) => {
        const field = e.target.name;
        const value = e.target.value
        const user: any = { ...newUser }
        user[field] = value
        setNewUser(user)

    }

    const handleRegister = (e: any) => {
        e.preventDefault()
        // ERROR
        RegisterUser(newUser.email, newUser.password, newUser.name, navigate)
        // console.log('user name', newUser.name, newUser.email, newUser.password);
    }
.......
</code>```

Could someone please tell me what type of mistake I made?

答:
If your object is not undefined, you should try</p>
```<code>   RegisterUser(newUser!.email, newUser!.password, newUser!.name, navigate)
</code>```

Body:
When I try to destructure my state object in react typescript, I get an Object is possibly 'undefined' error. If I use optional chaining I got this error const newUser: NewUser | undefined Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.

The error is showing when I am trying to destructure object RegisterUser(newUser?.email, newUser?.password, newUser?.name, navigate)

My Code:

type NewUser ={
    name: string,
    email: string,
    password: string,
    navigate: string
}

const Register = () => {
    const [newUser, setNewUser] = useState<NewUser>() // single object will return

    const [RegisterUser] = UseFirebase()
    const navigate = useNavigate()

    const handleValues = (e: any) => {
        const field = e.target.name;
        const value = e.target.value
        const user: any = { ...newUser }
        user[field] = value
        setNewUser(user)

    }

    const handleRegister = (e: any) => {
        e.preventDefault()
        // ERROR
        RegisterUser(newUser.email, newUser.password, newUser.name, navigate)
        // console.log('user name', newUser.name, newUser.email, newUser.password);
    }
.......

Could someone please tell me what type of mistake I made?

Body:
If your object is not undefined, you should try

   RegisterUser(newUser!.email, newUser!.password, newUser!.name, navigate)


问:
Call the same function with two different types from a when condition
I was wondering if it was possible to group a call to a function that is present for two different types, without having to create two branches in the "when" statement.

For example, in my case I have this class extensions:

// File: PublisherExtensions.kt

fun <T> Mono<T>.toServiceResponse(): Mono<Response<T>> =
    this.map { r -> Response(true, r, null) }
        .onErrorResume { e -> Mono.just(Response(false, null, Response.Error(500, e.message))) }

fun <T> Flux<T>.toServiceResponse(): Mono<Response<List<T>>> =
    this.collectList()
        .map { r -> Response(true, r, null) }
        .onErrorResume { e -> Mono.just(Response(false, null, Response.Error(500, e.message))) }
```
<p>And what I use with them is this statement:</p>
<pre class="lang-kotlin prettyprint-override"><code>val body = when (val value = result.returnValue) {
    is Mono<*> -> value.toServiceResponse()
    is Flux<*> -> value.toServiceResponse()
    else -> throw RuntimeException("The \"body\" should be Mono<*> or Flux<*>!")
}
</code>```

While what I would like would be this:

val body = when (val value = result.returnValue) {
    is Mono<*>, is Flux<*> -> value.toServiceResponse()
    else -> throw RuntimeException("The \"body\" should be Mono<*> or Flux<*>!")
}
```

The IDE gives me this error:

Unresolved reference.

None of the following candidates is applicable because of receiver type mismatch:

public fun  Flux<TypeVariable(T)>.toServiceResponse(): Mono<Response<List<TypeVariable(T)>>> defined in brc.studybuddy.backend.wrapper.util in file PublisherExtensions.kt

public fun  Mono<TypeVariable(T)>.toServiceResponse(): Mono<Response<TypeVariable(T)>> defined in brc.studybuddy.backend.wrapper.util in file PublisherExtensions.kt

答:
Notice that the second toServiceResponse can be defined in terms of the first:

```<code>fun <T> Flux<T>.toServiceResponse(): Mono<Response<List<T>>> =
    this.collectList().toServiceResponse()
</code>```

So you are almost doing the same thing on Monos and Fluxes, except that for Fluxes, you also call collectList first.

```<code>val body = when (val value = result.returnValue) {
    is Mono<*> -> value
    is Flux<*> -> value.collectList()
    else -> throw RuntimeException("The \"body\" should be Mono<*> or Flux<*>!")
}.toServiceResponse()
</code>```

Alternatively, without a when:

```<code>val body = result.returnValue.let { value ->
    (value as? Flux<*>)?.collectList()
    ?: (value as? Mono<*>)
    ?: throw RuntimeException("The \"body\" should be Mono<*> or Flux<*>!")
}.toServiceResponse()
</code>```

Body:
I was wondering if it was possible to group a call to a function that is present for two different types, without having to create two branches in the "when" statement.

For example, in my case I have this class extensions:

// File: PublisherExtensions.kt

fun <T> Mono<T>.toServiceResponse(): Mono<Response<T>> =
    this.map { r -> Response(true, r, null) }
        .onErrorResume { e -> Mono.just(Response(false, null, Response.Error(500, e.message))) }

fun <T> Flux<T>.toServiceResponse(): Mono<Response<List<T>>> =
    this.collectList()
        .map { r -> Response(true, r, null) }
        .onErrorResume { e -> Mono.just(Response(false, null, Response.Error(500, e.message))) }

And what I use with them is this statement:

val body = when (val value = result.returnValue) {
    is Mono<*> -> value.toServiceResponse()
    is Flux<*> -> value.toServiceResponse()
    else -> throw RuntimeException("The \"body\" should be Mono<*> or Flux<*>!")
}

While what I would like would be this:

val body = when (val value = result.returnValue) {
    is Mono<*>, is Flux<*> -> value.toServiceResponse()
    else -> throw RuntimeException("The \"body\" should be Mono<*> or Flux<*>!")
}

The IDE gives me this error:

Unresolved reference.

None of the following candidates is applicable because of receiver type mismatch:

public fun  Flux<TypeVariable(T)>.toServiceResponse(): Mono<Response<List<TypeVariable(T)>>> defined in brc.studybuddy.backend.wrapper.util in file PublisherExtensions.kt

public fun  Mono<TypeVariable(T)>.toServiceResponse(): Mono<Response<TypeVariable(T)>> defined in brc.studybuddy.backend.wrapper.util in file PublisherExtensions.kt

Body:
Notice that the second toServiceResponse can be defined in terms of the first:

fun <T> Flux<T>.toServiceResponse(): Mono<Response<List<T>>> =
    this.collectList().toServiceResponse()

So you are almost doing the same thing on Monos and Fluxes, except that for Fluxes, you also call collectList first.

val body = when (val value = result.returnValue) {
    is Mono<*> -> value
    is Flux<*> -> value.collectList()
    else -> throw RuntimeException("The \"body\" should be Mono<*> or Flux<*>!")
}.toServiceResponse()

Alternatively, without a when:

val body = result.returnValue.let { value ->
    (value as? Flux<*>)?.collectList()
    ?: (value as? Mono<*>)
    ?: throw RuntimeException("The \"body\" should be Mono<*> or Flux<*>!")
}.toServiceResponse()


问:
Error go: module github.com/golang/protobuf is deprecated: Use the "google.golang.org/protobuf" module instead
I am facing an error after generating the code in golang from .proto file

enter image description here

I tried this line after searching in stackoverflow :

```<code>go get -u github.com/golang/protobuf/protoc-gen-go
</code>```

and I get :

enter image description here

答:
I think you should run

```<code>go install google.golang.org/protobuf/cmd
</code>```

and generate your code using it.

P.S. after installation the binary will be put to $GOPATH/bin

Body:
I am facing an error after generating the code in golang from .proto file

enter image description here

I tried this line after searching in stackoverflow :

go get -u github.com/golang/protobuf/protoc-gen-go

and I get :

enter image description here

Body:
I think you should run

go install google.golang.org/protobuf/cmd

and generate your code using it.

P.S. after installation the binary will be put to $GOPATH/bin


答:
You can use np.select:

```<code>from datetime import time

condlist = [df['Date'].dt.time.between(time(6), time(14, 30)),
            df['Date'].dt.time.between(time(14,30), time(20))]

df['Time'] = np.select(condlist, ['Morning', 'Afternoon'], default='Night')
</code>```

Output:

```<code>>>> df
      A      B                Date  Defect     Time
0  test    aaa 2018-07-15 06:23:56       0  Morning
1  2222    aaa 2018-07-15 01:23:56       1    Night
2  1111   bbbb 2018-07-15 06:40:06       0  Morning
3  3333  ccccc 2018-07-15 11:38:27       1  Morning
4  1111    aaa 2018-07-15 21:38:27       0    Night
</code>```

Note, you don't need the condition for 'Night':

```<code>df['Date'].dt.time.between(time(20), time(23,59,59)) \
| df['Date'].dt.time.between(time(0), time(6))
</code>```

because np.select can take a default value as argument.

Title: Pandas Dataframe datetime condition

Body:
I have the following dataframe and would like to create a new column based on a condition. The new column should contain 'Night' for the hours between 20:00 and 06:00, 'Morning' for the time between 06:00 and 14:30 and 'Afternoon' for the time between 14:30 and 20:00. How can I formulate and apply such a condition best way?

import pandas as pd

df = {'A' : ['test', '2222', '1111', '3333', '1111'],
        'B' : ['aaa', 'aaa', 'bbbb', 'ccccc', 'aaa'],
        'Date' : ['15.07.2018 06:23:56', '15.07.2018 01:23:56', '15.07.2018 06:40:06', '15.07.2018 11:38:27', '15.07.2018 21:38:27'],
        'Defect': [0, 1, 0, 1, 0]
        }

df = pd.DataFrame(df)
df['Date'] = pd.to_datetime(df['Date'])

Body:
You can use np.select:

from datetime import time

condlist = [df['Date'].dt.time.between(time(6), time(14, 30)),
            df['Date'].dt.time.between(time(14,30), time(20))]

df['Time'] = np.select(condlist, ['Morning', 'Afternoon'], default='Night')

Output:

>>> df
      A      B                Date  Defect     Time
0  test    aaa 2018-07-15 06:23:56       0  Morning
1  2222    aaa 2018-07-15 01:23:56       1    Night
2  1111   bbbb 2018-07-15 06:40:06       0  Morning
3  3333  ccccc 2018-07-15 11:38:27       1  Morning
4  1111    aaa 2018-07-15 21:38:27       0    Night

Note, you don't need the condition for 'Night':

df['Date'].dt.time.between(time(20), time(23,59,59)) \
| df['Date'].dt.time.between(time(0), time(6))

because np.select can take a default value as argument.


问:
How can I fix my OpenCV4 installation on Ubuntu
I need some help. I want to install Opencv4 on my computer (which runs on Ubuntu) and use it with VSCode.

A lot of tutorial explains how to do it, so here is one of thoses I followed: https://vitux.com/opencv_ubuntu/

I, next, took a program my teacher sent me to check installation:

```<code>#include <iostream>
#include <string>
#include <opencv4/opencv2/highgui.hpp>

using namespace cv;
using namespace std;

int main(void)
{
    string imageName("/home/baptiste/Documents/M1/infographie/images/lena.jpg"); // path to the image

    Mat img;
    img = imread(imageName, IMREAD_COLOR); // Read the file as a color image
    if( img.empty() )                      // Check for invalid input
    {
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;
    }

    Mat img_gray;

    img_gray = imread(imageName,IMREAD_GRAYSCALE); //Read the file as a grayscale image
    if( img_gray.empty() )                      // Check for invalid input
    {
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;
    }

    imshow( "Image read", img );                // Show our color image inside the window.

    imshow("Grayscale image read", img_gray); //Show our grayscale image inside the window.

    waitKey(0); // Wait for a keystroke in the window
    imwrite("/home/baptiste/Documents/M1/infographie/images/lena_gray.jpg", img_gray); //Save our grayscale image into the file
    return 0;
}
</code>```

I also wrote a makefile:

```<code>CC=g++

read_image: read_image.cpp
    $(CC) read_image.cpp -o read_image `pkg-config --libs --cflags opencv4`

clean:
    rm -f read_image
</code>```

But when I am compiling, I got this:

```<code>g++ read_image.cpp -o read_image `pkg-config --libs --cflags opencv4`
In file included from read_image.cpp:3:
/usr/local/include/opencv4/opencv2/highgui.hpp:46:10: fatal error: opencv2/core.hpp: Aucun fichier ou dossier de ce type
   46 | #include "opencv2/core.hpp"
      |          ^~~~~~~~~~~~~~~~~~
compilation terminated.
make: *** [makefile:4 : read_image] Erreur 1
</code>```

I also spot a problem with my opencv installation: in /usr/local/include, I have a opencv4 folder, which contains...a opencv2 folder, and then the whole installation.

I am interpreting this as: the inclusion made by the modules are not reading at the good place. My program actually recognize the location of highgui.hpp, but that module does not recognize the good location for core.hpp

I did not saw anyone having that problem so it might be quite weird but can someone help me with that ?

Also, I added "/usr/local/include/opencv4/**" into my VSCode configuration.

Thank you for your answer, and for the time you will invest.

EDIT 1:
Here is my c_cpp_properties.json:

```<code>    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/local/include/opencv4/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/clang",
            "cStandard": "c11",
            "cppStandard": "c++14",
            "intelliSenseMode": "linux-clang-x64"
        }
    ],
    "version": 4
}
</code>```

And how do I the "tasks.json" file ?

答:
I am interpreting this as: the inclusion made by the modules are not reading at the good place. My program actually recognize the location of highgui.hpp, but that module does not recognize the good location for core.hpp

nice & correct analysis, for a noob !!

your teacher's test program is already incorrect

```<code>#include <opencv4/opencv2/highgui.hpp>
</code>```

should be:

```<code>#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>      // added for clarity
#include <opencv2/imgcodecs.hpp> // same
</code>```

and you should probably drop the (opaque and badly supported) pkg-config parts from your makefile, and add paths / libs manually, so you at least "know, what you're doing":

```<code>CC=g++
INC=/usr/local/include/opencv4
LIB=/usr/local/lib
LIBS=-lopencv_core -lopencv_highgui -lopencv_imgcodecs
read_image: read_image.cpp
    $(CC) -I$(INC) read_image.cpp -o read_image -L$(LIB) $(LIBS)

clean:
    rm -f read_image

</code>```

Body:
I need some help. I want to install Opencv4 on my computer (which runs on Ubuntu) and use it with VSCode.

A lot of tutorial explains how to do it, so here is one of thoses I followed: https://vitux.com/opencv_ubuntu/

I, next, took a program my teacher sent me to check installation:

#include <iostream>
#include <string>
#include <opencv4/opencv2/highgui.hpp>

using namespace cv;
using namespace std;

int main(void)
{
    string imageName("/home/baptiste/Documents/M1/infographie/images/lena.jpg"); // path to the image

    Mat img;
    img = imread(imageName, IMREAD_COLOR); // Read the file as a color image
    if( img.empty() )                      // Check for invalid input
    {
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;
    }

    Mat img_gray;

    img_gray = imread(imageName,IMREAD_GRAYSCALE); //Read the file as a grayscale image
    if( img_gray.empty() )                      // Check for invalid input
    {
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;
    }

    imshow( "Image read", img );                // Show our color image inside the window.

    imshow("Grayscale image read", img_gray); //Show our grayscale image inside the window.

    waitKey(0); // Wait for a keystroke in the window
    imwrite("/home/baptiste/Documents/M1/infographie/images/lena_gray.jpg", img_gray); //Save our grayscale image into the file
    return 0;
}

I also wrote a makefile:

CC=g++

read_image: read_image.cpp
    $(CC) read_image.cpp -o read_image `pkg-config --libs --cflags opencv4`

clean:
    rm -f read_image

But when I am compiling, I got this:

g++ read_image.cpp -o read_image `pkg-config --libs --cflags opencv4`
In file included from read_image.cpp:3:
/usr/local/include/opencv4/opencv2/highgui.hpp:46:10: fatal error: opencv2/core.hpp: Aucun fichier ou dossier de ce type
   46 | #include "opencv2/core.hpp"
      |          ^~~~~~~~~~~~~~~~~~
compilation terminated.
make: *** [makefile:4 : read_image] Erreur 1

I also spot a problem with my opencv installation: in /usr/local/include, I have a opencv4 folder, which contains...a opencv2 folder, and then the whole installation.

I am interpreting this as: the inclusion made by the modules are not reading at the good place. My program actually recognize the location of highgui.hpp, but that module does not recognize the good location for core.hpp

I did not saw anyone having that problem so it might be quite weird but can someone help me with that ?

Also, I added "/usr/local/include/opencv4/**" into my VSCode configuration.

Thank you for your answer, and for the time you will invest.

EDIT 1:
Here is my c_cpp_properties.json:

    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/local/include/opencv4/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/clang",
            "cStandard": "c11",
            "cppStandard": "c++14",
            "intelliSenseMode": "linux-clang-x64"
        }
    ],
    "version": 4
}

And how do I the "tasks.json" file ?

Body:
I am interpreting this as: the inclusion made by the modules are not reading at the good place. My program actually recognize the location of highgui.hpp, but that module does not recognize the good location for core.hpp

nice & correct analysis, for a noob !!

your teacher's test program is already incorrect

#include <opencv4/opencv2/highgui.hpp>

should be:

#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>      // added for clarity
#include <opencv2/imgcodecs.hpp> // same

and you should probably drop the (opaque and badly supported) pkg-config parts from your makefile, and add paths / libs manually, so you at least "know, what you're doing":

CC=g++
INC=/usr/local/include/opencv4
LIB=/usr/local/lib
LIBS=-lopencv_core -lopencv_highgui -lopencv_imgcodecs
read_image: read_image.cpp
    $(CC) -I$(INC) read_image.cpp -o read_image -L$(LIB) $(LIBS)

clean:
    rm -f read_image


问:
can html5 do this- change color x to color y (floodfill) on image?
I dont have any html5 knowldge.

I need to do  a simple floodfill - change color x to color y on existing images.

Can HTML5 do that?
Could you provide an  example on how to do that?

Thanks !

答:
You would need to draw that image on a <canvas> element first.

Here's how to do a fill and this tutorial describes how to load an image.


问:
GCloud powershell commands throw error but works fine in cmd
When I run GCloud comannds via windows cmd prompt it works.

But when I run them via powershell it throws an error in red, but the command gets completed successfully.

Eg:

1) Auth

```<code>gcloud auth activate-service-account xxx@xxx-xxx.iam.gserviceaccount.com --key-file=C:\xxxxx\cred.json
</code>```

Error:

```<code>python.exe : Activated service account credentials for: [xxxx@xxxx.iam.gserviceaccount.com]
At xxxxxxxxxxxx\gcloud.ps1:117 char:3
+   & "$cloudsdk_python" $run_args_array
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Activated servi...iceaccount.com]:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
</code>```

2) Upload file to storage bucket

```<code>gsutil cp $outputFile gs://bucketxxx
</code>```

Error:

```<code>gsutil : Copying file://N:\out\sqlserver\tag.csv [Content-Type=application/vnd.ms-excel]...
At xxxxxxx\RDS_SQLServer_ExportData_DataWarehouse.ps1:38 char:5
+     gsutil cp $outputFile gs://bucketxxx  | out-null
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Copying file://...nd.ms-excel]...:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

/ [0 files][    0.0 B/  2.8 MiB]
/ [1 files][  2.8 MiB/  2.8 MiB]
Operation completed over 1 objects/2.8 MiB.
</code>```

答:
I was not able comment, hence adding my inputs here.

First : The issue only seems to occur when this is run via Powershell ISE and not when executed via powershell prompt.

Second : This is not as such an error, for example when you see your own error you find the text after Not Specified as "Activated servi..."  which means the action is sucessfully performed. Hope this helps to someone else stumbeling over here

```<code>python.exe : Activated service account credentials for: [xxxx@xxxx.iam.gserviceaccount.com]
At xxxxxxxxxxxx\gcloud.ps1:117 char:3
+   & "$cloudsdk_python" $run_args_array
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Activated servi...iceaccount.com]:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
</code>```

Body:
When I run GCloud comannds via windows cmd prompt it works.

But when I run them via powershell it throws an error in red, but the command gets completed successfully.

Eg:

1) Auth

gcloud auth activate-service-account xxx@xxx-xxx.iam.gserviceaccount.com --key-file=C:\xxxxx\cred.json

Error:

python.exe : Activated service account credentials for: [xxxx@xxxx.iam.gserviceaccount.com]
At xxxxxxxxxxxx\gcloud.ps1:117 char:3
+   & "$cloudsdk_python" $run_args_array
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Activated servi...iceaccount.com]:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

2) Upload file to storage bucket

gsutil cp $outputFile gs://bucketxxx

Error:

gsutil : Copying file://N:\out\sqlserver\tag.csv [Content-Type=application/vnd.ms-excel]...
At xxxxxxx\RDS_SQLServer_ExportData_DataWarehouse.ps1:38 char:5
+     gsutil cp $outputFile gs://bucketxxx  | out-null
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Copying file://...nd.ms-excel]...:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

/ [0 files][    0.0 B/  2.8 MiB]
/ [1 files][  2.8 MiB/  2.8 MiB]
Operation completed over 1 objects/2.8 MiB.

Body:
I was not able comment, hence adding my inputs here.

First : The issue only seems to occur when this is run via Powershell ISE and not when executed via powershell prompt.

Second : This is not as such an error, for example when you see your own error you find the text after Not Specified as "Activated servi..."  which means the action is sucessfully performed. Hope this helps to someone else stumbeling over here

python.exe : Activated service account credentials for: [xxxx@xxxx.iam.gserviceaccount.com]
At xxxxxxxxxxxx\gcloud.ps1:117 char:3
+   & "$cloudsdk_python" $run_args_array
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Activated servi...iceaccount.com]:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError


答:
ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dict= {}

# enumerate will give you the index and value of the iterator
# f-string can compute the value inside the {} and format it like a string

for index,value in enumerate(ipv4_list):
    ipv4_dict[f"IP{index+1}"] = value
# or
ipv4_dict_1 = {f"IP{index+1}": value for index,value in enumerate(ipv4_list)}

# out:
print(ipv4_dict)
# {'IP1': '192.168.1.2', 'IP2': '192.168.1.3', 'IP3': '192.168.1.4'}
print(ipv4_dict_1)
# {'IP1': '192.168.1.2', 'IP2': '192.168.1.3', 'IP3': '192.168.1.4'}
```

Body:
Basically, I am trying to append values from a list as key-value pairs to a new dictionary. I want the key names in a specific format and order.

#!/usr/bin/env python3
ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for val in range(len(ipv4_list)):
    ipv4_dic[i] = ipv4_list[val]
    i+=1

print(ipv4_dic)

Current output:

{1: '192.168.1.2', 2: '192.168.1.3', 3: '192.168.1.4'}

The above is good but I want to change key names to something like IP1, IP2, etc.

How do I make that in the line ipv4_dic[i] = ipv4_list[key]

I tried something like ipv4_dic["IP"+i] but does not work.

    ipv4_dic["IP"+i] = ipv4_list[val]
TypeError: can only concatenate str (not "int") to str

The expected dictionary output as follows:

{IP1: '192.168.1.2', IP2: '192.168.1.3', IP3: '192.168.1.4'}


问:
Flutter - Custom Animation Using CustomPaint
I created a CustomPaint widget and I want to change the heigth from zero to end of screen with smooth animation as shown in the image.

答:
You can use Flutter's AnimationController to drive explicit CustomPaint animation as follows (DartPad):

class AnimatedHeightCustomPaint extends StatefulWidget {

  final AnimationController controller;
  final Size size;
  final Color color;
  final Curve curve;

  const AnimatedHeightCustomPaint({Key? key,
    required this.controller,
    required this.size,
    required this.color,
    this.curve = Curves.linear}) : super(key: key);

  @override
  State<StatefulWidget> createState() => AnimatedHeightCustomPaintState();

}

class AnimatedHeightCustomPaintState extends State<AnimatedHeightCustomPaint>  {

  @override
  void initState() {
    super.initState();
    // Listen to the animation progress and update the custom paint (height in this case)
    widget.controller.addListener(() => setState(() { }));
  }

  @override
  Widget build(BuildContext context) => CustomPaint(
    painter: AnimatedHeightPainter(
      // Here we can apply some fancy animation progress like bounce in
      heightProps: widget.curve.transform(widget.controller.value),
      color: widget.color,
    ),
    // Since you want to change the height, you need to provide a size
    size: widget.size,
  );

}

class AnimatedHeightPainter extends CustomPainter
{

  // Progress of the animation, i.e. between 0.0 and 1.0
  final double heightProps;
  final Color color;

  AnimatedHeightPainter({required this.heightProps, required this.color});

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(Offset(0.0, size.height * (1 - heightProps)) & Size(size.width, size.height * heightProps),
      Paint()..color = color,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;

}
```
<p>As a complete sample,</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {

  // Flutter's AnimationController
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this, // the SingleTickerProviderStateMixin
      duration: const Duration(seconds: 2),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: AnimatedHeightCustomPaint(
          controller: _animationController,
          size: MediaQuery.of(context).size,
          color: Colors.red,
          curve: Curves.bounceInOut,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: ()  {
          // In Parent widget, you can control the animation (back and forth here)
          if(_animationController.isCompleted)  {
            _animationController.reverse();
          }else if(_animationController.isDismissed)  {
            _animationController.forward();
          }
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

class AnimatedHeightCustomPaint extends StatefulWidget {

  final AnimationController controller;
  final Size size;
  final Color color;
  final Curve curve;

  const AnimatedHeightCustomPaint({Key? key,
    required this.controller,
    required this.size,
    required this.color,
    this.curve = Curves.linear}) : super(key: key);

  @override
  State<StatefulWidget> createState() => AnimatedHeightCustomPaintState();

}

class AnimatedHeightCustomPaintState extends State<AnimatedHeightCustomPaint>  {

  @override
  void initState() {
    super.initState();
    // Listen to the animation progress and update the custom paint (height in this case)
    widget.controller.addListener(() => setState(() { }));
  }

  @override
  Widget build(BuildContext context) => CustomPaint(
    painter: AnimatedHeightPainter(
      // Here we can apply some fancy animation progress like bounce in
      heightProps: widget.curve.transform(widget.controller.value),
      color: widget.color,
    ),
    // Since you want to change the height, you need to provide a size
    size: widget.size,
  );

}

class AnimatedHeightPainter extends CustomPainter
{

  // Progress of the animation, i.e. between 0.0 and 1.0
  final double heightProps;
  final Color color;

  AnimatedHeightPainter({required this.heightProps, required this.color});

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(Offset(0.0, size.height * (1 - heightProps)) & Size(size.width, size.height * heightProps),
      Paint()..color = color,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;

}
</code>```

Perhaps You can even use AnimatedContainer if there is no specific reason to use CustomPaint widget (DartPad):

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {

  // Flutter's AnimationController
  bool isExpanded = true;

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Stack(
        children: [
          Align(
            alignment: Alignment.bottomCenter,
            child: AnimatedContainer(
              curve: Curves.bounceInOut,
              width: screenSize.width,
              height: screenSize.height * (isExpanded ? 1: 0),
              duration: const Duration(seconds: 2),
              color: Colors.red,
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: ()  {
          setState(() => isExpanded = !isExpanded);
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
```

Body:
You can use Flutter's AnimationController to drive explicit CustomPaint animation as follows (DartPad):

class AnimatedHeightCustomPaint extends StatefulWidget {

  final AnimationController controller;
  final Size size;
  final Color color;
  final Curve curve;

  const AnimatedHeightCustomPaint({Key? key,
    required this.controller,
    required this.size,
    required this.color,
    this.curve = Curves.linear}) : super(key: key);

  @override
  State<StatefulWidget> createState() => AnimatedHeightCustomPaintState();

}

class AnimatedHeightCustomPaintState extends State<AnimatedHeightCustomPaint>  {

  @override
  void initState() {
    super.initState();
    // Listen to the animation progress and update the custom paint (height in this case)
    widget.controller.addListener(() => setState(() { }));
  }

  @override
  Widget build(BuildContext context) => CustomPaint(
    painter: AnimatedHeightPainter(
      // Here we can apply some fancy animation progress like bounce in
      heightProps: widget.curve.transform(widget.controller.value),
      color: widget.color,
    ),
    // Since you want to change the height, you need to provide a size
    size: widget.size,
  );

}

class AnimatedHeightPainter extends CustomPainter
{

  // Progress of the animation, i.e. between 0.0 and 1.0
  final double heightProps;
  final Color color;

  AnimatedHeightPainter({required this.heightProps, required this.color});

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(Offset(0.0, size.height * (1 - heightProps)) & Size(size.width, size.height * heightProps),
      Paint()..color = color,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;

}

As a complete sample,

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {

  // Flutter's AnimationController
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this, // the SingleTickerProviderStateMixin
      duration: const Duration(seconds: 2),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: AnimatedHeightCustomPaint(
          controller: _animationController,
          size: MediaQuery.of(context).size,
          color: Colors.red,
          curve: Curves.bounceInOut,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: ()  {
          // In Parent widget, you can control the animation (back and forth here)
          if(_animationController.isCompleted)  {
            _animationController.reverse();
          }else if(_animationController.isDismissed)  {
            _animationController.forward();
          }
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

class AnimatedHeightCustomPaint extends StatefulWidget {

  final AnimationController controller;
  final Size size;
  final Color color;
  final Curve curve;

  const AnimatedHeightCustomPaint({Key? key,
    required this.controller,
    required this.size,
    required this.color,
    this.curve = Curves.linear}) : super(key: key);

  @override
  State<StatefulWidget> createState() => AnimatedHeightCustomPaintState();

}

class AnimatedHeightCustomPaintState extends State<AnimatedHeightCustomPaint>  {

  @override
  void initState() {
    super.initState();
    // Listen to the animation progress and update the custom paint (height in this case)
    widget.controller.addListener(() => setState(() { }));
  }

  @override
  Widget build(BuildContext context) => CustomPaint(
    painter: AnimatedHeightPainter(
      // Here we can apply some fancy animation progress like bounce in
      heightProps: widget.curve.transform(widget.controller.value),
      color: widget.color,
    ),
    // Since you want to change the height, you need to provide a size
    size: widget.size,
  );

}

class AnimatedHeightPainter extends CustomPainter
{

  // Progress of the animation, i.e. between 0.0 and 1.0
  final double heightProps;
  final Color color;

  AnimatedHeightPainter({required this.heightProps, required this.color});

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(Offset(0.0, size.height * (1 - heightProps)) & Size(size.width, size.height * heightProps),
      Paint()..color = color,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;

}

Perhaps You can even use AnimatedContainer if there is no specific reason to use CustomPaint widget (DartPad):

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {

  // Flutter's AnimationController
  bool isExpanded = true;

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Stack(
        children: [
          Align(
            alignment: Alignment.bottomCenter,
            child: AnimatedContainer(
              curve: Curves.bounceInOut,
              width: screenSize.width,
              height: screenSize.height * (isExpanded ? 1: 0),
              duration: const Duration(seconds: 2),
              color: Colors.red,
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: ()  {
          setState(() => isExpanded = !isExpanded);
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}


问:
Make a Gradle project work without an internet connection
Given a Gradle project, that has:

Runtime/Compile-time dependencies.

Source/Javadoc Jars of dependencies.

Gradle plugins.

All of which are retrieved from the internet.

How can I download all of these online dependencies to a local folder, and then use them locally in a Gradle project?

The goal is to end up with a project that doesn't rely on an internet connection at all.

答:
You can do a one-time download of your required dependencies to a local folder, and add a local "maven repo", besides the dependencies, it should also work for sources.</p>
```<code>repositories {
   maven {
       url 'file://C:/LocalRepo'
   }
}
</code>```

Body:
You can do a one-time download of your required dependencies to a local folder, and add a local "maven repo", besides the dependencies, it should also work for sources.

repositories {
   maven {
       url 'file://C:/LocalRepo'
   }
}


问:
Gunicorn worker terminated with signal 9
I am running a Flask application and hosting it on Kubernetes from a Docker container. Gunicorn is managing workers that reply to API requests.

The following warning message is a regular occurrence, and it seems like requests are being canceled for some reason. On Kubernetes, the pod is showing no odd behavior or restarts and stays within 80% of its memory and CPU limits.

```<code>[2021-03-31 16:30:31 +0200] [1] [WARNING] Worker with pid 26 was terminated due to signal 9
</code>```

How can we find out why these workers are killed?

答:
In our case application was taking around 5-7 minutes to load ML models and dictionaries into memory.
So adding timeout period of 600 seconds solved the problem for us.

gunicorn main:app \
   --workers 1 \
   --worker-class uvicorn.workers.UvicornWorker \
   --bind 0.0.0.0:8443 \
   --timeout 600
```

Body:
I am running a Flask application and hosting it on Kubernetes from a Docker container. Gunicorn is managing workers that reply to API requests.

The following warning message is a regular occurrence, and it seems like requests are being canceled for some reason. On Kubernetes, the pod is showing no odd behavior or restarts and stays within 80% of its memory and CPU limits.

[2021-03-31 16:30:31 +0200] [1] [WARNING] Worker with pid 26 was terminated due to signal 9

How can we find out why these workers are killed?


问:
why does the outline buttons class show me only gray color?
I am trying to use the outline buttons class(btn btn-outline-primary) in bootstrap but for some reason, all the buttons aren't colored at all I only see them as gray here what I am mean
this is how buttons should look like: https://ibb.co/ChKf83y
but here is how they look for me: https://ibb.co/8X1nHSn
here is the code:</p>
```<code>    <html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <title>toggle</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <style>
    #p {
      position: absolute;
      top: 50%;
      left: 50%;
    }
  </style>
  <body>
    <button  id="p" class="btn btn-outline-warning ">Random Videos</button>
    <button type="button" class="btn btn-outline-primary">Success</button>
  </body>
</html>
</code>```

答: You are using Bootstrap 3 and outline buttons were introduced in Bootstrap 4. You can either upgrade to Bootstrap 4 or use CSS instead.</p>

Body:
I am trying to use the outline buttons class(btn btn-outline-primary) in bootstrap but for some reason, all the buttons aren't colored at all I only see them as gray here what I am mean
this is how buttons should look like: https://ibb.co/ChKf83y
but here is how they look for me: https://ibb.co/8X1nHSn
here is the code:

    <meta charset="utf-8" />
    <title>toggle</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    />

    <button  id="p" class="btn btn-outline-warning ">Random Videos</button>
    <button type="button" class="btn btn-outline-primary">Success</button>


问:
How can I encrypt url in Django Rest Framework?
I found a documentation since it is not working with python updated version so I am having this problem. I want to prevent scrapping from my application. There are some api where I am passing sensitive data and my api endpoing is like localhost:8000/api/products/1 but I want this url to be like
localhost:8000/api/products/dheudhuehdeidiwf4yfg4gfy4yf4f4fu4f84j4i this. So which procedure should I follow here?</p>

答:
One way to go about making your sensitive ids urlsafe would be to use urlsafe_base64_encode from django.utils.http. You could return encrypted ids along with your response to the frontend using:

uidb64 = urlsafe_base64_encode(force_bytes(model_name.pk))

the frontend can then persist the encrypted ids and when request are made to your endpoints using those ids, you then decrypt them using smart_str from django.utils.encoding like this:

model_name_pk = smart_str(urlsafe_base64_decode(uidb64))

assuming your endpoints looks something like this 'api/an-interesting-route/<uidb64>'

This approach is more useful with GET endpoints that do not just return the model directly but include some amount of processing of the id before a response is returned.


问:
Spring Boot : mapping between entity and database not working.(Getting {} in response body)
I'm trying to create a webservice but when I try to get records from database(MariaDB), the response is being shown as {} and does not show the actual fields.The code is as below.

(Imports are hidden)

Customer.java

```<code>
@AllArgsConstructor

@Data
@Entity
@Table(name ="customer")
public class Customer {
    @Id
    @Column(name="customer_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    Long customerId;

    @Column(name = "acc_holder_name")
    String accHolderName;

    @Column(name = "clear_balance")
    Long clearBalance;

    @Column(name = "over_draft")
    Boolean overDraft;

    public Customer() {}

    public Customer(Long id)
    {
        this.customerId = id;
        this.accHolderName = "default";
        this.clearBalance = (long) 0;
        this.overDraft = false;
    }

    public String toString()
    {
        return this.customerId + this.accHolderName;
    }

    public Customer(String accHolderName, long clearBalance, boolean overDraft)
    {
        this.accHolderName = accHolderName;
        this.clearBalance = clearBalance;
        this.overDraft = overDraft;
    }
}
</code>```

CustomerService.java

```<code>
@Service
public class CustomerService {
    private CustomerRepository customerRepo;

    @Autowired
    public CustomerService(CustomerRepository cr)
    {
        this.customerRepo = cr;
    }

    public List<Customer> getCustomers(){
        List<Customer> ls = customerRepo.findAll();
        return ls;
    }

}

</code>```

CustomerController.java

```<code>

@RestController
@RequestMapping("customer")
public class CustomerController {
    private CustomerService custService;

    @Autowired
    public CustomerController(CustomerService cs)
    {
        this.custService = cs;
    }
    @GetMapping
    @ResponseBody
    public List<Customer> getCustomers() {
        return custService.getCustomers();
    }
}
</code>```

application.properties

```<code>spring.datasource.url=jdbc:mariadb://localhost:3306/sample-db
spring.datasource.username=hidden
spring.datasource.password=hidden
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto = update
</code>```

CustomerRepostitory.java

```<code>@Repository
public interface CustomerRepository extends JpaRepository<Customer,Long> {

}
</code>```

My table is  follows

```<code>+-----------------+-------------+------+-----+---------+----------------+
| Field           | Type        | Null | Key | Default | Extra          |
+-----------------+-------------+------+-----+---------+----------------+
| customer_id     | int(11)     | NO   | PRI | NULL    | auto_increment |
| acc_holder_name | varchar(40) | YES  |     | NULL    |                |
| clear_balance   | int(11)     | YES  |     | NULL    |                |
| over_draft      | tinyint(1)  | YES  |     | NULL    |                |
+-----------------+-------------+------+-----+---------+----------------+
</code>```

My table has 6 records inserted. I send the following request

```<code>curl --location --request GET 'localhost:8080/customer/' \
--data-raw ''
</code>```

And get the following response

```<code>[
    {},
    {},
    {},
    {},
    {},
    {}
]
</code>```

答:
It seems it can't serialize the JSON to the output, so you can add @JsonProperty("variable") into all variables in Customer object, like this:

public class Customer {

    @Id
    @Column(name="customer_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @JsonProperty("customerId")
    Long customerId;

    @Column(name = "acc_holder_name")
    @JsonProperty("accHolderName")
    String accHolderName;

    @Column(name = "clear_balance")
    @JsonProperty("clearBalance")
    Long clearBalance;

    @Column(name = "over_draft")
    @JsonProperty("overDraft")
    Boolean overDraft;

    // ...

}
```

Body:
I'm trying to create a webservice but when I try to get records from database(MariaDB), the response is being shown as {} and does not show the actual fields.The code is as below.

(Imports are hidden)

Customer.java

@AllArgsConstructor

@Data
@Entity
@Table(name ="customer")
public class Customer {
    @Id
    @Column(name="customer_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    Long customerId;

    @Column(name = "acc_holder_name")
    String accHolderName;

    @Column(name = "clear_balance")
    Long clearBalance;

    @Column(name = "over_draft")
    Boolean overDraft;

    public Customer() {}

    public Customer(Long id)
    {
        this.customerId = id;
        this.accHolderName = "default";
        this.clearBalance = (long) 0;
        this.overDraft = false;
    }

    public String toString()
    {
        return this.customerId + this.accHolderName;
    }

    public Customer(String accHolderName, long clearBalance, boolean overDraft)
    {
        this.accHolderName = accHolderName;
        this.clearBalance = clearBalance;
        this.overDraft = overDraft;
    }
}

CustomerService.java

@Service
public class CustomerService {
    private CustomerRepository customerRepo;

    @Autowired
    public CustomerService(CustomerRepository cr)
    {
        this.customerRepo = cr;
    }

    public List<Customer> getCustomers(){
        List<Customer> ls = customerRepo.findAll();
        return ls;
    }

}

CustomerController.java

@RestController
@RequestMapping("customer")
public class CustomerController {
    private CustomerService custService;

    @Autowired
    public CustomerController(CustomerService cs)
    {
        this.custService = cs;
    }
    @GetMapping
    @ResponseBody
    public List<Customer> getCustomers() {
        return custService.getCustomers();
    }
}

application.properties

spring.datasource.url=jdbc:mariadb://localhost:3306/sample-db
spring.datasource.username=hidden
spring.datasource.password=hidden
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto = update

CustomerRepostitory.java

@Repository
public interface CustomerRepository extends JpaRepository<Customer,Long> {

}

My table is  follows

+-----------------+-------------+------+-----+---------+----------------+
| Field           | Type        | Null | Key | Default | Extra          |
+-----------------+-------------+------+-----+---------+----------------+
| customer_id     | int(11)     | NO   | PRI | NULL    | auto_increment |
| acc_holder_name | varchar(40) | YES  |     | NULL    |                |
| clear_balance   | int(11)     | YES  |     | NULL    |                |
| over_draft      | tinyint(1)  | YES  |     | NULL    |                |
+-----------------+-------------+------+-----+---------+----------------+

My table has 6 records inserted. I send the following request

curl --location --request GET 'localhost:8080/customer/' \
--data-raw ''

And get the following response

[
    {},
    {},
    {},
    {},
    {},
    {}
]


问:
c++ test if random number is positive or negative
I have school work with C++ and Im new to it. I have to generate 17 random numbers and then test if they are positive/negative/equal to zero. I can't seem to find a way to take the random generated number from the for loop to test it in the if/else if loop. Heeeeelp please :D (The b variable is just there from tests)</p>
```<code>#include <ctime>
using namespace std;
int main() {

    srand(
          (unsigned) time(0)
    );

    int a;
    int b;
    int num;

    for(int a = 0; a<17; a++) {
        cout << "Skaitlis: " << rand()% 20 + -10 << "\n";

        if(b > 0){
            cout << b << " is a positive number." << endl;
        }
        else if (b == 0){
            cout << b << " is equal to zero." << endl;
        }
        else {
            cout << b << " is a negative number." << endl;
        }
   }
}
</code>```

答:
First of all, your variable b has no value at all. In your loop, you are asking 17 times if b is greater, lesser or equal to 0, where is your problem.

You have never never assigned to b. You will fix it by adding
b = rand() % 20 + -10 inside your loop. Now your b has an actual value.

Also, instead of

cout << "Skaitlis: " << rand()% 20 + -10 << "\n";,

change to

cout << "Skaitlis: " << b << endl;.

Also, your cout doensn't exist since it's never declared. What I want to say is that you don't have cout function in your program because cout is found in "iostream" library. You have to include "iostream" library as well, with #include <iostream> at the start of the code.

To clarify:

Your b has no value. Assign a value to b before asking if it's greater, lesser or equal to 0;

cout is not added in your program. Include "iostream" with #include <iostream>

Final code can look like:

#include <iostream> // so I can use cout << and cin >>
#include <ctime>

int main() {
  int b;
  srand(time(NULL)); // NULL is same as 0

  for (int a = 0; a < 17; a++) {
    b = rand() % 21 - 10; // Assign a value between -10 and +10 to b

    if (b > 0) cout << b << "is greater than 0" << endl;

    else if (b < 0) cout << b << "is lower than 0" << endl;

    else cout << b << "is equal to 0" << endl;
  }

  return 0;
}

```

I hope this explanation helps.

Body:
I have school work with C++ and Im new to it. I have to generate 17 random numbers and then test if they are positive/negative/equal to zero. I can't seem to find a way to take the random generated number from the for loop to test it in the if/else if loop. Heeeeelp please :D (The b variable is just there from tests)

#include <ctime>
using namespace std;
int main() {

    srand(
          (unsigned) time(0)
    );

    int a;
    int b;
    int num;

    for(int a = 0; a<17; a++) {
        cout << "Skaitlis: " << rand()% 20 + -10 << "\n";

        if(b > 0){
            cout << b << " is a positive number." << endl;
        }
        else if (b == 0){
            cout << b << " is equal to zero." << endl;
        }
        else {
            cout << b << " is a negative number." << endl;
        }
   }
}

Body:
First of all, your variable b has no value at all. In your loop, you are asking 17 times if b is greater, lesser or equal to 0, where is your problem.

You have never never assigned to b. You will fix it by adding
b = rand() % 20 + -10 inside your loop. Now your b has an actual value.

Also, instead of

cout << "Skaitlis: " << rand()% 20 + -10 << "\n";,

change to

cout << "Skaitlis: " << b << endl;.

Also, your cout doensn't exist since it's never declared. What I want to say is that you don't have cout function in your program because cout is found in "iostream" library. You have to include "iostream" library as well, with #include <iostream> at the start of the code.

To clarify:

Your b has no value. Assign a value to b before asking if it's greater, lesser or equal to 0;

cout is not added in your program. Include "iostream" with #include <iostream>

Final code can look like:

#include <iostream> // so I can use cout << and cin >>
#include <ctime>

int main() {
  int b;
  srand(time(NULL)); // NULL is same as 0

  for (int a = 0; a < 17; a++) {
    b = rand() % 21 - 10; // Assign a value between -10 and +10 to b

    if (b > 0) cout << b << "is greater than 0" << endl;

    else if (b < 0) cout << b << "is lower than 0" << endl;

    else cout << b << "is equal to 0" << endl;
  }

  return 0;
}

I hope this explanation helps.


问:
Updating Bias in a neural network
I would like to know how does the algorithm update the biais in this situation?

Is it

or

?

both give me different results. Or is the way i put the bias above wrong? I think it should differents bias per perceptron.

答:
There is one bias per neuron, not one global bias. In typical implementations you see one bias variable because it is a vector, where i'th dimension is added to i'th neuron.

In the non standard network you drew the update rule is actually ... neither! It should be a sum of your equations. Note, that if you have bias that is a vector, then using a sum will actually work too, because your partial derivatives that you computed will only affect corresponding dimensions!

Title: Updating Bias in a neural network


问:
MySQL query to return rows ordered by averages from another table
I am building a database for a contest in which people upload photos and the jury grades them. I have two tables: photographs (id, name, user_id and section_id) and grades (id, grade, photo_id, juror_id).
What I want to achieve is a query to return all photos ordered by the average of all grades given to each photo.

For example, if we have 2 photographs with ids 1 and 2 with photo 1 having two grades (5, 6) and photo 2 also having two grades (8, 10) the first returned row will be the photo with id 2 (the average of the grades is 9 and it is greater than 5.5, the average of photo 1).

How could I achieve this?

Here is a pseudo-example of a query

```<code>SELECT * FROM photographs ORDER BY AVERAGE(SELECT grade FROM grades)
</code>```

答:
This is a job for AVG() and GROUP BY.

To get the average grade by photo from your grades table this subquery does it.

```<code>                 SELECT AVG(grade) avg_grade,
                        photo_id
                   FROM grades
                  GROUP BY photo_id
</code>```

That subquery is guaranteed to return exactly one row per photo_id value. So you can LEFT JOIN it to your photographs table like so.

```<code>SELECT avg_grade.avg_grade,
       photographs.*
  FROM photographs
  LEFT JOIN (
                 SELECT AVG(grade) avg_grade,
                        photo_id
                   FROM grades
                  GROUP BY photo_id
       ) avg_grade ON photographs.id = avg_grade.photo_id
 ORDER BY avg_grade.avg_grade DESC
</code>```

Body:
I am building a database for a contest in which people upload photos and the jury grades them. I have two tables: photographs (id, name, user_id and section_id) and grades (id, grade, photo_id, juror_id).
What I want to achieve is a query to return all photos ordered by the average of all grades given to each photo.

For example, if we have 2 photographs with ids 1 and 2 with photo 1 having two grades (5, 6) and photo 2 also having two grades (8, 10) the first returned row will be the photo with id 2 (the average of the grades is 9 and it is greater than 5.5, the average of photo 1).

How could I achieve this?

Here is a pseudo-example of a query

SELECT * FROM photographs ORDER BY AVERAGE(SELECT grade FROM grades)

Body:
This is a job for AVG() and GROUP BY.

To get the average grade by photo from your grades table this subquery does it.

                 SELECT AVG(grade) avg_grade,
                        photo_id
                   FROM grades
                  GROUP BY photo_id

That subquery is guaranteed to return exactly one row per photo_id value. So you can LEFT JOIN it to your photographs table like so.

SELECT avg_grade.avg_grade,
       photographs.*
  FROM photographs
  LEFT JOIN (
                 SELECT AVG(grade) avg_grade,
                        photo_id
                   FROM grades
                  GROUP BY photo_id
       ) avg_grade ON photographs.id = avg_grade.photo_id
 ORDER BY avg_grade.avg_grade DESC


问:
Where is an .o file stored when using setup.py install?
Generally, where is the x.o file stored when x.cpp and x.h are compiled?

Specifically, how to fix the error

megatron/fused_kernels/scaled_upper_triang_masked_softmax.o: file not recognized: File format not recognized
collect2: error: ld returned 1 exit status
error: command 'x86_64-linux-gnu-g++' failed with exit status 1
```

when running python ./megatron/fused_kernels/setup.py install?

答: The .o file is included in the .exe/.out file if you don't compile the .cpp file with the -c compiler flag. But if you use the -c compiler flag, it is stored in the same directory as the .cpp file.</p>

Body:
Generally, where is the x.o file stored when x.cpp and x.h are compiled?

Specifically, how to fix the error

megatron/fused_kernels/scaled_upper_triang_masked_softmax.o: file not recognized: File format not recognized
collect2: error: ld returned 1 exit status
error: command 'x86_64-linux-gnu-g++' failed with exit status 1

when running python ./megatron/fused_kernels/setup.py install?


问:
use xarray and numba packages to read data and calculate climatology
To speed up calculation of xarray packages, I tried to add numba guvectorize to functions, but there are several problems:

If I write two functions: read_pr and day_clim, input of day_clim is no longer xarray since guvectorize is set to float64[:], float64[:]. Thus, groupby function does not work. I tried also xr.core.dataarray.DataArray[:], xr.core.dataarray.DataArray[:], but error pops NameError: name 'xr' is not defined.

I would like to apply @guvectorize to read_pr, too. However, guvectorize needs type and shape  declared at first, and the shape along each dimension should remain the same.
For example,

```<code>    (m),(n),(n) -> (m,n)  # ok
    (n),() -> (m,n)  # error
</code>```

Input in read_pr are string and float ( shape: () ), while the output is xarray ( type: <class 'xarray.core.dataarray.DataArray'>, shape: (l,m,n) )

Code:

```<code>from numba import float64, guvectorize
import numba
import numpy as np
import xarray as xr

path = '/data3/USERS/waynetsai/pyaos_wks_samples/data/'
fname = 'cmorph_sample.nc'

lats = -20
latn =  30
lon1 =  89
lon2 = 171
time1 = '2000-01-01'
time2 = '2020-12-31'

def read_pr(path, fname, time1, time2, lats, latn, lon1, lon2):
    with xr.open_dataset(path + fname) as pr_ds:
        pr = (pr_ds.sel(time=slice(time1,time2),
                               lat=slice(lats,latn),
                               lon=slice(lon1,lon2)).cmorph)
    return pr

pr = xr.apply_ufunc(read_pr, path, fname, time1, time2, lats, latn, lon1, lon2)

@guvectorize(
    "(float64[:], float64[:])",
    "(l,m,n) -> (l,m,n)"
)
def day_clim(pr):
    prGB = pr.groupby("time.day")
    prDayClim = prGB.mean("time")
    return prDayClim
prDayClim = xr.apply_ufunc(day_clim, pr)

</code>```

All suggestions are welcome!

答: Numba does not support the functions of the xarray module. Thus, you cannot use Numba to speed up the function read_pr and day_clim. If you want to use Numba for such function, you need to get somehow Numpy arrays from xarrays, and even if you could, there is no groupby function in Numpy yet so this means you will need to rewrite this function, and even if you do that, I expect Numba not to be faster in this case (unless you write a very optimized implementation yourself).

Body:
To speed up calculation of xarray packages, I tried to add numba guvectorize to functions, but there are several problems:

If I write two functions: read_pr and day_clim, input of day_clim is no longer xarray since guvectorize is set to float64[:], float64[:]. Thus, groupby function does not work. I tried also xr.core.dataarray.DataArray[:], xr.core.dataarray.DataArray[:], but error pops NameError: name 'xr' is not defined.

I would like to apply @guvectorize to read_pr, too. However, guvectorize needs type and shape  declared at first, and the shape along each dimension should remain the same.
For example,

    (m),(n),(n) -> (m,n)  # ok
    (n),() -> (m,n)  # error

Input in read_pr are string and float ( shape: () ), while the output is xarray ( type: <class 'xarray.core.dataarray.DataArray'>, shape: (l,m,n) )

Code:

from numba import float64, guvectorize
import numba
import numpy as np
import xarray as xr

path = '/data3/USERS/waynetsai/pyaos_wks_samples/data/'
fname = 'cmorph_sample.nc'

lats = -20
latn =  30
lon1 =  89
lon2 = 171
time1 = '2000-01-01'
time2 = '2020-12-31'

def read_pr(path, fname, time1, time2, lats, latn, lon1, lon2):
    with xr.open_dataset(path + fname) as pr_ds:
        pr = (pr_ds.sel(time=slice(time1,time2),
                               lat=slice(lats,latn),
                               lon=slice(lon1,lon2)).cmorph)
    return pr

pr = xr.apply_ufunc(read_pr, path, fname, time1, time2, lats, latn, lon1, lon2)

@guvectorize(
    "(float64[:], float64[:])",
    "(l,m,n) -> (l,m,n)"
)
def day_clim(pr):
    prGB = pr.groupby("time.day")
    prDayClim = prGB.mean("time")
    return prDayClim
prDayClim = xr.apply_ufunc(day_clim, pr)

All suggestions are welcome!


答:
First of all you need to join your table properly, then to agreagat result, and after that to order output:</p>
```<code>SELECT
    p.id,
    AVG(g.grade) AS averageGrade
    FROM photographs AS p
    JOIN grade AS g ON g.photo_id = p.id
    GROUP BY p.Id
    ORDER BY AVG(g.grade) DESC
</code>```

Title: MySQL query to return rows ordered by averages from another table

Body:
First of all you need to join your table properly, then to agreagat result, and after that to order output:

SELECT
    p.id,
    AVG(g.grade) AS averageGrade
    FROM photographs AS p
    JOIN grade AS g ON g.photo_id = p.id
    GROUP BY p.Id
    ORDER BY AVG(g.grade) DESC


问:
Mic Volume Meter
i'm currently working on a personal project to create a c# small program that let me know when people clap laugther (i just need to know the volume peak value)? Using Laptop Internal mic or input line (for external mic).
I'm not much of an expert so i was wondering if someone can give me a guidance of how to use NAudio to achieve my goal.

Best Regards.

答:
First download latest version of NAudio from dll-files.com

Then add NAudio to your project reference

Then insert this code given below in using group:

using NAudio;
using NAudio.CoreAudioApi;
using NAudio.Wave;
```
<p>After adding code given above, add this void "For Mono Use" or if you want for stereo, go down</p>
<pre class="lang-cs prettyprint-override"><code>private void Mono_REC(ProgressBar pb)
{
    MMDeviceEnumerator MDE = new MMDeviceEnumerator();
    MMDevice MD = MDE.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
    WaveIn mic = new WaveIn();
    mic.StartRecording();
    var AMI = MD.AudioMeterInformation;
    pb.Value = AMI.MasterPeakValue * 100;
}
</code>```

Stereo

private void Stereo_REC(ProgressBar left, ProgressBar right)
{
    MMDeviceEnumerator MDE = new MMDeviceEnumerator();
    MMDevice MD = MDE.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
    WaveIn mic = new WaveIn();
    mic.StartRecording();
    var AMI = MD.AudioMeterInformation;
    left.Value = AMI.PeakValues[0] * 100;
    right.Value = AMI.PeakValues[1] * 100;
}
```
<p>If <code>mic.StartRecording();</code> isn't working in any one or both voids, then remove:</p>
<pre class="lang-cs prettyprint-override"><code>WaveIn mic = new WaveIn();
mic.StartRecording();
</code>```

And add: WaveIn mic = new WaveIn(); outside all voids and add mic.StartRecording(); in any 1 of following:

private void Form1_Load(Object sender, EventArgs e) {}
private void Button1_Click(Object sender, EventArgs e) {}
```

Title: Mic Volume Meter

Body:
First download latest version of NAudio from dll-files.com

Then add NAudio to your project reference

Then insert this code given below in using group:

using NAudio;
using NAudio.CoreAudioApi;
using NAudio.Wave;

After adding code given above, add this void "For Mono Use" or if you want for stereo, go down

private void Mono_REC(ProgressBar pb)
{
    MMDeviceEnumerator MDE = new MMDeviceEnumerator();
    MMDevice MD = MDE.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
    WaveIn mic = new WaveIn();
    mic.StartRecording();
    var AMI = MD.AudioMeterInformation;
    pb.Value = AMI.MasterPeakValue * 100;
}

Stereo

private void Stereo_REC(ProgressBar left, ProgressBar right)
{
    MMDeviceEnumerator MDE = new MMDeviceEnumerator();
    MMDevice MD = MDE.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
    WaveIn mic = new WaveIn();
    mic.StartRecording();
    var AMI = MD.AudioMeterInformation;
    left.Value = AMI.PeakValues[0] * 100;
    right.Value = AMI.PeakValues[1] * 100;
}

If mic.StartRecording(); isn't working in any one or both voids, then remove:

WaveIn mic = new WaveIn();
mic.StartRecording();

And add: WaveIn mic = new WaveIn(); outside all voids and add mic.StartRecording(); in any 1 of following:

private void Form1_Load(Object sender, EventArgs e) {}
private void Button1_Click(Object sender, EventArgs e) {}


问:
Retrieve a data from an ArrayList
I have this variable:

```<code>protected ArrayList<String> list = new ArrayList<String>();
</code>```

The data is in this form:

```<code>data = date + ": " + y + "L/100KM "+ " " + value1 + "dt "+ value2 + "KM\n";
</code>```

I want to retrieve a data value1 from it. How can I do this?

答: You will have to use regular expressions.</p>

Title: Retrieve a data from an ArrayList

Body:
I have this variable:

protected ArrayList<String> list = new ArrayList<String>();

The data is in this form:

data = date + ": " + y + "L/100KM "+ " " + value1 + "dt "+ value2 + "KM\n";

I want to retrieve a data value1 from it. How can I do this?