问:
requests.get(link, headers=headers).json() fails to load but on browser it load ok
I am trying to access an url with requests.get but on terminal I always get this error:

```<code>Failed to open https://api-mainnet.magiceden.io/rpc/getListedNFTsByQuery?q=%7B%22%24match%22%3A%7B%22collectionSymbol%22%3A%22meekolony%22%7D%2C%22%24sort%22%3A%7B%22takerAmount%22%3A1%2C%22createdAt%22%3A-1%7D%2C%22%24skip%22%3A0%2C%22%24limit%22%3A5%7D
</code>```

However if I click that same link to open it on browser it loads just fine.
Here is some part of the code:

```<code>link = "https://api-mainnet.magiceden.io/rpc/getListedNFTsByQuery?q=%7B%22%24match%22%3A%7B%22collectionSymbol%22%3A%22"+str(nameCollection)+"%22%7D%2C%22%24sort%22%3A%7B%22takerAmount%22%3A1%2C%22createdAt%22%3A-1%7D%2C%22%24skip%22%3A0%2C%22%24limit%22%3A5%7D"
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36'
}
# make the request from the website and convert the data into a JSON file
try:
    # print(resp) will show all the data collected
    resp = requests.get(link, headers=headers).json()

except:
    return None
</code>```

It is strange because some weeks ago everything worked perfect. So maybe the website changed the way of accessing data recently?

Thank you in advance for your help :)

答:
You may have more success with urllib3 as follows:</p>
```<code>import sys
import io
import json
import urllib3

URL = 'https://api-mainnet.magiceden.io/rpc/getListedNFTsByQuery?q={"$match":{"collectionSymbol":"meekolony"},"$sort":{"takerAmount":1,"createdAt":-1},"$skip":0,"$limit":5}'

HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:97.0) Gecko/20100101 Firefox/97.0'
}

with urllib3.PoolManager() as http:
    try:
        if (r := http.request('GET', URL, headers=HEADERS, preload_content=False)).status != 200:
            raise Exception(f'HTTP status {r.status}')
        r.auto_close = False
        j = json.load(io.TextIOWrapper(r))
        print(json.dumps(j, indent=2))
    except Exception as e:
        print(e, file=sys.stderr)
</code>```

Body:
I am trying to access an url with requests.get but on terminal I always get this error:

Failed to open https://api-mainnet.magiceden.io/rpc/getListedNFTsByQuery?q=%7B%22%24match%22%3A%7B%22collectionSymbol%22%3A%22meekolony%22%7D%2C%22%24sort%22%3A%7B%22takerAmount%22%3A1%2C%22createdAt%22%3A-1%7D%2C%22%24skip%22%3A0%2C%22%24limit%22%3A5%7D

However if I click that same link to open it on browser it loads just fine.
Here is some part of the code:

link = "https://api-mainnet.magiceden.io/rpc/getListedNFTsByQuery?q=%7B%22%24match%22%3A%7B%22collectionSymbol%22%3A%22"+str(nameCollection)+"%22%7D%2C%22%24sort%22%3A%7B%22takerAmount%22%3A1%2C%22createdAt%22%3A-1%7D%2C%22%24skip%22%3A0%2C%22%24limit%22%3A5%7D"
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36'
}
# make the request from the website and convert the data into a JSON file
try:
    # print(resp) will show all the data collected
    resp = requests.get(link, headers=headers).json()

except:
    return None

It is strange because some weeks ago everything worked perfect. So maybe the website changed the way of accessing data recently?

Thank you in advance for your help :)

Body:
You may have more success with urllib3 as follows:

import sys
import io
import json
import urllib3

URL = 'https://api-mainnet.magiceden.io/rpc/getListedNFTsByQuery?q={"$match":{"collectionSymbol":"meekolony"},"$sort":{"takerAmount":1,"createdAt":-1},"$skip":0,"$limit":5}'

HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:97.0) Gecko/20100101 Firefox/97.0'
}

with urllib3.PoolManager() as http:
    try:
        if (r := http.request('GET', URL, headers=HEADERS, preload_content=False)).status != 200:
            raise Exception(f'HTTP status {r.status}')
        r.auto_close = False
        j = json.load(io.TextIOWrapper(r))
        print(json.dumps(j, indent=2))
    except Exception as e:
        print(e, file=sys.stderr)


来源: stackexchange

问:
Strip blanks at the beginning & trailing blanks in AWK
I am asking for your assistance to strip blanks/spaces before & at the end each field. ie Remove the trailing space from the $1, the same apply to the beginning & trailing spaces in $2, and the leading spaces from $3 using AWK on AIX 7.2 platform. Below is some data in the file Employee.txt

```<code>001 |  George John Aden Brown   | gbrown
002 |   Barry Street White      | bwhite
003 |    Kelly Jones            | kjones
004 |   Jolene Davidson Smith   | jsmith
</code>```

My objective is to achieve the following set of data (without the leading/trailing spaces)

```<code>001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith
</code>```

I have tried the following without satisfaction.

```<code>awk -F"|" '{ print $1 "|" gsub(" ", "", $2) "|" $3 }' Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[ \t]/,"",$2) "|" $3 }'  Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[[:blank:]]/, "", $2) "|" $3 }' Employee.txt

001 |8| gbrown
002 |11| bwhite
003 |17| kjones
004 |8| jsmith
</code>```

答:
Also with awk

```<code>awk '{$2=$2;gsub(/ \| /,"|")} 1' file
001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith
</code>```

The stripping of leading and trailing whitespace also comes into play whenever $0 is recomputed. (see: http://gnu.ist.utl.pt/software/gawk/manual/html_node/Regexp-Field-Splitting.html )

$2=$2 The assignment of $2 to $2 rebuilds $0. Now we have a new $0 without leading and trailing whitespace.

And we apply to $0 the gsub() function: regexp / \| / for space followed by | character followed by space. This is substituted by | character.

ContentLicense: CC BY-SA 4.0

Body:
I am asking for your assistance to strip blanks/spaces before & at the end each field. ie Remove the trailing space from the $1, the same apply to the beginning & trailing spaces in $2, and the leading spaces from $3 using AWK on AIX 7.2 platform. Below is some data in the file Employee.txt

001 |  George John Aden Brown   | gbrown
002 |   Barry Street White      | bwhite
003 |    Kelly Jones            | kjones
004 |   Jolene Davidson Smith   | jsmith

My objective is to achieve the following set of data (without the leading/trailing spaces)

001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith

I have tried the following without satisfaction.

awk -F"|" '{ print $1 "|" gsub(" ", "", $2) "|" $3 }' Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[ \t]/,"",$2) "|" $3 }'  Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[[:blank:]]/, "", $2) "|" $3 }' Employee.txt

001 |8| gbrown
002 |11| bwhite
003 |17| kjones
004 |8| jsmith

Body:
Also with awk

awk '{$2=$2;gsub(/ \| /,"|")} 1' file
001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith

The stripping of leading and trailing whitespace also comes into play whenever $0 is recomputed. (see: http://gnu.ist.utl.pt/software/gawk/manual/html_node/Regexp-Field-Splitting.html )

$2=$2 The assignment of $2 to $2 rebuilds $0. Now we have a new $0 without leading and trailing whitespace.

And we apply to $0 the gsub() function: regexp / \| / for space followed by | character followed by space. This is substituted by | character.


问:
How to make repaint for JDialog in Swing?
How to make repaint for JDialog in Swing?
If I click on convert button in JDialog I need to change GUI design of JDialog but it's not happening? Is their any solution?

```<code>    _convertAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            String para = new String();
            _task.setBookTypeId(13);
             initComponents();
           //   validate();
           //   repaint();
            setVisible(true);
        }
      };
</code>```

I'm setting booking type id is 13 .

```<code>if(_task.getBookTypeId()== 1){
    String colnames[] = {"Leg","Departure", "Date","Time", "Arrival","Date", "Time","How","Aircraft","PIC","Copilot"};
    MyTableModel mytablemodel = new MyTableModel(colnames);
    legdetailsTable = new JTable(mytablemodel);
    legdetailsTable.setRowSelectionAllowed(true);
}else {
    System.out.println("Brokered booking table");
    String   colnames[] = {"Leg","Departure", "Date","Time", "Arrival","Date", "Time","How"};
    MyTableModel mytablemodel = new MyTableModel(colnames);
    legdetailsTable = new JTable(mytablemodel);
    legdetailsTable.setRowSelectionAllowed(true);
}
</code>```

Using Id I'm changing componenents in initcomponents method.

答:
Instead of

```<code>legdetailsTable = new JTable(mytablemodel);
</code>```

add

```<code>legdetailsTable.setModel(mytablemodel);
</code>```

You recreate JTable but the new one isn't added to layout

ContentLicense: CC BY-SA 3.0

Body:
How to make repaint for JDialog in Swing?
If I click on convert button in JDialog I need to change GUI design of JDialog but it's not happening? Is their any solution?

    _convertAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            String para = new String();
            _task.setBookTypeId(13);
             initComponents();
           //   validate();
           //   repaint();
            setVisible(true);
        }
      };

I'm setting booking type id is 13 .

if(_task.getBookTypeId()== 1){
    String colnames[] = {"Leg","Departure", "Date","Time", "Arrival","Date", "Time","How","Aircraft","PIC","Copilot"};
    MyTableModel mytablemodel = new MyTableModel(colnames);
    legdetailsTable = new JTable(mytablemodel);
    legdetailsTable.setRowSelectionAllowed(true);
}else {
    System.out.println("Brokered booking table");
    String   colnames[] = {"Leg","Departure", "Date","Time", "Arrival","Date", "Time","How"};
    MyTableModel mytablemodel = new MyTableModel(colnames);
    legdetailsTable = new JTable(mytablemodel);
    legdetailsTable.setRowSelectionAllowed(true);
}

Using Id I'm changing componenents in initcomponents method.

Body:
Instead of

legdetailsTable = new JTable(mytablemodel);

add

legdetailsTable.setModel(mytablemodel);

You recreate JTable but the new one isn't added to layout


问:
Multiple sweet alerts execute always the first confirmation callback
When i use multiple sweet alerts in the same page, it calls always the first callback.

I explain:

I have a button to send friend request which becomes a "pending/cancel" button after click

```<code>{{#if addFriend}}
    <li>{{> addFriendBtn user=usr}}</li>
{{/if}}
{{#if pending}}
    <li>{{> pendingFriendBtn user=usr}}</li>
{{/if}}
</code>```

Each btn has a click event calling sweet alert:

```<code>Template.addFriendBtn.events({
'click .add-friend': function (evt,tpl) {
        console.log('inside click .add-friend...');
        const options = {
            title: "Friend request",
            showCancelButton: true,
            confirmButtonText: "Oui",
            closeOnConfirm: true,
            closeOnCancel:true,
            allowOutsideClick: false,
            allowEscapeKey:true
        };

        swal(options, function () {
           console.log("Inside add-friend confirmation swal...");
           Meteor.call('sendFriendRequest', tpl.data.user);
        });
   }
});

Template.pendingFriendBtn.events({
    'click .cancel-request': function (evt, tpl) {
        console.log('inside click .cancel-request');
        const options = {
                    title: "Confirmation",
                    showCancelButton: true,
                    closeOnConfirm: true,
                    closeOnCancel:true,
                    allowOutsideClick: false,
                    allowEscapeKey:true
                };

        swal(options, function(){
           console.log("inside cancel-request confirmation swal...");
           Meteor.call('cancelFriendRequest', tpl.data.user);
         });

    }
});

Meteor.methods({
  sendFriendRequest: function (recipient) {
    console.log('Inside sendFriendRequest...');
    ...
  },

  cancelFriendRequest: function (recipient) {
    console.log('Inside cancelFriendRequest ...');
    ....
  }
});
</code>```

When I click on "Add friend" button the first time, it works fine. I get the sweet alert and after confirmation, my callback is done correctly, and the button becomes "Pending/cancel" button.

When I click after that on this "Pending/cancel" button to cancel my friend request, i get the right sweet alert, but when i confirm, it executes the callback "sendFriendRequest" for the first button "add friend".

I couldn't figure out why it behaves like this... Any thoughts on this issue ? Thanks in advance.

UPDATE:  After adding logs

First click: add friend:

Client logs:

inside click .add-friend…

Inside add-friend confirmation swal…

Server logs:

Inside sendFriendRequest...

Second click: cancel pending request:

Client logs

inside click .cancel-request

Inside add-friend confirmation swal…

Server logs:

Inside sendFriendRequest...

答:
tried two things which solved my problem.

close the first swal by swal.close();

add setTimeout to call the second swal

Body:
When i use multiple sweet alerts in the same page, it calls always the first callback.

I explain:

I have a button to send friend request which becomes a "pending/cancel" button after click

{{#if addFriend}}

{{> addFriendBtn user=usr}}

{{/if}}
{{#if pending}}

{{> pendingFriendBtn user=usr}}

{{/if}}

Each btn has a click event calling sweet alert:

Template.addFriendBtn.events({
'click .add-friend': function (evt,tpl) {
        console.log('inside click .add-friend...');
        const options = {
            title: "Friend request",
            showCancelButton: true,
            confirmButtonText: "Oui",
            closeOnConfirm: true,
            closeOnCancel:true,
            allowOutsideClick: false,
            allowEscapeKey:true
        };

        swal(options, function () {
           console.log("Inside add-friend confirmation swal...");
           Meteor.call('sendFriendRequest', tpl.data.user);
        });
   }
});

Template.pendingFriendBtn.events({
    'click .cancel-request': function (evt, tpl) {
        console.log('inside click .cancel-request');
        const options = {
                    title: "Confirmation",
                    showCancelButton: true,
                    closeOnConfirm: true,
                    closeOnCancel:true,
                    allowOutsideClick: false,
                    allowEscapeKey:true
                };

        swal(options, function(){
           console.log("inside cancel-request confirmation swal...");
           Meteor.call('cancelFriendRequest', tpl.data.user);
         });

    }
});

Meteor.methods({
  sendFriendRequest: function (recipient) {
    console.log('Inside sendFriendRequest...');
    ...
  },

  cancelFriendRequest: function (recipient) {
    console.log('Inside cancelFriendRequest ...');
    ....
  }
});

When I click on "Add friend" button the first time, it works fine. I get the sweet alert and after confirmation, my callback is done correctly, and the button becomes "Pending/cancel" button.

When I click after that on this "Pending/cancel" button to cancel my friend request, i get the right sweet alert, but when i confirm, it executes the callback "sendFriendRequest" for the first button "add friend".

I couldn't figure out why it behaves like this... Any thoughts on this issue ? Thanks in advance.

UPDATE:  After adding logs

First click: add friend:

Client logs:

inside click .add-friend…

Inside add-friend confirmation swal…

Server logs:

Inside sendFriendRequest...

Second click: cancel pending request:

Client logs

inside click .cancel-request

Inside add-friend confirmation swal…

Server logs:

Inside sendFriendRequest...


问:
Deserializing XML with nested fields to a single JavaObject
My goal is to convert the XML to JavaObject and have the JavaObject be able to handle one or more "Tasks".

I would also like to be able to convert the JavaObject to JSON as well.

How can this be done? At it's current state, I am able to convert if only one task exists, anymore results in an error.

I have an XML file that follows this structure:

```<code><Plan>
    <ID></ID>
    <Comment></Comment>
    <CreateTime></CreateTime>
    <Task>...</Task>
    <Task>...</Task>
    <Task>...</Task>
</Plan>
</code>```

Each Task element is structured like so:

```<code>    <Task>
      <Type></Type>
      <Time></Time>
      <Target>
         <Code></Code>
         <TargetId></TargetId>
         <Content>
            <Stuff1></Stuff1>
            <Stuff2></Stuff2>
            <Stuff3></Stuff3>
         </Content>
      </Target>
    </Task>
</code>```

I am able to deserialize the XML when there is only one Task involved. Anymore gives me errors.

My Classes (simplified) are as follows:

```<code>@Root(name = "Plan")
public class Plan{
   @Element(name = "ID")
   private String id;

   @Element(name = "Comment")
   private String comment;

   @Element(name = "CreateTime")
   private String createTime;

   @Element(name = "Task")
   private Task task;
}

@Root(name = "Task")
public class Task{

   @Element(name = "Type")
   private String type;

   @Element(name = "Time")
   private String time;

   @Element(name = "Target")
   private Target target;
}

@Root(name = "Target")
public class Target{

   @Element(name = "Code")
   private String code;

   @Element(name = "TargetId")
   private String targetId;

   @Element(name = "Content")
   private Content content;
}

@Root(name = "Content")
public class Content{

   @Element(name = "Stuff1")
   private String stuff1;

   @Element(name = "Stuff2")
   private String stuff2;

   @Element(name = "Stuff3")
   private String stuff3;
}
</code>```

In the schema file, I set this but doesn't seem to work:

```<code><xs:element name="Task" type="Task" minOccurs="1" maxOccurs="unbounded">
</code>```

答:
At it's current state, I am able to convert if only one task exists,
anymore results in an error.

This happens because your element annotation interprets the task tag as a property, so if there is more than one it raises an error. To avoid this behaviour you can use the JacksonXmlElementWrapper annotation you can apply to your task list:

```<code>public class Plan {

    @JacksonXmlProperty(localName = "Task")
    @JacksonXmlElementWrapper(useWrapping = false)
    List<Task> tasks;
}

public class Task {}
</code>```

This above is a starting basic example you can use to define more complicated xmls.

Body:
My goal is to convert the XML to JavaObject and have the JavaObject be able to handle one or more "Tasks".

I would also like to be able to convert the JavaObject to JSON as well.

How can this be done? At it's current state, I am able to convert if only one task exists, anymore results in an error.

I have an XML file that follows this structure:

<Plan>
    <ID></ID>
    <Comment></Comment>
    <CreateTime></CreateTime>
    <Task>...</Task>
    <Task>...</Task>
    <Task>...</Task>
</Plan>

Each Task element is structured like so:

    <Task>
      <Type></Type>
      <Time></Time>
      <Target>

         <TargetId></TargetId>
         <Content>
            <Stuff1></Stuff1>
            <Stuff2></Stuff2>
            <Stuff3></Stuff3>
         </Content>
      </Target>
    </Task>

I am able to deserialize the XML when there is only one Task involved. Anymore gives me errors.

My Classes (simplified) are as follows:

@Root(name = "Plan")
public class Plan{
   @Element(name = "ID")
   private String id;

   @Element(name = "Comment")
   private String comment;

   @Element(name = "CreateTime")
   private String createTime;

   @Element(name = "Task")
   private Task task;
}

@Root(name = "Task")
public class Task{

   @Element(name = "Type")
   private String type;

   @Element(name = "Time")
   private String time;

   @Element(name = "Target")
   private Target target;
}

@Root(name = "Target")
public class Target{

   @Element(name = "Code")
   private String code;

   @Element(name = "TargetId")
   private String targetId;

   @Element(name = "Content")
   private Content content;
}

@Root(name = "Content")
public class Content{

   @Element(name = "Stuff1")
   private String stuff1;

   @Element(name = "Stuff2")
   private String stuff2;

   @Element(name = "Stuff3")
   private String stuff3;
}

In the schema file, I set this but doesn't seem to work:

<xs:element name="Task" type="Task" minOccurs="1" maxOccurs="unbounded">

Body:
At it's current state, I am able to convert if only one task exists,
anymore results in an error.

This happens because your element annotation interprets the task tag as a property, so if there is more than one it raises an error. To avoid this behaviour you can use the JacksonXmlElementWrapper annotation you can apply to your task list:

public class Plan {

    @JacksonXmlProperty(localName = "Task")
    @JacksonXmlElementWrapper(useWrapping = false)
    List<Task> tasks;
}

public class Task {}

This above is a starting basic example you can use to define more complicated xmls.


问:
Getting corrupted output when using NVENCODE API
I’m trying to use the NVENC API (specifically the AppEncode application) available as part of Video Codec SDK 11.1.5 to encode a yuv video (saved from IMX490 sensor) using H.264 encoding.

After building the required libraries using CMake, I give the following command:

./AppEncCuda -i ~/Desktop/input-yuv420p.yuv -s 320x320 -tuninginfo lowlatency -rc cbr -gpu 0 -bitrate 2M -maxbitrate 4M -vbvbufsize 6M -vbvinit 25 -bf 0 -aq 0 -cq 20 -multipass qres -o ~/Desktop/output-yuv.h264

A bit of additional information:
input-yuv420p.yuv has pixel format yuyv422(progressive), 2880x1860
All the flags set were based on recommended settings (NVENC Video Encoder API Programming Guide :: NVIDIA Video Codec SDK Documentation)

Hardware used: CUDA 11.4, NVIDIA GeForce RTX 3050 Ti

I also tried the equivalent using ffmpeg (h264_nvenc and h264_cuvid) and it works perfectly. However, when I try to encode just using the NVENC APIs I get corrupted outputs. I have tried converting the pixel format to yuv420p and encode, still doesn’t work. When I try to display by encoded files using VLC media player I get green pixels/lines and random colours.

I’m quite new to using NVENC API so I started right away with the Video SDK but I’m facing these issues. I’m not sure what’s causing it, so any advice would be really helpful!

答:
It was as simple as changing -s 320x320 to -s 2880x1860. -s flag denotes the input resolution size rather than scale (which is what I initially assumed).

Ideally a command like this should work smoothly:

```<code>./AppEncCuda -i ~/Desktop/input-yuv420p.yuv -s 2880x1860 -tuninginfo lowlatency -rc cbr -gpu 0 -bitrate 2M -maxbitrate 4M -vbvbufsize 6M -vbvinit 25 -bf 0 -aq 0 -cq 20 -multipass qres -o ~/Desktop/output-yuv.h264
</code>```

Body:
It was as simple as changing -s 320x320 to -s 2880x1860. -s flag denotes the input resolution size rather than scale (which is what I initially assumed).

Ideally a command like this should work smoothly:

./AppEncCuda -i ~/Desktop/input-yuv420p.yuv -s 2880x1860 -tuninginfo lowlatency -rc cbr -gpu 0 -bitrate 2M -maxbitrate 4M -vbvbufsize 6M -vbvinit 25 -bf 0 -aq 0 -cq 20 -multipass qres -o ~/Desktop/output-yuv.h264


问:
@Data from lombok in Android Studio doesn't work
I have proper dependencies

And lombok plugin was installed, so Android Studio know where generation was applied but i still got an error

Please can anyone give me idea what is happening?

答:
EDIT:

from kotlin 1.7.20 with K2 compiler it is possible.

https://kotlinlang.org/docs/whatsnew1720.html#support-for-kotlin-k2-compiler-plugins

OLD:

Ok, I guess my problem somewhat solved. My project have mixed Kotlin\Java code, I found this closed issue in project lombok: https://github.com/projectlombok/lombok/issues/1169

Corresponding to this lombok cant work in Kotlin\Java code normal way cause reasons... and there is two solutions:

Multi module project where all Java code with lobmok separated from Kotlin code and java module should using only java compiler.

Use special plugin from Kotlin which in part solving issue https://kotlinlang.org/docs/lombok.html

Another dum-dum solution: drop lombok annotation on java class and then using some instruments delombok it.This way no javac will be required.


问:
java cannot find symbol class Generated
Hello guys my problem is I generate QClasses with querydsl everything generate nice but if I want run project build failed because cant find symbol. Before that it worked well and suddenly without changing the pom.xml so it not work. I've had this problem before, and if I remember correctly, I fixed it by being in an intellij idea I unmark Generated Sources Root in folder generated-sources.

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>sk.adambarca</groupId>
    <artifactId>server-spring-boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>server-spring-boot</name>
    <description>VUT FIT bachelor thesis</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.16.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <version>5.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>5.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.mysema.commons</groupId>
            <artifactId>mysema-commons-jetty</artifactId>
            <version>6.1.15</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>1.4.2.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.1.3</version>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/generated-sources/java</outputDirectory>
                            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                            <showWarnings>true</showWarnings>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>1.4.2.Final</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>1.4.2.Final</version>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>1.18.22</version>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok-mapstruct-binding</artifactId>
                            <version>0.2.0</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Here is image
enter image description here

答: Ok I solved it the problem was that in intellij idea not enough unmark Generated Sources Root in folder generated-sources but also its subfolders.</p>

Title: java cannot find symbol class Generated

Body:
Hello guys my problem is I generate QClasses with querydsl everything generate nice but if I want run project build failed because cant find symbol. Before that it worked well and suddenly without changing the pom.xml so it not work. I've had this problem before, and if I remember correctly, I fixed it by being in an intellij idea I unmark Generated Sources Root in folder generated-sources.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/>
    </parent>
    <groupId>sk.adambarca</groupId>
    <artifactId>server-spring-boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>server-spring-boot</name>
    <description>VUT FIT bachelor thesis</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.16.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <version>5.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>5.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.mysema.commons</groupId>
            <artifactId>mysema-commons-jetty</artifactId>
            <version>6.1.15</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>1.4.2.Final</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.1.3</version>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/generated-sources/java</outputDirectory>
                            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                            <showWarnings>true</showWarnings>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>1.4.2.Final</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>1.4.2.Final</version>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>1.18.22</version>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok-mapstruct-binding</artifactId>
                            <version>0.2.0</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Here is image
enter image description here


问:
jQuery/JavaScript "this" pointer confusion
The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

```<code>// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("<div>click me</div>").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}
</code>```

答:
Welcome to the world of javascript! :D

You have wandered into the realm of javascript scope and closure.

For the short answer:

```<code>this.bar()
</code>```

is executed under the scope of foo, (as this refers to foo)

```<code>var barf = this.bar;
barf();
</code>```

is executed under the global scope.

this.bar basically means:

execute the function pointed by this.bar, under the scope of this (foo).
When you copied this.bar to barf, and run barf. Javascript understood as, run the function pointed by barf, and since there is no this, it just runs in global scope.

To correct this, you can change

```<code>barf();
</code>```

to something like this:

```<code>barf.apply(this);
</code>```

This tells Javascript to bind the scope of this to barf before executing it.

For jquery events, you will need to use an anonymous function, or extend the bind function in prototype to support scoping.

For more info:

Good explanation on scoping

Extending jQuery bind to supportscoping

OwnerDisplayName: I. J. Kennedy

ContentLicense: CC BY-SA 2.5

Body:
The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("
click me
").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}

Body:
Welcome to the world of javascript! :D

You have wandered into the realm of javascript scope and closure.

For the short answer:

this.bar()

is executed under the scope of foo, (as this refers to foo)

var barf = this.bar;
barf();

is executed under the global scope.

this.bar basically means:

execute the function pointed by this.bar, under the scope of this (foo).
When you copied this.bar to barf, and run barf. Javascript understood as, run the function pointed by barf, and since there is no this, it just runs in global scope.

To correct this, you can change

barf();

to something like this:

barf.apply(this);

This tells Javascript to bind the scope of this to barf before executing it.

For jquery events, you will need to use an anonymous function, or extend the bind function in prototype to support scoping.

For more info:

Good explanation on scoping

Extending jQuery bind to supportscoping

OwnerDisplayName: Aaron Qian

LastEditorDisplayName: Aaron Qian


问:
Type mismatch: cannot convert from element type Object to int
I'm getting the following error on the line where it says ht.keySet():

Type mismatch: cannot convert from element type Object to int

ht is a LinkedHashMap.

```<code>for (int key : ht.keySet())
{
    if(ht.get(key).size() == 0)
    {
         System.out.println("There is no errors in " + key) ;
    }
    else
    {
        System.out.println("ERROR: there are unexpected errors in " + key);
    }
}
</code>```

答:
ht is a LinkedHashMap, if it contains only Integers, you should declare it as LinkedHashMap<Integer,Object>.

If it will be declared as LinkedHashMap<Integer,Object>, the unboxing to an int will be done automatically.

(*) even better if you declare it as LinkedHashMap<Integer,[actual-object-type]>

Body:
I'm getting the following error on the line where it says ht.keySet():

Type mismatch: cannot convert from element type Object to int

ht is a LinkedHashMap.

for (int key : ht.keySet())
{
    if(ht.get(key).size() == 0)
    {
         System.out.println("There is no errors in " + key) ;
    }
    else
    {
        System.out.println("ERROR: there are unexpected errors in " + key);
    }
}


问:
SwiftUI drag gesture coordinates
I'm trying to add a rating system to an application I'm writing. My approach is less than elegant by using a Stepper. I'd like an interactive way of dragging to fill the star rating if possible.

I'm not sure if DragGesture is what I'm looking for, would this suffice? Also, I'm unsure how I would convert the coordinates to the proper width to fill the stars. Any help would be appreciated.

struct ContentView: View {
    @State var rating: Double = 0.0

    var body: some View {
        VStack {
            HStack(spacing: 3) {
                let stars = HStack(spacing: 0) {
                    ForEach(0..<5) { _ in
                        Image(systemName: "star.fill")
                            .font(.title3)
                    }
                }
                stars.overlay(
                    GeometryReader { geometry in
                        ZStack(alignment: .leading) {
                            Rectangle()
                                .frame(width: CGFloat(rating / 2) / 5 * geometry.size.width)
                                .foregroundColor(Color.yellow)
                        }
                    }.mask(stars)
                ).foregroundColor(Color.secondary)
            }
            Stepper("Rating \(String(format: "(%.0f%%)", rating * 10))", value: $rating, in: 0...10, step: 0.5)
        }
        .padding()

        Spacer()
            .frame(height: 100)
        HStack(spacing: 3) {
            let stars = HStack(spacing: 0) {
                ForEach(0..<5) { _ in
                    Image(systemName: "star.fill")
                        .font(.title3)
                }
            }
            stars.overlay(
                GeometryReader { geometry in
                    ZStack(alignment: .leading) {
                        Rectangle()
                            .frame(width: CGFloat(rating / 2) / 5 * geometry.size.width)
                            .foregroundColor(Color.yellow)
                    }
                }.mask(stars)
            ).foregroundColor(Color.secondary)
                .gesture(
                    DragGesture(minimumDistance: 0)
                        .onEnded { end in
                            if (end.location.x - end.startLocation.x) > 0 {
                                print("Right")
                            } else {
                                print("Left")
                            }
                        })
        }
    }
}
```

答:
I used circles as clip shape, but the rest should do what you want.
If you change the @State rating to @Binding you can call it as a subview.

```<code>struct ContentView: View {

    @State var rating = 50.0

    var body: some View {
        VStack {
            Text("Your Rating \(rating, specifier: "%.0f")")

            GeometryReader { geo in
                HStack(spacing: 0) {
                    Color.yellow
                        .frame(width: geo.size.width * rating / 100)
                    Color.gray
                        .frame(width: geo.size.width * (100 - rating) / 100)
                }
                .gesture(
                    DragGesture()
                        .onChanged({ value in
                            rating = ((value.translation.width + value.startLocation.x)
                                      / geo.size.width * 100.0)
                            rating = min(100, max(rating, 0))
                        })
                )
                .clipShape(RatingClipShape())
            }
            .frame(height: 80)
        }
        .padding(30)
    }
}

struct RatingClipShape: Shape {
    let paddingAmount = 5.0 // %
    func path(in rect: CGRect) -> Path {
        let padding = rect.width * paddingAmount / 100
        let diameter = (rect.width - (4 * padding)) / 5
        let step = diameter + padding
        var path = Path()
        for i in 0..<5 {
            path.addEllipse(in: CGRect(x: Double(i)*step, y: 0, width: diameter, height: diameter))
        }
        return path
    }
}
</code>```

Result:

Title: SwiftUI drag gesture coordinates

Body:
I used circles as clip shape, but the rest should do what you want.
If you change the @State rating to @Binding you can call it as a subview.

struct ContentView: View {

    @State var rating = 50.0

    var body: some View {
        VStack {
            Text("Your Rating \(rating, specifier: "%.0f")")

            GeometryReader { geo in
                HStack(spacing: 0) {
                    Color.yellow
                        .frame(width: geo.size.width * rating / 100)
                    Color.gray
                        .frame(width: geo.size.width * (100 - rating) / 100)
                }
                .gesture(
                    DragGesture()
                        .onChanged({ value in
                            rating = ((value.translation.width + value.startLocation.x)
                                      / geo.size.width * 100.0)
                            rating = min(100, max(rating, 0))
                        })
                )
                .clipShape(RatingClipShape())
            }
            .frame(height: 80)
        }
        .padding(30)
    }
}

struct RatingClipShape: Shape {
    let paddingAmount = 5.0 // %
    func path(in rect: CGRect) -> Path {
        let padding = rect.width * paddingAmount / 100
        let diameter = (rect.width - (4 * padding)) / 5
        let step = diameter + padding
        var path = Path()
        for i in 0..<5 {
            path.addEllipse(in: CGRect(x: Double(i)*step, y: 0, width: diameter, height: diameter))
        }
        return path
    }
}

Result:


问:
When running "npm run dev" [webpack-cli] Error: Cannot find module 'vue/compiler-sfc' [Laravel with Vue.js]
after I installed vue.js on my laravel project and running npm run dev this error comes out.

答:
I was having the same problem, basically what was happening is that my version of VUE did not match the version of vue-loader and vue-template-compiler

To solve it I just had to match the versions in package.json and npm install
here are the versions I'm using

```<code>"vue": "^2.6.11",
"vue-loader": "^15.9.6",
"vue-template-compiler": "^2.6.12",
"laravel-mix": "^6.0.6",
</code>```

Body:
I was having the same problem, basically what was happening is that my version of VUE did not match the version of vue-loader and vue-template-compiler

To solve it I just had to match the versions in package.json and npm install
here are the versions I'm using

"vue": "^2.6.11",
"vue-loader": "^15.9.6",
"vue-template-compiler": "^2.6.12",
"laravel-mix": "^6.0.6",


问:
Not able to change the background color of the bs4Dash::dashboardSidebar() properly
1. Color issue using only the bs4Dash package

I am starting to use the package bs4Dash and I am facing a problem with the background color of the left sidebar bs4Dash::dashboardSidebar(). I observe that when I start the app the background color of the left sidebar is always in gray, but when I switch to dark mode and back to light mode the color render with a white color background.

You can observe this behavior using the code below that was taken from help webpage of bs4Dash

```<code>library(shiny)
library(bs4Dash)

shinyApp(
    ui = dashboardPage(
        title = "Basic Dashboard",
        header = dashboardHeader(),
        sidebar = dashboardSidebar(),
        controlbar = dashboardControlbar(),
        footer = dashboardFooter(),
        body = dashboardBody()
    ),
    server = function(input, output) {}
)
</code>```

2. Color problem using fresh and bs4Dash package

Using the package fresh when I open the app for the first time It is still with the grey background color, but when I switch from dark mode to light It renders the color according to fresh::create_theme().

Here is an example

```<code># library

library(shiny)
library(bs4Dash)
library(fresh)

# theme creator with fresh::

mytheme <- create_theme(
    bs4dash_sidebar_light(
        bg = "#FFFF00")
)

#shinyApp

shinyApp(
    ui = dashboardPage(
        title = "Basic Dashboard",
        header = dashboardHeader(),
        sidebar = dashboardSidebar(),
        controlbar = dashboardControlbar(),
        footer = dashboardFooter(),
        body = dashboardBody(use_theme(mytheme)),
        freshTheme = TRUE
    ),
    server = function(input, output) {}
)
</code>```

I found out this issue in the Github but can't figure out how to solve this problem.

答:
This problem was mentioned in this issue. You can fix it by adding skin = "light" in dashboardSidebar(), as below:

```<code>library(shiny)
library(bs4Dash)

shinyApp(
  ui = dashboardPage(
    title = "Basic Dashboard",
    header = dashboardHeader(),
    sidebar = dashboardSidebar(skin = "light"),
    controlbar = dashboardControlbar(),
    footer = dashboardFooter(),
    body = dashboardBody()
  ),
  server = function(input, output) {}
)
</code>```

Body:
1. Color issue using only the bs4Dash package

I am starting to use the package bs4Dash and I am facing a problem with the background color of the left sidebar bs4Dash::dashboardSidebar(). I observe that when I start the app the background color of the left sidebar is always in gray, but when I switch to dark mode and back to light mode the color render with a white color background.

You can observe this behavior using the code below that was taken from help webpage of bs4Dash

library(shiny)
library(bs4Dash)

shinyApp(
    ui = dashboardPage(
        title = "Basic Dashboard",
        header = dashboardHeader(),
        sidebar = dashboardSidebar(),
        controlbar = dashboardControlbar(),
        footer = dashboardFooter(),
        body = dashboardBody()
    ),
    server = function(input, output) {}
)

2. Color problem using fresh and bs4Dash package

Using the package fresh when I open the app for the first time It is still with the grey background color, but when I switch from dark mode to light It renders the color according to fresh::create_theme().

Here is an example

# library

library(shiny)
library(bs4Dash)
library(fresh)

# theme creator with fresh::

mytheme <- create_theme(
    bs4dash_sidebar_light(
        bg = "#FFFF00")
)

#shinyApp

shinyApp(
    ui = dashboardPage(
        title = "Basic Dashboard",
        header = dashboardHeader(),
        sidebar = dashboardSidebar(),
        controlbar = dashboardControlbar(),
        footer = dashboardFooter(),
        body = dashboardBody(use_theme(mytheme)),
        freshTheme = TRUE
    ),
    server = function(input, output) {}
)

I found out this issue in the Github but can't figure out how to solve this problem.

Body:
This problem was mentioned in this issue. You can fix it by adding skin = "light" in dashboardSidebar(), as below:

library(shiny)
library(bs4Dash)

shinyApp(
  ui = dashboardPage(
    title = "Basic Dashboard",
    header = dashboardHeader(),
    sidebar = dashboardSidebar(skin = "light"),
    controlbar = dashboardControlbar(),
    footer = dashboardFooter(),
    body = dashboardBody()
  ),
  server = function(input, output) {}
)


问:
React app will not upload image to aws S3
I have a React app that I'm trying to configure to enable users to upload images via a post form.  The form has other fields in it.

The back end is here: https://github.com/JohnTarvis/a2backend
The front end is here: https://github.com/JohnTarvis/a2frontend

The site is hosted here: https://anonsanonymous.netlify.app/

I'm attempting to incorporate code from this thread:Simple file upload to S3 using aws-sdk and Node/Express

specifically this:

```<code>
const express = require('express'); //"^4.13.4"
const aws = require('aws-sdk'); //"^2.2.41"
const bodyParser = require('body-parser');
const multer = require('multer'); // "^1.3.0"
const multerS3 = require('multer-s3'); //"^2.7.0"

aws.config.update({
    secretAccessKey: 'YOUR_ACCESS_SECRET_KEY',
    accessKeyId: 'YOUR_ACCESS_KEY_ID',
    region: 'us-east-1'
});

const app = express();
const s3 = new aws.S3();

app.use(bodyParser.json());

const upload = multer({
    storage: multerS3({
        s3: s3,
        acl: 'public-read',
        bucket: 'YOUR_BUCKET_NAME',
        key: function (req, file, cb) {
            console.log(file);
            cb(null, file.originalname); //use Date.now() for unique file keys
        }
    })
});

//open http://localhost:3000/ in browser to see upload form
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

//used by upload form
app.post('/upload', upload.array('upl',1), (req, res, next) => {
    res.send("Uploaded!");
});

app.listen(3000, () => {
    console.log('Example app listening on port 3000!');
});

</code>```

And I have something like this in my back end using router.js instead of app.js

```<code>router.post("/",upload.array('upload',1), async function (req, res, next) {
  try {
    const validator = jsonschema.validate(req.body, postNewSchema);
    if (!validator.valid) {
      const errs = validator.errors.map(e => e.stack);
      throw new BadRequestError(errs);
    }

    const newPost = await Post.create(req.body);
    return res.status(201).json({ newPost });
  } catch (err) {
    return next(err);
  }
});
</code>```

This is in my upload form on the front end:

```<code>                <div className="form-group">
                  <label>Upload File</label>
                  <input
                    type="file"
                    name="upload"
                    value={formData.image}
                    onChange={(e) => setSelectedFile(e.target.files[0])}
                  />
                </div>
</code>```

The post appears but the image does not upload.  I'm thinking it could be a problem communicating the file between my front end and back end.  The basic app that I copied from here uploads to my S3 but not the main one I'm working on.  Is it my upload form or my express back end that is having the problem?  I only posted part of my code cause it's several dozen files but if you need to see more, I'll add it.

答:
Step 0: Log in to your aws console. Search for Amazon S3 and click on Create bucket.
Step 1: bootstrap react. you need to create our react app.
Step 2: Import react-aws-s3.
Step 3: Set up file structure.
Step 4: Adding environment variables to .
Step 5: Setting up our Upload component.
Step 6: Grabbing the file.
Step 7: Updating AWS S3 CORS.
Step 6: Implementing the upload functionality.

I'm still new to react  but i hope i can help ,goodluck! :)

Body:
I have a React app that I'm trying to configure to enable users to upload images via a post form.  The form has other fields in it.

The back end is here: https://github.com/JohnTarvis/a2backend
The front end is here: https://github.com/JohnTarvis/a2frontend

The site is hosted here: https://anonsanonymous.netlify.app/

I'm attempting to incorporate code from this thread:Simple file upload to S3 using aws-sdk and Node/Express

specifically this:

const express = require('express'); //"^4.13.4"
const aws = require('aws-sdk'); //"^2.2.41"
const bodyParser = require('body-parser');
const multer = require('multer'); // "^1.3.0"
const multerS3 = require('multer-s3'); //"^2.7.0"

aws.config.update({
    secretAccessKey: 'YOUR_ACCESS_SECRET_KEY',
    accessKeyId: 'YOUR_ACCESS_KEY_ID',
    region: 'us-east-1'
});

const app = express();
const s3 = new aws.S3();

app.use(bodyParser.json());

const upload = multer({
    storage: multerS3({
        s3: s3,
        acl: 'public-read',
        bucket: 'YOUR_BUCKET_NAME',
        key: function (req, file, cb) {
            console.log(file);
            cb(null, file.originalname); //use Date.now() for unique file keys
        }
    })
});

//open http://localhost:3000/ in browser to see upload form
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

//used by upload form
app.post('/upload', upload.array('upl',1), (req, res, next) => {
    res.send("Uploaded!");
});

app.listen(3000, () => {
    console.log('Example app listening on port 3000!');
});

And I have something like this in my back end using router.js instead of app.js

router.post("/",upload.array('upload',1), async function (req, res, next) {
  try {
    const validator = jsonschema.validate(req.body, postNewSchema);
    if (!validator.valid) {
      const errs = validator.errors.map(e => e.stack);
      throw new BadRequestError(errs);
    }

    const newPost = await Post.create(req.body);
    return res.status(201).json({ newPost });
  } catch (err) {
    return next(err);
  }
});

This is in my upload form on the front end:

                  Upload File
                  <input
                    type="file"
                    name="upload"
                    value={formData.image}
                    onChange={(e) => setSelectedFile(e.target.files[0])}
                  />

The post appears but the image does not upload.  I'm thinking it could be a problem communicating the file between my front end and back end.  The basic app that I copied from here uploads to my S3 but not the main one I'm working on.  Is it my upload form or my express back end that is having the problem?  I only posted part of my code cause it's several dozen files but if you need to see more, I'll add it.


问:
Does it matter which type of exception you use in Python?
I'm new to working with exceptions in Python. Wondering how much it matters that you get the type of exception -- i.e. ValueError, FileNotFoundError, TypeError, etc. -- correct. For example:

```<code>files = os.listdir(path)
if not files:
    msg = "directory is empty"
    raise ValueError(msg)
</code>```

Obviously this is not a ValueError. But an error will be raised and the message will be displayed. So, does it matter (functionally) which error type I use? Or is it primarily to inform the user what went wrong?

答:
It's important for being able to selectively handle exceptions correctly. You'll want to have a look at the builtin exception hierarchy. You can see that different exception types inherent from each other, and thus allow you to be specific in which errors you expect and want to handle explicitly, and which you don't:

```<code>except Exception:
</code>```

This handles all exceptions (that you should handle except for ones that you shouldn't).

```<code>except OSError:
</code>```

This handles all errors coming from interactions with the OS.

```<code>except FileNotFoundError:
</code>```

This very specifically handles the case where files aren't found, but not for example PermissionError, which is a separate error within the OSError hierarchy.

You should only handle exceptions when you have a plan what to do with them, and otherwise let them bubble up to either be handled by a higher caller, or let the program terminate if there's an unhandleable error that your program can't do anything about.

Using that hierarchy properly, and defining your own exceptions in a proper hierarchy, makes error handling much easier and your code more maintainable in the long run.

Body:
I'm new to working with exceptions in Python. Wondering how much it matters that you get the type of exception -- i.e. ValueError, FileNotFoundError, TypeError, etc. -- correct. For example:

files = os.listdir(path)
if not files:
    msg = "directory is empty"
    raise ValueError(msg)

Obviously this is not a ValueError. But an error will be raised and the message will be displayed. So, does it matter (functionally) which error type I use? Or is it primarily to inform the user what went wrong?

Body:
It's important for being able to selectively handle exceptions correctly. You'll want to have a look at the builtin exception hierarchy. You can see that different exception types inherent from each other, and thus allow you to be specific in which errors you expect and want to handle explicitly, and which you don't:

except Exception:

This handles all exceptions (that you should handle except for ones that you shouldn't).

except OSError:

This handles all errors coming from interactions with the OS.

except FileNotFoundError:

This very specifically handles the case where files aren't found, but not for example PermissionError, which is a separate error within the OSError hierarchy.

You should only handle exceptions when you have a plan what to do with them, and otherwise let them bubble up to either be handled by a higher caller, or let the program terminate if there's an unhandleable error that your program can't do anything about.

Using that hierarchy properly, and defining your own exceptions in a proper hierarchy, makes error handling much easier and your code more maintainable in the long run.


问:
Signing into slack-desktop not working on 4.23.0 64-bit (Ubuntu)
In the app, going File > Workspace > Sign in to new workspace launches a browser window. After selecting the workspace in browser, it launches back a deep link back to slack but it doesn't work. Nothing happens on the slack-desktop.

When inspecting the commands being run during the linking process it looks like KDE is modifying the link. What do I do to fix this?

答:
The answer provided by Boon is correct. I wanted to leave comment under that answer but apparently I need 50 points to comment so I can only add new answer...

After digging into the matter it sounds like the kde-open5 from kde-cli-tools is doing some funky lower-casing on first element of URL (slack://A/B/C becomes slack://a/B/C). This sounds like an old bug: https://bugs.kde.org/show_bug.cgi?id=429408

I suspect that slack changed in how they handle the links/links has changed - it aligns with slack upgrade in my case: slack-desktop:amd64 from 4.22.0 to 4.23.0.

Looking at process list:

the slack website asks browser to open link with upper case

kde-open5 is run with correct link

slack is run with lower-cased workspace

I've reported this to slack with all the details so I hope it will be fixed.

Workaround:

Just adding some details to what (Boon suggested)

Run the quick script in bash:

```<code>while sleep .1; do ps aux | grep slack | grep -v grep | grep magic; done
</code>```

Try logging in to slack - accept login attempt in browser

You should see login link in console:

```<code>kde-open5 slack://WORKSPACE_ID/magic-login/...
/usr/lib/slack/slack --enable-crashpad slack://workspace_id/magic-login/...
</code>```

Open the slack with correct link:

```<code>/usr/lib/slack/slack --enable-crashpad slack://WORKSPACE_ID/magic-login/...
</code>```

Body:
The answer provided by Boon is correct. I wanted to leave comment under that answer but apparently I need 50 points to comment so I can only add new answer...

After digging into the matter it sounds like the kde-open5 from kde-cli-tools is doing some funky lower-casing on first element of URL (slack://A/B/C becomes slack://a/B/C). This sounds like an old bug: https://bugs.kde.org/show_bug.cgi?id=429408

I suspect that slack changed in how they handle the links/links has changed - it aligns with slack upgrade in my case: slack-desktop:amd64 from 4.22.0 to 4.23.0.

Looking at process list:

the slack website asks browser to open link with upper case

kde-open5 is run with correct link

slack is run with lower-cased workspace

I've reported this to slack with all the details so I hope it will be fixed.

Workaround:

Just adding some details to what (Boon suggested)

Run the quick script in bash:

while sleep .1; do ps aux | grep slack | grep -v grep | grep magic; done

Try logging in to slack - accept login attempt in browser

You should see login link in console:

kde-open5 slack://WORKSPACE_ID/magic-login/...
/usr/lib/slack/slack --enable-crashpad slack://workspace_id/magic-login/...

Open the slack with correct link:

/usr/lib/slack/slack --enable-crashpad slack://WORKSPACE_ID/magic-login/...


问:
C# Reflection- using FieldInfo.SetValue to set a struct field to null safe?
If you use C# reflection to set a (non-nullable) value-type field to null, it appears to accept that and just sets the default value.  But since this behavior is slightly unexpected (I'd expect an exception) and I can't find any docs describing this behavior, I want to know if this is safe.  Or am I relying on some undocumented / undefined behavior?

Example:

```<code>using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        FieldInfo pointField = (typeof(ClassWithAPoint)).GetField("point");

        ClassWithAPoint classWithAPoint = new ClassWithAPoint();
        classWithAPoint.point.x = 1;
        classWithAPoint.point.y = 2;

        //This works to create a default Point struct (0, 0).  But is this safe?
        pointField.SetValue(classWithAPoint, null);

        //Prints: "Point = 0, 0"
        Console.WriteLine($"Point = {classWithAPoint.point.x}, {classWithAPoint.point.y}");
    }

    public struct Point
    {
        public int x;
        public int y;
    }

    public class ClassWithAPoint
    {
        public Point point;
    }
}
</code>```

答:
The behaviour of FieldInfo.SetValue() under these circumstances is not explicitly documented/defined as far as I can find (Feb 2022) but because it takes object (reference type) parameters, any value type value must be boxed.

The behaviour of Convert.To[U]IntXX(object) is to return zero for a null parameter, confirmed by documentation which says something equivalent to this statement for Int32 "A 32-bit signed integer equivalent to the value of value, or zero if value is null."

So you should be safe as long as SetValue() remains true to (consistent with) Convert() method behaviours and documentation.

*** A word of caution ***
Try setting a char field value to null using FieldInfo.SetValue(). Convert.ToChar(null) currently (.NET 6.0) throws a NullReferenceException even though the documentation says "The Unicode character equivalent to the value of value. -or- Char.MinValue if value equals null." but the behaviour itself is consistent with the (C#) fact that other types do not have implicit conversions to char.

Body:
If you use C# reflection to set a (non-nullable) value-type field to null, it appears to accept that and just sets the default value.  But since this behavior is slightly unexpected (I'd expect an exception) and I can't find any docs describing this behavior, I want to know if this is safe.  Or am I relying on some undocumented / undefined behavior?

Example:

using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        FieldInfo pointField = (typeof(ClassWithAPoint)).GetField("point");

        ClassWithAPoint classWithAPoint = new ClassWithAPoint();
        classWithAPoint.point.x = 1;
        classWithAPoint.point.y = 2;

        //This works to create a default Point struct (0, 0).  But is this safe?
        pointField.SetValue(classWithAPoint, null);

        //Prints: "Point = 0, 0"
        Console.WriteLine($"Point = {classWithAPoint.point.x}, {classWithAPoint.point.y}");
    }

    public struct Point
    {
        public int x;
        public int y;
    }

    public class ClassWithAPoint
    {
        public Point point;
    }
}


问:
Should 'make install' depend on compilation?
I have always written build (compilation) and install as completely different (to make(1), even unrelated) stages.  I could even write them in two separate Makefiles since they are completely isolated.

But a year ago or so, I wrote a Makefile where I specified the dependencies between install and compilation, and noticed some good things.

See the following minimal example:

```<code>.PHONY: all
all: build

.PHONY: build
build: foo

.PHONY: install
install: /usr/local/bin/foo

foo: foo.c
    cc -o $@ $<

/usr/local/bin/foo: foo
    install -m 755 -T $< $@
</code>```

Should /usr/local/bin/foo depend on foo or not?

Reasons to state the dependency:

Only install if necessary (if foo was recompiled).
Of course, that saves considerable install time.

The Makefile can compile something if we forgot to compile it (but see below).

Reasons to not state the dependency:

Make sure that you never compile accidentally as root.

Make sure you install the correct files,
even if they were edited more recently than the compiled files.
This would be similar to the concept of a reinstall.
But for that rare scenario, one could run 'make uninstall && make install'.

答:
The GNU Make Manual, section Standard Targets, lists several standard targets and what make users should expect from them. About the install target:

Compile the program and copy the executables, libraries, and so on to the file names where they should reside for actual use. If there is a simple test to verify that a program is properly installed, this target should run that test.

As for running make as root, I think most do sudo make install without second thoughts. If you're not sure what the makefile will do you can review the output of make -n install for any shenanigans (after running make all to review just the install part).

Body:
I have always written build (compilation) and install as completely different (to make(1), even unrelated) stages.  I could even write them in two separate Makefiles since they are completely isolated.

But a year ago or so, I wrote a Makefile where I specified the dependencies between install and compilation, and noticed some good things.

See the following minimal example:

.PHONY: all
all: build

.PHONY: build
build: foo

.PHONY: install
install: /usr/local/bin/foo

foo: foo.c
    cc -o $@ $<

/usr/local/bin/foo: foo
    install -m 755 -T $< $@

Should /usr/local/bin/foo depend on foo or not?

Reasons to state the dependency:

Only install if necessary (if foo was recompiled).
Of course, that saves considerable install time.

The Makefile can compile something if we forgot to compile it (but see below).

Reasons to not state the dependency:

Make sure that you never compile accidentally as root.

Make sure you install the correct files,
even if they were edited more recently than the compiled files.
This would be similar to the concept of a reinstall.
But for that rare scenario, one could run 'make uninstall && make install'.


问:
Display all data of all tables
I want to display all data in my Database without writing a select for each table - how can I do this?

I do not want to do this:

```<code>select * from Customer
select * from Employee
select .............
</code>```

I am using TSQL with MSSQL Server.

答:
For mysql:

Run
SELECT information_schema.TABLES.TABLE_NAME FROM information_schema.TABLES where   table_schema='db_name'

Create a loop which will run select query for each table gotten from the first query.

Title: Display all data of all tables

Body:
I want to display all data in my Database without writing a select for each table - how can I do this?

I do not want to do this:

select * from Customer
select * from Employee
select .............

I am using TSQL with MSSQL Server.


问:
Handling back press from fragment after app get's back from background
I want to handle user back presses in one of the activity's (Java) fragments (Kotlin).

In activity's onCreate method I call

```<code>OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
(...) handling back press when there's other BackPressedDispatcherCallbacks registered (...)
}
getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
</code>```

Then in onCreateView() of a fragment that I want to handle back press instead, I call

```<code>activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
(...) handling back press here, not in activity (...)
}})
</code>```

Everything works as expected until I get the app in the background and then back into the foreground, causing OnStop -> OnStart of both Activity and Fragment to be called.

When this is the case application ignores Fragment callback and Activity's callback is being invoked.

What I figured out is that

onBackPressedDispatcher calls callbacks in reverse order in which they were added. Only if the most recently added callback is not enabled will any previously added callback be called (only last enabled callback is being invoked)

Adding an observer to both Activity and Fragment lifecycles and logging result prints:

FRAG: ON_START
ACT: ON_START
FRAG: ON_RESUME
ACT: ON_RESUME

Activity on OnStart and OnResume gets called after Fragments equivalents, which effectively makes Activity's callback being last active one and receiving back event instead of the fragment.

I'm looking for a solution to that. I would really appreciate any suggestions on how to push it forward.

PS. Approach with calling last fragments method (last on the stack of activity fragmentManager) is not going to work, as currently, it's crucial for the app that these fragments are NOT added to back stack.

答:
You can just use in the activity

```<code>getOnBackPressedDispatcher().addCallback(onBackPressedCallback);
</code>```

Instead of

```<code>getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
</code>```

If you don't pass the lyfecycleOwner in addCallback the callback is immediatly added to the chain of responsibility, so you don't have to wait for the activity state to be STARTED

Body:
I want to handle user back presses in one of the activity's (Java) fragments (Kotlin).

In activity's onCreate method I call

OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
(...) handling back press when there's other BackPressedDispatcherCallbacks registered (...)
}
getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);

Then in onCreateView() of a fragment that I want to handle back press instead, I call

activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
(...) handling back press here, not in activity (...)
}})

Everything works as expected until I get the app in the background and then back into the foreground, causing OnStop -> OnStart of both Activity and Fragment to be called.

When this is the case application ignores Fragment callback and Activity's callback is being invoked.

What I figured out is that

onBackPressedDispatcher calls callbacks in reverse order in which they were added. Only if the most recently added callback is not enabled will any previously added callback be called (only last enabled callback is being invoked)

Adding an observer to both Activity and Fragment lifecycles and logging result prints:

FRAG: ON_START
ACT: ON_START
FRAG: ON_RESUME
ACT: ON_RESUME

Activity on OnStart and OnResume gets called after Fragments equivalents, which effectively makes Activity's callback being last active one and receiving back event instead of the fragment.

I'm looking for a solution to that. I would really appreciate any suggestions on how to push it forward.

PS. Approach with calling last fragments method (last on the stack of activity fragmentManager) is not going to work, as currently, it's crucial for the app that these fragments are NOT added to back stack.

Body:
You can just use in the activity

getOnBackPressedDispatcher().addCallback(onBackPressedCallback);

Instead of

getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);

If you don't pass the lyfecycleOwner in addCallback the callback is immediatly added to the chain of responsibility, so you don't have to wait for the activity state to be STARTED


问:
How to create a mongoose object and simultaneously log the _id
I'm creating subdocuments in my event model under guests that look like below. I would like to console.log the corresponding subdoc Id as each guest id is created.

```<code> {
   "guests" : [
          { "phone" : 11111,
            "_id" : ObjectId("61ef629981f154bead6b0de4")
          },
          { "phone" : 4444444444,
            "_id" : ObjectId("61fca19f95b626e017732139")
          }
       ]
  }
</code>```

I followed the mongoose docs but the code from the docs (below) only logs the first id even as each subsequent doc is created because of the index 0.

```<code>// create a comment
parent.children.push({ name: 'Liesl' });
const subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true
</code>```

I tried removing the index 0 and the console log just produces the ever-growing guests array.

```<code>module.exports.addGuest = async (req, res) => {
    const event = await Event.findById(req.params.id);
    const phone = req.body.guest;
    event.guests.push(phone);
    const guestId = event.guests[0];
    console.log(guestId);
    await event.save();
    res.redirect(`/events/${event._id}`);
}
</code>```

How do I adjust my function to log the corresponding subdoc Id as it's created?

答:
try applying mongoose hooks on your subschema.
mongoose pre save hook is triggered every time a document is saved in your collection and you can log the id of your document which is being saved.

Body:
I'm creating subdocuments in my event model under guests that look like below. I would like to console.log the corresponding subdoc Id as each guest id is created.

 {
   "guests" : [
          { "phone" : 11111,
            "_id" : ObjectId("61ef629981f154bead6b0de4")
          },
          { "phone" : 4444444444,
            "_id" : ObjectId("61fca19f95b626e017732139")
          }
       ]
  }

I followed the mongoose docs but the code from the docs (below) only logs the first id even as each subsequent doc is created because of the index 0.

// create a comment
parent.children.push({ name: 'Liesl' });
const subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true

I tried removing the index 0 and the console log just produces the ever-growing guests array.

module.exports.addGuest = async (req, res) => {
    const event = await Event.findById(req.params.id);
    const phone = req.body.guest;
    event.guests.push(phone);
    const guestId = event.guests[0];
    console.log(guestId);
    await event.save();
    res.redirect(`/events/${event._id}`);
}

How do I adjust my function to log the corresponding subdoc Id as it's created?


问:
flutter don't use plugin versions that require android 31
I have an essential plugin that hasn't been updated in a year. I made the mistake of updating flutter, and now, when I try to build, it is telling me about a whole list of plugins that require android 31. Unfortunately, android 31 breaks the one plugin that I must use. Caret notation in the pubspec.yaml is funny because the documentation says it's supposed to choose a version of the package that works with the dependencies, but it's just not doing that.

答: Run flutter downgrade in command line or reinstall your old version.


问:
Remove whole parent div if contained child div is empty
I'm trying to achieve the following:

I have multiple divs with the class "et_pb_row_inner" that contain two columns each. Each of the columns contain a text container with the class "et_pb_text".

Here's the basic html:

```<code><div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
</div>

<div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
</div>

<div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
</div>

</code>```

I need a way to check if the text in the second column of each row is empty and if so remove the whole row. Like so:

```<code><div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
</div>

<div class="et_pb_row_inner"> <!-- second column text empty, remove whole row -->
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
   <div class="et_pb_column"><div class="et_pb_text">EMPTY</div></div>
</div>

<div class=".et_pb_row_inner"> <!-- second column text empty, remove whole row -->
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
   <div class="et_pb_column"><div class="et_pb_text">EMPTY</div></div>
</div>

</code>```

I found a code snippet and tried the following:

```<code>$(function() {
    $('.et_pb_row_inner').each(function() {
        if ($('.et_pb_text', this).text() == "" ) {
            $('.et_pb_row_inner').hide();
        }
    });
});
</code>```

It kind of works, but it removes ALL divs with the class "et_pb_row_inner", not just the ones that contain the empty text div.

I guess it's just tweaking the code a little, but I can't get it working.

Any ideas?

答:
You could use the :contains selector to achieve what you require in a single line of code. The caveat here is that it's a greedy match, ie. in this case it would also match 'NOT EMPTY'. I'll leave that as a matter for the OP to determine if this fits their use case.

$('.et_pb_row_inner:contains("EMPTY")').remove();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="et_pb_row_inner">
  <div class="et_pb_column">
    <div class="et_pb_text">HAS TEXT</div>
  </div>
  <div class="et_pb_column">
    <div class="et_pb_text">HAS TEXT</div>
  </div>
</div>

<div class="et_pb_row_inner">
  <div class="et_pb_column">
    <div class="et_pb_text">HAS TEXT</div>
  </div>
  <div class="et_pb_column">
    <div class="et_pb_text">EMPTY</div>
  </div>
</div>

<div class="et_pb_row_inner">
  <div class="et_pb_column">
    <div class="et_pb_text">HAS TEXT</div>
  </div>
  <div class="et_pb_column">
    <div class="et_pb_text">EMPTY</div>
  </div>
</div></code>```

Body:
I'm trying to achieve the following:

I have multiple divs with the class "et_pb_row_inner" that contain two columns each. Each of the columns contain a text container with the class "et_pb_text".

Here's the basic html:

I need a way to check if the text in the second column of each row is empty and if so remove the whole row. Like so:

HAS TEXT

HAS TEXT

HAS TEXT

EMPTY

HAS TEXT

EMPTY

I found a code snippet and tried the following:

$(function() {
    $('.et_pb_row_inner').each(function() {
        if ($('.et_pb_text', this).text() == "" ) {
            $('.et_pb_row_inner').hide();
        }
    });
});

It kind of works, but it removes ALL divs with the class "et_pb_row_inner", not just the ones that contain the empty text div.

I guess it's just tweaking the code a little, but I can't get it working.

Any ideas?

Body:
You could use the :contains selector to achieve what you require in a single line of code. The caveat here is that it's a greedy match, ie. in this case it would also match 'NOT EMPTY'. I'll leave that as a matter for the OP to determine if this fits their use case.

$('.et_pb_row_inner:contains("EMPTY")').remove();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="et_pb_row_inner">
  <div class="et_pb_column">
    <div class="et_pb_text">HAS TEXT</div>
  </div>
  <div class="et_pb_column">
    <div class="et_pb_text">HAS TEXT</div>
  </div>
</div>

<div class="et_pb_row_inner">
  <div class="et_pb_column">
    <div class="et_pb_text">HAS TEXT</div>
  </div>
  <div class="et_pb_column">
    <div class="et_pb_text">EMPTY</div>
  </div>
</div>

<div class="et_pb_row_inner">
  <div class="et_pb_column">
    <div class="et_pb_text">HAS TEXT</div>
  </div>
  <div class="et_pb_column">
    <div class="et_pb_text">EMPTY</div>
  </div>
</div>


问:
Is There A Technical Reason SystemVerilog Cannot Pass Module Name as Parameter?
I want to do something like this:

```<code>module BusinessLogicVersion_1(clk, rst, d, q);
// Erudite business logic goes here
endmodule

module BusinessLogicVersion_2(clk, rst, d, q);
// Different implementation of same interface.
endmodule

// Then, when instantiating the module that requires an implementation of whatever interface,
// I want to do something like this:
ModuleXyz #(
    .business_logic(BusinessLogicVersion_2) // <--- Pass an implementation of an interface as parameter
) (.clk(clk), .rst(rst), ...);
</code>```

I have tried to find ways to do this, and from what I've read SV does not allow it.

My question is:

Is there a technical reason why this shouldn't be possible?

答:
I assume you're trying to do some kind of dependency injection, where the modules you're passing in are supposed to be different strategies. Also, I see from your profile that you're familiar with C++, so I'll try to map what you're trying to do onto that language. (Beware of gross simplifications or not-so-accurate analogies.)

A SystemVerilog module is akin to a C++ class. By passing a module name to you ModuleXyz, you're trying to do something like pass a class as a function argument in C++. This isn't possible in that language either. You generally pass instances of classes.

In order to pass an instance of a class, you'd need to first construct it. This would mean passing it your desired constructor arguments. Your module has ports, which are conceptually similar to a class's constructor arguments. When you instantiate a module, you connect its ports.

In your example, I'm guessing you would like to pass in the type of module that ModuleXyz should instantiate inside. In C++ you would generally pass a factory object, which knows how to construct the object you need, with the constructor arguments you want. This pattern isn't possible with modules, as only "direct" instantiation is allowed.

As @dave_59 pointed out, switching out module types is done using configurations. It's sort of like doing dynamic loading of different shared libraries, to switch out the implementations.

If your simulator doesn't support configurations (as language constructs), it will usually provide compile switches that allow you to implement something similar. It will compile different versions of the module, but you will be able to choose which one gets "linked".

If you really, really need to use dependency injection, I'd suggest you try to migrate your code from trying to pass modules, to passing interfaces. It is possible to pass instances of those around. Just remember, that you'll be passing already constructed instances, not types.

Body:
I want to do something like this:

module BusinessLogicVersion_1(clk, rst, d, q);
// Erudite business logic goes here
endmodule

module BusinessLogicVersion_2(clk, rst, d, q);
// Different implementation of same interface.
endmodule

// Then, when instantiating the module that requires an implementation of whatever interface,
// I want to do something like this:
ModuleXyz #(
    .business_logic(BusinessLogicVersion_2) // <--- Pass an implementation of an interface as parameter
) (.clk(clk), .rst(rst), ...);

I have tried to find ways to do this, and from what I've read SV does not allow it.

My question is:

Is there a technical reason why this shouldn't be possible?


问:
Can i trigger browser to focus element in JS
When i want to focus on some element I use focus() function which gave me :focus from css. The thing is that when i am focusing with TAB keyboard button i get that styling from css but also some blue styling around element which is probably some browser focus. Can I trigger that blue browser focus somehow too with js?

答:
we can use outline: none;,it hides outline

:not(.focusable){
  outline: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input placeholder="You can't focus me*" type="text" />

<p>press tab</p>

<button class="focusable">You can focus me</button>
<button >You can't focus me*</button>

<p>again repeat</p>

<input placeholder="You can't focus me*" type="text" />

<p>press tab</p>

<button class="focusable">You can focus me</button>
<button >You can't focus me*</button>

<p>*Focus is possible to all element,but border is only hided,as per OP's question</p></code>```

Body:
we can use outline: none;,it hides outline

:not(.focusable){
  outline: none;
}

<input placeholder="You can't focus me*" type="text" />

<p>press tab</p>

<button class="focusable">You can focus me</button>
<button >You can't focus me*</button>

<p>again repeat</p>

<input placeholder="You can't focus me*" type="text" />

<p>press tab</p>

<button class="focusable">You can focus me</button>
<button >You can't focus me*</button>

<p>*Focus is possible to all element,but border is only hided,as per OP's question</p>


问:
Output Japanese characters with git bash
I am trying to run a Python script with Japanese characters using git bash.

python test_print_jp.py

The code executed by this script is:

```<code>jp_str = u'ァアィイゥ'
print(jp_str)
</code>```

While I am able to print the Japanese string in a notebook, I am not able to print the same string from git bash terminal.

The error is
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-4: character maps to <undefined>

I have tried changing the locale setting in .bash_profile:

```<code>export LANG=ja_JP.UTF-8
export LC_CTYPE=ja_JP.UTF-8
export LC_ALL=ja_JP.UTF-8
</code>```

I have also tried modifying the string encoding:

```<code>str = u'ァアィイゥ'
print(str.encode('shift_jis'))
</code>```

While there is no more error with the second solution, the output of the original string becomes b'\x83@\x83A\x83B\x83C\x83D'

I have also tried modifying the setting from the interface:

change_locale_setting_with_git_bash_interface

Is there a way to print the original Japanese string from git bash terminal?

Thank you for any inputs and suggestions :)

答:
Thanks to the hints from @furas, I found an answer to the posted problem. It was not sufficient to just change the locale setting for the git bash application, I have to also change the locale setting in Windows as well.

 Region -> Administrative -> Change System Locale" />

After making this change and restarting windows, the Japanese characters are rendered correctly in the terminal without needing to use encoding.

```<code>jp_str = 'ァアィイゥ'
print(jp_str)
</code>```

The output on terminal will also be: ァアィイゥ

Note:
I should also mention that using the beta version of utf-8 encoding for worldwide language support, as shown in the following screenshot is also not sufficient.

Although there is no more UnicodeEncodeError, the original Japanese characters become gibberish on the output.

Body:
I am trying to run a Python script with Japanese characters using git bash.

python test_print_jp.py

The code executed by this script is:

jp_str = u'ァアィイゥ'
print(jp_str)

While I am able to print the Japanese string in a notebook, I am not able to print the same string from git bash terminal.

The error is
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-4: character maps to <undefined>

I have tried changing the locale setting in .bash_profile:

export LANG=ja_JP.UTF-8
export LC_CTYPE=ja_JP.UTF-8
export LC_ALL=ja_JP.UTF-8

I have also tried modifying the string encoding:

str = u'ァアィイゥ'
print(str.encode('shift_jis'))

While there is no more error with the second solution, the output of the original string becomes b'\x83@\x83A\x83B\x83C\x83D'

I have also tried modifying the setting from the interface:

change_locale_setting_with_git_bash_interface

Is there a way to print the original Japanese string from git bash terminal?

Thank you for any inputs and suggestions :)

Body:
Thanks to the hints from @furas, I found an answer to the posted problem. It was not sufficient to just change the locale setting for the git bash application, I have to also change the locale setting in Windows as well.

After making this change and restarting windows, the Japanese characters are rendered correctly in the terminal without needing to use encoding.

jp_str = 'ァアィイゥ'
print(jp_str)

The output on terminal will also be: ァアィイゥ

Note:
I should also mention that using the beta version of utf-8 encoding for worldwide language support, as shown in the following screenshot is also not sufficient.

Although there is no more UnicodeEncodeError, the original Japanese characters become gibberish on the output.