问:
Undefined global variable in python when using classes
```<code>from bookrecmodified import *
import tkinter as tk

#button = tk.Button(canvas, text="Friends",bg="white",fg="black")
#button.pack()

#button = tk.Button(canvas, text="Recommend",bg = 'white',fg='black')
#button.pack()

#button = tk.Button(canvas, text="Report", bg = "white", fg="black")
#button.pack()

class BuckysButtons:

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.printButton = Button(frame, text="Print Message", command=self.printMessage)
        self.printButton.pack(side=LEFT)

        self.quitButton = Button(frame, text="Quit", command=frame.quit)
        self.quitButton.pack(side=LEFT)

        def printMessage(self):
            print("WOw")

    def printMessage(self):
        print("Wow this actually works")

root = tk.Tk()
b = BuckysButtons(root)
root.mainloop
</code>```

I have a class that is for a GUI i am trying to make a class for it. I followed a youtube video tutorial and im wondering why I am getting a global variable not defined error

For some reason I am getting a undefined variable scope for the frame, when it is clearly defined in the init_ function. Why is it stating its undefined? I do not understand

```<code> frame = Frame(master)
NameError: global name 'Frame' is not defined
</code>```

Thanks

答:
The way you wrote your import, you want tk.Frame and tk.Button. You could do

```<code>from tkinter import *
</code>```

or

```<code>from tkinter import Frame, Button
</code>```

but personally I prefer the tk.Frame (and etc...) way of doing things so that the reader isn't left guessing what type of frame it is.

Body:
from bookrecmodified import *
import tkinter as tk

#button = tk.Button(canvas, text="Friends",bg="white",fg="black")
#button.pack()

#button = tk.Button(canvas, text="Recommend",bg = 'white',fg='black')
#button.pack()

#button = tk.Button(canvas, text="Report", bg = "white", fg="black")
#button.pack()

class BuckysButtons:

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.printButton = Button(frame, text="Print Message", command=self.printMessage)
        self.printButton.pack(side=LEFT)

        self.quitButton = Button(frame, text="Quit", command=frame.quit)
        self.quitButton.pack(side=LEFT)

        def printMessage(self):
            print("WOw")

    def printMessage(self):
        print("Wow this actually works")

root = tk.Tk()
b = BuckysButtons(root)
root.mainloop

I have a class that is for a GUI i am trying to make a class for it. I followed a youtube video tutorial and im wondering why I am getting a global variable not defined error

For some reason I am getting a undefined variable scope for the frame, when it is clearly defined in the init_ function. Why is it stating its undefined? I do not understand

 frame = Frame(master)
NameError: global name 'Frame' is not defined

Thanks

Body:
The way you wrote your import, you want tk.Frame and tk.Button. You could do

from tkinter import *

or

from tkinter import Frame, Button

but personally I prefer the tk.Frame (and etc...) way of doing things so that the reader isn't left guessing what type of frame it is.


来源: stackexchange

问:
How do I fix VirtualBox Bridged Adapter problem?
I have not had this problem in the past.
I have searched the internet but not found a solution.
I have asked the same question in Virtualbox forum but not received any answers.

I have the following setup

Host: Windows 10 (192.168.86.35), wired eth.

VirtualBox v6.0.16

Networking: Bridged Adapter

Guest 1: Ubuntu 18.04 (192.168.86.29)

Guest 2: Ubuntu 18.04 (192.168.86.26)

Both host and guests recieves IP from the same DHCP server and is on the same subnet.
Both host and guests can ping the DHCP server successfully or any WAN address for that matter.

The problem: However neither can ping each other.

Guest ping

```<code>avec@GUEST:~$ ping 192.168.86.35
PING 192.168.86.35 (192.168.86.35) 56(84) bytes of data.
^C
--- 192.168.86.35 ping statistics ---
4 packets transmitted, 0 received, 100% packet loss, time 3050ms
</code>```

Host ping

```<code>C:\>ping 192.168.86.29

Pinging 192.168.86.29 with 32 bytes of data:
General failure.
General failure.
General failure.
General failure.

Ping statistics for 192.168.86.29:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
</code>```

What I have tried

Host: Turned Avast Shields off. There is no difference. I have not
tried to uninstall Avast it as I do not think this is the problem.

Guest: Condirmed Ubuntu firewall have "status: inactive"

Host: Repaired later reinstalled Virtualbox

Host: Started guest as Ubuntu Live cd. All is the same as running from the vdi (disk)

Host: Created a second Guest (cloned Guest 1 vdi)

Does anyone have any idea what the problem might be? I'm stuck.

答:
I have found the solution and it had nothing to do with VirtualBox or the configuration/setup.

I had NordVPN installed and running as a background process on the host.
There is a setting in NordVPN called "Invisibility on LAN" defaulting to ON. That was the problem. As fast as I turned that setting to OFF host and guests could reach each other.

Turn 'invisibility on LAN' to OFF

ContentLicense: CC BY-SA 4.0

Body:
I have not had this problem in the past.
I have searched the internet but not found a solution.
I have asked the same question in Virtualbox forum but not received any answers.

I have the following setup

Host: Windows 10 (192.168.86.35), wired eth.

VirtualBox v6.0.16

Networking: Bridged Adapter

Guest 1: Ubuntu 18.04 (192.168.86.29)

Guest 2: Ubuntu 18.04 (192.168.86.26)

Both host and guests recieves IP from the same DHCP server and is on the same subnet.
Both host and guests can ping the DHCP server successfully or any WAN address for that matter.

The problem: However neither can ping each other.

Guest ping

avec@GUEST:~$ ping 192.168.86.35
PING 192.168.86.35 (192.168.86.35) 56(84) bytes of data.
^C
--- 192.168.86.35 ping statistics ---
4 packets transmitted, 0 received, 100% packet loss, time 3050ms

Host ping

C:\>ping 192.168.86.29

Pinging 192.168.86.29 with 32 bytes of data:
General failure.
General failure.
General failure.
General failure.

Ping statistics for 192.168.86.29:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),

What I have tried

Host: Turned Avast Shields off. There is no difference. I have not
tried to uninstall Avast it as I do not think this is the problem.

Guest: Condirmed Ubuntu firewall have "status: inactive"

Host: Repaired later reinstalled Virtualbox

Host: Started guest as Ubuntu Live cd. All is the same as running from the vdi (disk)

Host: Created a second Guest (cloned Guest 1 vdi)

Does anyone have any idea what the problem might be? I'm stuck.


问:
Docker - Name is already in use by container
Running the docker registry with below command always throws an error:

```<code>dev:tmp me$ docker run \
     -d --name registry-v1 \
     -e SETTINGS_FLAVOR=local \
     -e STORAGE_PATH=/registry \
     -e SEARCH_BACKEND=sqlalchemy \
     -e LOGLEVEL=DEBUG \
     -p 5000:5000 \
     registry:0.9.1
Error response from daemon: Conflict. The name "registry-v1" is already in use by container f9e5798a82e0. You have to delete (or rename) that container to be able to reuse that name.
</code>```

How can I prevent this error ?

答:
Here is how I solved this on ubuntu 18:

$ sudo docker ps -a

copy the container ID

For each container do:

$ sudo docker stop container_ID

$ sudo docker rm container_ID

Body:
Running the docker registry with below command always throws an error:

dev:tmp me$ docker run \
     -d --name registry-v1 \
     -e SETTINGS_FLAVOR=local \
     -e STORAGE_PATH=/registry \
     -e SEARCH_BACKEND=sqlalchemy \
     -e LOGLEVEL=DEBUG \
     -p 5000:5000 \
     registry:0.9.1
Error response from daemon: Conflict. The name "registry-v1" is already in use by container f9e5798a82e0. You have to delete (or rename) that container to be able to reuse that name.

How can I prevent this error ?


问:
linking pdfium on linux
I'm trying to use the pdfium libraries in linux(debian 64-bit). I managed (finally) to compile the release _x64 version of pdfium and the test programs seem to work. However, I can't seem to to use the libraries in a separate project.
This is my file:

```<code>#include <iostream>
#include "fpdfview.h"
#include "fpdftext.h"
#include "fpdfdoc.h"
#include "fpdfedit.h"
main(){
 FPDF_InitLibrary();
 std::cout << "Hello World!"<<std::endl;
 return 0;
}
</code>```

And this is my Makefile:

```<code>CC = g++
CFLAGS = -Wall  -g -Wno-unused-variable -Wno-reorder -I/usr/include/pdfium/core/include  -I/usr/include/pdfium/fpdfsdk/include  -I/usr/include/pdfium/third_party  -I/usr/include/pdfium/v8/include
LIBS_pdfium =  -static -L/usr/lib/pdfium
LDFLAGS = $(LIBS_pdfium)

Main : Main.o
    ${CC} ${CFLAGS} Main.o ${LDFLAGS}  -o Main

Main.o : Main.cpp
    ${CC} ${CFLAGS} -c -std=c++11 Main.cpp

clean:
    rm *o Main
</code>```

When I run the makefile the result is:

```<code>g++ -Wall  -g -Wno-unused-variable -Wno-reorder -I/usr/include/pdfium/core/include  -I/usr/include/pdfium/fpdfsdk/include  -I/usr/include/pdfium/third_party  -I/usr/include/pdfium/v8/include     Main.o -static -L/usr/lib/pdfium  -o Main
Main.cpp:11: error: undefined reference to 'FPDF_InitLibrary'
collect2: error: ld returned 1 exit status
</code>```

I've also tried to use the libraries in /home/username/pdfium/out/Release_x64/obj but got the same error

I know that error: undefined reference to FPDF_InitLibrary  means that there is a linking error. Therefore I checked the libraries in /home/username/pdfium/out/Release_x64/obj using objdump and one of them contained the InitLibrary symbol. This doesn't seem to make sense...

I don't know if I am referring to the wrong paths in the include or the libraries or if it is something else that is wrong.

I tried to understand the chromiums pdf plugin project makefile since I thought that might help me understand what I am supposed to use but unfortunately it didn't help.

Any ideas for what I am doing wrong?

答:
I haven't personally built it - because it was too time taking. But I managed to make it work with my golang application using cgo. I used ubuntu 16.04 as my base image in docker. This depends on https://github.com/bblanchon/pdfium-binaries

Following dockerfile downloads the pdfium binary and links to the app you are developing using pkg-config.

```<code>FROM ubuntu:16.04
# Specify pdfium version
ARG PdfiumVersion=4026

# Install pkg-config, etc.
RUN apt-get -yqq update && apt-get clean && apt-get install -yqq apt-utils pkg-config tzdata && dpkg-reconfigure -f noninteractive tzdata

# Create .pc file for pkg-config
RUN echo "\n" \
     "prefix=/home\n" \
     "Name: pdfium\n" \
     "Description: pdfium\n" \
     "Version: $PdfiumVersion\n" \
     "Requires:\n" \
     "Libs: -L/home/lib -lpdfium\n" \
     "Cflags: -I/home/include\n" >  /home/pdfium.pc

# Download and extract pdfium binary
RUN cd /home && wget --quiet https://github.com/bblanchon/pdfium-binaries/releases/download/chromium%2F$PdfiumVersion/pdfium-linux.tgz \
&& tar -xf pdfium-linux.tgz && rm pdfium-linux.tgz

# Setting up paths for pkg-config
ENV LD_LIBRARY_PATH=/home/lib
ENV PKG_CONFIG_PATH=/home/

## COPY YOUR APP TO /app/src/yourApp
# BUILD YOUR APP
WORKDIR /app/src/yourApp

# RUN your app which is linked to pdfium
ENTRYPOINT [“./yourApp"]
</code>```

ContentLicense: CC BY-SA 3.0

Title: linking pdfium on linux

Body:
I'm trying to use the pdfium libraries in linux(debian 64-bit). I managed (finally) to compile the release _x64 version of pdfium and the test programs seem to work. However, I can't seem to to use the libraries in a separate project.
This is my file:

#include <iostream>
#include "fpdfview.h"
#include "fpdftext.h"
#include "fpdfdoc.h"
#include "fpdfedit.h"
main(){
 FPDF_InitLibrary();
 std::cout << "Hello World!"<<std::endl;
 return 0;
}

And this is my Makefile:

CC = g++
CFLAGS = -Wall  -g -Wno-unused-variable -Wno-reorder -I/usr/include/pdfium/core/include  -I/usr/include/pdfium/fpdfsdk/include  -I/usr/include/pdfium/third_party  -I/usr/include/pdfium/v8/include
LIBS_pdfium =  -static -L/usr/lib/pdfium
LDFLAGS = $(LIBS_pdfium)

Main : Main.o
    ${CC} ${CFLAGS} Main.o ${LDFLAGS}  -o Main

Main.o : Main.cpp
    ${CC} ${CFLAGS} -c -std=c++11 Main.cpp

clean:
    rm *o Main

When I run the makefile the result is:

g++ -Wall  -g -Wno-unused-variable -Wno-reorder -I/usr/include/pdfium/core/include  -I/usr/include/pdfium/fpdfsdk/include  -I/usr/include/pdfium/third_party  -I/usr/include/pdfium/v8/include     Main.o -static -L/usr/lib/pdfium  -o Main
Main.cpp:11: error: undefined reference to 'FPDF_InitLibrary'
collect2: error: ld returned 1 exit status

I've also tried to use the libraries in /home/username/pdfium/out/Release_x64/obj but got the same error

I know that error: undefined reference to FPDF_InitLibrary  means that there is a linking error. Therefore I checked the libraries in /home/username/pdfium/out/Release_x64/obj using objdump and one of them contained the InitLibrary symbol. This doesn't seem to make sense...

I don't know if I am referring to the wrong paths in the include or the libraries or if it is something else that is wrong.

I tried to understand the chromiums pdf plugin project makefile since I thought that might help me understand what I am supposed to use but unfortunately it didn't help.

Any ideas for what I am doing wrong?

Body:
I haven't personally built it - because it was too time taking. But I managed to make it work with my golang application using cgo. I used ubuntu 16.04 as my base image in docker. This depends on https://github.com/bblanchon/pdfium-binaries

Following dockerfile downloads the pdfium binary and links to the app you are developing using pkg-config.

FROM ubuntu:16.04
# Specify pdfium version
ARG PdfiumVersion=4026

# Install pkg-config, etc.
RUN apt-get -yqq update && apt-get clean && apt-get install -yqq apt-utils pkg-config tzdata && dpkg-reconfigure -f noninteractive tzdata

# Create .pc file for pkg-config
RUN echo "\n" \
     "prefix=/home\n" \
     "Name: pdfium\n" \
     "Description: pdfium\n" \
     "Version: $PdfiumVersion\n" \
     "Requires:\n" \
     "Libs: -L/home/lib -lpdfium\n" \
     "Cflags: -I/home/include\n" >  /home/pdfium.pc

# Download and extract pdfium binary
RUN cd /home && wget --quiet https://github.com/bblanchon/pdfium-binaries/releases/download/chromium%2F$PdfiumVersion/pdfium-linux.tgz \
&& tar -xf pdfium-linux.tgz && rm pdfium-linux.tgz

# Setting up paths for pkg-config
ENV LD_LIBRARY_PATH=/home/lib
ENV PKG_CONFIG_PATH=/home/

## COPY YOUR APP TO /app/src/yourApp
# BUILD YOUR APP
WORKDIR /app/src/yourApp

# RUN your app which is linked to pdfium
ENTRYPOINT [“./yourApp"]


问:
Error when importing Sparkling Water (H2O) pipeline in Apache Spark: py4j.protocol.Py4JError
I recently created a PySpark pipeline using Sparkling Water's AutoML in the last stage (very similar to https://github.com/h2oai/sparkling-water/blob/master/py/examples/pipelines/ham_or_spam_multi_algo.py), but when I load my model from a file I get this error:

Ex:

```<code>model = loaded_pipeline.fit(data)
model.write().overwrite().save("examples/build/model")
loaded_model = PipelineModel.load("examples/build/model")

py4j.protocol.Py4JError: ai.h2o.sparkling.ml.models.H2OMOJOModel.H2OSupervisedMOJOModel does not exist in the JVM
</code>```

I have the current packages/versions: H2O (3.28.0.3), h2o-pysparkling-2-4 (3.28.0.3-1), PySpark (2.4.3), Py4j (0.10.7).
I only got this error when I updated H2O/Sparkling Water to the 3.28 version. Can it be related to the definition of some environment variable or package version?

答: Please run from pysparkling import * at the beggining of the code. This call ensures that we add Sparkling Water dependencies to the Spark app.

Body:
I recently created a PySpark pipeline using Sparkling Water's AutoML in the last stage (very similar to https://github.com/h2oai/sparkling-water/blob/master/py/examples/pipelines/ham_or_spam_multi_algo.py), but when I load my model from a file I get this error:

Ex:

model = loaded_pipeline.fit(data)
model.write().overwrite().save("examples/build/model")
loaded_model = PipelineModel.load("examples/build/model")

py4j.protocol.Py4JError: ai.h2o.sparkling.ml.models.H2OMOJOModel.H2OSupervisedMOJOModel does not exist in the JVM

I have the current packages/versions: H2O (3.28.0.3), h2o-pysparkling-2-4 (3.28.0.3-1), PySpark (2.4.3), Py4j (0.10.7).
I only got this error when I updated H2O/Sparkling Water to the 3.28 version. Can it be related to the definition of some environment variable or package version?


问:
Verifying Hashed password
Good day Guys,

I have an issue. I have been able to create User accounts with user_ID, Username and Password fields.

The password is Hashed and salted and its working fine.
Now i want to create a login form where user needs to be authenticated with username and password.

I want to verify if the password supplied and username is correct. this password has to be hash first and then compare with what is in the database.

Below is my code, but it keeps bringing error of incorrect password.

```<code>try
        {

            string connString = CommonVariables.ConnectionString;
            // Hashing the password field first for it to be

            string sql = "SELECT * FROM tbl_Users WHERE (Username = @Username) ";
            using (SqlConnection cnn = new SqlConnection(connString))
            {
                cnn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, cnn))
                {
                    //cmd.Parameters.AddWithValue("@Password", SqlDbType.NVarChar).Value = txt_Password.Text.Trim();
                    cmd.Parameters.AddWithValue("@Username", SqlDbType.NVarChar).Value = txt_Username.Text.Trim();

                    SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (reader.HasRows)
                    {

                        while (reader.Read())
                        {
                            //  string vsibility = reader["Visibility"].ToString(); //Getting the  value of the visibility to determine if the user can logon or not
                            // string user_role = reader["User_Role"].ToString(); // Getting the User_role of the person login on
                            string mypassword = reader["password"].ToString();
                            var hash = PasswordHashing.SecurePasswordHasher.Hash(mypassword);
                            var hashverify = PasswordHashing.SecurePasswordHasher.Verify(txt_Password.Text.Trim(), hash);

                            if (hashverify == true)
                            {
                                this.Hide();
                                new Mainmenu().Show(); ;

                            }
                            else
                            {
                                MessageBox.Show("incorrect password" + mypassword);
                            }
                        }

                    }
                    else
                    {
                        MessageBox.Show("Invalid Username, Please Confirm", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txt_Username.Focus();
                        return;

                    }

                }
            }
        }
        catch (Exception c)
        {
            MessageBox.Show(c.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
</code>```

答:
Assuming that you are storing the hash of the password in the database, it appears that you are double hashing it. In particular, the line

```<code>var hash = PasswordHashing.SecurePasswordHasher.Hash(mypassword);
</code>```

appears to be computing the hash of an already hashed password. Changing this to var hash = mypassword; could help with comparing the passwords.

Title: Verifying Hashed password

Body:
Good day Guys,

I have an issue. I have been able to create User accounts with user_ID, Username and Password fields.

The password is Hashed and salted and its working fine.
Now i want to create a login form where user needs to be authenticated with username and password.

I want to verify if the password supplied and username is correct. this password has to be hash first and then compare with what is in the database.

Below is my code, but it keeps bringing error of incorrect password.

try
        {

            string connString = CommonVariables.ConnectionString;
            // Hashing the password field first for it to be

            string sql = "SELECT * FROM tbl_Users WHERE (Username = @Username) ";
            using (SqlConnection cnn = new SqlConnection(connString))
            {
                cnn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, cnn))
                {
                    //cmd.Parameters.AddWithValue("@Password", SqlDbType.NVarChar).Value = txt_Password.Text.Trim();
                    cmd.Parameters.AddWithValue("@Username", SqlDbType.NVarChar).Value = txt_Username.Text.Trim();

                    SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (reader.HasRows)
                    {

                        while (reader.Read())
                        {
                            //  string vsibility = reader["Visibility"].ToString(); //Getting the  value of the visibility to determine if the user can logon or not
                            // string user_role = reader["User_Role"].ToString(); // Getting the User_role of the person login on
                            string mypassword = reader["password"].ToString();
                            var hash = PasswordHashing.SecurePasswordHasher.Hash(mypassword);
                            var hashverify = PasswordHashing.SecurePasswordHasher.Verify(txt_Password.Text.Trim(), hash);

                            if (hashverify == true)
                            {
                                this.Hide();
                                new Mainmenu().Show(); ;

                            }
                            else
                            {
                                MessageBox.Show("incorrect password" + mypassword);
                            }
                        }

                    }
                    else
                    {
                        MessageBox.Show("Invalid Username, Please Confirm", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txt_Username.Focus();
                        return;

                    }

                }
            }
        }
        catch (Exception c)
        {
            MessageBox.Show(c.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }

Body:
Assuming that you are storing the hash of the password in the database, it appears that you are double hashing it. In particular, the line

var hash = PasswordHashing.SecurePasswordHasher.Hash(mypassword);

appears to be computing the hash of an already hashed password. Changing this to var hash = mypassword; could help with comparing the passwords.


问:
socket read issue in multithreaded JAVA application
We have created a socket in a multithreaded JAVA application on Windows, which has to read data in sequential form. But we are facing issue in reading the data from the inputstream

For example , data order is

```<code>1-100 (1,2,3,4,...100)
101-200
201-200
and so on..
</code>```

We are able  to read from 1-100 in proper sequential manner, but not able to read next set of data, i.e. 101-200. But can read further set of data properly.

The data is coming at our end properly (as seen in etheral log's), but stream is not able to read it.

Here is the code snippet

```<code>socket.getInputStream.read(buffer);
</code>```

socket is of Socket class type.

What can be the possible reason behind the same? Please share your views.

答:
Here is the code snippet

```<code>> socket.getInputStream.read(buffer);
</code>```

No it isn't. That snippet doesn't compile. And the correct snippet is trivially obvious.

The only ways that can miss data are (i) if another thread is reading the socket at the same time, or (ii) if you are using BufferedInputStream or BufferedReader at one time and not at another.

Body:
We have created a socket in a multithreaded JAVA application on Windows, which has to read data in sequential form. But we are facing issue in reading the data from the inputstream

For example , data order is

1-100 (1,2,3,4,...100)
101-200
201-200
and so on..

We are able  to read from 1-100 in proper sequential manner, but not able to read next set of data, i.e. 101-200. But can read further set of data properly.

The data is coming at our end properly (as seen in etheral log's), but stream is not able to read it.

Here is the code snippet

socket.getInputStream.read(buffer);

socket is of Socket class type.

What can be the possible reason behind the same? Please share your views.

Body:
Here is the code snippet

> socket.getInputStream.read(buffer);

No it isn't. That snippet doesn't compile. And the correct snippet is trivially obvious.

The only ways that can miss data are (i) if another thread is reading the socket at the same time, or (ii) if you are using BufferedInputStream or BufferedReader at one time and not at another.


问:
How does the called function interprets the address of an array when using called by reference?
In the example, adapted from a book, I want to fully understand how passing and array by reference really works. From playing with the below code in Code Blocks and some reading here and there, I get that passing by value doesn't change the initial variable's value ( the example_pass_by_value). As for the other two variables whose adresses are passed by reference to the change function, I only understood the  example_pass_by_reference case like this : when calling the function like this "change (&example_pass_by_reference), you actually put and "=" sign between the formal parameter "by_reference" ( this being declared as pointer in the change function definition) and the address of "example_pass_by_reference" variable whic is passed to the change function ( ex: by_reference = 0x6644fe, or better by_reference = &example_pass_by_reference); The thing i don't understand is how the "=" is put between the address of array in the calling of function "change(array, ....) and the formal parameter "int arr[]" from definition of the function "change(int arr[], ...)", since int arr[] is an array, not a pointer, to be able to receive the address of variable "array".( like int arr[] = array, or int arr[] = 0x7856ff, for example);
Thank you in advance and sorry for the subsequent errors in my code or language.</p>

```<code>#include <stdio.h>
#include <string.h>

main()
{
    int array[3] = {1,2,3};
    int example_pass_by_value = 5;
    int example_pass_by_reference = 6;

    change(array, example_pass_by_value, &example_pass_by_reference);

    printf("Back in main(), the array[1] is now %d.\n", array[1]);
    printf("Back in main(), the example_pass_by_value is now %d.\n, unchanged", example_pass_by_value);
    printf("Back in main(), the example_pass_by_reference is now %d.\n", example_pass_by_reference);
    return(0);
}

/******************************************************************/

change(int arr[], int by_value, int *by_reference)
{
    // Changes made to all three variables;
      arr[1] = 10;
      by_value = 100;
      *by_reference = 1000;
      return;
}
</code>```

答:
In this function declaration:

```<code>void change(int arr[], int by_value, int *by_reference)
</code>```

C does not support passing arrays as arguments. When you declare a parameter to be an array, the compiler automatically adjusts it to be a pointer. So this declaration is as if it were:

```<code>void change(int *arr, int by_value, int *by_reference)
</code>```

(Note, I added an int before the function declaration. You should always write a return type, such as int or void, before a function that is being declared. Your compiler may insert a default type of int, but that is an old C feature and should not be used anymore.)

To match the automatic adjustment in the declaration, C also automatically converts arrays in arguments (and most other expressions). In the function call:

```<code>change(array, example_pass_by_value, &example_pass_by_reference);
</code>```

The array array is automatically converted to a pointer to its first element, as if it were:

```<code>change(&array[0], example_pass_by_value, &example_pass_by_reference);
</code>```

Now let us look at the code inside the function. This statement:

```<code>arr[1] = 10;
</code>```

says to take the pointer arr, which has the address of the first element of array, add 1 to it, and use the element there. One element beyond array[0] is array[1], so arr[1] refers to array[1]. This statement assigns 10 to it. So array[1] becomes ten. Note that the array was not passed by value, because C automatically converted it to a pointer. The pointer was passed by value, and the pointer gives us a reference to elements of the array, and arr[1] uses that reference to access elements of the array.

This statement:

```<code>by_value = 100;
</code>```

sets the parameter by_value to 100. Since it is only changing the parameter, it does not change the argument example_pass_by_value in the main function.

This statement:

```<code>*by_reference = 1000;
</code>```

uses the pointer by_reference to access an int in memory. The * operator says to use the pointer to refer to the object it points to. So this statement assigns the value 1000 to the int that by_reference points to. The pointer by_reference was passed by value, and it provides a reference to example_pass_by_reference, because the address of example_pass_by_reference was passed as the argument.

Body:
In the example, adapted from a book, I want to fully understand how passing and array by reference really works. From playing with the below code in Code Blocks and some reading here and there, I get that passing by value doesn't change the initial variable's value ( the example_pass_by_value). As for the other two variables whose adresses are passed by reference to the change function, I only understood the  example_pass_by_reference case like this : when calling the function like this "change (&example_pass_by_reference), you actually put and "=" sign between the formal parameter "by_reference" ( this being declared as pointer in the change function definition) and the address of "example_pass_by_reference" variable whic is passed to the change function ( ex: by_reference = 0x6644fe, or better by_reference = &example_pass_by_reference); The thing i don't understand is how the "=" is put between the address of array in the calling of function "change(array, ....) and the formal parameter "int arr[]" from definition of the function "change(int arr[], ...)", since int arr[] is an array, not a pointer, to be able to receive the address of variable "array".( like int arr[] = array, or int arr[] = 0x7856ff, for example);
Thank you in advance and sorry for the subsequent errors in my code or language.

#include <stdio.h>
#include <string.h>

main()
{
    int array[3] = {1,2,3};
    int example_pass_by_value = 5;
    int example_pass_by_reference = 6;

    change(array, example_pass_by_value, &example_pass_by_reference);

    printf("Back in main(), the array[1] is now %d.\n", array[1]);
    printf("Back in main(), the example_pass_by_value is now %d.\n, unchanged", example_pass_by_value);
    printf("Back in main(), the example_pass_by_reference is now %d.\n", example_pass_by_reference);
    return(0);
}

/******************************************************************/

change(int arr[], int by_value, int *by_reference)
{
    // Changes made to all three variables;
      arr[1] = 10;
      by_value = 100;
      *by_reference = 1000;
      return;
}

Body:
In this function declaration:

void change(int arr[], int by_value, int *by_reference)

C does not support passing arrays as arguments. When you declare a parameter to be an array, the compiler automatically adjusts it to be a pointer. So this declaration is as if it were:

void change(int *arr, int by_value, int *by_reference)

(Note, I added an int before the function declaration. You should always write a return type, such as int or void, before a function that is being declared. Your compiler may insert a default type of int, but that is an old C feature and should not be used anymore.)

To match the automatic adjustment in the declaration, C also automatically converts arrays in arguments (and most other expressions). In the function call:

change(array, example_pass_by_value, &example_pass_by_reference);

The array array is automatically converted to a pointer to its first element, as if it were:

change(&array[0], example_pass_by_value, &example_pass_by_reference);

Now let us look at the code inside the function. This statement:

arr[1] = 10;

says to take the pointer arr, which has the address of the first element of array, add 1 to it, and use the element there. One element beyond array[0] is array[1], so arr[1] refers to array[1]. This statement assigns 10 to it. So array[1] becomes ten. Note that the array was not passed by value, because C automatically converted it to a pointer. The pointer was passed by value, and the pointer gives us a reference to elements of the array, and arr[1] uses that reference to access elements of the array.

This statement:

by_value = 100;

sets the parameter by_value to 100. Since it is only changing the parameter, it does not change the argument example_pass_by_value in the main function.

This statement:

*by_reference = 1000;

uses the pointer by_reference to access an int in memory. The * operator says to use the pointer to refer to the object it points to. So this statement assigns the value 1000 to the int that by_reference points to. The pointer by_reference was passed by value, and it provides a reference to example_pass_by_reference, because the address of example_pass_by_reference was passed as the argument.


问:
comparing the value of each round of a for loop?
Is there a way to grab the resulting number from each iteration of this loop and compare it to the next?

This is a Slot Machine Sim in Java,
I'm trying to find a way to see how many of the results match.
so I thought I would capture the number that is resulted from each round of the For loop and compare it to the previous one.

but I have no idea how to write that?

is there a better way to do this?

what I have so far:

```<code>      for (int count=1; count<= 3 ; ++count)
      {

         number = slotM.nextInt(6);

         switch (number)
         {
            case 0:
               System.out.print("-cherries-");
               break;
            case 1:
               System.out.print("-Oranges-");
               break;
            case 2:
               System.out.print("-Palms-");
               break;
            case 3:
               System.out.print("-Bells-");
               break;
            case 4:
               System.out.print("-Melones-");
               break;
            default:
               System.out.print("-Bars-");
               break;
         }
         System.out.print(number);
      }

</code>```

答:
You’ll need some kind of storage outside of the loop so that each iteration can reference it.

int[] results Look in to arrays - you can put the results of each round into a part of the array, and look up the value.

Body:
Is there a way to grab the resulting number from each iteration of this loop and compare it to the next?

This is a Slot Machine Sim in Java,
I'm trying to find a way to see how many of the results match.
so I thought I would capture the number that is resulted from each round of the For loop and compare it to the previous one.

but I have no idea how to write that?

is there a better way to do this?

what I have so far:

      for (int count=1; count<= 3 ; ++count)
      {

         number = slotM.nextInt(6);

         switch (number)
         {
            case 0:
               System.out.print("-cherries-");
               break;
            case 1:
               System.out.print("-Oranges-");
               break;
            case 2:
               System.out.print("-Palms-");
               break;
            case 3:
               System.out.print("-Bells-");
               break;
            case 4:
               System.out.print("-Melones-");
               break;
            default:
               System.out.print("-Bars-");
               break;
         }
         System.out.print(number);
      }


答: You are declaring your count variable in the for loop, just declare outside and make a comparison with it</p>

Title: comparing the value of each round of a for loop?


问:
Drupal 6 Mimemail with attachment
Can anyone help me with drupal mimemail for attachment i am using below mentioned code to send attachment file on specific email, but somehow its not working, kinldy help me thanks in advance</p>

```<code>    $body = "test body with attachments";
    $subject = "My test message";

$attachments[]=array(
    'filepath' => file_directory_path().'/document.pdf',
    'filename' => 'wonderful.pdf',
    'filemime' => 'application/pdf',
);

mimemail("xxxxx@gmail.com", "xxxxxx2@gmail.com", $subject, $body, NULL, array(), NULL, $attachments,'');
</code>```

答:
I'm doing something very similar. My code is basically:

```<code>$message['attachments'][] = array(
  'filepath' => $zipfilepath,
  'filename' => 'my-attachment.zip',
  'filemime' => 'application/zip',
);
</code>```

from within my hook_mail module callback. See http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_mail/6

Are you sure that you've done the following:

enabled "mimemail" module;

checked the option in admin to "Use mime mail for all messages";

selected "mimemail" as the "E-mail Engine" (at the bottom of the admin page).

Mine is working just fine. I have SMTP module installed as well, and it works with either module selected as the Email Engine.

Title: Drupal 6 Mimemail with attachment

Body:
Can anyone help me with drupal mimemail for attachment i am using below mentioned code to send attachment file on specific email, but somehow its not working, kinldy help me thanks in advance

    $body = "test body with attachments";
    $subject = "My test message";

$attachments[]=array(
    'filepath' => file_directory_path().'/document.pdf',
    'filename' => 'wonderful.pdf',
    'filemime' => 'application/pdf',
);

mimemail("xxxxx@gmail.com", "xxxxxx2@gmail.com", $subject, $body, NULL, array(), NULL, $attachments,'');

Body:
I'm doing something very similar. My code is basically:

$message['attachments'][] = array(
  'filepath' => $zipfilepath,
  'filename' => 'my-attachment.zip',
  'filemime' => 'application/zip',
);

from within my hook_mail module callback. See http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_mail/6

Are you sure that you've done the following:

enabled "mimemail" module;

checked the option in admin to "Use mime mail for all messages";

selected "mimemail" as the "E-mail Engine" (at the bottom of the admin page).

Mine is working just fine. I have SMTP module installed as well, and it works with either module selected as the Email Engine.


问:
flatten list column within dataframe in R
I have a data frame with two columns containing lists.

```<code>test <- data.frame(var_1 = c("ONE", "TWO"))

test$var_2 <- c(list(data.frame(Date = c("Date 1", "Date 2")), list(data.frame(Date = c("Date 3", "Date 4", "Date 5")))))
test$var_3 <- c(list(data.frame(Name = c("Name 1", "Name 2")), list(data.frame(Date = c("Name 3", "Name 4", "Name 5")))))
</code>```

I'd like to loop over the lists to create a flattened data frame, repeating var_1 for the length of the list of each row

Desired Output

```<code>data.frame(var_1 = c("ONE", "ONE", "TWO", "TWO", "TWO"),
           Date = c("Date 1", "Date 2", "Date 3", "Date 4", "Date 5"),
           Name = c("Name 1", "Name 2", "Name 3", "Name 4", "Name 5"))

  var_1   Date   Name
1   ONE Date 1 Name 1
2   ONE Date 2 Name 2
3   TWO Date 3 Name 3
4   TWO Date 4 Name 4
5   TWO Date 5 Name 5
</code>```

I tried applying some of the proposed solutions like using unnest from this post Flatten list column in data frame with ID column but this didn't quite give me my desired result.

答:
Here is one option where we unlist the 'var_2', 'var_3', and unnest

```<code>library(dplyr)
library(purrr)
library(tidyr)
test %>%
    group_split(var_1) %>%
    map_dfr(~ .x %>%
                mutate_at(-1, ~ list(unlist(.))) %>%
                unnest(c(var_2, var_3)))
# A tibble: 5 x 3
#  var_1 var_2  var_3
#  <fct> <fct>  <fct>
#1 ONE   Date 1 Name 1
#2 ONE   Date 2 Name 2
#3 TWO   Date 3 Name 3
#4 TWO   Date 4 Name 4
#5 TWO   Date 5 Name 5
</code>```

Or  we can do

```<code>test %>%
     rowwise %>%
     summarise_all(~ list(unlist(.))) %>%
     unnest(cols = everything())
# A tibble: 5 x 3
#  var_1 var_2  var_3
#  <fct> <fct>  <fct>
#1 ONE   Date 1 Name 1
#2 ONE   Date 2 Name 2
#3 TWO   Date 3 Name 3
#4 TWO   Date 4 Name 4
#5 TWO   Date 5 Name 5
</code>```

Or with

```<code>test  %>%
    group_by(var_1) %>%
    nest %>%
    mutate(data = map(data, ~ summarise_all(.x, ~ list(unlist(.))) %>%
    unnest(everything())))   %>%
    unnest(data)
</code>```

Body:
I have a data frame with two columns containing lists.

test <- data.frame(var_1 = c("ONE", "TWO"))

test$var_2 <- c(list(data.frame(Date = c("Date 1", "Date 2")), list(data.frame(Date = c("Date 3", "Date 4", "Date 5")))))
test$var_3 <- c(list(data.frame(Name = c("Name 1", "Name 2")), list(data.frame(Date = c("Name 3", "Name 4", "Name 5")))))

I'd like to loop over the lists to create a flattened data frame, repeating var_1 for the length of the list of each row

Desired Output

data.frame(var_1 = c("ONE", "ONE", "TWO", "TWO", "TWO"),
           Date = c("Date 1", "Date 2", "Date 3", "Date 4", "Date 5"),
           Name = c("Name 1", "Name 2", "Name 3", "Name 4", "Name 5"))

  var_1   Date   Name
1   ONE Date 1 Name 1
2   ONE Date 2 Name 2
3   TWO Date 3 Name 3
4   TWO Date 4 Name 4
5   TWO Date 5 Name 5

I tried applying some of the proposed solutions like using unnest from this post Flatten list column in data frame with ID column but this didn't quite give me my desired result.

Body:
Here is one option where we unlist the 'var_2', 'var_3', and unnest

library(dplyr)
library(purrr)
library(tidyr)
test %>%
    group_split(var_1) %>%
    map_dfr(~ .x %>%
                mutate_at(-1, ~ list(unlist(.))) %>%
                unnest(c(var_2, var_3)))
# A tibble: 5 x 3
#  var_1 var_2  var_3
#  <fct> <fct>  <fct>
#1 ONE   Date 1 Name 1
#2 ONE   Date 2 Name 2
#3 TWO   Date 3 Name 3
#4 TWO   Date 4 Name 4
#5 TWO   Date 5 Name 5

Or  we can do

test %>%
     rowwise %>%
     summarise_all(~ list(unlist(.))) %>%
     unnest(cols = everything())
# A tibble: 5 x 3
#  var_1 var_2  var_3
#  <fct> <fct>  <fct>
#1 ONE   Date 1 Name 1
#2 ONE   Date 2 Name 2
#3 TWO   Date 3 Name 3
#4 TWO   Date 4 Name 4
#5 TWO   Date 5 Name 5

Or with

test  %>%
    group_by(var_1) %>%
    nest %>%
    mutate(data = map(data, ~ summarise_all(.x, ~ list(unlist(.))) %>%
    unnest(everything())))   %>%
    unnest(data)


问:
How to reuse sparklyr context with mclapply?
I have a R code that does some distributed data preprocessing in sparklyr, and then collects the data to R local dataframe to finally save the result in the CSV. Everything works as expected and now I plan to re-use the spark context across multiple input files processing.

My code looks similar to this reproducible example:

library(dplyr)
library(sparklyr)

sc <- spark_connect(master = "local")

# Generate random input
matrix(rbinom(1000, 1, .5), ncol=1) %>% write.csv('/tmp/input/df0.csv')
matrix(rbinom(1000, 1, .5), ncol=1) %>% write.csv('/tmp/input/df1.csv')

# Multi-job input
input = list(
    list(name="df0", path="/tmp/input/df0.csv"),
    list(name="df1", path="/tmp/input/df1.csv")
)
global_parallelism = 2
results_dir = "/tmp/results2"

# Function executed on each file
f <- function (job) {
    spark_df <- spark_read_csv(sc, "df_tbl", job$path)
    local_df <- spark_df %>%
      group_by(V1) %>%
      summarise(n=n()) %>%
      sdf_collect

    output_path <- paste(results_dir, "/", job$name, ".csv", sep="")
    local_df %>% write.csv(output_path)
    return (output_path)
}
```

<p>If I execute the function of a job inputs in sequential way with <code>lapply</code> everything works as expected:</p>

<pre class="lang-r prettyprint-override"><code>> lapply(input, f)

[[1]]
[1] "/tmp/results2/df0.csv"

[[2]]
[1] "/tmp/results2/df1.csv"
</code>```

However, if I plan to run it in parallel to maximize usage of spark context (if df0 spark processing is done and the local R is working on it, df1 can be already processed by spark):

```<code>> library(parallel)
> library(MASS)
> mclapply(input, f, mc.cores = global_parallelism)

 *** caught segfault ***
address 0x560b2c134003, cause 'memory not mapped'
[[1]]
[1] "Error in as.vector(x, \"list\") : \n  cannot coerce type 'environment' to vector of type 'list'\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in as.vector(x, "list"): cannot coerce type 'environment' to vector of type 'list'>

[[2]]
NULL

Warning messages:
1: In mclapply(input, f, mc.cores = global_parallelism) :
  scheduled core 2 did not deliver a result, all values of the job will be affected
2: In mclapply(input, f, mc.cores = global_parallelism) :
  scheduled core 1 encountered error in user code, all values of the job will be affected
</code>```

When I'm doing similar with Python and ThreadPoolExcutor, the spark context is shared across threads, same for Scala and Java.

Is this possible to reuse sparklyr context in parallel execution in R?

答:
Yeah, unfortunately, the sc object, which is of class spark_connection, cannot be exported to another R process (even if forked processing is used).  If you use the future.apply package, part of the future ecosystem, you can see this if you use:

library(future.apply)
plan(multicore)

## Look for non-exportable objects and given an error if found
options(future.globals.onReference = "error")

y <- future_lapply(input, f)
```

<p>That will throw:</p>

<pre class="lang-r prettyprint-override"><code>Error: Detected a non-exportable reference (‘externalptr’) in one of the
globals (‘sc’ of class ‘spark_connection’) used in the future expression
</code>```

Body:
I have a R code that does some distributed data preprocessing in sparklyr, and then collects the data to R local dataframe to finally save the result in the CSV. Everything works as expected and now I plan to re-use the spark context across multiple input files processing.

My code looks similar to this reproducible example:

library(dplyr)
library(sparklyr)

sc <- spark_connect(master = "local")

# Generate random input
matrix(rbinom(1000, 1, .5), ncol=1) %>% write.csv('/tmp/input/df0.csv')
matrix(rbinom(1000, 1, .5), ncol=1) %>% write.csv('/tmp/input/df1.csv')

# Multi-job input
input = list(
    list(name="df0", path="/tmp/input/df0.csv"),
    list(name="df1", path="/tmp/input/df1.csv")
)
global_parallelism = 2
results_dir = "/tmp/results2"

# Function executed on each file
f <- function (job) {
    spark_df <- spark_read_csv(sc, "df_tbl", job$path)
    local_df <- spark_df %>%
      group_by(V1) %>%
      summarise(n=n()) %>%
      sdf_collect

    output_path <- paste(results_dir, "/", job$name, ".csv", sep="")
    local_df %>% write.csv(output_path)
    return (output_path)
}

If I execute the function of a job inputs in sequential way with lapply everything works as expected:

> lapply(input, f)

[[1]]
[1] "/tmp/results2/df0.csv"

[[2]]
[1] "/tmp/results2/df1.csv"

However, if I plan to run it in parallel to maximize usage of spark context (if df0 spark processing is done and the local R is working on it, df1 can be already processed by spark):

> library(parallel)
> library(MASS)
> mclapply(input, f, mc.cores = global_parallelism)

 *** caught segfault ***
address 0x560b2c134003, cause 'memory not mapped'
[[1]]
[1] "Error in as.vector(x, \"list\") : \n  cannot coerce type 'environment' to vector of type 'list'\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in as.vector(x, "list"): cannot coerce type 'environment' to vector of type 'list'>

[[2]]
NULL

Warning messages:
1: In mclapply(input, f, mc.cores = global_parallelism) :
  scheduled core 2 did not deliver a result, all values of the job will be affected
2: In mclapply(input, f, mc.cores = global_parallelism) :
  scheduled core 1 encountered error in user code, all values of the job will be affected

When I'm doing similar with Python and ThreadPoolExcutor, the spark context is shared across threads, same for Scala and Java.

Is this possible to reuse sparklyr context in parallel execution in R?

Body:
Yeah, unfortunately, the sc object, which is of class spark_connection, cannot be exported to another R process (even if forked processing is used).  If you use the future.apply package, part of the future ecosystem, you can see this if you use:

library(future.apply)
plan(multicore)

## Look for non-exportable objects and given an error if found
options(future.globals.onReference = "error")

y <- future_lapply(input, f)

That will throw:

Error: Detected a non-exportable reference (‘externalptr’) in one of the
globals (‘sc’ of class ‘spark_connection’) used in the future expression


答:
Yep there are several better ways. If you have a fixed number of options (6 in your case) an enum might be a good option:

```<code>enum Picture {
    CHERRIES, ORANGES, PALMS, BELLS, MELONS, BARS;

    public String getName() {
        return "-" + name().substring(0, 1) + name().substring(1).toLowerCase() + "-";
}
</code>```

That way you can store your numbers as pictures rather than numbers.

```<code>Picture pictures[3];
Random random = new Random();
for (int i = 0; i < pictures.length; i++)
    picture[i] = Picture.values[random.nextInt(pictures.length)];
</code>```

To get the printed version:

```<code>for (Picture picture: picture)
    System.out.print(picture.getName());
</code>```

Body:
Yep there are several better ways. If you have a fixed number of options (6 in your case) an enum might be a good option:

enum Picture {
    CHERRIES, ORANGES, PALMS, BELLS, MELONS, BARS;

    public String getName() {
        return "-" + name().substring(0, 1) + name().substring(1).toLowerCase() + "-";
}

That way you can store your numbers as pictures rather than numbers.

Picture pictures[3];
Random random = new Random();
for (int i = 0; i < pictures.length; i++)
    picture[i] = Picture.values[random.nextInt(pictures.length)];

To get the printed version:

for (Picture picture: picture)
    System.out.print(picture.getName());


问:
Loop help in a C++ MPG program
I'm stuck in an infinite loop and can't figure out where I went wrong with my below code. I've googled, read & re-read my textbook and still can't figure out where my mistake is. Can someone help point me in the right direction so I can fix this Do-While loop issue? </p>

```<code>#include <iostream>
#include <cmath>

using namespace std;

const double liter = 0.264179;

int main()
{
    double litersOfGas, miles, gallons, mpg;
    char ans;
    do
    {
        cout << "Enter the number of liters of gas consumed: \n";
        cin >> litersOfGas;
        cout << "Enter the number of miles driven: \n";
        cin >> miles;
        gallons = (litersOfGas * liter);
        mpg = (miles / gallons);
        cout << litersOfGas << " liters of gasoline consumed, "`enter code here`
            << miles << " miles traveled = " << mpg << " mpg." << endl;

        cout << "Would you like to calculate again (Y/N)?" << endl;
        cin >> ans;
    } while ((ans == 'y') && (ans == 'Y'));

    system("Pause");
    return 0;
}
</code>```

答:
Your other syntax errors aside, other commentators pointed out that your loop shouldn't be re-evaluating, this is true.

However the case, you cannot have both Y and y in one character variable, had the options been inverted (and syntax mistakes corrected) this would've resulted in a infinite loop.

```<code>int main()
{
    char ans;
    do
    {
        cout << "Would you like to calculate again (Y/N)?" << endl;
        cin >> ans;
        if(ans=='y' || ans=='Y') // even if you choose not to continue again, the last statement of a do-while will execute unless you set a condition for it
            cout<<"Going again \n";
    } while ((ans == 'y') || (ans == 'Y')); // ans can be only 'Y' or 'y' , not both

    return 0;
}
</code>```

A while-loop would be more beneficial for your case (based on the code you posted):

```<code>char ans = 'Y';
while ((ans == 'Y') || (ans == 'y')) {
    cout << "Would you like to calculate again (Y/N)?" << endl;
    cin >> ans;
}
</code>```

Title: Loop help in a C++ MPG program

Body:
I'm stuck in an infinite loop and can't figure out where I went wrong with my below code. I've googled, read & re-read my textbook and still can't figure out where my mistake is. Can someone help point me in the right direction so I can fix this Do-While loop issue?

#include <iostream>
#include <cmath>

using namespace std;

const double liter = 0.264179;

int main()
{
    double litersOfGas, miles, gallons, mpg;
    char ans;
    do
    {
        cout << "Enter the number of liters of gas consumed: \n";
        cin >> litersOfGas;
        cout << "Enter the number of miles driven: \n";
        cin >> miles;
        gallons = (litersOfGas * liter);
        mpg = (miles / gallons);
        cout << litersOfGas << " liters of gasoline consumed, "`enter code here`
            << miles << " miles traveled = " << mpg << " mpg." << endl;

        cout << "Would you like to calculate again (Y/N)?" << endl;
        cin >> ans;
    } while ((ans == 'y') && (ans == 'Y'));

    system("Pause");
    return 0;
}

Body:
Your other syntax errors aside, other commentators pointed out that your loop shouldn't be re-evaluating, this is true.

However the case, you cannot have both Y and y in one character variable, had the options been inverted (and syntax mistakes corrected) this would've resulted in a infinite loop.

int main()
{
    char ans;
    do
    {
        cout << "Would you like to calculate again (Y/N)?" << endl;
        cin >> ans;
        if(ans=='y' || ans=='Y') // even if you choose not to continue again, the last statement of a do-while will execute unless you set a condition for it
            cout<<"Going again \n";
    } while ((ans == 'y') || (ans == 'Y')); // ans can be only 'Y' or 'y' , not both

    return 0;
}

A while-loop would be more beneficial for your case (based on the code you posted):

char ans = 'Y';
while ((ans == 'Y') || (ans == 'y')) {
    cout << "Would you like to calculate again (Y/N)?" << endl;
    cin >> ans;
}


问:
Why does String.format accept ints in place of %s?
Looking at a couple of references for Java String.format(), I see they mention it has the following format:

```<code>public static String format(String format, Object... args)
</code>```

So it allows me to write the following:

```<code>String newStr = String.format("%s,%s,%s", 1, 2, 3);
</code>```

But I cannot do this:

```<code>String newStr = String.format("%d,%d,%d", "1", "2", "3");
</code>```

Why can i use ints in place of %s but not vice-versa? Is it doing type-conversion from int to string itself?

答:
Yes. For %s it calls toString on whatever you set in there. That works for everything in Java (may produce funny output though).

For %d you need to give an integral type (like Integer, Long or BigInteger). No automatic conversion is attempted.

You can read more about it in the Javadoc (look at the section about Conversions).

Body:
Looking at a couple of references for Java String.format(), I see they mention it has the following format:

public static String format(String format, Object... args)

So it allows me to write the following:

String newStr = String.format("%s,%s,%s", 1, 2, 3);

But I cannot do this:

String newStr = String.format("%d,%d,%d", "1", "2", "3");

Why can i use ints in place of %s but not vice-versa? Is it doing type-conversion from int to string itself?


问:
Override JButton paintComponent() doesn't work java
I wanted to paint my own version of JButton, so I have overridden the paintComponent() method, and drew a gradient roundRect. This works, but after that, I want to draw the String of the Button over it, and at compile-time, I got no error messages. But at runtime, I only see the roundRect, gradient, just as I intended it to be (I can click on it too), but the String is invisible...

Here's my code:

```<code>import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

public class JIconButton extends JButton implements MouseListener
{
    private boolean mouseInside;
    public JIconButton(String file, String text)
    {
        super(text, new ImageIcon(file));
        setBorder(new LineBorder(Color.LIGHT_GRAY, 0, true));
        setContentAreaFilled(false);
        setFocusPainted(false);
        addMouseListener(this);
        setVisible(true);
    }

    public void mouseClicked(MouseEvent e)
    {

    }

    public void mouseEntered(MouseEvent e)
    {

    }

    public void mouseExited(MouseEvent e)
    {

    }

    public void mousePressed(MouseEvent e)
    {

    }

    public void mouseReleased(MouseEvent e)
    {

    }

    @Override
    protected void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g.create();
        g2.setPaint(Color.BLACK);
        g2.drawString(getText(), 0, 0);
        g2.setPaint(new GradientPaint(
                new Point(0, 0),
                Color.WHITE,
                new Point(0, getHeight()),
                Color.PINK.darker()));
        g2.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30);
        g2.dispose();

        //super.paintComponent(g);
    }
}
</code>```

答: Just call setContentAreaFilled(false) for your JButton, override paint() method and at last of paint() method call super.paint().

Body:
I wanted to paint my own version of JButton, so I have overridden the paintComponent() method, and drew a gradient roundRect. This works, but after that, I want to draw the String of the Button over it, and at compile-time, I got no error messages. But at runtime, I only see the roundRect, gradient, just as I intended it to be (I can click on it too), but the String is invisible...

Here's my code:

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

public class JIconButton extends JButton implements MouseListener
{
    private boolean mouseInside;
    public JIconButton(String file, String text)
    {
        super(text, new ImageIcon(file));
        setBorder(new LineBorder(Color.LIGHT_GRAY, 0, true));
        setContentAreaFilled(false);
        setFocusPainted(false);
        addMouseListener(this);
        setVisible(true);
    }

    public void mouseClicked(MouseEvent e)
    {

    }

    public void mouseEntered(MouseEvent e)
    {

    }

    public void mouseExited(MouseEvent e)
    {

    }

    public void mousePressed(MouseEvent e)
    {

    }

    public void mouseReleased(MouseEvent e)
    {

    }

    @Override
    protected void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g.create();
        g2.setPaint(Color.BLACK);
        g2.drawString(getText(), 0, 0);
        g2.setPaint(new GradientPaint(
                new Point(0, 0),
                Color.WHITE,
                new Point(0, getHeight()),
                Color.PINK.darker()));
        g2.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30);
        g2.dispose();

        //super.paintComponent(g);
    }
}


问:
Creating string values from for loop
Slightly strange question, but I have a for loop that loops through, and builds a list:

function buildList(jsonList) {
  var list = "
";
  for (i = 0; i < jsonList.length; i++) {
    list += "
";
    list += "
" + jsonList[i].keyNumber + "
";
    list +=
      "
" +
      "<button type='button' class='btn' onclick='deleteRow(this)'>" +
      "Remove" +
      "</button>" +
      "
";
    list += "
";
  }
  list += "
";
  document.getElementById("htmlList").innerHTML = list;
}
```

Is there anyway I can pass the jsonList[i].keyNumber value to inside my onlick function inside my button?

onclick= 'deleteRow(this, jsonList[i].keyNumber)'.

That way, deleteRow will know which list to delete.

I would like to keep the above format and not use Jquery.

I need the ID, sending it to an API

答:
try this:

```<code>onclick="this.parentNode.parentNode.removeChild(this.parentNode)"
</code>```

in javascript you can only remove a child so you must select the parent of the element you want to remove and then you can delete the child.
in your example : this // is the button
                  this.parentNode // is Li
                  this.parentNode.parentNode // is ul
when you have the ul you can delate your element 'li' .

Title: Creating string values from for loop

Body:
Slightly strange question, but I have a for loop that loops through, and builds a list:

function buildList(jsonList) {
  var list = "
";
  for (i = 0; i < jsonList.length; i++) {
    list += "
";
    list += "
" + jsonList[i].keyNumber + "
";
    list +=
      "
" +
      "<button type='button' class='btn' onclick='deleteRow(this)'>" +
      "Remove" +
      "</button>" +
      "
";
    list += "
";
  }
  list += "
";
  document.getElementById("htmlList").innerHTML = list;
}

Is there anyway I can pass the jsonList[i].keyNumber value to inside my onlick function inside my button?

onclick= 'deleteRow(this, jsonList[i].keyNumber)'.

That way, deleteRow will know which list to delete.

I would like to keep the above format and not use Jquery.

I need the ID, sending it to an API

Body:
try this:

onclick="this.parentNode.parentNode.removeChild(this.parentNode)"

in javascript you can only remove a child so you must select the parent of the element you want to remove and then you can delete the child.
in your example : this // is the button
                  this.parentNode // is Li
                  this.parentNode.parentNode // is ul
when you have the ul you can delate your element 'li' .


问:
What is Blogger API reading quota?
I am going to create a simple blog app which has included only reading facility (list/search/get). So, what is the quota limitation for reading in Blogger API? In my Quotas section which show as follows,

Queries per day    10,000

Queries per 100 seconds per user    100

I wanted know that what is the reading data quota limit from above stats?

答:
10,000 request (list/search/get) per day; with the limit of 100 request per 100 second for each unique IP address.

These numbers are since, as stated here:

Depending on the API, Quota information may include requests per day,
  requests per minute, and requests per minute per user.

Additionally, according to this you may modify these limits given your preference and performance, as well as monitor your API Usage following this.

Title: What is Blogger API reading quota?


问:
ICal not updating existing event
I have created two ical files, one is ical with method:request, and another one is ical with method cancel. When I import them into my outlook calendar, both of them are creating new event.(If I specify the meeting with the status:CANCELLED it is not updating the existing one, but it's creating new one with cancelled status). Both of the icals have the same UID. Do You know how to change that? Or how to update existing meeting via ical file in outlook. However on google calendar everything works as expected, so I am curious whether outlook has some strange behaviour specified for ical files.</p>

```<code>BEGIN:VCALENDAR
METHOD:REQUEST/CANCEL(in cancel ical)
PRODID:prod
VERSION:2.0
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Warsaw
X-LIC-LOCATION:Europe/Warsaw
BEGIN:DAYLIGHT
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
TZNAME:CEST
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
TZNAME:CET
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
DTSTART;TZID=Europe/Warsaw:20191231T160000
DTEND;TZID=Europe/Warsaw:20191231T170000
LOCATION:Loc
SUMMARY:summ
DESCRIPTION:description
SEQUENCE:0/1 (in cancel ical)
CLASS:PUBLIC
UID:SAME_UID
DTSTAMP:20191227T090501Z
END:VEVENT
END:VCALENDAR
</code>```

答:
According to the Spec https://www.rfc-editor.org/rfc/rfc2446#section-3.2.5, a CANCEL to a REQUEST, must include all the attendees:

```<code>ATTENDEE        0+     MUST include all "Attendees" being removed
                       the event. MUST include all "Attendees" if
                       the entire event is cancelled.
</code>```

If you don't have attendees, a PUBLISH may be more appropriate.  Then any items you remove in this published feed, are removed from the calendar.

Title: ICal not updating existing event

Body:
I have created two ical files, one is ical with method:request, and another one is ical with method cancel. When I import them into my outlook calendar, both of them are creating new event.(If I specify the meeting with the status:CANCELLED it is not updating the existing one, but it's creating new one with cancelled status). Both of the icals have the same UID. Do You know how to change that? Or how to update existing meeting via ical file in outlook. However on google calendar everything works as expected, so I am curious whether outlook has some strange behaviour specified for ical files.

BEGIN:VCALENDAR
METHOD:REQUEST/CANCEL(in cancel ical)
PRODID:prod
VERSION:2.0
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Warsaw
X-LIC-LOCATION:Europe/Warsaw
BEGIN:DAYLIGHT
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
TZNAME:CEST
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
TZNAME:CET
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
DTSTART;TZID=Europe/Warsaw:20191231T160000
DTEND;TZID=Europe/Warsaw:20191231T170000
LOCATION:Loc
SUMMARY:summ
DESCRIPTION:description
SEQUENCE:0/1 (in cancel ical)
CLASS:PUBLIC
UID:SAME_UID
DTSTAMP:20191227T090501Z
END:VEVENT
END:VCALENDAR

Body:
According to the Spec https://www.rfc-editor.org/rfc/rfc2446#section-3.2.5, a CANCEL to a REQUEST, must include all the attendees:

ATTENDEE        0+     MUST include all "Attendees" being removed
                       the event. MUST include all "Attendees" if
                       the entire event is cancelled.

If you don't have attendees, a PUBLISH may be more appropriate.  Then any items you remove in this published feed, are removed from the calendar.


问:
Excel Automatically Open Dropdown List with Focus / NumLock issue
I have a group of cells in my worksheet that use a data validation list. It works great, but I'd like the list to dropdown automatically when one of these cells gets the focus. I found some code online to make this work.

```<code>Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
   If Target.Worksheet.Name = "Sheet1" And Target.Column = 1 Then
       Application.SendKeys ("%{down}")
   End If
End Sub
</code>```

Courtesy of: http://howoffice.com/automatically-open-the-drop-down-list-when-a-cell-get-focus-in-excel/

However, the issue I'm having is with the SendKeys causing the NumLock to toggle on and off. I looked this up and it's a known issue with the command.

Are there any other alternatives to the SendKey command to accomplish what I'm looking to do here?

Any help is appreciated.

答:
This code works for me:

Courtesy of: On focus after tabbing of Excel drop down, automatically show list for selection

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range

    On Error GoTo Err1:

    If Target = Range("I5") Then
        Application.SendKeys ("%{UP}")
    End If

    If Target = Range("I6") Then
        Application.SendKeys ("%{UP}")
    End If

    If Target = Range("I7") Then
        Application.SendKeys ("%{UP}")
    End If

Err1:
    'do nothing
End Sub
</code>```

And here's the code with SDB MadDog's corrections:

If you want it to apply to all cell's with data validation
( 'On focus after tabbing of Excel drop down, automatically show list for selection )

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    On Error GoTo Err1:
If Target.Cells.Count = 1 Then

        If Target.Validation.InCellDropdown = True Then
        Application.SendKeys ("%{UP}")

        End If
End If

Err1:
    'do nothing
End Sub
</code>```

However, it changes my NUMLOCK status (toogle ON / off) everytime!
He mentioned he fixed it with an API, I tried, but it doesn't work because it can't get numlock status read correctly (this one http://www.freevbcode.com/ShowCode.asp?ID=1151)

But hope this helps someone in need!

Body:
I have a group of cells in my worksheet that use a data validation list. It works great, but I'd like the list to dropdown automatically when one of these cells gets the focus. I found some code online to make this work.

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
   If Target.Worksheet.Name = "Sheet1" And Target.Column = 1 Then
       Application.SendKeys ("%{down}")
   End If
End Sub

Courtesy of: http://howoffice.com/automatically-open-the-drop-down-list-when-a-cell-get-focus-in-excel/

However, the issue I'm having is with the SendKeys causing the NumLock to toggle on and off. I looked this up and it's a known issue with the command.

Are there any other alternatives to the SendKey command to accomplish what I'm looking to do here?

Any help is appreciated.

Body:
This code works for me:

Courtesy of: On focus after tabbing of Excel drop down, automatically show list for selection

Private Sub Worksheet_SelectionChange(ByVal Target As Range

    On Error GoTo Err1:

    If Target = Range("I5") Then
        Application.SendKeys ("%{UP}")
    End If

    If Target = Range("I6") Then
        Application.SendKeys ("%{UP}")
    End If

    If Target = Range("I7") Then
        Application.SendKeys ("%{UP}")
    End If

Err1:
    'do nothing
End Sub

And here's the code with SDB MadDog's corrections:

If you want it to apply to all cell's with data validation
( 'On focus after tabbing of Excel drop down, automatically show list for selection )

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    On Error GoTo Err1:
If Target.Cells.Count = 1 Then

        If Target.Validation.InCellDropdown = True Then
        Application.SendKeys ("%{UP}")

        End If
End If

Err1:
    'do nothing
End Sub

However, it changes my NUMLOCK status (toogle ON / off) everytime!
He mentioned he fixed it with an API, I tried, but it doesn't work because it can't get numlock status read correctly (this one http://www.freevbcode.com/ShowCode.asp?ID=1151)

But hope this helps someone in need!


答:
To keep your current format, you'll have to concatenate the HTML string with the current keyNumber:

```<code>list +=
  "<li>" +
  "<button type='button' class='btn' onclick='deleteRow(" + jsonList[i].keyNumber + ")'>" +
  "Remove" +
  "</button>" +
  "</li>";
list += "</ul>";
</code>```

Also, tbodys should not have ul children. Maybe create just a plain container instead, like a div, and use a template literal instead, for better readability:

```<code>function buildList(jsonList) {
  var list = "<div>";
  for (const { keyNumber } of jsonList) {
    list += `
      <ul class ='list'>";
        <li>${keyNumber}</li>";
        <li>
          <button type='button' class='btn' onclick='deleteRow(${keyNumber})'>Remove</button>
        </li>
      </ul>
    `;
  }
  list += "</div>";
  document.getElementById("htmlList").innerHTML = list;
}
</code>```

But inline handlers have many problems and should be avoided whenever possible. If feasible, consider creating the elements with document.createElement and then adding the listener with addEventListener instead:

```<code>function buildList(jsonList) {
  const div = document.getElementById("htmlList").appendChild(document.createElement('div'));
  for (const { keyNumber } of jsonList) {
    const ul = div.appendChild(document.createElement('ul'));
    ul.className = 'list';
    ul.innerHTML = `
      <li>${keyNumber}</li>";
      <li>
        <button type='button' class='btn' onclick='deleteRow(${keyNumber})'>Remove</button>
      </li>
    `;
    ul.querySelector('button').addEventListener('click', () => deleteRow(keyNumber));
  }
}
</code>```

Title: Creating string values from for loop

Body:
To keep your current format, you'll have to concatenate the HTML string with the current keyNumber:

list +=
  "<li>" +
  "<button type='button' class='btn' onclick='deleteRow(" + jsonList[i].keyNumber + ")'>" +
  "Remove" +
  "</button>" +
  "</li>";
list += "</ul>";

Also, tbodys should not have ul children. Maybe create just a plain container instead, like a div, and use a template literal instead, for better readability:

function buildList(jsonList) {
  var list = "<div>";
  for (const { keyNumber } of jsonList) {
    list += `
      <ul class ='list'>";
        <li>${keyNumber}</li>";
        <li>
          <button type='button' class='btn' onclick='deleteRow(${keyNumber})'>Remove</button>
        </li>
      </ul>
    `;
  }
  list += "</div>";
  document.getElementById("htmlList").innerHTML = list;
}

But inline handlers have many problems and should be avoided whenever possible. If feasible, consider creating the elements with document.createElement and then adding the listener with addEventListener instead:

function buildList(jsonList) {
  const div = document.getElementById("htmlList").appendChild(document.createElement('div'));
  for (const { keyNumber } of jsonList) {
    const ul = div.appendChild(document.createElement('ul'));
    ul.className = 'list';
    ul.innerHTML = `
      <li>${keyNumber}</li>";
      <li>
        <button type='button' class='btn' onclick='deleteRow(${keyNumber})'>Remove</button>
      </li>
    `;
    ul.querySelector('button').addEventListener('click', () => deleteRow(keyNumber));
  }
}


问:
Persistent AKS container's log
I have an AKS cluster on Dev Env that has some containers running on it. I have also enabled the Azure Log Analytics on it. But I can see the logs of the current container that are running not the old ones which has been killed or stopped.

I'm wondering how I can keep the logs permanently even the container that has been deleted ot stopped. What is the best solution for it? I hoped that Azure logs can do it but it seems it doesn't.

答:
Your best option is to use Azure Monitor for Containers (can be enabled post-deployment of the cluster): https://learn.microsoft.com/en-us/azure/azure-monitor/insights/container-insights-overview

It collects logs from pods and stores them in a Log Analytics workspace, where they can be queried using the Kusto Query Language.

Title: Persistent AKS container's log


问:
How do I temporarily disable a CSS transition for a carousel?
I have an HTML/CSS/JS carousel with the following basic markup:

```<code><div class="carousel">
    <ul>
        <li><img src="img1.png"></li>
        <li><img src="img2.png"></li>
        <li><img src="img3.png"></li>
        <li><img src="img1.png"></li>
    </ul>
</div>
</code>```

And the following basic CSS:

```<code>.carousel {
    overflow: hidden;
    white-space: nowrap;

    ul {
        left: 0;
        position: relative;
        transition: left 1s;

        li {
            display: inline-block;

            img {
                width: 100%;
            }
        }
    }
}
</code>```

I have the JS set up so that every 3 seconds, I change the left property of the ul tag by adding a negative amount of pixels to it equal to the width of the carousel so that it creates the carousel transition effect of sliding from one image to the next.

The problem I'm having though is related to what happens when the carousel reaches the end. I added a second copy of img1.png on the end, and when it gets there, I want to set the left offset back to 0 so that it'll start all over again and loop forever.

The issue specifically is that when the left property is, for example, -1000px and I change it to 0, the carousel suddenly animates all the way back to the first image. I want to set the left property to 0 without the transition animation taking place.

I thought that if I temporary set the transition property to none, then set left to 0, and then set the transition back to left 1s, then it would work, but it doesn't. It still animates from the end all the way back to the beginning when I set left to 0.

How can I achieve the effect I want with CSS transitions and the left property, or is the approach I'm taking fundamentally wrong and need to be completely rethought? Thank you.

答:
duhaime gave a great suggestion to just have two carousel images at a time and always be swapping out the image paths.

However, I was still having an issue with the transition property animating things when I set left: 0 to go back to the start. In essence, this is originally what I had and hoped would work:

```<code>// ulElem is equal to the ul element with the following CSS:
// ul {
//     left: 0;
//     position: relative;
//     transition: left 0.5s;
// }

ulElem.style.transition = 'none';
ulElem.style.left = '0';
ulElem.style.transition = 'left 0.5s';
</code>```

However, that was creating the problem I was seeing. Since I'm using Vue.js, I thought that putting some of the code within a this.$nextTick call might do the trick. So I changed it to the following:

```<code>ulElem.style.transition = 'none';
ulElem.style.left = '0';

this.$nextTick(() => {
    ulElem.style.transition = 'left 0.5s';
});
</code>```

However, that still didn't work. However, the following did:

```<code>ulElem.style.transition = 'none';
ulElem.style.left = '0';

setTimeout(() => {
    ulElem.style.transition = 'left 0.5s';
}, 0);
</code>```

I've read stuff before about setting a setTimeout time of 0 ms and how that places it on the end of the call stack, which can help. Seems weird to me, but it works.

For anyone else that has a similar problem, this may be your solution. I'm not entirely sure why $nextTick didn't work, but I'm not familiar enough with the inner-workings of Vue.js to comment. All the same, setTimeout with a 0 ms setting worked. Thanks.

Body:
I have an HTML/CSS/JS carousel with the following basic markup:

And the following basic CSS:

.carousel {
    overflow: hidden;
    white-space: nowrap;

    ul {
        left: 0;
        position: relative;
        transition: left 1s;

        li {
            display: inline-block;

            img {
                width: 100%;
            }
        }
    }
}

I have the JS set up so that every 3 seconds, I change the left property of the ul tag by adding a negative amount of pixels to it equal to the width of the carousel so that it creates the carousel transition effect of sliding from one image to the next.

The problem I'm having though is related to what happens when the carousel reaches the end. I added a second copy of img1.png on the end, and when it gets there, I want to set the left offset back to 0 so that it'll start all over again and loop forever.

The issue specifically is that when the left property is, for example, -1000px and I change it to 0, the carousel suddenly animates all the way back to the first image. I want to set the left property to 0 without the transition animation taking place.

I thought that if I temporary set the transition property to none, then set left to 0, and then set the transition back to left 1s, then it would work, but it doesn't. It still animates from the end all the way back to the beginning when I set left to 0.

How can I achieve the effect I want with CSS transitions and the left property, or is the approach I'm taking fundamentally wrong and need to be completely rethought? Thank you.

Body:
duhaime gave a great suggestion to just have two carousel images at a time and always be swapping out the image paths.

However, I was still having an issue with the transition property animating things when I set left: 0 to go back to the start. In essence, this is originally what I had and hoped would work:

// ulElem is equal to the ul element with the following CSS:
// ul {
//     left: 0;
//     position: relative;
//     transition: left 0.5s;
// }

ulElem.style.transition = 'none';
ulElem.style.left = '0';
ulElem.style.transition = 'left 0.5s';

However, that was creating the problem I was seeing. Since I'm using Vue.js, I thought that putting some of the code within a this.$nextTick call might do the trick. So I changed it to the following:

ulElem.style.transition = 'none';
ulElem.style.left = '0';

this.$nextTick(() => {
    ulElem.style.transition = 'left 0.5s';
});

However, that still didn't work. However, the following did:

ulElem.style.transition = 'none';
ulElem.style.left = '0';

setTimeout(() => {
    ulElem.style.transition = 'left 0.5s';
}, 0);

I've read stuff before about setting a setTimeout time of 0 ms and how that places it on the end of the call stack, which can help. Seems weird to me, but it works.

For anyone else that has a similar problem, this may be your solution. I'm not entirely sure why $nextTick didn't work, but I'm not familiar enough with the inner-workings of Vue.js to comment. All the same, setTimeout with a 0 ms setting worked. Thanks.