问:
Java NullPointerException when there are no variables not initialiased
I am creating this login form using java swing and what I basically do is I get the values from the relevant JtextFields and send them onto another class. Thereafter I check it with the database records. However the program is always displaying a NullPointerException everytime I run it. I tested every variable and saw that none of them contain any Null Values at all.

This is the first method (in the LoginPage class) that gets the values from the JTextField

```<code>public void actionPerformed(ActionEvent e) {
String user=textField.getText();
String pass=String.valueOf(passwordField.getPassword());

//try{
//if((user!=null)&&(pass!=null)){
//  System.out.println("user is not null");

ui.sendLogin(user,pass);

//}else{}
//}catch(NullPointerException ex){
    //System.out.println("Entered catch block og view"+ex.getMessage());
//}
</code>```

}

Thereafter it calls this method (in class LoginController)

```<code>public void sendLogin(String user, String pass) {
try{
    System.out.println("values from sendLogin"+user+"pass"+pass);
    model.verifyUser(user,pass);
}catch(NullPointerException ex){
    System.out.println("Entered catch block os sendLogin"+ex);
    ex.printStackTrace();
}
}
</code>```

Finally the verifyUser method (in class LoginModel) checks it with the database

```<code> public void verifyUser(String user,String pass){
        String username="";
        String password="";
        String acc="";
         try{
             String sql="SELECT * FROM users";
             con1.getInstance();
             Statement st = con1.getConn().createStatement();
             ResultSet rs=st.executeQuery(sql);
             rs.next();
             username=rs.getString("username");
             password=rs.getString("password");
             acc=rs.getString("accountType");
             if(username.equals(user)&&password.equals(pass)){
                 System.out.println("Logged into the system");
                 global_username=username;
                 accountType=acc;
             }else{
                 System.out.println("Unsuccessful login"+username+user+password+pass);
             }
            st.execute(sql);
        } catch (SQLException s){
            System.out.println("SQL statement is not executed!"+s);
        }

}
</code>```

This is the Stack Trace

```<code>java.lang.NullPointerException
    at org.application.view.LoginController.sendLogin(LoginController.java:64)
    at org.application.view.LoginPage$2.actionPerformed(LoginPage.java:94)
user is not null
values from sendLoginapassabc
Entered catch block os sendLoginjava.lang.NullPointerException
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
</code>```

答: I'm guessing that the model variable is null and causing the NullPointerException.

Body:
I am creating this login form using java swing and what I basically do is I get the values from the relevant JtextFields and send them onto another class. Thereafter I check it with the database records. However the program is always displaying a NullPointerException everytime I run it. I tested every variable and saw that none of them contain any Null Values at all.

This is the first method (in the LoginPage class) that gets the values from the JTextField

public void actionPerformed(ActionEvent e) {
String user=textField.getText();
String pass=String.valueOf(passwordField.getPassword());

//try{
//if((user!=null)&&(pass!=null)){
//  System.out.println("user is not null");

ui.sendLogin(user,pass);

//}else{}
//}catch(NullPointerException ex){
    //System.out.println("Entered catch block og view"+ex.getMessage());
//}

}

Thereafter it calls this method (in class LoginController)

public void sendLogin(String user, String pass) {
try{
    System.out.println("values from sendLogin"+user+"pass"+pass);
    model.verifyUser(user,pass);
}catch(NullPointerException ex){
    System.out.println("Entered catch block os sendLogin"+ex);
    ex.printStackTrace();
}
}

Finally the verifyUser method (in class LoginModel) checks it with the database

 public void verifyUser(String user,String pass){
        String username="";
        String password="";
        String acc="";
         try{
             String sql="SELECT * FROM users";
             con1.getInstance();
             Statement st = con1.getConn().createStatement();
             ResultSet rs=st.executeQuery(sql);
             rs.next();
             username=rs.getString("username");
             password=rs.getString("password");
             acc=rs.getString("accountType");
             if(username.equals(user)&&password.equals(pass)){
                 System.out.println("Logged into the system");
                 global_username=username;
                 accountType=acc;
             }else{
                 System.out.println("Unsuccessful login"+username+user+password+pass);
             }
            st.execute(sql);
        } catch (SQLException s){
            System.out.println("SQL statement is not executed!"+s);
        }

}

This is the Stack Trace

java.lang.NullPointerException
    at org.application.view.LoginController.sendLogin(LoginController.java:64)
    at org.application.view.LoginPage$2.actionPerformed(LoginPage.java:94)
user is not null
values from sendLoginapassabc
Entered catch block os sendLoginjava.lang.NullPointerException
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)


来源: stackexchange

问:
Perl backticks using bash
In Perl, the default shell to execute backticks is sh. I'd like to switch to use bash for its richer syntax. So far I found that the suggested solution is

```<code>`bash -c \"echo a b\"`
</code>```

The apparent drawback is that the escaped double quotes, which means I will have difficulty to use double quotes in my bash args. For example, if I wanted to run commands requiring double quotes in bash

```<code>echo "a'b"
</code>```

The above method will be very awkward.

Perl's system() call has a solution for this problem: to use ARRAY args,

```<code>system("bash", "-c", qq(echo "a'b"));
</code>```

This keeps my original bash command unmodified, and almost always.

I'd like to use ARRAY args in backticks too. Is it possible?

答:
Given

my @cmd = ( "bash", "-c", qq(echo "a'b") );
```
<p>You can use any of the following:</p>
<pre class="lang-perl prettyprint-override"><code>use Shell::Quote qw( shell_quote );

my $cmd = shell_quote( @cmd );
my $output = `$cmd`;
die "Can't spawn child: $!\n"                    if $? == -1;
die "Child killed by signal ".( $? & 0x7F )."\n" if $? & 0x7F;
die "Child exited with error ".( $? >> 8 )."\n"  if $? >> 8;
</code>```

or

use IPC::System::Simple qw( capturex );

my $output = capturex( @cmd );
```
<p>or</p>
<pre class="lang-perl prettyprint-override"><code>use IPC::Run qw( run );

run \@cmd, '>', \my $output;
die "Child killed by signal ".( $? & 0x7F )."\n" if $? & 0x7F;
die "Child exited with error ".( $? >> 8 )."\n"  if $? >> 8;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Perl backticks using bash

Body:
In Perl, the default shell to execute backticks is sh. I'd like to switch to use bash for its richer syntax. So far I found that the suggested solution is

`bash -c \"echo a b\"`

The apparent drawback is that the escaped double quotes, which means I will have difficulty to use double quotes in my bash args. For example, if I wanted to run commands requiring double quotes in bash

echo "a'b"

The above method will be very awkward.

Perl's system() call has a solution for this problem: to use ARRAY args,

system("bash", "-c", qq(echo "a'b"));

This keeps my original bash command unmodified, and almost always.

I'd like to use ARRAY args in backticks too. Is it possible?

Body:
Given

my @cmd = ( "bash", "-c", qq(echo "a'b") );

You can use any of the following:

use Shell::Quote qw( shell_quote );

my $cmd = shell_quote( @cmd );
my $output = `$cmd`;
die "Can't spawn child: $!\n"                    if $? == -1;
die "Child killed by signal ".( $? & 0x7F )."\n" if $? & 0x7F;
die "Child exited with error ".( $? >> 8 )."\n"  if $? >> 8;

or

use IPC::System::Simple qw( capturex );

my $output = capturex( @cmd );

or

use IPC::Run qw( run );

run \@cmd, '>', \my $output;
die "Child killed by signal ".( $? & 0x7F )."\n" if $? & 0x7F;
die "Child exited with error ".( $? >> 8 )."\n"  if $? >> 8;


问:
Elasticsearch: find document doesn't have intersecting nested items
I have a document with nested collection and the goal is to find that ones which don't have any inner items intersecting particular period considering also an item's status.

inb4 I've found at least two SO items that didn't help me (probably I'm noob):

ElasticSearch - find all documents whose nested documents do not intersect with date range

and

Elasticsearch inverse range overlap query

So, my document, let's say, simple (I'll paste a JSON definition, just for simplicity. all mappings are fine, trust me ;) ):

{
  "maintenances": [ // <-- this is nested collection
  {
    "start": "date/time",
    "end": "date/time",
    "status": boolean
  } ]
}
```
<p>What I need is to write a query for documents that don't have any active (<code>status = true</code>) maintenance items intersecting some period (<code>from</code> and <code>to</code> for instance).</p>
<p>I started from simple expression:</p>
<pre class="lang-json prettyprint-override"><code>must_not { nested { exists { field: maintenances } } }
or
must_not { nested { must [
  { maintenances.start <= to },
  { maintenances.end >= from },
  { status = true }
] } }
</code>```

That returned me any document from test entries.

Remembering that nested query will return outer document in case if any document will match expression I decided to make a query complex, something like:

maintenances not exists
or
(
  any maintenance within range is not active
  and
  any maintenance outside range is active
)
```
<p>But it became clear (not very fast unfortunately) that this query doesn't work for sorts of edge-cases: like all nested maintenance items are inactive, or all maintenance are outside requested bounds.</p>
<p>Currently I'm not sure, but I assume that query should contain as many <strong>or</strong>-d items as many edge-cases are? Like:</p>
<pre class="lang-json prettyprint-override"><code>maintenances not exists
or
(
  any maintenance within range is not active
  and
  any maintenance outside range
)
or
(
  any maintenance within range is not active
  and
  no maintenance outside range
)
or
(
  no maintenance within range
  and
  any maintenance outside range
)
or
OVER9000 of them
</code>```

Does anyone know simplest way to query Elastic for my case?

答:
all mappings are fine, trust me

Suddenly (no actually) this was an issue. Absence of mapping for status prevented from data being filtered correctly.

Body:
I have a document with nested collection and the goal is to find that ones which don't have any inner items intersecting particular period considering also an item's status.

inb4 I've found at least two SO items that didn't help me (probably I'm noob):

ElasticSearch - find all documents whose nested documents do not intersect with date range

and

Elasticsearch inverse range overlap query

So, my document, let's say, simple (I'll paste a JSON definition, just for simplicity. all mappings are fine, trust me ;) ):

{
  "maintenances": [ // <-- this is nested collection
  {
    "start": "date/time",
    "end": "date/time",
    "status": boolean
  } ]
}

What I need is to write a query for documents that don't have any active (status = true) maintenance items intersecting some period (from and to for instance).

I started from simple expression:

must_not { nested { exists { field: maintenances } } }
or
must_not { nested { must [
  { maintenances.start <= to },
  { maintenances.end >= from },
  { status = true }
] } }

That returned me any document from test entries.

Remembering that nested query will return outer document in case if any document will match expression I decided to make a query complex, something like:

maintenances not exists
or
(
  any maintenance within range is not active
  and
  any maintenance outside range is active
)

But it became clear (not very fast unfortunately) that this query doesn't work for sorts of edge-cases: like all nested maintenance items are inactive, or all maintenance are outside requested bounds.

Currently I'm not sure, but I assume that query should contain as many or-d items as many edge-cases are? Like:

maintenances not exists
or
(
  any maintenance within range is not active
  and
  any maintenance outside range
)
or
(
  any maintenance within range is not active
  and
  no maintenance outside range
)
or
(
  no maintenance within range
  and
  any maintenance outside range
)
or
OVER9000 of them

Does anyone know simplest way to query Elastic for my case?


问:
Checkout several branches from Git
I want to clone some Git repository on local machine, and create 3 folders:

master - for master branch of the project

tag777 - for the specific    tag of the project

commit888 - for the specific commit from master    branch

I want these 3 folders with the specific versions of the project to reside on local machine simultaneously.

So the question is - do I have to clone git repo 3 times or it is sufficient to clone it only once and create these 3 folders after cloning?
What commands do I have to run?

For now I want only to "download" these 3 version of the project and don't want to modify or commit anything.

答:
You want to look into Git Worktree. It basically allow you to create multiple working directories backed by the same .git folders.

```<code>git clone https://github.com/your/repo master
git worktree add -b tag777 ../tag777 tag777
git worktree add -b commit888 ../commit888 commit888
</code>```

This puts the .git directory only 1 time on disc, saving you a lot of data and keepinp stuff in sync a little easier.
https://git-scm.com/docs/git-worktree

Title: Checkout several branches from Git

Body:
You want to look into Git Worktree. It basically allow you to create multiple working directories backed by the same .git folders.

git clone https://github.com/your/repo master
git worktree add -b tag777 ../tag777 tag777
git worktree add -b commit888 ../commit888 commit888

This puts the .git directory only 1 time on disc, saving you a lot of data and keepinp stuff in sync a little easier.
https://git-scm.com/docs/git-worktree


问:
how to solve element overlap problem in flutter
I have a row of 3 children and I am sending one of them from another page. I want it to be side by side with the text, but it stays above the text. How can I fix this problem?

Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            textComponent ?? Container(),
                            Flexible(
                              fit: FlexFit.loose,
                              child: SizedBox(
                                width: 140,
                                child: Row(
                                  children: [
                                    Text(
                                      state.value == initialValue
                                          ? initialValueLabel ?? ""
                                          : valueLabel ?? "",
                                      style: TextStyle(
                                        fontWeight: FontWeight.normal,
                                        fontSize: 16,
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Icon(Icons.arrow_drop_down)
                          ],
                        ),```
</div>
</div>
</p>
<p><img src="https://i.stack.imgur.com/8XTXQ.png" alt="enter image description here" /></p>
```textComponent: girisHesapTipi != ""
                      ? ClipOval(
                          child: Container(
                          //todo renk dinamik değişecek
                          color: Colors.grey,
                          padding: EdgeInsets.symmetric(horizontal: 5),
                          child: Text(
                            girisHesapTipi,
                            style: TextStyle(color: Colors.black, fontSize: 20),
                          ),
                        ))
                      : null,

```

答:
 textComponent: detayTemp?.cikisValue?[0]  != null
                      ? Row(
                        children: [
                          ClipOval(
                          child: Container(
                            //todo renk dinamik değişecek
                            color: Colors.grey,
                            padding: EdgeInsets.symmetric(horizontal: 5),
                            child: Text(
                              detayTemp?.cikisValue?[0] ?? "",
                              style: TextStyle(color: Colors.black, fontSize: 20),
                            ),
                          )),
                          SizedBox(width: 5,)
                        ],
                      )
                      : null,```

Body:
I have a row of 3 children and I am sending one of them from another page. I want it to be side by side with the text, but it stays above the text. How can I fix this problem?

Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            textComponent ?? Container(),
                            Flexible(
                              fit: FlexFit.loose,
                              child: SizedBox(
                                width: 140,
                                child: Row(
                                  children: [
                                    Text(
                                      state.value == initialValue
                                          ? initialValueLabel ?? ""
                                          : valueLabel ?? "",
                                      style: TextStyle(
                                        fontWeight: FontWeight.normal,
                                        fontSize: 16,
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Icon(Icons.arrow_drop_down)
                          ],
                        ),

textComponent: girisHesapTipi != ""
                      ? ClipOval(
                          child: Container(
                          //todo renk dinamik değişecek
                          color: Colors.grey,
                          padding: EdgeInsets.symmetric(horizontal: 5),
                          child: Text(
                            girisHesapTipi,
                            style: TextStyle(color: Colors.black, fontSize: 20),
                          ),
                        ))
                      : null,


问:
Docker does not find R despite pre-built layers
I create a docker image to run R scripts on a VM server with no access to the internet.

For the first layer I load R and all libraries

Dockerfile1

```<code>FROM r-base

## Needed to access R
ENV R_HOME /usr/lib/R

## install required libraries
RUN apt-get update
RUN apt-get -y install libgdal-dev

## install R-packages
RUN R -e "install.packages('dplyr',dependencies=TRUE, repos='http://cran.rstudio.com/')"
...
</code>```

and create it

```<code>docker build -t mycreate_od/libraries -f Dockerfile1 .
</code>```

Then I use this library layer to load the R script

Dockerfile2

```<code>FROM mycreate_od/libraries

## Create directory
RUN mkdir -p /home/analysis/

## Copy files
COPY my_script_dir /home/analysis/

## Run the script
CMD R -e "source('/home/analysis/my_script_dir/main.R')"
</code>```

Create the analysis layer

```<code>docker build -t mycreate_od/analysis -f vault/Dockerfile2 .
</code>```

On my master VM, this runs and suceeds, but on the fresh VM I get

```<code>docker run mycreate_od/analysis

R docker ERROR: R_HOME ('/usr/lib/R') not found - Recherche Google
</code>```

From a previous bug search I have set the ENV variable in the Docker (see Dockerfile1),
but it looks like docker installs R on some other place.

答:
Thanks to Dirk advice I managed to get it done using r-apt (see Dockerfile below).

The image get then built and can be run without the R_HOME error.

BTW much faster and with a significantly smaller resulting image.

```<code>FROM rocker/r-apt:bionic

RUN apt-get update && \
    apt-get -y install libgdal-dev && \
    apt-get install -y -qq \
    r-cran-dplyr \
    r-cran-rjson \
    r-cran-data.table  \
    r-cran-crayon \
    r-cran-geosphere \
    r-cran-lubridate  \
    r-cran-sp \
    r-cran-R.utils

RUN R -e 'install.packages("tools")'
RUN R -e 'install.packages("rgdal", repos="http://R-Forge.R-project.org")'
</code>```

This is unfortunately a cargo-boat solution, as I am unable to explain why the previous Dockerfile failed.

Body:
I create a docker image to run R scripts on a VM server with no access to the internet.

For the first layer I load R and all libraries

Dockerfile1

FROM r-base

## Needed to access R
ENV R_HOME /usr/lib/R

## install required libraries
RUN apt-get update
RUN apt-get -y install libgdal-dev

## install R-packages
RUN R -e "install.packages('dplyr',dependencies=TRUE, repos='http://cran.rstudio.com/')"
...

and create it

docker build -t mycreate_od/libraries -f Dockerfile1 .

Then I use this library layer to load the R script

Dockerfile2

FROM mycreate_od/libraries

## Create directory
RUN mkdir -p /home/analysis/

## Copy files
COPY my_script_dir /home/analysis/

## Run the script
CMD R -e "source('/home/analysis/my_script_dir/main.R')"

Create the analysis layer

docker build -t mycreate_od/analysis -f vault/Dockerfile2 .

On my master VM, this runs and suceeds, but on the fresh VM I get

docker run mycreate_od/analysis

R docker ERROR: R_HOME ('/usr/lib/R') not found - Recherche Google

From a previous bug search I have set the ENV variable in the Docker (see Dockerfile1),
but it looks like docker installs R on some other place.

Body:
Thanks to Dirk advice I managed to get it done using r-apt (see Dockerfile below).

The image get then built and can be run without the R_HOME error.

BTW much faster and with a significantly smaller resulting image.

FROM rocker/r-apt:bionic

RUN apt-get update && \
    apt-get -y install libgdal-dev && \
    apt-get install -y -qq \
    r-cran-dplyr \
    r-cran-rjson \
    r-cran-data.table  \
    r-cran-crayon \
    r-cran-geosphere \
    r-cran-lubridate  \
    r-cran-sp \
    r-cran-R.utils

RUN R -e 'install.packages("tools")'
RUN R -e 'install.packages("rgdal", repos="http://R-Forge.R-project.org")'

This is unfortunately a cargo-boat solution, as I am unable to explain why the previous Dockerfile failed.


问:
Javascript autofill text fields
How do I autofill two fields with JavaScript code?

Field 1 should be written "Paragraph".

Field 2 should be written "Source".

Field 1 HTML:

```
<p>Field 2 HTML:</p>
<pre class="lang-html prettyprint-override"><code><p dir="auto" data-placeholder="Name story..." class="empty">
  <br>
</p>
</code>```

答:
Is this what you are looking for?

[["h1","Paragraph"],["p","Source"]].forEach(([sel,txt])=>
 document.querySelector(sel).textContent=txt);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 dir="auto" data-placeholder="Title" data-label="Title" class="empty"><br></h1>
<p dir="auto" data-placeholder="Name story..." class="empty"><br></p></code>```

Title: Javascript autofill text fields

Body:
How do I autofill two fields with JavaScript code?

Field 1 should be written "Paragraph".

Field 2 should be written "Source".

Field 1 HTML:

Field 2 HTML:

Body:
Is this what you are looking for?

[["h1","Paragraph"],["p","Source"]].forEach(([sel,txt])=>
 document.querySelector(sel).textContent=txt);

<h1 dir="auto" data-placeholder="Title" data-label="Title" class="empty"><br></h1>
<p dir="auto" data-placeholder="Name story..." class="empty"><br></p>


问:
pull access denied for docker.wso2.com/wso2am
I logged in successfully in docker.wso2.com registry and I am trying to pull docker.wso2.com/wso2am but it gives me the following error.</p>
```<code>Error response from daemon: pull access denied for docker.wso2.com/wso2am, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
</code>```

答: Your trial/subscription might have expired. You may contact WSO2 directly to verify it.</p>

Body:
I logged in successfully in docker.wso2.com registry and I am trying to pull docker.wso2.com/wso2am but it gives me the following error.

Error response from daemon: pull access denied for docker.wso2.com/wso2am, repository does not exist or may require 'docker login': denied: requested access to the resource is denied


问:
Gitlab CI: PreLoad database with data
I'm trying to reload the test database with data using a dump.

The idea is the prefill postgres:14.1 with the dump, before running the test.

So far, I have the following .gitlab-ci.yml but the DB can't file the dump file.

```<code>image: "custom_image:latest"
services:
  - "postgres:14.1"

variables:
  RAILS_ENV: test
  POSTGRES_DB: test
  POSTGRES_USER: postgres
  POSTGRES_PASSWORD: postgres
  PGPASSWORD: postgres
  POSTGRES_HOST_AUTH_METHOD: trust
  DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/test"

pg_restore:
  stage: build
  image: postgres:14.1
  script:
    - pg_restore --version
    - pg_restore --no-privileges --no-owner --dbname=postgresql://postgres:postgres@0.0.0.0:5432/test db/test.dump
  artifacts:
    paths:
      - ./db

test:
  stage: test
  dependencies:
    - pg_restore
  script:
    - bundle exec rake db:migrate
    - bundle exec rake test
</code>```

答:
--dbname=postgresql://postgres:postgres@0.0.0.0:5432/test

In the case where you use services: the database is not on localhost. So 0.0.0.0 is not the correct host to use here. Instead, it will be the hostname postgres. The DATABASE_URL is the value you want to use instead. postgresql://postgres:postgres@postgres:5432/test

You can also define an explicit hostname alias:

services:
  - name: "postgres:14.1"
    alias: mydatabasehostname
```

Additionally, services are ephemeral and do not carry state between jobs. So your test: job won't see any changes made to the database in any other job. You must setup the DB in every job.

Title: Gitlab CI: PreLoad database with data

Body:
I'm trying to reload the test database with data using a dump.

The idea is the prefill postgres:14.1 with the dump, before running the test.

So far, I have the following .gitlab-ci.yml but the DB can't file the dump file.

image: "custom_image:latest"
services:
  - "postgres:14.1"

variables:
  RAILS_ENV: test
  POSTGRES_DB: test
  POSTGRES_USER: postgres
  POSTGRES_PASSWORD: postgres
  PGPASSWORD: postgres
  POSTGRES_HOST_AUTH_METHOD: trust
  DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/test"

pg_restore:
  stage: build
  image: postgres:14.1
  script:
    - pg_restore --version
    - pg_restore --no-privileges --no-owner --dbname=postgresql://postgres:postgres@0.0.0.0:5432/test db/test.dump
  artifacts:
    paths:
      - ./db

test:
  stage: test
  dependencies:
    - pg_restore
  script:
    - bundle exec rake db:migrate
    - bundle exec rake test

Body:
--dbname=postgresql://postgres:postgres@0.0.0.0:5432/test

In the case where you use services: the database is not on localhost. So 0.0.0.0 is not the correct host to use here. Instead, it will be the hostname postgres. The DATABASE_URL is the value you want to use instead. postgresql://postgres:postgres@postgres:5432/test

You can also define an explicit hostname alias:

services:
  - name: "postgres:14.1"
    alias: mydatabasehostname

Additionally, services are ephemeral and do not carry state between jobs. So your test: job won't see any changes made to the database in any other job. You must setup the DB in every job.


问:
App Immediatley crashes once app runs with error ClassNotFoundException: Didn't find class application on path: DexPathList
Starting a new project and I am experiencing the following error... I have tried other solutions but seem to be dated

Steps I have tried:

Double checked plugins (listed below)

Instance Run (not listed)

tried using kapt in-place of annotationProccessor (produces a different error)

```<code>    Process: com.example.transfer_tracker, PID: 28953
    java.lang.RuntimeException: Unable to instantiate application com.example.transfer_tracker.CoreApplication package com.example.transfer_tracker: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1364)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76)
        at androidx.core.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:52)
        at android.app.Instrumentation.newApplication(Instrumentation.java:1177)
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1356)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
        Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
                ... 15 more
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.Hilt_CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                ... 18 more
        [CIRCULAR REFERENCE:java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;]
</code>```

Android Manifest

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.transfer_tracker">

    <application
        android:name=".CoreApplication"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TransferTracker">
        <activity
            android:name=".login.LauncherActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

</code>```

Project build.gradle

```<code>buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40.5'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Module project.gradle

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-kapt'
    id 'kotlin-android'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.transfer_tracker"
        minSdk 22
        targetSdk 31
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'com.google.dagger:hilt-android:2.40.5'
    annotationProcessor 'com.google.dagger:hilt-compiler:2.40.5'
}
</code>```

Application Class

```<code>package com.example.transfer_tracker

import android.app.Application
import androidx.multidex.MultiDexApplication
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class CoreApplication : Application()
</code>```

when using kapt instead of annotationProccessor

```<code>public final class CoreApplication extends android.app.Application {
             ^
  Expected @HiltAndroidApp to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
  See https://dagger.dev/hilt/gradle-setup.html
  [Hilt] Processing did not complete. See error above for details.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
   > java.lang.reflect.InvocationTargetException (no error message)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
</code>```

UPDATE

Implemented with Dagger2 error is gone... maybe this is due to a bug within the Hilt library

答:
I think your Application class is getting saved in a different Dex file.

Trying to keep them in a single Dex file should work.

Try this Procedure

Suggestion:

To check Dex file classes you can use Android Studio,
open your apk into Android Studio. You can see your dex files in the apk explorer.

Then select the dex file to see what classes are inside it.

Body:
Starting a new project and I am experiencing the following error... I have tried other solutions but seem to be dated

Steps I have tried:

Double checked plugins (listed below)

Instance Run (not listed)

tried using kapt in-place of annotationProccessor (produces a different error)

    Process: com.example.transfer_tracker, PID: 28953
    java.lang.RuntimeException: Unable to instantiate application com.example.transfer_tracker.CoreApplication package com.example.transfer_tracker: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1364)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76)
        at androidx.core.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:52)
        at android.app.Instrumentation.newApplication(Instrumentation.java:1177)
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1356)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
        Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
                ... 15 more
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.Hilt_CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                ... 18 more
        [CIRCULAR REFERENCE:java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;]

Android Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.transfer_tracker">

    <application
        android:name=".CoreApplication"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TransferTracker">
        <activity
            android:name=".login.LauncherActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Project build.gradle

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40.5'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module project.gradle

plugins {
    id 'com.android.application'
    id 'kotlin-kapt'
    id 'kotlin-android'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.transfer_tracker"
        minSdk 22
        targetSdk 31
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'com.google.dagger:hilt-android:2.40.5'
    annotationProcessor 'com.google.dagger:hilt-compiler:2.40.5'
}

Application Class

package com.example.transfer_tracker

import android.app.Application
import androidx.multidex.MultiDexApplication
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class CoreApplication : Application()

when using kapt instead of annotationProccessor

public final class CoreApplication extends android.app.Application {
             ^
  Expected @HiltAndroidApp to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
  See https://dagger.dev/hilt/gradle-setup.html
  [Hilt] Processing did not complete. See error above for details.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
   > java.lang.reflect.InvocationTargetException (no error message)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

UPDATE

Implemented with Dagger2 error is gone... maybe this is due to a bug within the Hilt library


问:
Is if(A | B) always faster than if(A || B)?
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

```<code>void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}
</code>```

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

答:
Is if(A | B) always faster than if(A || B)?

No, if(A | B) is not always faster than if(A || B).

Consider a case where A is true and the B expression is a very expensive operation. Not doing the operation can save that expense.

So the question is why don't we always use | instead of || in branches?

Besides the cases where the logical or is more efficient, the efficiency is not the only concern. There are often operations that have pre-conditions, and there are cases where the result of the left hand operation signals whether the pre-condition is satisfied for the right hand operation. In such case, we must use the logical operator.

```<code>if (b1[i])  // maybe this exists somewhere in the program
    b2 = nullptr;

if(b1[i] || b2[i]) // OK
if(b1[i]  | b2[i]) // NOT OK; indirection through null pointer
</code>```

It is this possibility that is typically the problem when the optimiser is unable to replace logical with bitwise. In the example of if(b1[i] || b2[i]), the optimiser can do such replacement only if it can prove that b2 is valid at least when b1[i] != 0. That condition might not exist in your example, but that doesn't mean that it would necessarily be easy or - sometimes even possible - for the optimiser to prove that it doesn't exist.

Furthermore, there can be a dependency on the order of the operations, for example if one operand modifies a value read by the other operation:

```<code>if(a || (a = b)) // OK
if(a  | (a = b)) // NOT OK; undefined behaviour
</code>```

Also, there are types that are convertible to bool and thus are valid operands for ||, but are not valid operators for |:

```<code>if(ptr1 || ptr2) // OK
if(ptr1  | ptr2) // NOT OK; no bitwise or for pointers
</code>```

TL;DR If we could always use bitwise or instead of logical operators, then there would be no need for logical operators and they probably wouldn't be in the language. But such replacement is not always a possibility, which is the reason why we use logical operators, and also the reason why optimiser sometimes cannot use the faster option.

Body:
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

Body:
Is if(A | B) always faster than if(A || B)?

No, if(A | B) is not always faster than if(A || B).

Consider a case where A is true and the B expression is a very expensive operation. Not doing the operation can save that expense.

So the question is why don't we always use | instead of || in branches?

Besides the cases where the logical or is more efficient, the efficiency is not the only concern. There are often operations that have pre-conditions, and there are cases where the result of the left hand operation signals whether the pre-condition is satisfied for the right hand operation. In such case, we must use the logical operator.

if (b1[i])  // maybe this exists somewhere in the program
    b2 = nullptr;

if(b1[i] || b2[i]) // OK
if(b1[i]  | b2[i]) // NOT OK; indirection through null pointer

It is this possibility that is typically the problem when the optimiser is unable to replace logical with bitwise. In the example of if(b1[i] || b2[i]), the optimiser can do such replacement only if it can prove that b2 is valid at least when b1[i] != 0. That condition might not exist in your example, but that doesn't mean that it would necessarily be easy or - sometimes even possible - for the optimiser to prove that it doesn't exist.

Furthermore, there can be a dependency on the order of the operations, for example if one operand modifies a value read by the other operation:

if(a || (a = b)) // OK
if(a  | (a = b)) // NOT OK; undefined behaviour

Also, there are types that are convertible to bool and thus are valid operands for ||, but are not valid operators for |:

if(ptr1 || ptr2) // OK
if(ptr1  | ptr2) // NOT OK; no bitwise or for pointers

TL;DR If we could always use bitwise or instead of logical operators, then there would be no need for logical operators and they probably wouldn't be in the language. But such replacement is not always a possibility, which is the reason why we use logical operators, and also the reason why optimiser sometimes cannot use the faster option.


问:
xlsxwriter: chart is removed from excel file if dot and underscore in category names
there is something I don't understand:

```<code>import xlsxwriter

workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()

# Create a new Chart object.
chart = workbook.add_chart({'type': 'column'})

# Write some data to add to plot on the chart.
names_ok = ['A', 'B']
names_notok = ['1.1_1', '2.2_2']
data = [1, 2]

worksheet.write_row('A1', names_notok)
worksheet.write_row('A2', data)

chart.add_series({
    'values':     ['Sheet1', 1, 0, 1, 4],
    'categories': ['Sheet1', 0, 0, 0, 4],
})

# Insert the chart into the worksheet.
worksheet.insert_chart('A4', chart)

workbook.close()
</code>```

running this script using names_ok in line 14 is fine, everything as expected. If using names_notok there is no error from python. But after opening with Office 2016, Excel reports an error and removes the chart from the sheet.

答:
This is a bug of sorts in XlsxWriter.

First off you can work around it by adding a empty category_data list property to the series:

import xlsxwriter

workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()

chart = workbook.add_chart({'type': 'column'})

names_notok = ['1.1_1', '2.2_2']
data = [1, 2]

worksheet.write_row('A1', names_notok)
worksheet.write_row('A2', data)

chart.add_series({
    'categories':      ['Sheet1', 0, 0, 0, 1],
    'values':          ['Sheet1', 1, 0, 1, 1],
    'categories_data': [],
})

worksheet.insert_chart('A4', chart)

workbook.close()
```
<p><strong>Output</strong>:</p>
<p><img src="https://i.stack.imgur.com/mNOJZ.png" alt="enter image description here" /></p>
<p>The issue occurs because <code>'1.1_1'</code> is a string but can evaluate as a float, since underscores are valid after PEP-0515:</p>
```>>> float('1.1_1')
1.11
```

Update: fixed on xlsxwriter main.

Body:
there is something I don't understand:

import xlsxwriter

workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()

# Create a new Chart object.
chart = workbook.add_chart({'type': 'column'})

# Write some data to add to plot on the chart.
names_ok = ['A', 'B']
names_notok = ['1.1_1', '2.2_2']
data = [1, 2]

worksheet.write_row('A1', names_notok)
worksheet.write_row('A2', data)

chart.add_series({
    'values':     ['Sheet1', 1, 0, 1, 4],
    'categories': ['Sheet1', 0, 0, 0, 4],
})

# Insert the chart into the worksheet.
worksheet.insert_chart('A4', chart)

workbook.close()

running this script using names_ok in line 14 is fine, everything as expected. If using names_notok there is no error from python. But after opening with Office 2016, Excel reports an error and removes the chart from the sheet.

Body:
This is a bug of sorts in XlsxWriter.

First off you can work around it by adding a empty category_data list property to the series:

import xlsxwriter

workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()

chart = workbook.add_chart({'type': 'column'})

names_notok = ['1.1_1', '2.2_2']
data = [1, 2]

worksheet.write_row('A1', names_notok)
worksheet.write_row('A2', data)

chart.add_series({
    'categories':      ['Sheet1', 0, 0, 0, 1],
    'values':          ['Sheet1', 1, 0, 1, 1],
    'categories_data': [],
})

worksheet.insert_chart('A4', chart)

workbook.close()

Output:

The issue occurs because '1.1_1' is a string but can evaluate as a float, since underscores are valid after PEP-0515:

>>> float('1.1_1')
1.11

Update: fixed on xlsxwriter main.


问:
Can't get Instagram Business Account ID through Facebook Graph API
I'm trying to access the media of my Instagram business account through Facebook Graph API. I'm following this guide:
https://developers.facebook.com/docs/instagram-api/getting-started/

I've set up everything as requested: I have an Instagram business account, a Facebook page connected to this account and a Facebook app.

In step 5, when I try to get the Instagram Account ID with

GET /v3.0/{page id}?fields=instagram_business_account

the response I get looks different than the one in the guide. The Instagram business account field is missing, I only get back the ID of the Facebook page, which I already have.

Does anyone have an idea what could be wrong here?

答:
After an entire day searching the web (to no use) and reading Facebook/Instagram API docs (which is sometime misleading) I still could not successfully get the Instagram Business Account ID to make requests that use it, like the ig_hashtag_search request.

That's when I decided to ignore everything on the web, trust God, and start using Graph API Explorer's auto complete to try and make some sense of the whole thing!

It finally worked!

Before getting to the actual steps, make sure both Facebook and Instagram accounts are properly configured as business accounts! I don't know if it is a bug in the Brazilian version of Instagram's website, but the process to convert a regular Instagram account to a business account could only be completed using the native Instagram Android app. Specially the part where you link your Instagram account to a Facebook page that should already exist, and that should already have been created using Meta Business Suite.

Again, for me, as of today, the Public Business Information section was missing from the Brazilian version of Instagram's website!

After having configured and properly linked the accounts, it is possible to make the calls using Graph API v12.0.

Step 1

Access the Graph API Explorer.

Step 2

Add the following permissions:

ads_management

business_management

instagram_basic

public_profile

Step 3

Generate the Access Token using the button on the screen (in the popup, be sure to log in using a Facebook account that has both Facebook Business and Instagram Business accounts properly linked and configured).

Step 4

After obtaining the Access Token, get all Businesses IDs:

GET https://graph.facebook.com/v12.0/me/businesses?access_token=xxx

In the Graph API Explorer, you must type only this:

me/businesses

The response should be something like this:

{
  "data": [
    {
      "id": "BUSINESS_ID",
      "name": "Business Name"
    }
  ],
  ...
}
```
<h1>Step 5</h1>
<p>Use the <code>BUSINESS_ID</code> to finally get the <strong>Instagram Business Account ID</strong>:</p>
<p><code>GET https://graph.facebook.com/v12.0/BUSINESS_ID/instagram_business_accounts?access_token=xxx</code></p>
<p>In the Graph API Explorer, you must type only this:</p>
<p><code>BUSINESS_ID/instagram_business_accounts</code></p>
<p>The response should be something like this:</p>
<pre class="lang-json prettyprint-override"><code>{
  "data": [
    {
      "id": "INSTAGRAM_BUSINESS_ACCOUNT_ID"
    }
  ],
  ...
}
</code>```

And that's it!

If everything worked as expected, you can use this INSTAGRAM_BUSINESS_ACCOUNT_ID to make the desired requests, such as ig_hashtag_search or recent_media requests:

GET https://graph.facebook.com/v12.0/ig_hashtag_search?user_id=INSTAGRAM_BUSINESS_ACCOUNT_ID&q=DESIRED_HASHTAG&access_token=xxx

In the Graph API Explorer, you must type only this:

ig_hashtag_search?user_id=INSTAGRAM_BUSINESS_ACCOUNT_ID&q=DESIRED_HASHTAG

The response should be something like this:

{
  "data": [
    {
      "id": "HASHTAG_ID"
    }
  ]
}
```

Hope to have helped!

Body:
After an entire day searching the web (to no use) and reading Facebook/Instagram API docs (which is sometime misleading) I still could not successfully get the Instagram Business Account ID to make requests that use it, like the ig_hashtag_search request.

That's when I decided to ignore everything on the web, trust God, and start using Graph API Explorer's auto complete to try and make some sense of the whole thing!

It finally worked!

Before getting to the actual steps, make sure both Facebook and Instagram accounts are properly configured as business accounts! I don't know if it is a bug in the Brazilian version of Instagram's website, but the process to convert a regular Instagram account to a business account could only be completed using the native Instagram Android app. Specially the part where you link your Instagram account to a Facebook page that should already exist, and that should already have been created using Meta Business Suite.

Again, for me, as of today, the Public Business Information section was missing from the Brazilian version of Instagram's website!

After having configured and properly linked the accounts, it is possible to make the calls using Graph API v12.0.

Step 1

Access the Graph API Explorer.

Step 2

Add the following permissions:

ads_management

business_management

instagram_basic

public_profile

Step 3

Generate the Access Token using the button on the screen (in the popup, be sure to log in using a Facebook account that has both Facebook Business and Instagram Business accounts properly linked and configured).

Step 4

After obtaining the Access Token, get all Businesses IDs:

GET https://graph.facebook.com/v12.0/me/businesses?access_token=xxx

In the Graph API Explorer, you must type only this:

me/businesses

The response should be something like this:

{
  "data": [
    {
      "id": "BUSINESS_ID",
      "name": "Business Name"
    }
  ],
  ...
}

Step 5

Use the BUSINESS_ID to finally get the Instagram Business Account ID:

GET https://graph.facebook.com/v12.0/BUSINESS_ID/instagram_business_accounts?access_token=xxx

In the Graph API Explorer, you must type only this:

BUSINESS_ID/instagram_business_accounts

The response should be something like this:

{
  "data": [
    {
      "id": "INSTAGRAM_BUSINESS_ACCOUNT_ID"
    }
  ],
  ...
}

And that's it!

If everything worked as expected, you can use this INSTAGRAM_BUSINESS_ACCOUNT_ID to make the desired requests, such as ig_hashtag_search or recent_media requests:

GET https://graph.facebook.com/v12.0/ig_hashtag_search?user_id=INSTAGRAM_BUSINESS_ACCOUNT_ID&q=DESIRED_HASHTAG&access_token=xxx

In the Graph API Explorer, you must type only this:

ig_hashtag_search?user_id=INSTAGRAM_BUSINESS_ACCOUNT_ID&q=DESIRED_HASHTAG

The response should be something like this:

{
  "data": [
    {
      "id": "HASHTAG_ID"
    }
  ]
}

Hope to have helped!


问:
Start Dagster Schedule automatically
Hi i am learning dagster and i want help with starting schedule
I am able to add and start schedule in dagit but i want to start schedule automatically instead of turn on every schedule from dagit.

#Here is my code

```<code>@solid()
def test(context):
   context.log.info("test")

@pipeline()
def testPipeline():
    test()

@schedule(
    cron_schedule="* * * * *", pipeline_name="testPipeline", execution_timezone="Asia/Kolkata"
)
def scheduleTest():
    return {}

@repository()
def testRepo():
    return [testPipeline, scheduleTest]
</code>```

答:
I had a very same question on dagster slack so I'm forwarding Daniel Gibson's answer which might help.

since 0.14.0 release, it will be possible to create already enabled schedule (will be released in a week).

also, there's a dagster schedule start --start-all command line command, calling that any time you add a schedule would be one workaround

Title: Start Dagster Schedule automatically

Body:
Hi i am learning dagster and i want help with starting schedule
I am able to add and start schedule in dagit but i want to start schedule automatically instead of turn on every schedule from dagit.

#Here is my code

@solid()
def test(context):
   context.log.info("test")

@pipeline()
def testPipeline():
    test()

@schedule(
    cron_schedule="* * * * *", pipeline_name="testPipeline", execution_timezone="Asia/Kolkata"
)
def scheduleTest():
    return {}

@repository()
def testRepo():
    return [testPipeline, scheduleTest]


答:
I believe your model variable is null.
That is what is causing your NullPointerException.

Is this line 64 model.verifyUser(user,pass);

ContentLicense: CC BY-SA 3.0

Title: Java NullPointerException when there are no variables not initialiased

Body:
I am creating this login form using java swing and what I basically do is I get the values from the relevant JtextFields and send them onto another class. Thereafter I check it with the database records. However the program is always displaying a NullPointerException everytime I run it. I tested every variable and saw that none of them contain any Null Values at all.

This is the first method (in the LoginPage class) that gets the values from the JTextField

public void actionPerformed(ActionEvent e) {
String user=textField.getText();
String pass=String.valueOf(passwordField.getPassword());

//try{
//if((user!=null)&&(pass!=null)){
//  System.out.println("user is not null");

ui.sendLogin(user,pass);

//}else{}
//}catch(NullPointerException ex){
    //System.out.println("Entered catch block og view"+ex.getMessage());
//}

}

Thereafter it calls this method (in class LoginController)

public void sendLogin(String user, String pass) {
try{
    System.out.println("values from sendLogin"+user+"pass"+pass);
    model.verifyUser(user,pass);
}catch(NullPointerException ex){
    System.out.println("Entered catch block os sendLogin"+ex);
    ex.printStackTrace();
}
}

Finally the verifyUser method (in class LoginModel) checks it with the database

 public void verifyUser(String user,String pass){
        String username="";
        String password="";
        String acc="";
         try{
             String sql="SELECT * FROM users";
             con1.getInstance();
             Statement st = con1.getConn().createStatement();
             ResultSet rs=st.executeQuery(sql);
             rs.next();
             username=rs.getString("username");
             password=rs.getString("password");
             acc=rs.getString("accountType");
             if(username.equals(user)&&password.equals(pass)){
                 System.out.println("Logged into the system");
                 global_username=username;
                 accountType=acc;
             }else{
                 System.out.println("Unsuccessful login"+username+user+password+pass);
             }
            st.execute(sql);
        } catch (SQLException s){
            System.out.println("SQL statement is not executed!"+s);
        }

}

This is the Stack Trace

java.lang.NullPointerException
    at org.application.view.LoginController.sendLogin(LoginController.java:64)
    at org.application.view.LoginPage$2.actionPerformed(LoginPage.java:94)
user is not null
values from sendLoginapassabc
Entered catch block os sendLoginjava.lang.NullPointerException
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)


问:
UnicodeEncodeError: 'ascii' codec can't encode character '\u2013' in position 13: ordinal not in range(128)
I have used the SerpApi to web scrape from google product search. The API key has been taken out for obvious reasons. Every time I run the program, this error keeps coming up. How would I stop this from happening?

```<code>import json
from serpapi import GoogleSearch

params = {
  "api_key": "api_key",
  "engine": "google",
  "q": "marvel",
  "gl": "uk",
  "hl": "en",
  "tbm": "shop"
}

search = GoogleSearch(params)
results = search.get_dict()

for i in range(3):
  for shopping_result in results['shopping_results']:
        try:
              title = shopping_result['title']  #Finds relating title
        except:
              title = "None"
        try:
              source = shopping_result['source']  #Finds relating title
        except:
              source = "None"
        try:
              price = shopping_result['price']  #Finds relating title
        except:
              price = "None"

        print(title)
        print(source)
        print(price)
</code>```

答:
I have simplified the code and removed the pointless range iteration. I have created a REPL on replit.com and this executes without error:</p>
```<code>from serpapi import GoogleSearch

params = {
    "api_key": "<my api key>",
    "engine": "google",
    "q": "marvel",
    "gl": "uk",
    "hl": "en",
    "tbm": "shop"
}

results = GoogleSearch(params).get_dict()

for shopping_result in results.get('shopping_results', []):
    print(shopping_result.get('title', 'None'))
    print(shopping_result.get('source', 'None'))
    print(shopping_result.get('price', 'None'))
</code>```

Body:
I have used the SerpApi to web scrape from google product search. The API key has been taken out for obvious reasons. Every time I run the program, this error keeps coming up. How would I stop this from happening?

import json
from serpapi import GoogleSearch

params = {
  "api_key": "api_key",
  "engine": "google",
  "q": "marvel",
  "gl": "uk",
  "hl": "en",
  "tbm": "shop"
}

search = GoogleSearch(params)
results = search.get_dict()

for i in range(3):
  for shopping_result in results['shopping_results']:
        try:
              title = shopping_result['title']  #Finds relating title
        except:
              title = "None"
        try:
              source = shopping_result['source']  #Finds relating title
        except:
              source = "None"
        try:
              price = shopping_result['price']  #Finds relating title
        except:
              price = "None"

        print(title)
        print(source)
        print(price)

Body:
I have simplified the code and removed the pointless range iteration. I have created a REPL on replit.com and this executes without error:

from serpapi import GoogleSearch

params = {
    "api_key": "<my api key>",
    "engine": "google",
    "q": "marvel",
    "gl": "uk",
    "hl": "en",
    "tbm": "shop"
}

results = GoogleSearch(params).get_dict()

for shopping_result in results.get('shopping_results', []):
    print(shopping_result.get('title', 'None'))
    print(shopping_result.get('source', 'None'))
    print(shopping_result.get('price', 'None'))


问:
Bit Hack to get location of bit change
I am needing to figure out a bit-hack to find the first location where the bit-value changes. It could be from 0 to 1 or 1 to 0.

// This would give 0 since no changes happen
let x1 = 0b00000000

// This also gives 0 since there is no change
let x2 = 0b11111111

// This would give 1 since the value changes after the first bit
let x3 = 0b10000000

// This would also give 1 since the value change
// happens at the first bit
let x4 = 0b01111111

// This would return 7 since the change is at the 7th bit
let x5 = 0b00000001

// This would also return 7
let x6 = 0b11111110
```

Any recommendations on an incantation that would give these results?

答:
The key building-block is a bit-scan like bsr.  (Or 31-lzcnt).

That finds the position of the highest 1 bit, and we can transform your input to work for this.

If the leading bit is set, NOT it before bit-scan.  Like x = ((int32_t)x<0) ? ~x : x; with mov ecx, eax / xor eax, -1 (like NOT but sets FLAGS) / cmovns ecx, eax.  So like an absolute-value idiom, but with NOT instead of NEG . Another option is sar reg,31 (or cdq) / xor with that to flip or not.

```<code>#include <bit>          // C++20
#include <stdint.h>

int transition_position(uint32_t x)
{
    x = ((int32_t)x<0) ? ~x : x;            // make the leading bits zero
    if (x == 0) __builtin_unreachable();    // optional, x|=1 is another way to handle the case where all bits are the same, allowing BSF without branching
    return std::countl_zero(x) ^ 31;        // 31-lzcnt in a way that GCC can optimize back to bsf
}
</code>```

This compiles nicely with GCC / clang: https://godbolt.org/z/63nEcnTso

```<code>gcc11.2 and clang13 -O3 both make this asm
transition_position(unsigned int):
        mov     eax, edi
        sar     eax, 31            # missed optimization: should shift EDI so mov is off the critical path on CPUs without mov-elimination
        xor     eax, edi
        bsr     eax, eax
        ret
</code>```

With -march=haswell, they both de-optimize by using lzcnt and then an actual xor eax,31.  (That asm is still better for AMD, where bsf is significantly slower than tzcnt/lzcnt, so it's good for -mtune=generic -mbmi, but not for -march=haswell)

Title: Bit Hack to get location of bit change

Body:
I am needing to figure out a bit-hack to find the first location where the bit-value changes. It could be from 0 to 1 or 1 to 0.

// This would give 0 since no changes happen
let x1 = 0b00000000

// This also gives 0 since there is no change
let x2 = 0b11111111

// This would give 1 since the value changes after the first bit
let x3 = 0b10000000

// This would also give 1 since the value change
// happens at the first bit
let x4 = 0b01111111

// This would return 7 since the change is at the 7th bit
let x5 = 0b00000001

// This would also return 7
let x6 = 0b11111110

Any recommendations on an incantation that would give these results?

Body:
The key building-block is a bit-scan like bsr.  (Or 31-lzcnt).

That finds the position of the highest 1 bit, and we can transform your input to work for this.

If the leading bit is set, NOT it before bit-scan.  Like x = ((int32_t)x<0) ? ~x : x; with mov ecx, eax / xor eax, -1 (like NOT but sets FLAGS) / cmovns ecx, eax.  So like an absolute-value idiom, but with NOT instead of NEG . Another option is sar reg,31 (or cdq) / xor with that to flip or not.

#include <bit>          // C++20
#include <stdint.h>

int transition_position(uint32_t x)
{
    x = ((int32_t)x<0) ? ~x : x;            // make the leading bits zero
    if (x == 0) __builtin_unreachable();    // optional, x|=1 is another way to handle the case where all bits are the same, allowing BSF without branching
    return std::countl_zero(x) ^ 31;        // 31-lzcnt in a way that GCC can optimize back to bsf
}

This compiles nicely with GCC / clang: https://godbolt.org/z/63nEcnTso

gcc11.2 and clang13 -O3 both make this asm
transition_position(unsigned int):
        mov     eax, edi
        sar     eax, 31            # missed optimization: should shift EDI so mov is off the critical path on CPUs without mov-elimination
        xor     eax, edi
        bsr     eax, eax
        ret

With -march=haswell, they both de-optimize by using lzcnt and then an actual xor eax,31.  (That asm is still better for AMD, where bsf is significantly slower than tzcnt/lzcnt, so it's good for -mtune=generic -mbmi, but not for -march=haswell)


问:
Plugin 'org.apache.maven.plugins:maven-compiler-plugin:3.8.0' not found
I am having problems with the maven-compiler-plugin version.
It's underlined in red color, when I hover over the <version>3.8.0</version> field, a pop-up with below error appears:

Plugin 'org.apache.maven.plugins:maven-compiler-plugin:3.8.0' not found

Here down my plugin declaration section:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <source>11</source>
                <target>11</target>
            </configuration>
        </plugin>
    </plugins>
</build>
```

<p>After executing the maven project: </p>

```[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  25.886 s
[INFO] Finished at: 2020-04-19T22:13:16+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java (default-cli) on project untitled19: The parameters 'mainClass' for goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java are missing or invalid -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginParameterException```
</code>```

答:
For my part, try adding a new dependency:

```<code><!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.9.0</version>
</dependency>
</code>```

And that's it, check the version and try it.

Body:
I am having problems with the maven-compiler-plugin version.
It's underlined in red color, when I hover over the <version>3.8.0</version> field, a pop-up with below error appears:

Plugin 'org.apache.maven.plugins:maven-compiler-plugin:3.8.0' not found

Here down my plugin declaration section:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <source>11</source>
                <target>11</target>
            </configuration>
        </plugin>
    </plugins>
</build>

After executing the maven project:

[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  25.886 s
[INFO] Finished at: 2020-04-19T22:13:16+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java (default-cli) on project untitled19: The parameters 'mainClass' for goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java are missing or invalid -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginParameterException```

Body:
For my part, try adding a new dependency:

<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.9.0</version>
</dependency>

And that's it, check the version and try it.


问:
TypeError: fs.readFileSync is not a function in Next.js
In a JSON file, I save data for a bot in total.json.

```<code>{ "guilds": 3, "users": 21 }
</code>```

In my index.tsx, I would like to put this data in the page, so I try this:

```<code>import fs from 'fs';

function stats() {
  const botcount = JSON.parse(fs.readFileSync(`../util/total.json`, { encoding: 'utf8' }));
  const userscount = botcount.users;

  console.log(userscount);
  return userscount;
}
</code>```

In the terminal, the function correctly returned the number (21), but in my page, I found this error:

```<code>TypeError: fs__WEBPACK_IMPORTED_MODULE_6___default(...).readFileSync is not a function
</code>```

答:
You can only use fs module in Node js NOT in browser. To access JSON data from a file in Nextjs you can use axios or fetch. Here is an example with axios

```<code>import axios from 'axios';

  async function stats() {
    var {data} = await axios.get("http://localhost:8888/utils/total.json");//Change this to your url
    const botcount = JSON.parse(data)
    const userscount = botcount.users;

    console.log(userscount);
    return userscount;
  }
</code>```

Body:
In a JSON file, I save data for a bot in total.json.

{ "guilds": 3, "users": 21 }

In my index.tsx, I would like to put this data in the page, so I try this:

import fs from 'fs';

function stats() {
  const botcount = JSON.parse(fs.readFileSync(`../util/total.json`, { encoding: 'utf8' }));
  const userscount = botcount.users;

  console.log(userscount);
  return userscount;
}

In the terminal, the function correctly returned the number (21), but in my page, I found this error:

TypeError: fs__WEBPACK_IMPORTED_MODULE_6___default(...).readFileSync is not a function

Body:
You can only use fs module in Node js NOT in browser. To access JSON data from a file in Nextjs you can use axios or fetch. Here is an example with axios

import axios from 'axios';

  async function stats() {
    var {data} = await axios.get("http://localhost:8888/utils/total.json");//Change this to your url
    const botcount = JSON.parse(data)
    const userscount = botcount.users;

    console.log(userscount);
    return userscount;
  }


问:
I can't get an image to appear when hovering on another image, Cargo
I'm having issues trying to make an image {image 16} appear when hovering on another image with a link {image 15}. I'm building my website on Cargo, as I don't know much about coding. This site-builder is limiting my options to only place my images in grids, and as these grids already have a div class each, i can't get Cargo to accept the div classes im making for each image- probably because i'm doing it wrong. To top it all off, Cargo doesn't allow me to see all of the HTML, just specific parts. Any help would be super welcomed, thank you in advance!

HTML:

```<code><div class="image-gallery" gid="21">

<div class="hover-image">{image 16}</div>

</div> <br>

<br><br>
<br>
<div grid-row="" grid-pad="0" grid-gutter="0" grid-responsive="">
    <div grid-col="x12" grid-pad="0"></div>
</div><br>
<div grid-row="" grid-pad="0" grid-gutter="0" grid-responsive="">
    <div grid-col="x12" grid-pad="0"><div style="text-align: left"><div class="image-gallery" gid="22">

<div class="hover-title">
<a rel="history" href="enlightened-type" class="image-link">{image 15}</a>
</div>

{image 5}
{image 13}
{image 14}
{image 12}
{image 11}
</div><br></div>
</div>
</div>
<br><div class="image-gallery" gid="23">
{image 17}
</div>2
</code>```

CSS:

```<code>.hover-title {
    display: inline;
    pointer-events: auto;
    cursor: pointer;
}

.hover-image {
    visibility: hidden;
}

body:not(.mobile) .hover-title:hover + .hover-image {
    visibility: visible;
    pointer-events: none;
}

.hover-image {
    display: flex;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: -1;
    pointer-events: none;
    flex-direction: column;
    align-items: center;
    justify-content: center;

/* Change width and height to scale images */
    width: 90vw;
    height: 90vh;
}

.hover-image img {
    max-width: 100% !important;
    max-height: 100% !important;
    width: auto !important;
    height: auto !important;
    margin-bottom: 0;
}
</code>```

答: You can do the document. calls inline.

Body:
I'm having issues trying to make an image {image 16} appear when hovering on another image with a link {image 15}. I'm building my website on Cargo, as I don't know much about coding. This site-builder is limiting my options to only place my images in grids, and as these grids already have a div class each, i can't get Cargo to accept the div classes im making for each image- probably because i'm doing it wrong. To top it all off, Cargo doesn't allow me to see all of the HTML, just specific parts. Any help would be super welcomed, thank you in advance!

HTML:

{image 16}

{image 15}

{image 5}
{image 13}
{image 14}
{image 12}
{image 11}

{image 17}

2

CSS:

.hover-title {
    display: inline;
    pointer-events: auto;
    cursor: pointer;
}

.hover-image {
    visibility: hidden;
}

body:not(.mobile) .hover-title:hover + .hover-image {
    visibility: visible;
    pointer-events: none;
}

.hover-image {
    display: flex;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: -1;
    pointer-events: none;
    flex-direction: column;
    align-items: center;
    justify-content: center;

/* Change width and height to scale images */
    width: 90vw;
    height: 90vh;
}

.hover-image img {
    max-width: 100% !important;
    max-height: 100% !important;
    width: auto !important;
    height: auto !important;
    margin-bottom: 0;
}

Body:
You can do the document. calls inline.

<a href="" onMouseOver="document.MyImage.src='./icon-on.png';" onMouseOut="document.MyImage.src='./icon-off.png';"> <img src="./icon-off.png" name="MyImage"></a>


问:
Flash in WebView not working on Android 3.2
I am having a problem that only happens on my Motorola Xoom which I have updated to 3.2 through OTA. I have a simple application that uses a WebView to load a small html that has flash content in it. Here is the code snippet.

```<code>mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
</code>```

I know it is correct because it can run fine on my Samsung Galaxy S running Android 2.2. Anybody else seen this problem? Any idea how I can solve this problem?

Many thanks and I am really stuck here.

答: Try to build your application with the latest android Api (13), and activate hardware acceleration (same link, just a little below) on your activity that need to display flash.</p>

Body:
I am having a problem that only happens on my Motorola Xoom which I have updated to 3.2 through OTA. I have a simple application that uses a WebView to load a small html that has flash content in it. Here is the code snippet.

mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);

I know it is correct because it can run fine on my Samsung Galaxy S running Android 2.2. Anybody else seen this problem? Any idea how I can solve this problem?

Many thanks and I am really stuck here.