问:
No qualifying bean - FxWeaver and Spring Boot
I am trying to refactor a Java program I wrote last year to use Spring Boot. The front end uses JavaFX, and so I am trying to use FxWeaver.

However, when I run my program, I get the following error on startup:

```<code>Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'net.rgielen.fxweaver.core.FxWeaver' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
    ...
</code>```

From rgielen's website, it shouldn't be necessary to provide an RxWeaver "... when using the Spring Boot Starter, since it provides auto-configuration for a FxWeaver instance."

So I'm stumped as to why I'm getting this error. Would anyone be able to take a look please?

Main Application

```<code>package application;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import javafx.application.Application;

@SpringBootApplication
public class MainApplication  {

    public static void main(String[] args) {

        Application.launch(SpringbootJavaFxApplication.class, args);
    }

}
</code>```

SpringBootJavaFxApplication

```<code>package application;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import net.rgielen.fxweaver.core.FxWeaver;

public class SpringbootJavaFxApplication extends Application {

    private ConfigurableApplicationContext applicationContext;

    @Override
    public void init() throws Exception {
        this.applicationContext = new SpringApplicationBuilder()
                .sources(MainApplication.class)
                .run(getParameters().getRaw().toArray(new String[0]));
    }

    @Override
    public void start(Stage stage) {
        FxWeaver fxWeaver = applicationContext.getBean(FxWeaver.class);
        Parent root = fxWeaver.loadView(Controller.class);
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    @Override
    public void stop() {
        this.applicationContext.close();
        Platform.exit();
    }

}
</code>```

pom

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>xxxxx</groupId>
    <artifactId>xxxxx</artifactId>
    <version>1.0</version>
    <name>xxxxx</name>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
        </dependency>

        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>12.0.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.rgielen</groupId>
            <artifactId>javafx-weaver-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.3</version>
                <configuration>
                    <mainClass>application.Main</mainClass>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

(Obviously the pom contains things not specifically related to this issue, but I'm including the whole file in case anything else present is causing this issue.)

Please can you let me know if you have worked out what is causing the problem? I'm tearing my hair out with this now!

Also, apologies if I've not included the right/sufficient information. This is my first post on here. I am using eclipse.

Thank you!

答:
Just a brief update for anybody who finds this in future. I was unable to resolve the problem in the end, so instead went for a full refactor of the code, without the use of FxWeaver.

More labour-intensive, but the resulting code is arguably much better as a result.

Body:
I am trying to refactor a Java program I wrote last year to use Spring Boot. The front end uses JavaFX, and so I am trying to use FxWeaver.

However, when I run my program, I get the following error on startup:

Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'net.rgielen.fxweaver.core.FxWeaver' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
    ...

From rgielen's website, it shouldn't be necessary to provide an RxWeaver "... when using the Spring Boot Starter, since it provides auto-configuration for a FxWeaver instance."

So I'm stumped as to why I'm getting this error. Would anyone be able to take a look please?

Main Application

package application;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import javafx.application.Application;

@SpringBootApplication
public class MainApplication  {

    public static void main(String[] args) {

        Application.launch(SpringbootJavaFxApplication.class, args);
    }

}

SpringBootJavaFxApplication

package application;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import net.rgielen.fxweaver.core.FxWeaver;

public class SpringbootJavaFxApplication extends Application {

    private ConfigurableApplicationContext applicationContext;

    @Override
    public void init() throws Exception {
        this.applicationContext = new SpringApplicationBuilder()
                .sources(MainApplication.class)
                .run(getParameters().getRaw().toArray(new String[0]));
    }

    @Override
    public void start(Stage stage) {
        FxWeaver fxWeaver = applicationContext.getBean(FxWeaver.class);
        Parent root = fxWeaver.loadView(Controller.class);
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    @Override
    public void stop() {
        this.applicationContext.close();
        Platform.exit();
    }

}

pom

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>xxxxx</groupId>
    <artifactId>xxxxx</artifactId>
    <version>1.0</version>
    <name>xxxxx</name>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
        </dependency>

        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>12.0.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.rgielen</groupId>
            <artifactId>javafx-weaver-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.3</version>
                <configuration>
                    <mainClass>application.Main</mainClass>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

(Obviously the pom contains things not specifically related to this issue, but I'm including the whole file in case anything else present is causing this issue.)

Please can you let me know if you have worked out what is causing the problem? I'm tearing my hair out with this now!

Also, apologies if I've not included the right/sufficient information. This is my first post on here. I am using eclipse.

Thank you!


来源: stackexchange

问:
How To Create TimerHandler Using Boost Library
I'm working on a project using C++.

I want a TimerHandler to be called after a specified time, but at the same time I don't want to block the current thread or any code after io.run() in the following code:

```<code>#include <iostream>
#include <string>
#include <boost/format.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

class TimerTest
{
public:
    static void PrintOutTimerHandler(const boost::system::error_code&, const std::string& message)
    {
        std::cout << "PrintOutTimerHandler called: " << ", message: " << message << std::endl;
    }

    void run()
    {
        boost::asio::io_service io;
        boost::asio::deadline_timer dt(io, boost::posix_time::seconds(5));

        std::cout << "Start:\t" << std::endl;

        dt.async_wait(boost::bind(PrintOutTimerHandler, boost::asio::placeholders::error, std::string("here is the message")));

        // Do some job here
        for (int i = 0; i < 1000000; ++i)
            ++i, --i;

        std::cout << "End:\t" << std::endl;

        io.run();

        std::cout << "When to reach here 1: " << std::endl;
    }
};

int main()
{
    TimerTest tt;
    tt.run();

    std::cout << "When to reach here 2: " << std::endl;

    return 0;
}

/* Current output:
Start:
End:
PrintOutTimerHandler called: , message: here is the message
When to reach here 1:
When to reach here 2:
 */

/* Expected output:
Start:
End:
When to reach here 1:
When to reach here 2:
PrintOutTimerHandler called: , message: here is the message
 */
</code>```

I think I made myself clear.  My questions are:

If this can be solved without
introducing a new thread, like Flex
ActionScript, that's is the best, but
I guess not (I guess ActionScript is
using a hidden thread);

If we have to
introduce an extra thread to do the
job, would you mind writing down the
pseudo code for me?

Thanks.

Peter

答:
Here is an example . Run the io_service in a separate thread

```<code>asio::io_service io_service;
asio::thread t(boost::bind(&asio::io_service::run, &io_service));
</code>```

or run it in a thread group

```<code>boost::thread_group threads;
for (std::size_t i = 0; i < my_thread_count; ++i)
    threads.create_thread(boost::bind(&asio::io_service::run, &io_service));
</code>```

Remember that your main thread should always run because when it exists all threads spawned will also exit.

I hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a project using C++.

I want a TimerHandler to be called after a specified time, but at the same time I don't want to block the current thread or any code after io.run() in the following code:

#include <iostream>
#include <string>
#include <boost/format.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

class TimerTest
{
public:
    static void PrintOutTimerHandler(const boost::system::error_code&, const std::string& message)
    {
        std::cout << "PrintOutTimerHandler called: " << ", message: " << message << std::endl;
    }

    void run()
    {
        boost::asio::io_service io;
        boost::asio::deadline_timer dt(io, boost::posix_time::seconds(5));

        std::cout << "Start:\t" << std::endl;

        dt.async_wait(boost::bind(PrintOutTimerHandler, boost::asio::placeholders::error, std::string("here is the message")));

        // Do some job here
        for (int i = 0; i < 1000000; ++i)
            ++i, --i;

        std::cout << "End:\t" << std::endl;

        io.run();

        std::cout << "When to reach here 1: " << std::endl;
    }
};

int main()
{
    TimerTest tt;
    tt.run();

    std::cout << "When to reach here 2: " << std::endl;

    return 0;
}

/* Current output:
Start:
End:
PrintOutTimerHandler called: , message: here is the message
When to reach here 1:
When to reach here 2:
 */

/* Expected output:
Start:
End:
When to reach here 1:
When to reach here 2:
PrintOutTimerHandler called: , message: here is the message
 */

I think I made myself clear.  My questions are:

If this can be solved without
introducing a new thread, like Flex
ActionScript, that's is the best, but
I guess not (I guess ActionScript is
using a hidden thread);

If we have to
introduce an extra thread to do the
job, would you mind writing down the
pseudo code for me?

Thanks.

Peter

Body:
Here is an example . Run the io_service in a separate thread

asio::io_service io_service;
asio::thread t(boost::bind(&asio::io_service::run, &io_service));

or run it in a thread group

boost::thread_group threads;
for (std::size_t i = 0; i < my_thread_count; ++i)
    threads.create_thread(boost::bind(&asio::io_service::run, &io_service));

Remember that your main thread should always run because when it exists all threads spawned will also exit.

I hope this helps.


问:
SQLite and C# - INSERT and UPDATE whit CASE check
I'm trying to edit the insertions in this table, using C# and sqlite.

SQLite Table:

```<code>CREATE TABLE "utenti" (
    "id"    INTEGER NOT NULL,
    "grado" TEXT,
    "cognome"   TEXT NOT NULL,
    "nome"  TEXT NOT NULL,
    "codice_fiscale"    TEXT
)
</code>```

```<code>CREATE TABLE "entrate" (
    "id"    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    "id_utente" INTEGER NOT NULL,
    "nome"  TEXT NOT NULL,
    "entrata"   TEXT NOT NULL,
    "uscita"    TEXT
);
</code>```

I would like to make sure that first we go to check if there is a record with the "id_utente" inserted in the textbox.
If it exists and the value of the "uscita" column is empty, update the row and add value in "uscita" column .
While if there are no lines with "id_utente" inserted in the textbox, or if they exist but "entrata" and "uscita" column value has been entered, insert a new record.

Test Code:

```<code>public static bool SavePerson(int idUtente, string nome, string orario)
        {
            using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
            {
                var output = cnn.Query($"select * from utenti where id = {idUtente}").FirstOrDefault();

                if (output != null) {
                    nome = FindCognome(idUtente);
                    string query;

                    query = $"IF NOT EXISTS(SELECT (id_utente, nome, entrata) FROM entrate WHERE id_utente = '\"{idUtente}\"')" +
                    $"BEGIN"
                    $"INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")" +
                    $"END" +
                    $"ELSE" +
                    $"BEGIN" +
                    $"UPDATE entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\") WHERE id_utente = '\"{idUtente}\"')" +
                    $"END";

                    //cnn.Execute($"INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")");

                    cnn.Execute(query);
                    cnn.Close();
                    return true;
                }
                else return false;

            }
        }
</code>```

I have made various tests and various attempts but I find myself in difficulty, for the control variable of the row in the table.

OTHER WRONG TEST

```<code>query = $"UPDATE entrate SET uscita = \"{orario}\"," +
                        $"CASE WHEN id_utente = {idUtente}" +
                        $"ELSE INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")";
</code>```

答:
I fixed the problem by going to change some tables and how they are read

SQLite Table:

```<code>CREATE TABLE "utenti" (
    "id"    INTEGER NOT NULL,
    "grado" TEXT,
    "cognome"   TEXT NOT NULL,
    "nome"  TEXT NOT NULL,
    "codice_fiscale"    TEXT,
    "presente"  INTEGER
)
</code>```

```<code>CREATE TABLE "entrate" (
    "id"    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    "id_utente" INTEGER NOT NULL,
    "nome"  TEXT NOT NULL,
    "entrata"   TEXT NOT NULL,
    "uscita"    TEXT
)
</code>```

Code:

```<code>public static bool SavePerson(int idUtente, string nome, string orario)
{
    using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        var output = cnn.Query($"select * from utenti where id = {idUtente}").FirstOrDefault();

        if (output != null) {
            nome = FindCognome(idUtente);
            var checkpresenza = cnn.QuerySingle<int>($"select presente from utenti where id = \"{idUtente}\" limit 1");
            Console.WriteLine(checkpresenza);

            if (checkpresenza == 0)
            {
                cnn.Execute($"INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")");
                cnn.Execute($"UPDATE utenti SET presente = \"1\"  WHERE id = {idUtente}");
                presenza = 0;

            }
            else if (checkpresenza == 1)
            {
                cnn.Execute($"UPDATE entrate SET uscita = \"{orario}\" where id_utente = {idUtente}");
                cnn.Execute($"UPDATE utenti SET presente = \"0\"  WHERE id = {idUtente}");
                presenza = 1;
            }

            cnn.Close();
            return true;
        }
        else return false;

        }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to edit the insertions in this table, using C# and sqlite.

SQLite Table:

CREATE TABLE "utenti" (
    "id"    INTEGER NOT NULL,
    "grado" TEXT,
    "cognome"   TEXT NOT NULL,
    "nome"  TEXT NOT NULL,
    "codice_fiscale"    TEXT
)

CREATE TABLE "entrate" (
    "id"    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    "id_utente" INTEGER NOT NULL,
    "nome"  TEXT NOT NULL,
    "entrata"   TEXT NOT NULL,
    "uscita"    TEXT
);

I would like to make sure that first we go to check if there is a record with the "id_utente" inserted in the textbox.
If it exists and the value of the "uscita" column is empty, update the row and add value in "uscita" column .
While if there are no lines with "id_utente" inserted in the textbox, or if they exist but "entrata" and "uscita" column value has been entered, insert a new record.

Test Code:

public static bool SavePerson(int idUtente, string nome, string orario)
        {
            using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
            {
                var output = cnn.Query($"select * from utenti where id = {idUtente}").FirstOrDefault();

                if (output != null) {
                    nome = FindCognome(idUtente);
                    string query;

                    query = $"IF NOT EXISTS(SELECT (id_utente, nome, entrata) FROM entrate WHERE id_utente = '\"{idUtente}\"')" +
                    $"BEGIN"
                    $"INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")" +
                    $"END" +
                    $"ELSE" +
                    $"BEGIN" +
                    $"UPDATE entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\") WHERE id_utente = '\"{idUtente}\"')" +
                    $"END";

                    //cnn.Execute($"INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")");

                    cnn.Execute(query);
                    cnn.Close();
                    return true;
                }
                else return false;

            }
        }

I have made various tests and various attempts but I find myself in difficulty, for the control variable of the row in the table.

OTHER WRONG TEST

query = $"UPDATE entrate SET uscita = \"{orario}\"," +
                        $"CASE WHEN id_utente = {idUtente}" +
                        $"ELSE INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")";

Body:
I fixed the problem by going to change some tables and how they are read

SQLite Table:

CREATE TABLE "utenti" (
    "id"    INTEGER NOT NULL,
    "grado" TEXT,
    "cognome"   TEXT NOT NULL,
    "nome"  TEXT NOT NULL,
    "codice_fiscale"    TEXT,
    "presente"  INTEGER
)

CREATE TABLE "entrate" (
    "id"    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    "id_utente" INTEGER NOT NULL,
    "nome"  TEXT NOT NULL,
    "entrata"   TEXT NOT NULL,
    "uscita"    TEXT
)

Code:

public static bool SavePerson(int idUtente, string nome, string orario)
{
    using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        var output = cnn.Query($"select * from utenti where id = {idUtente}").FirstOrDefault();

        if (output != null) {
            nome = FindCognome(idUtente);
            var checkpresenza = cnn.QuerySingle<int>($"select presente from utenti where id = \"{idUtente}\" limit 1");
            Console.WriteLine(checkpresenza);

            if (checkpresenza == 0)
            {
                cnn.Execute($"INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")");
                cnn.Execute($"UPDATE utenti SET presente = \"1\"  WHERE id = {idUtente}");
                presenza = 0;

            }
            else if (checkpresenza == 1)
            {
                cnn.Execute($"UPDATE entrate SET uscita = \"{orario}\" where id_utente = {idUtente}");
                cnn.Execute($"UPDATE utenti SET presente = \"0\"  WHERE id = {idUtente}");
                presenza = 1;
            }

            cnn.Close();
            return true;
        }
        else return false;

        }

}


问:
How to add minutes to a Time object
In Ruby, how do I do Time.now + 10.hours?

Is there an equivalent for secs and mins?  For example:

```<code>Time.now + 15.mins
</code>```

答:
Time Object

time = Time.now

Adding minutes to a time object:

time + 5.minutes

Title: How to add minutes to a Time object

Body:
In Ruby, how do I do Time.now + 10.hours?

Is there an equivalent for secs and mins?  For example:

Time.now + 15.mins


问:
getBackStackEntryCount return 0 when Activity is recreated
I know this has to be simple and I'm probably not seeing the solution.
Here is the brief description of what I have:
SignInActivity(AppCompatActivity) - handle the Firebase authentication, on success calls the method:

```<code>private void onAuthSuccess(FirebaseUser user) {
    // Go to MainActivity
    startActivity(new Intent(SignInActivity.this, MainActivity.class));
    finish();
}
</code>```

MainActivity(AppCompatActivity) - handle the menus for the application, this menu in particular are fragments with buttons. When a button is clicked I change the fragment that contains other buttons. Something like this:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.slide_in_up, R.anim.slide_out_left)
                .replace(R.id.fragmentContent, MainMenuFragment.newInstance())
                .commitNow();
    }

    getSupportFragmentManager().addOnBackStackChangedListener(new
        FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                int stackHeight = getSupportFragmentManager().getBackStackEntryCount();
                getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
                getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);
            }
        });
}

public void replaceFragments(Class fragmentClass, boolean isBack) {
    Fragment fragment = null;
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    if (isBack) {
        ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
    } else {
        ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right);
    }

    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        fragment = null;
        e.printStackTrace();
    }

    if (fragment != null) {
        ft.replace(R.id.fragmentContent, fragment);
        ft.addToBackStack(fragmentClass.getName());
        ft.commit();
    }
}
</code>```

MainMenuFragment(Fragment) - First set of options, several buttons on top of each other. Depending on the button clicked will call MainActivity.replaceFragment passing the next Fragment to go.

```<code>public class MainMenuFragment extends Fragment {
    private static final String TAG = "MainMenuFragment";

    public static MainMenuFragment newInstance() {
        return new MainMenuFragment();
    }

    public MainMenuFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main_menu, container, false);

        final Button btnAssets = view.findViewById(R.id.btnAssets);
        final Button btnAudit = view.findViewById(R.id.btnAudit);

        btnAssets.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "BtnAssets_onClick");
                ((MainActivity)getActivity()).replaceFragments(AssetMenuFragment.class);
            }
        });

        btnAudit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "BtnAudit_onClick");
                ((MainActivity)getActivity()).replaceFragments(AuditMenuFragment.class);
            }
        });
        return view;
    }
}
</code>```

The AssetMenuFragment and the AuditMenuFragment are pretty much the same as the MainMenu, only the text for the buttons and some layout details changes.

When I'm using the app I first signIn, which leads me to the MainActivity, which loads the MainMenuFragment on onCreate. There I'm presented with two buttons, one to go to the AssetMenuFragment and the other to go to the AuditMenuFragment, they replace the fragment with their according layouts.
If I click the Asset button, once the fragment is replaced, because of:

```<code>getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);
</code>```

I'm presented with the back arrow to go back to MainMenuFragment. Everything works as expected.

Now the problem! If I'm in this AssetMenuFragment, with my beautiful back arrow showing on the ActionBar and decided to click the "Square" button on the device, which is probably run the onPause and onStop, and them click on the app again, which will run the onCreate and onStart again, my back arrow disappears, because now int stackHeight = getSupportFragmentManager().getBackStackEntryCount(); is zero.

How can I save my stack and restore it later so I can press back on the AssetMenuFragment and go back to MainMenuFragment.

It is a lot to read, but I'll appreciate the help, thanks!

答:
In the end I knew it had to be something simple.

Both checks are correct.

```<code>getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);
</code>```

The problem was that I didn't check for them on onCreate, only on the getSupportFragmentManager().addOnBackStackChangedListener event.

Here is the MainActivity now:

```<code>private ActionBar actionBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
                .replace(R.id.fragmentContent, MainMenuFragment.newInstance())
                .commitNow();
    }

    actionBar = getSupportActionBar();
    updateActionBarBackButton();

    getSupportFragmentManager().addOnBackStackChangedListener(new
        FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                updateActionBarBackButton();
            }
        });
}

private void updateActionBarBackButton() {
    int stackHeight = getSupportFragmentManager().getBackStackEntryCount();
    getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
    getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);
}

</code>```

Body:
I know this has to be simple and I'm probably not seeing the solution.
Here is the brief description of what I have:
SignInActivity(AppCompatActivity) - handle the Firebase authentication, on success calls the method:

private void onAuthSuccess(FirebaseUser user) {
    // Go to MainActivity
    startActivity(new Intent(SignInActivity.this, MainActivity.class));
    finish();
}

MainActivity(AppCompatActivity) - handle the menus for the application, this menu in particular are fragments with buttons. When a button is clicked I change the fragment that contains other buttons. Something like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.slide_in_up, R.anim.slide_out_left)
                .replace(R.id.fragmentContent, MainMenuFragment.newInstance())
                .commitNow();
    }

    getSupportFragmentManager().addOnBackStackChangedListener(new
        FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                int stackHeight = getSupportFragmentManager().getBackStackEntryCount();
                getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
                getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);
            }
        });
}

public void replaceFragments(Class fragmentClass, boolean isBack) {
    Fragment fragment = null;
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    if (isBack) {
        ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
    } else {
        ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right);
    }

    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        fragment = null;
        e.printStackTrace();
    }

    if (fragment != null) {
        ft.replace(R.id.fragmentContent, fragment);
        ft.addToBackStack(fragmentClass.getName());
        ft.commit();
    }
}

MainMenuFragment(Fragment) - First set of options, several buttons on top of each other. Depending on the button clicked will call MainActivity.replaceFragment passing the next Fragment to go.

public class MainMenuFragment extends Fragment {
    private static final String TAG = "MainMenuFragment";

    public static MainMenuFragment newInstance() {
        return new MainMenuFragment();
    }

    public MainMenuFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main_menu, container, false);

        final Button btnAssets = view.findViewById(R.id.btnAssets);
        final Button btnAudit = view.findViewById(R.id.btnAudit);

        btnAssets.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "BtnAssets_onClick");
                ((MainActivity)getActivity()).replaceFragments(AssetMenuFragment.class);
            }
        });

        btnAudit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "BtnAudit_onClick");
                ((MainActivity)getActivity()).replaceFragments(AuditMenuFragment.class);
            }
        });
        return view;
    }
}

The AssetMenuFragment and the AuditMenuFragment are pretty much the same as the MainMenu, only the text for the buttons and some layout details changes.

When I'm using the app I first signIn, which leads me to the MainActivity, which loads the MainMenuFragment on onCreate. There I'm presented with two buttons, one to go to the AssetMenuFragment and the other to go to the AuditMenuFragment, they replace the fragment with their according layouts.
If I click the Asset button, once the fragment is replaced, because of:

getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);

I'm presented with the back arrow to go back to MainMenuFragment. Everything works as expected.

Now the problem! If I'm in this AssetMenuFragment, with my beautiful back arrow showing on the ActionBar and decided to click the "Square" button on the device, which is probably run the onPause and onStop, and them click on the app again, which will run the onCreate and onStart again, my back arrow disappears, because now int stackHeight = getSupportFragmentManager().getBackStackEntryCount(); is zero.

How can I save my stack and restore it later so I can press back on the AssetMenuFragment and go back to MainMenuFragment.

It is a lot to read, but I'll appreciate the help, thanks!

Body:
In the end I knew it had to be something simple.

Both checks are correct.

getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);

The problem was that I didn't check for them on onCreate, only on the getSupportFragmentManager().addOnBackStackChangedListener event.

Here is the MainActivity now:

private ActionBar actionBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
                .replace(R.id.fragmentContent, MainMenuFragment.newInstance())
                .commitNow();
    }

    actionBar = getSupportActionBar();
    updateActionBarBackButton();

    getSupportFragmentManager().addOnBackStackChangedListener(new
        FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                updateActionBarBackButton();
            }
        });
}

private void updateActionBarBackButton() {
    int stackHeight = getSupportFragmentManager().getBackStackEntryCount();
    getSupportActionBar().setHomeButtonEnabled(stackHeight > 0);
    getSupportActionBar().setDisplayHomeAsUpEnabled(stackHeight > 0);
}


问:
using bash command in perl
i have short bash code

```<code>cat example.txt | grep mail | awk -F, '{print $1}' | awk -F= '{print $2}'
</code>```

I want to use it in perl script, and put its output to an array line by line.
I tried this but did not work

```<code>@array = system('cat /path/example.txt | grep mail | awk -F, {print $1} | awk -F= {print $2}');
</code>```

Thanks for helping...

答:
The return value of system() is the return status of the command you executed. If you want the output, use backticks:

```<code>@array = `cat /path/example.txt | grep mail | awk -F, {print \$1} | awk -F= {print \$2}`;
</code>```

When evaluated in list context (e.g. when the return value is assigned to an array), you'll get the lines of output (or an empty list if there's no output).

Title: using bash command in perl

Body:
i have short bash code

cat example.txt | grep mail | awk -F, '{print $1}' | awk -F= '{print $2}'

I want to use it in perl script, and put its output to an array line by line.
I tried this but did not work

@array = system('cat /path/example.txt | grep mail | awk -F, {print $1} | awk -F= {print $2}');

Thanks for helping...

Body:
The return value of system() is the return status of the command you executed. If you want the output, use backticks:

@array = `cat /path/example.txt | grep mail | awk -F, {print \$1} | awk -F= {print \$2}`;

When evaluated in list context (e.g. when the return value is assigned to an array), you'll get the lines of output (or an empty list if there's no output).


问:
A constraint with function that contains Select is never satisfied
I have a table like this:

```<code>CREATE TABLE CarRentSchedule
(
    carId INTEGER NOT NULL,
    rent_start INTEGER NOT NULL,
    rent_end INTEGER NOT NULL,
    personId INTEGER NOT NULL,
    tariff INTEGER NOT NULL,
    PRIMARY KEY carId,
    FOREIGN KEY (personId) REFERENCES Persons(PersonID)
    CONSTRAINT CHK_CR_AVLBL CHECK (dbo.CarCheck(carId , rent_start , rent_end ) = 1))
</code>```

And I need to forbid any rent time intersection for the same car.
I found that, when a function is used (example below) inside the constraint, the value it returns is different from whent it is used outside the constraint.

```<code>if exists (select * from dbo.CarRentSchedule rt
               where rt.carId = @id
                 and ((rt.rent_Start >= @startTime and rt.rent_end < @endTime)
                      or
                      (rt.rent_end <= @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start < @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start >= @startTime and rt.rent_end <= @endTime)))
        return 0
</code>```

So when I'm trying to insert data into the table, the constraint would never allow me to for some reason.

I have checked, when called from the constraint the function seems to return NULL, however calling the function like

```<code>select dbo.CheckFunc(1, 10, 15, 1, 1)
</code>```

would return 0/1 as it is supposed to. I have also checked and found out that if there is no SELECT in the function (a simple comparison operation, for example) it would work just fine in the constraint too.

Could anybody explain why does this work this way? Is it some restriction forbidding using SELECT's inside the constraints or is it because the SELECT references to the same table the constraint applied to?

答:
My guess is that when checking the second constraint the new enty is already considered to be a part of the table so it always overlaps with itself. But this is seems strainge, doesn't it?

So, yes, it appears as so, I have rewirritten the function so that it would not consider the newly added entry and it works now. Strange, tho, I just wouldn't imagine that an entry that is currently being tested to be added would participate in the side select from that table.

Body:
I have a table like this:

CREATE TABLE CarRentSchedule
(
    carId INTEGER NOT NULL,
    rent_start INTEGER NOT NULL,
    rent_end INTEGER NOT NULL,
    personId INTEGER NOT NULL,
    tariff INTEGER NOT NULL,
    PRIMARY KEY carId,
    FOREIGN KEY (personId) REFERENCES Persons(PersonID)
    CONSTRAINT CHK_CR_AVLBL CHECK (dbo.CarCheck(carId , rent_start , rent_end ) = 1))

And I need to forbid any rent time intersection for the same car.
I found that, when a function is used (example below) inside the constraint, the value it returns is different from whent it is used outside the constraint.

if exists (select * from dbo.CarRentSchedule rt
               where rt.carId = @id
                 and ((rt.rent_Start >= @startTime and rt.rent_end < @endTime)
                      or
                      (rt.rent_end <= @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start < @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start >= @startTime and rt.rent_end <= @endTime)))
        return 0

So when I'm trying to insert data into the table, the constraint would never allow me to for some reason.

I have checked, when called from the constraint the function seems to return NULL, however calling the function like

select dbo.CheckFunc(1, 10, 15, 1, 1)

would return 0/1 as it is supposed to. I have also checked and found out that if there is no SELECT in the function (a simple comparison operation, for example) it would work just fine in the constraint too.

Could anybody explain why does this work this way? Is it some restriction forbidding using SELECT's inside the constraints or is it because the SELECT references to the same table the constraint applied to?


问:
Output the index of map()
I want to output the index of each element using map().

const arr = [1,2,3,4,5,6,7,8,9];
const div = document.querySelector('.container')
div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
}
.it {
    border: 2px solid;
    background-color: burlywood;
    color: white;
    width: 60px;
    height: 50px;
}</code>```

```

How to output indexes of each element inside div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');?

答:
Considering you have the following:

```<code>const arr = [1,2,3,4,5,6,7,8,9];
...
div.innerHTML = arr.map((index,val) => "<div class='it'>"+val+"</div>" ).join('');
</code>```

Array.prototype.map has index of the element as the second parameter. So to get this index, your code should be like:

```<code>div.innerHTML = arr.map((val,index)=>`<div>${val} - ${index}</div>`).join('');
</code>```

This should solve your problem.

Title: Output the index of map()

Body:
I want to output the index of each element using map().

const arr = [1,2,3,4,5,6,7,8,9];
const div = document.querySelector('.container')
div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');

* {
    margin: 0;
    padding: 0;
}
.it {
    border: 2px solid;
    background-color: burlywood;
    color: white;
    width: 60px;
    height: 50px;
}

How to output indexes of each element inside div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');?

Body:
Considering you have the following:

const arr = [1,2,3,4,5,6,7,8,9];
...
div.innerHTML = arr.map((index,val) => "<div class='it'>"+val+"</div>" ).join('');

Array.prototype.map has index of the element as the second parameter. So to get this index, your code should be like:

div.innerHTML = arr.map((val,index)=>`<div>${val} - ${index}</div>`).join('');

This should solve your problem.


问:
Testing Accuracy is high compared actual output. How to increase the actual output accuracy?
My logistic predict model is giving me a training accuracy of 80% and testing accuracy of 79%.

Training Model Accuracy:0.8039535210772422
Testing Model Accuracy:0.7937496044721021

My confusion matrix give me these values:

Using hyper parameter tuning and printing my classification reports:

```<code>                  precision    recall  f1-score   support

           0       0.87      0.88      0.87    172299
           1       0.77      0.70      0.74     17321

   micro avg       0.85      0.85      0.85    189620
   macro avg       0.77      0.74      0.76    189620
weighted avg       0.85      0.85      0.85    189620
</code>```

When i compare the results to actual data it i tested the prediction model on only 40% of the data matches. How could i improve my actual output.

This is my code any suggestions would be really helpful.

```<code># Create the hyperparameter grid
c_space = np.logspace(-5, 8, 15)
log_param_grid = {'C': c_space, 'penalty': ['l1', 'l2']}

# Setup the GridSearchCV object: logReg_cv

logReg=LogisticRegression()
logReg_cv = GridSearchCV(logReg,log_param_grid,cv=5)

y=predict_pi.P_I
X=pd.get_dummies(X)
test=pd.get_dummies(test)

extra_cols_train = [i for i in list(test) if i not in list(X)]
extra_cols_test = [i for i in list(X) if i not in list(test)]

X = X.reindex(columns=X.columns.tolist() + extra_cols_train)
X[extra_cols_train] = 0

test = test.reindex(columns=test.columns.tolist() + extra_cols_test)
test[extra_cols_test] = 0

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.4,random_state=42)

logReg_cv.fit(X_train,y_train)
pred_pi=logReg_cv.predict(X_test)
test_pi=logReg_cv.predict(X_train)

print("Training Model Accuracy:{}".format(accuracy_score(y_train,test_pi)))
print("Testing Model Accuracy:{}".format(accuracy_score(y_test,pred_pi)))

print(confusion_matrix(y_test, pred_pi))
print(classification_report(y_test, pred_pi))
print("Tuned Logistic Regression Parameter: {}".format(logReg_cv.best_params_))
print("Tuned Logistic Regression Accuracy: {}".format(logReg_cv.best_score_))
</code>```

答:
This may mean that your model is overfitting your training data. Have you done a EDA on your actual data to see if its behavior is what you expected and your training/testing data actually represents your actual data.

Is your training set a subset of your actual data? I would recommend train your model on your actual data entirely, use every bit of data you have for the training.

When you test your model, I would recommend using Cross Validation. When you do like 5 folds or 10 folds of training/testing on your data, you should have a decent model.

Body:
My logistic predict model is giving me a training accuracy of 80% and testing accuracy of 79%.

Training Model Accuracy:0.8039535210772422
Testing Model Accuracy:0.7937496044721021

My confusion matrix give me these values:

Using hyper parameter tuning and printing my classification reports:

                  precision    recall  f1-score   support

           0       0.87      0.88      0.87    172299
           1       0.77      0.70      0.74     17321

   micro avg       0.85      0.85      0.85    189620
   macro avg       0.77      0.74      0.76    189620
weighted avg       0.85      0.85      0.85    189620

When i compare the results to actual data it i tested the prediction model on only 40% of the data matches. How could i improve my actual output.

This is my code any suggestions would be really helpful.

# Create the hyperparameter grid
c_space = np.logspace(-5, 8, 15)
log_param_grid = {'C': c_space, 'penalty': ['l1', 'l2']}

# Setup the GridSearchCV object: logReg_cv

logReg=LogisticRegression()
logReg_cv = GridSearchCV(logReg,log_param_grid,cv=5)

y=predict_pi.P_I
X=pd.get_dummies(X)
test=pd.get_dummies(test)

extra_cols_train = [i for i in list(test) if i not in list(X)]
extra_cols_test = [i for i in list(X) if i not in list(test)]

X = X.reindex(columns=X.columns.tolist() + extra_cols_train)
X[extra_cols_train] = 0

test = test.reindex(columns=test.columns.tolist() + extra_cols_test)
test[extra_cols_test] = 0

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.4,random_state=42)

logReg_cv.fit(X_train,y_train)
pred_pi=logReg_cv.predict(X_test)
test_pi=logReg_cv.predict(X_train)

print("Training Model Accuracy:{}".format(accuracy_score(y_train,test_pi)))
print("Testing Model Accuracy:{}".format(accuracy_score(y_test,pred_pi)))

print(confusion_matrix(y_test, pred_pi))
print(classification_report(y_test, pred_pi))
print("Tuned Logistic Regression Parameter: {}".format(logReg_cv.best_params_))
print("Tuned Logistic Regression Accuracy: {}".format(logReg_cv.best_score_))


问:
How to switch visibility GONE and VISIBLE in Swift
I want to switch between visibility GONE and VISIBLE.
This is really easy to achieve in Android development, but I don't know how to use the same approach in Swift

I tried this code to set a label as gone:

```<code>// set the width constraint to 0
let widthConstraint = NSLayoutConstraint(item:  self.labelShortDescription, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 0)
self.labelShortDescription.addConstraint(widthConstraint)

// set the height constraint to 0
let heightConstraint = NSLayoutConstraint(item:  self.labelShortDescription, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 0)
self.labelShortDescription.addConstraint(heightConstraint)
</code>```

答:
I wrote an UIView extension in swift to manage the views visibility similarly to the android SDK approach for views visibility.

This extension automatically adds the required constraints to collapse the view vertically, horizontally, or both. These constraints are never added multiple times and they're only needed when the visibility type is gone, goneY or goneX. They're automatically set as not active when the visibility is dynamically changed again to visible or invisible status. The visible and invisible status are managed by the isHidden property, so the view won't be visible but it still takes space.

Extension

```<code>extension UIView {

    // MARK: visibility methods

    public enum Visibility : Int {
        case visible = 0
        case invisible = 1
        case gone = 2
        case goneY = 3
        case goneX = 4
    }

    public var visibility: Visibility {
        set {
            switch newValue {
                case .visible:
                    isHidden = false
                    getConstraintY(false)?.isActive = false
                    getConstraintX(false)?.isActive = false
                case .invisible:
                    isHidden = true
                    getConstraintY(false)?.isActive = false
                    getConstraintX(false)?.isActive = false
                case .gone:
                    isHidden = true
                    getConstraintY(true)?.isActive = true
                    getConstraintX(true)?.isActive = true
                case .goneY:
                    isHidden = true
                    getConstraintY(true)?.isActive = true
                    getConstraintX(false)?.isActive = false
                case .goneX:
                    isHidden = true
                    getConstraintY(false)?.isActive = false
                    getConstraintX(true)?.isActive = true
            }
        }
        get {
            if isHidden == false {
                return .visible
            }
            if getConstraintY(false)?.isActive == true && getConstraintX(false)?.isActive == true {
                return .gone
            }
            if getConstraintY(false)?.isActive == true {
                return .goneY
            }
            if getConstraintX(false)?.isActive == true {
                return .goneX
            }
            return .invisible
        }
    }

    fileprivate func getConstraintY(_ createIfNotExists: Bool = false) -> NSLayoutConstraint? {
        return getConstraint(.height, createIfNotExists)
    }

    fileprivate func getConstraintX(_ createIfNotExists: Bool = false) -> NSLayoutConstraint? {
        return getConstraint(.width, createIfNotExists)
    }

    fileprivate func getConstraint(_ attribute: NSLayoutConstraint.Attribute, _ createIfNotExists: Bool = false) -> NSLayoutConstraint? {
        let identifier = "random_id"
        var result: NSLayoutConstraint? = nil
        for constraint in constraints {
            if constraint.identifier == identifier {
                result = constraint
                break
            }
        }
        if result == nil && createIfNotExists {
            // create and add the constraint
            result = NSLayoutConstraint(item: self, attribute: attribute, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 0)
            result?.identifier = identifier
            addConstraint(result!)
        }
        return result
    }
}
</code>```

Usage

```<code>myView.visibility = .visible
myView.visibility = .invisible
myView.visibility = .gone
myView.visibility = .goneX
myView.visibility = .goneY
</code>```

Body:
I want to switch between visibility GONE and VISIBLE.
This is really easy to achieve in Android development, but I don't know how to use the same approach in Swift

I tried this code to set a label as gone:

// set the width constraint to 0
let widthConstraint = NSLayoutConstraint(item:  self.labelShortDescription, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 0)
self.labelShortDescription.addConstraint(widthConstraint)

// set the height constraint to 0
let heightConstraint = NSLayoutConstraint(item:  self.labelShortDescription, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 0)
self.labelShortDescription.addConstraint(heightConstraint)

Body:
I wrote an UIView extension in swift to manage the views visibility similarly to the android SDK approach for views visibility.

This extension automatically adds the required constraints to collapse the view vertically, horizontally, or both. These constraints are never added multiple times and they're only needed when the visibility type is gone, goneY or goneX. They're automatically set as not active when the visibility is dynamically changed again to visible or invisible status. The visible and invisible status are managed by the isHidden property, so the view won't be visible but it still takes space.

Extension

extension UIView {

    // MARK: visibility methods

    public enum Visibility : Int {
        case visible = 0
        case invisible = 1
        case gone = 2
        case goneY = 3
        case goneX = 4
    }

    public var visibility: Visibility {
        set {
            switch newValue {
                case .visible:
                    isHidden = false
                    getConstraintY(false)?.isActive = false
                    getConstraintX(false)?.isActive = false
                case .invisible:
                    isHidden = true
                    getConstraintY(false)?.isActive = false
                    getConstraintX(false)?.isActive = false
                case .gone:
                    isHidden = true
                    getConstraintY(true)?.isActive = true
                    getConstraintX(true)?.isActive = true
                case .goneY:
                    isHidden = true
                    getConstraintY(true)?.isActive = true
                    getConstraintX(false)?.isActive = false
                case .goneX:
                    isHidden = true
                    getConstraintY(false)?.isActive = false
                    getConstraintX(true)?.isActive = true
            }
        }
        get {
            if isHidden == false {
                return .visible
            }
            if getConstraintY(false)?.isActive == true && getConstraintX(false)?.isActive == true {
                return .gone
            }
            if getConstraintY(false)?.isActive == true {
                return .goneY
            }
            if getConstraintX(false)?.isActive == true {
                return .goneX
            }
            return .invisible
        }
    }

    fileprivate func getConstraintY(_ createIfNotExists: Bool = false) -> NSLayoutConstraint? {
        return getConstraint(.height, createIfNotExists)
    }

    fileprivate func getConstraintX(_ createIfNotExists: Bool = false) -> NSLayoutConstraint? {
        return getConstraint(.width, createIfNotExists)
    }

    fileprivate func getConstraint(_ attribute: NSLayoutConstraint.Attribute, _ createIfNotExists: Bool = false) -> NSLayoutConstraint? {
        let identifier = "random_id"
        var result: NSLayoutConstraint? = nil
        for constraint in constraints {
            if constraint.identifier == identifier {
                result = constraint
                break
            }
        }
        if result == nil && createIfNotExists {
            // create and add the constraint
            result = NSLayoutConstraint(item: self, attribute: attribute, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 0)
            result?.identifier = identifier
            addConstraint(result!)
        }
        return result
    }
}

Usage

myView.visibility = .visible
myView.visibility = .invisible
myView.visibility = .gone
myView.visibility = .goneX
myView.visibility = .goneY


问:
More Efficient Way To Merge Unique Values From Dynamically Selected Tables using Oracle PLSQL
Given a declared PLSQL Procedure

```<code>PROCEDURE GET_DISTINCT_TIMES(dtypes IN VARCHAR2, start IN NUMBER, end IN NUMBER
   distinct_times_cursor OUT SYS_REFCURSOR)
</code>```

Where:

'Dtypes' is a comma delimited string, with each value corresponding to a general type of data I want to retrieve.  One data type may correspond to one or many different tables where distinct times need to be retrieved

'Start' & 'End' are the two times I am querying between

I have written implementations that dynamically create the SQL using Unions to pull out only unique time values from each table.  However, due to the dynamic nature of the 'Dtypes' argument, I am forced to generate this SQL in a loop control, and have not been able to figure a way to implement bind variables.

I believe that losing the benefit of bind variables may have caused the queries to take longer than necessary

So I am wondering, is there a way to either:

Associate bind variables with a dynamically created SQL string when the number of bind variables is completely variable with the arguments passed in to the procedure.

Take a different approach, where for each dtype - execute another stored procedure, or SQL Statement, store the recordset for each query, then merge the unique results and assign a cursor to the new results

Admittedly, I am quite new with PLSQL programming and haven't had the opportunity yet to grab a good reference/book on the language.  Any comments, insights, or suggested readings would be appreciated too.

答:
See this SO question.  You can use the DBMS_SQL package to bind a varying number of bind variables.

One other possibility is to use a pipelined table function.  For each dtype, you would execute a stored procedure or SQL statement and use PIPE ROW to output the results.  If you still need the results in a ref cursor, you can do SELECT * FROM TABLE(pipelined_function()).

Body:
Given a declared PLSQL Procedure

PROCEDURE GET_DISTINCT_TIMES(dtypes IN VARCHAR2, start IN NUMBER, end IN NUMBER
   distinct_times_cursor OUT SYS_REFCURSOR)

Where:

'Dtypes' is a comma delimited string, with each value corresponding to a general type of data I want to retrieve.  One data type may correspond to one or many different tables where distinct times need to be retrieved

'Start' & 'End' are the two times I am querying between

I have written implementations that dynamically create the SQL using Unions to pull out only unique time values from each table.  However, due to the dynamic nature of the 'Dtypes' argument, I am forced to generate this SQL in a loop control, and have not been able to figure a way to implement bind variables.

I believe that losing the benefit of bind variables may have caused the queries to take longer than necessary

So I am wondering, is there a way to either:

Associate bind variables with a dynamically created SQL string when the number of bind variables is completely variable with the arguments passed in to the procedure.

Take a different approach, where for each dtype - execute another stored procedure, or SQL Statement, store the recordset for each query, then merge the unique results and assign a cursor to the new results

Admittedly, I am quite new with PLSQL programming and haven't had the opportunity yet to grab a good reference/book on the language.  Any comments, insights, or suggested readings would be appreciated too.


问:
What can I use to stop a loop instead of 'return 0'?
so I made a simple loop that finds out if an array has the elements with the values of 0 and 1.
if the loop indeed finds 0 or 1 inside of the array, it will say "YES", otherwise "NO".
yes, the program works just fine, but at the end of the program it prints out "YES" or "NO" as many times as i put cin>>dim to.
for example if dim which means (dimension[of the array]) is 5 it's going to print either "YESYESYESYESYES" or "NONONONONO"
I have to use return 0 in order to make it print it out like once, but I feel like this is not the right way to do it. Please help me with this. thanks!

```<code>#include <bits/stdc++.h>
using namespace std;
int main()
{
int i, dim, v[100];
cin>>dim;
for(i=0;i<dim;i++)
    cin>>v[i];
for(i=0;i<dim;i++)
    if(v[i]==0 || v[i]==1){
        cout<<"YES"; return 0;}
    else{
        cout<<"NO"; return 0;}
  return 0;
}
</code>```

答:
The break statement can be used to break out of loops. The example from cppreference:

```<code>for (int j = 0; j < 2; j++) {
    for (int k = 0; k < 5; k++) {         //only this loop is affected by break
        if (k == 2) break;
        std::cout << j << k << " ";
    }
}
</code>```

As the comment suggests, break only breaks the innermost loop.

In your code you always exit from the loop on the very first iteration, hence you do not need the loop in the first place. This will have the same output as your code:

```<code>int main() {
    int i, dim, v[100];
    cin >> dim;
    for(i=0; i < dim; i++)
        cin >> v[i];

    if(v[0] == 0 || v[0] == 1) {
        cout << "YES";
    } else {
        cout << "NO";
    }
}
</code>```

After reading the question again...

I made a simple loop that finds out if an array has the elements with the values of 0 and 1

If you exit the loop after checking the first element then you only check the first element. If you want to see if an array contains only 1 or 0 or it contains at least one element which is 0 or 1 (not 100% clear which one you want), then you rather need this:

```<code>bool only_zero_or_one = true;
bool one_zero_or_one = false;
for (int i = 0; i < dim; ++i) {
     zero_or_one = ( v[i] == 0 | v[i] == 1);
     only_zero_or_one = zero_or_one && only_zero_or_one;
     one_zero_or_one = zero_or_one || one_zero_or_one;
}
</code>```

Only for one_zero_or_one you can break the loop once zero_or_one == true.

Moreover, you should rather use a std::vector. In your code, if the user enters a dim which is greater than 100 you write beyond the bounds of v. This can be avoided easily:

```<code> size_t dim;
 std::cin >> dim;
 // construct vector with dim elements
 std::vector v(dim);
 // read elements
 for (size_t i=0; i < v.size(); ++i) std::cin >> v[i];
 // .. or use range based for loop
 for (auto& e : v) std::cin >> e;
</code>```

Body:
so I made a simple loop that finds out if an array has the elements with the values of 0 and 1.
if the loop indeed finds 0 or 1 inside of the array, it will say "YES", otherwise "NO".
yes, the program works just fine, but at the end of the program it prints out "YES" or "NO" as many times as i put cin>>dim to.
for example if dim which means (dimension[of the array]) is 5 it's going to print either "YESYESYESYESYES" or "NONONONONO"
I have to use return 0 in order to make it print it out like once, but I feel like this is not the right way to do it. Please help me with this. thanks!

#include <bits/stdc++.h>
using namespace std;
int main()
{
int i, dim, v[100];
cin>>dim;
for(i=0;i<dim;i++)
    cin>>v[i];
for(i=0;i<dim;i++)
    if(v[i]==0 || v[i]==1){
        cout<<"YES"; return 0;}
    else{
        cout<<"NO"; return 0;}
  return 0;
}

Body:
The break statement can be used to break out of loops. The example from cppreference:

for (int j = 0; j < 2; j++) {
    for (int k = 0; k < 5; k++) {         //only this loop is affected by break
        if (k == 2) break;
        std::cout << j << k << " ";
    }
}

As the comment suggests, break only breaks the innermost loop.

In your code you always exit from the loop on the very first iteration, hence you do not need the loop in the first place. This will have the same output as your code:

int main() {
    int i, dim, v[100];
    cin >> dim;
    for(i=0; i < dim; i++)
        cin >> v[i];

    if(v[0] == 0 || v[0] == 1) {
        cout << "YES";
    } else {
        cout << "NO";
    }
}

After reading the question again...

I made a simple loop that finds out if an array has the elements with the values of 0 and 1

If you exit the loop after checking the first element then you only check the first element. If you want to see if an array contains only 1 or 0 or it contains at least one element which is 0 or 1 (not 100% clear which one you want), then you rather need this:

bool only_zero_or_one = true;
bool one_zero_or_one = false;
for (int i = 0; i < dim; ++i) {
     zero_or_one = ( v[i] == 0 | v[i] == 1);
     only_zero_or_one = zero_or_one && only_zero_or_one;
     one_zero_or_one = zero_or_one || one_zero_or_one;
}

Only for one_zero_or_one you can break the loop once zero_or_one == true.

Moreover, you should rather use a std::vector. In your code, if the user enters a dim which is greater than 100 you write beyond the bounds of v. This can be avoided easily:

 size_t dim;
 std::cin >> dim;
 // construct vector with dim elements
 std::vector v(dim);
 // read elements
 for (size_t i=0; i < v.size(); ++i) std::cin >> v[i];
 // .. or use range based for loop
 for (auto& e : v) std::cin >> e;


问:
How to create a single dask array from multiple files?
I am trying to create a single dask array from multiple files. I am using dask.array.Array class to do that. Consider the following code snippet where I am generating 100 random integer array of size (3, 10, 10) and saving each of them in a separate npy file. Then I am trying to create a single dask array to combine all these arrays into a single dask array of shape (3, 100, 100).

```<code>import numpy as np
from itertools import product
from dask import array as da
from dask.base import tokenize

names = list()
for i in range(100):
    arr = np.random.randint(0, 9, (3, 10, 10))
    fn = 'data/array_{}.npy'.format(i)
    np.save(fn, arr)
    names.append('Array-{}'.format(tokenize(fn)))

indices = list(product(range(10), range(10)))

dsk = {
    (name, 0, *index): (np.load, name)
    for name, index in zip(names, indices)
}
namex = 'Combined_Array'
dtype=int
shape = (3, 100, 100)
chunks = (3, 10, 10)
d = da.Array(dsk, namex, chunks, dtype, shape)
</code>```

Unfortunately it throws an error in normalize_chunks method:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-4-008559464c9e> in <module>
----> 1 d = da.Array(dsk, namex, chunks, dtype, shape)

~/.conda/envs/Py3Dev/lib/python3.7/site-packages/dask/array/core.py in __new__(cls, dask, name, chunks, dtype, meta, shape)
   1026         else:
   1027             dt = None
-> 1028         self._chunks = normalize_chunks(chunks, shape, dtype=dt)
   1029         if self._chunks is None:
   1030             raise ValueError(CHUNKS_NONE_ERROR_MESSAGE)

~/.conda/envs/Py3Dev/lib/python3.7/site-packages/dask/array/core.py in normalize_chunks(chunks, shape, limit, dtype, previous_chunks)
   2481             )
   2482
-> 2483     return tuple(tuple(int(x) if not math.isnan(x) else x for x in c) for c in chunks)
   2484
   2485

~/.conda/envs/Py3Dev/lib/python3.7/site-packages/dask/array/core.py in <genexpr>(.0)
   2481             )
   2482
-> 2483     return tuple(tuple(int(x) if not math.isnan(x) else x for x in c) for c in chunks)
   2484
   2485

TypeError: 'int' object is not iterable

</code>```

Am I doing something wrong here?

答:
Passing the arguments as named arguments solved the problem as there are parameters which are not included in this example and order of those arguments changed. Also there are other bugs in the code. The correct code would be:

import numpy as np
from itertools import product
from dask import array as da

names = list()
for i in range(100):
    arr = np.random.randint(0, 9, (3, 10, 10))
    fn = 'data/array_{}.npy'.format(i)
    np.save(fn, arr)
    names.append(fn)

indices = list(product(range(10), range(10)))
namex = 'Combined_Array'
dsk = {
    (namex, 0, *index): (np.load, name)
    for name, index in zip(names, indices)
}

dtype=int
shape = (3, 100, 100)
chunks = (3, 10, 10)

d = da.Array(dask=dsk, name=namex, chunks=chunks, dtype=dtype, shape=shape)
```

See the related github issue for the detailed discussion.

Body:
I am trying to create a single dask array from multiple files. I am using dask.array.Array class to do that. Consider the following code snippet where I am generating 100 random integer array of size (3, 10, 10) and saving each of them in a separate npy file. Then I am trying to create a single dask array to combine all these arrays into a single dask array of shape (3, 100, 100).

import numpy as np
from itertools import product
from dask import array as da
from dask.base import tokenize

names = list()
for i in range(100):
    arr = np.random.randint(0, 9, (3, 10, 10))
    fn = 'data/array_{}.npy'.format(i)
    np.save(fn, arr)
    names.append('Array-{}'.format(tokenize(fn)))

indices = list(product(range(10), range(10)))

dsk = {
    (name, 0, *index): (np.load, name)
    for name, index in zip(names, indices)
}
namex = 'Combined_Array'
dtype=int
shape = (3, 100, 100)
chunks = (3, 10, 10)
d = da.Array(dsk, namex, chunks, dtype, shape)

Unfortunately it throws an error in normalize_chunks method:

TypeError                                 Traceback (most recent call last)
<ipython-input-4-008559464c9e> in <module>
----> 1 d = da.Array(dsk, namex, chunks, dtype, shape)

~/.conda/envs/Py3Dev/lib/python3.7/site-packages/dask/array/core.py in __new__(cls, dask, name, chunks, dtype, meta, shape)
   1026         else:
   1027             dt = None
-> 1028         self._chunks = normalize_chunks(chunks, shape, dtype=dt)
   1029         if self._chunks is None:
   1030             raise ValueError(CHUNKS_NONE_ERROR_MESSAGE)

~/.conda/envs/Py3Dev/lib/python3.7/site-packages/dask/array/core.py in normalize_chunks(chunks, shape, limit, dtype, previous_chunks)
   2481             )
   2482
-> 2483     return tuple(tuple(int(x) if not math.isnan(x) else x for x in c) for c in chunks)
   2484
   2485

~/.conda/envs/Py3Dev/lib/python3.7/site-packages/dask/array/core.py in <genexpr>(.0)
   2481             )
   2482
-> 2483     return tuple(tuple(int(x) if not math.isnan(x) else x for x in c) for c in chunks)
   2484
   2485

TypeError: 'int' object is not iterable

Am I doing something wrong here?

Body:
Passing the arguments as named arguments solved the problem as there are parameters which are not included in this example and order of those arguments changed. Also there are other bugs in the code. The correct code would be:

import numpy as np
from itertools import product
from dask import array as da

names = list()
for i in range(100):
    arr = np.random.randint(0, 9, (3, 10, 10))
    fn = 'data/array_{}.npy'.format(i)
    np.save(fn, arr)
    names.append(fn)

indices = list(product(range(10), range(10)))
namex = 'Combined_Array'
dsk = {
    (namex, 0, *index): (np.load, name)
    for name, index in zip(names, indices)
}

dtype=int
shape = (3, 100, 100)
chunks = (3, 10, 10)

d = da.Array(dask=dsk, name=namex, chunks=chunks, dtype=dtype, shape=shape)

See the related github issue for the detailed discussion.


问:
Python socket - downloading files only work in chrome
So I created a code which a client uploads a file to the server folder and he has an option to download it back, it works perfectly fine in chrome, I click on the item I want to download and it downloads it

```<code>def send_image(request, cs):
    request = request.split('=')
    try:
        name = request[1]
    except:
        name = request[0]
    print('using send_iamge!')
    print('Na ' + name)
    path = 'C:\\Users\\x\\Desktop\\webroot\\uploads' + '\\file-name=' + name
    print(path)
    with open(path, 'rb') as re:
        print('exist!')
        read = re.read()
        cs.send(read)
</code>```

the code above reads the file that you choose and sends the data as bytes to the client back.
In chrome, it downloads the file as I showed you already but in for example internet explorer, it just prints the data to the client and doesn't download it The real question is why doesn't it just prints the data in chrome, why does it download it and doesn't print it as internet explorer does and how can I fix it?(for your info: all the files that I download have the name file-name before them that's why I put it there)

http request:
UPDATE:

```<code> POST /upload?file-name=Screenshot_2.png HTTP/1.1
Host: 127.0.0.1
Connection: keep-alive
Content-Length: 3534
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
Content-Type: application/octet-stream
Origin: http://127.0.0.1
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Referer: http://127.0.0.1/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,he;q=0.7
</code>```

答:
It looks like that you don't send a HTTP/1 response but a HTTP/0.9 response (Note that I'm talking about the response send from the server not the request send from the client). A HTTP/1 response consists of a HTTP header and a HTTP body, similar to how a HTTP request is constructed. A HTTP/0.9 response instead only consists of the actual body, i.e. no header and thus no meta information in the header which tell the browser what to do with the body.

HTTP/0.9 is obsolete for 25 years but some browsers still support it. When a browser gets a HTTP/0.9 request it could anything with it since there is no defined meaning from the HTTP header. Browsers might try to interpret is as HTML, as plain text, offer it for download, refuse it in total ... - whatever.

The way to fix the problem is to send an actual HTTP response header before sending the body, i.e. something like this

```<code> cs.send("HTTP/1.0 200 ok\r\nContent-type: application/octet-stream\r\n\r\n")
 with open(path, 'rb') as re:
     ...
     cs.send(read)
</code>```

In any case: HTTP is way more complex than you might think. There are established libraries to deal with this complexity. If you insist on not using any library please study the standard in order  to avoid such problems.

Body:
So I created a code which a client uploads a file to the server folder and he has an option to download it back, it works perfectly fine in chrome, I click on the item I want to download and it downloads it

def send_image(request, cs):
    request = request.split('=')
    try:
        name = request[1]
    except:
        name = request[0]
    print('using send_iamge!')
    print('Na ' + name)
    path = 'C:\\Users\\x\\Desktop\\webroot\\uploads' + '\\file-name=' + name
    print(path)
    with open(path, 'rb') as re:
        print('exist!')
        read = re.read()
        cs.send(read)

the code above reads the file that you choose and sends the data as bytes to the client back.
In chrome, it downloads the file as I showed you already but in for example internet explorer, it just prints the data to the client and doesn't download it The real question is why doesn't it just prints the data in chrome, why does it download it and doesn't print it as internet explorer does and how can I fix it?(for your info: all the files that I download have the name file-name before them that's why I put it there)

http request:
UPDATE:

 POST /upload?file-name=Screenshot_2.png HTTP/1.1
Host: 127.0.0.1
Connection: keep-alive
Content-Length: 3534
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
Content-Type: application/octet-stream
Origin: http://127.0.0.1
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Referer: http://127.0.0.1/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,he;q=0.7

Body:
It looks like that you don't send a HTTP/1 response but a HTTP/0.9 response (Note that I'm talking about the response send from the server not the request send from the client). A HTTP/1 response consists of a HTTP header and a HTTP body, similar to how a HTTP request is constructed. A HTTP/0.9 response instead only consists of the actual body, i.e. no header and thus no meta information in the header which tell the browser what to do with the body.

HTTP/0.9 is obsolete for 25 years but some browsers still support it. When a browser gets a HTTP/0.9 request it could anything with it since there is no defined meaning from the HTTP header. Browsers might try to interpret is as HTML, as plain text, offer it for download, refuse it in total ... - whatever.

The way to fix the problem is to send an actual HTTP response header before sending the body, i.e. something like this

 cs.send("HTTP/1.0 200 ok\r\nContent-type: application/octet-stream\r\n\r\n")
 with open(path, 'rb') as re:
     ...
     cs.send(read)

In any case: HTTP is way more complex than you might think. There are established libraries to deal with this complexity. If you insist on not using any library please study the standard in order  to avoid such problems.


问:
How does Linked List function to make another linked list with different order of elements. Explanation please
```<code>struct node* question4(struct node *list){ //list = 66, 9, 14, 52, 87, 14, 17
      struct node* a = list; //a = 66, 9, 14, 52, 87, 14, 17 pointing to head (66)
      struct node* b = list; //b = 66, 9, 14, 52, 87, 14, 17 pointing to head (66)
      struct node* c;
      if(a == NULL) return NULL; // a is not NULL it's pointing to 66
      while(a->next != NULL) // run until a points to the last element (17)
            a = a->next;
      a->next = b; //next element of 17 points to b (which is 66).
      c = b->next; // c points to what b is pointing to next which is 9.
      b -> next = NULL; // next element of b is NULL(instead of 14). what happens here?
      return c;
}
</code>```

So a is connected to b. so a's element goes like this?
66->9->14->52->87->14->17->66->9->14->52->87->14->17

and b is just 66->9->NULL?

c is 9->14->52->87->14->17? OR 9->14->52->87->14->17->66 ? why?

I'm currently learning about linked list, thank you guys for your help!

答:
The program shifts the head of the linked list right by one element, and loops back the original first element to the end. You have followed correctly for the most part, the last few lines work as follows:

```<code>a->next = b;
</code>```

This links the original last element to the original first element, i.e., creates a link 17->66.

```<code>c = b->next;
</code>```

c here is used to store the new head element. Since b was pointing to the original head, and we want the second element to be the new head, c points to b's next element, i.e., 9.

```<code>b -> next = NULL;
</code>```

The a->next = b; made the linked list circular, this breaks the circle, by removing the 66->9 link.

Finally, c is returned, so the list at the end is:

```<code>9->14->52->87->14->17->66
</code>```

Body:
struct node* question4(struct node *list){ //list = 66, 9, 14, 52, 87, 14, 17
      struct node* a = list; //a = 66, 9, 14, 52, 87, 14, 17 pointing to head (66)
      struct node* b = list; //b = 66, 9, 14, 52, 87, 14, 17 pointing to head (66)
      struct node* c;
      if(a == NULL) return NULL; // a is not NULL it's pointing to 66
      while(a->next != NULL) // run until a points to the last element (17)
            a = a->next;
      a->next = b; //next element of 17 points to b (which is 66).
      c = b->next; // c points to what b is pointing to next which is 9.
      b -> next = NULL; // next element of b is NULL(instead of 14). what happens here?
      return c;
}

So a is connected to b. so a's element goes like this?
66->9->14->52->87->14->17->66->9->14->52->87->14->17

and b is just 66->9->NULL?

c is 9->14->52->87->14->17? OR 9->14->52->87->14->17->66 ? why?

I'm currently learning about linked list, thank you guys for your help!

Body:
The program shifts the head of the linked list right by one element, and loops back the original first element to the end. You have followed correctly for the most part, the last few lines work as follows:

a->next = b;

This links the original last element to the original first element, i.e., creates a link 17->66.

c = b->next;

c here is used to store the new head element. Since b was pointing to the original head, and we want the second element to be the new head, c points to b's next element, i.e., 9.

b -> next = NULL;

The a->next = b; made the linked list circular, this breaks the circle, by removing the 66->9 link.

Finally, c is returned, so the list at the end is:

9->14->52->87->14->17->66


答:
but I feel like this is not the right way to do it

Returning is an entirely right way to break out from a loop.

Another right way is the break statement, which jumps to after the loop.

Title: What can I use to stop a loop instead of 'return 0'?


问:
Wordpress REST API: How to retrieve posts tagged by multiple tags?
Some people suggested using /posts?tags=tag_id_1,tag_id_2 or /posts?tags[]=tag_id_1&tags[]=tag_id_2
but wordpress seems to be returning posts that are tagged either with tag1 OR tag2. What I actually need is posts tagged with tag1 AND tag2.

Anyone has an idea?

答:
I will share with you what I have done.

I created a new endpoint for my custom needs,
which ends like myapi/v1/posts/tag1/tag2

```<code>add_action('rest_api_init', function () {
  register_rest_route( 'myapi/v1', 'posts/(?P<tag_1>[-\w]+)/(?P<tag_2>[-\w]+)',array(
        'methods'  => 'GET',
        'callback' => 'get_posts_set'
  ));
});
</code>```

Then, created

```<code>function get_posts_set($request) {

    $args = array(
        'category_name' => $request['category_name'],
        'tag_slug__and'    => array( $request['tag_1'],$request['tag_2'] ),
    );

    $posts = get_posts($args);

    if (empty($posts)) {
        return new WP_Error( 'empty_category', 'there is no post in this category', array('status' => 404) );
    }

    // Following code is my processing of output. Customize it to suit your needs

    $post_data = array();
    $i = 0;
    foreach( $posts as $post) {
        $post_id = $post->ID;
        $post_title = remove_html_comments($post->post_title);
        $post_content = remove_html_comments($post->post_content);
        $post_data[ $i ][ 'id' ] = $post_id;
        $post_data[ $i ][ 'title' ] = $post_title;
        $post_data[ $i ][ 'content' ] = $post_content;
        $i++;
    }

    $response = new WP_REST_Response($post_data);
    $response->set_status(200);

    return $response;
}

function remove_html_comments($content = '') {
    return preg_replace('/<!--(.|\s)*?-->/', '', $content);
}
</code>```

This will return only the PostID, Post Title and Post Content with HTML formatting for direcr reuse. Hope this solves your question.

Body:
I will share with you what I have done.

I created a new endpoint for my custom needs,
which ends like myapi/v1/posts/tag1/tag2

add_action('rest_api_init', function () {
  register_rest_route( 'myapi/v1', 'posts/(?P<tag_1>[-\w]+)/(?P<tag_2>[-\w]+)',array(
        'methods'  => 'GET',
        'callback' => 'get_posts_set'
  ));
});

Then, created

function get_posts_set($request) {

    $args = array(
        'category_name' => $request['category_name'],
        'tag_slug__and'    => array( $request['tag_1'],$request['tag_2'] ),
    );

    $posts = get_posts($args);

    if (empty($posts)) {
        return new WP_Error( 'empty_category', 'there is no post in this category', array('status' => 404) );
    }

    // Following code is my processing of output. Customize it to suit your needs

    $post_data = array();
    $i = 0;
    foreach( $posts as $post) {
        $post_id = $post->ID;
        $post_title = remove_html_comments($post->post_title);
        $post_content = remove_html_comments($post->post_content);
        $post_data[ $i ][ 'id' ] = $post_id;
        $post_data[ $i ][ 'title' ] = $post_title;
        $post_data[ $i ][ 'content' ] = $post_content;
        $i++;
    }

    $response = new WP_REST_Response($post_data);
    $response->set_status(200);

    return $response;
}

function remove_html_comments($content = '') {
    return preg_replace('/<!--(.|\s)*?-->/', '', $content);
}

This will return only the PostID, Post Title and Post Content with HTML formatting for direcr reuse. Hope this solves your question.


问:
Slack post payload in wrong format
How to get payload printed in json format

Getting payload like %7B%22type%22%3A%22interactive_message%22%2C%22actions%22%3A%5B%7B%22

```<code>2020-02-17 14:09:22,624 200 POST /slack/message_actions HTTP/1.1 Host: myipteventsbot.tunnel.com X-Real-IP: 3.93.14.114 Content-Length: 5159 User-Agent: Slackbot 1.0 (+https://api.slack.com/robots) Accept-Encoding: gzip,deflate Accept: application/json,*/*
X-Slack-Signature: v0=96ab9dd1e89047f6cea117313a17989eb25849f7a86ad1f1eff8a0be692238cf X-Slack-Request-Timestamp: 1581970162 Content-Type: application/x-www-form-urlencoded
payload=%7B%22type%22%3A%22interactive_message%22%2C%22actions%22%3A%5B%7B%22name%22%3A%22fullfilment_list%22%2C%22type%22%3A%22select%22%2C%22selected_options%22%3A%5B%7B%22value%22%3A%22spu%22%7D%5D%7D%5D%2C%22callback_id%22%3A%22test%22%2C%22team%22%3A%7B%22id%22%3A%22TFHGD33RV%22%2C%22domain%22%3A%22bby-sandbox-general%22%2C%22enterprise_id%22%3A%22EFGBDRLNP%22%2C%22enterprise_name%22%3A%22Best+Buy+Test%22%7D%2C%22channel%22%3A%7B%22id%22%3A%22DTHBLNXD0%22%2C%22name%22%3A%22directmessage%22%7D%2C%22user%22%3A%7B%22id%22%3A%22WLCLZ2LDP%22%2C%22name%22%3A%22a6002043%22%2C%
</code>```

My code snippet

```<code>@app.route("/slack/message_actions", methods=["POST"])
def message_actions():

    # Parse the request payload
    form_json = json.loads(request.form["payload"])

    # Verify that the request came from Slack
    verify_slack_token(form_json["token"])

    # Check to see what the user's selection was and update the message accordingly
    selection = form_json["actions"][0]["selected_options"][0]["value"]

    if selection == "spu":
        message_text = "spu"
    else:
        message_text = "sth"

    response = slack_client.api_call(
        "chat.update",
        channel=form_json["channel"]["id"],
        ts=form_json["message_ts"],
        text="One {} order coming up! :coffee:".format(message_text),
        attachments=[] # empty `attachments` to clear the existing massage attachments
    )

    # Send an HTTP 200 response with empty body so Slack knows we're done here
    return make_response("", 200)
</code>```

答:
figured out i need update my code as below </p>

```<code>request.form.get('payload')
</code>```

Title: Slack post payload in wrong format

Body:
How to get payload printed in json format

Getting payload like %7B%22type%22%3A%22interactive_message%22%2C%22actions%22%3A%5B%7B%22

2020-02-17 14:09:22,624 200 POST /slack/message_actions HTTP/1.1 Host: myipteventsbot.tunnel.com X-Real-IP: 3.93.14.114 Content-Length: 5159 User-Agent: Slackbot 1.0 (+https://api.slack.com/robots) Accept-Encoding: gzip,deflate Accept: application/json,*/*
X-Slack-Signature: v0=96ab9dd1e89047f6cea117313a17989eb25849f7a86ad1f1eff8a0be692238cf X-Slack-Request-Timestamp: 1581970162 Content-Type: application/x-www-form-urlencoded
payload=%7B%22type%22%3A%22interactive_message%22%2C%22actions%22%3A%5B%7B%22name%22%3A%22fullfilment_list%22%2C%22type%22%3A%22select%22%2C%22selected_options%22%3A%5B%7B%22value%22%3A%22spu%22%7D%5D%7D%5D%2C%22callback_id%22%3A%22test%22%2C%22team%22%3A%7B%22id%22%3A%22TFHGD33RV%22%2C%22domain%22%3A%22bby-sandbox-general%22%2C%22enterprise_id%22%3A%22EFGBDRLNP%22%2C%22enterprise_name%22%3A%22Best+Buy+Test%22%7D%2C%22channel%22%3A%7B%22id%22%3A%22DTHBLNXD0%22%2C%22name%22%3A%22directmessage%22%7D%2C%22user%22%3A%7B%22id%22%3A%22WLCLZ2LDP%22%2C%22name%22%3A%22a6002043%22%2C%

My code snippet

@app.route("/slack/message_actions", methods=["POST"])
def message_actions():

    # Parse the request payload
    form_json = json.loads(request.form["payload"])

    # Verify that the request came from Slack
    verify_slack_token(form_json["token"])

    # Check to see what the user's selection was and update the message accordingly
    selection = form_json["actions"][0]["selected_options"][0]["value"]

    if selection == "spu":
        message_text = "spu"
    else:
        message_text = "sth"

    response = slack_client.api_call(
        "chat.update",
        channel=form_json["channel"]["id"],
        ts=form_json["message_ts"],
        text="One {} order coming up! :coffee:".format(message_text),
        attachments=[] # empty `attachments` to clear the existing massage attachments
    )

    # Send an HTTP 200 response with empty body so Slack knows we're done here
    return make_response("", 200)

Body:
figured out i need update my code as below

request.form.get('payload')


问:
How to keep column order after df.update() + df.reset_index()
I have two dataframes.

data_df

```<code>  Investor   Company Name      CUSIP Symbol
0     Hank       FaCeBoOk  30303M102
1     Dale       Fraud Co  88160R101
2     Bill    Netflix Inc  64110L106
3     Kahn                 64110L106
4    Peggy         Amazon   23135106
5    Rusty         Costco  22160K105
6    Bobby  BankAmericard  92826C839
7     Minh    Placeholder  92826C839
8   Chappy          Other  29786A106
</code>```

and cusips_df:

```<code>         Company Name Symbol      CUSIP
0            Facebook     FB  30303M102
1               Tesla   TSLA  88160R101
2         Netflix Inc   NFLX  64110L106
3              Amazon   AMZN   23135106
4              Costco   COST  22160K105
5                Visa      V  92826C839
6        Mega-Lo Mart    MLM  543535F63
7  Strickland Propane   SPPN  453HGR001
8                Etsy   ETSY  29786A106
</code>```

I am matching the two dataframes on CUSIP, and then updating the Company Name and Symbol in data_df with those values from cusips_df.

```<code>data_df = data_df.set_index('CUSIP')
cusips_df = cusips_df.set_index('CUSIP')
data_df.update(cusips_df)
data_df = data_df.reset_index()
print(data_df)
</code>```

But when I do, the CUSIP column gets moved to position 0, rather than stay in position 2:

```<code>       CUSIP Investor Company Name Symbol
0  30303M102     Hank     Facebook     FB
1  88160R101     Dale        Tesla   TSLA
2  64110L106     Bill  Netflix Inc   NFLX
3  64110L106     Kahn  Netflix Inc   NFLX
4   23135106    Peggy       Amazon   AMZN
5  22160K105    Rusty       Costco   COST
6  92826C839    Bobby         Visa      V
7  92826C839     Minh         Visa      V
8  29786A106   Chappy         Etsy   ETSY
</code>```

I know I can simply reorder the dataframe columns, but is there a more pythonic way of doing this so that the order of the columns in data_df stays the same?

答:
We can do </p>

```<code>d=dict(zip(cusips_df.CUSIP, cusips_df.Symbol))
data_df.Symbol.update(data_df.CUSIP.map(d))
</code>```

Body:
I have two dataframes.

data_df

  Investor   Company Name      CUSIP Symbol
0     Hank       FaCeBoOk  30303M102
1     Dale       Fraud Co  88160R101
2     Bill    Netflix Inc  64110L106
3     Kahn                 64110L106
4    Peggy         Amazon   23135106
5    Rusty         Costco  22160K105
6    Bobby  BankAmericard  92826C839
7     Minh    Placeholder  92826C839
8   Chappy          Other  29786A106

and cusips_df:

         Company Name Symbol      CUSIP
0            Facebook     FB  30303M102
1               Tesla   TSLA  88160R101
2         Netflix Inc   NFLX  64110L106
3              Amazon   AMZN   23135106
4              Costco   COST  22160K105
5                Visa      V  92826C839
6        Mega-Lo Mart    MLM  543535F63
7  Strickland Propane   SPPN  453HGR001
8                Etsy   ETSY  29786A106

I am matching the two dataframes on CUSIP, and then updating the Company Name and Symbol in data_df with those values from cusips_df.

data_df = data_df.set_index('CUSIP')
cusips_df = cusips_df.set_index('CUSIP')
data_df.update(cusips_df)
data_df = data_df.reset_index()
print(data_df)

But when I do, the CUSIP column gets moved to position 0, rather than stay in position 2:

       CUSIP Investor Company Name Symbol
0  30303M102     Hank     Facebook     FB
1  88160R101     Dale        Tesla   TSLA
2  64110L106     Bill  Netflix Inc   NFLX
3  64110L106     Kahn  Netflix Inc   NFLX
4   23135106    Peggy       Amazon   AMZN
5  22160K105    Rusty       Costco   COST
6  92826C839    Bobby         Visa      V
7  92826C839     Minh         Visa      V
8  29786A106   Chappy         Etsy   ETSY

I know I can simply reorder the dataframe columns, but is there a more pythonic way of doing this so that the order of the columns in data_df stays the same?

Body:
We can do

d=dict(zip(cusips_df.CUSIP, cusips_df.Symbol))
data_df.Symbol.update(data_df.CUSIP.map(d))