问:
What can mutable do in C++?

I was given this code on sequential programming and lock programming. I have to analyze the difference, but I’m not sure what some of the code is doing. The code is below, and the parts I don’t understand are also mentioned in the bullets.

Effect of keyword: Mutable

Another StackOverflow answer says that mutable allows a const to be

modified but I don’t see what that has to do with this project

What is the effect of removing “mutable” in this program? Does it disable
the locks?

Mutable for not_full and not_empty

Furthering my lack of understanding of this, why is mutable not required for not_full and not_empty?

Thank you for reading, any help would be appreciated!

```<code>```
    #ifndef LOCKEDBUFFER_H
    #define LOCKEDBUFFER_H

    #include <memory>
    #include <mutex>
    #include <condition_variable>
    #include <atomic>

    #include "optional.h"

    template <typename T>
    class locked_buffer {
    public:
      // Creates buffer of size n
      locked_buffer(int n) :
        size_{n},
        buf_{new optional<T>[size_]}
      {
      }

      // Remove copy constructor
      locked_buffer(const locked_buffer &) = delete;

      // Destructor (default generated)
      ~locked_buffer() = default;

      // Gets buffer size
      int size() const noexcept {
        return size_;
      }

      // Checks if buffer is empty
      bool empty() const noexcept {
        std::lock_guard<std::mutex> l{mut_};
        return is_empty();
      }

      // Checks if buffer is full
      bool full() const noexcept {
        std::lock_guard<std::mutex> l{mut_};
        return is_full();
      }

      // Put an optional value in the queue
      void put(const optional<T> & x);

      // Get a value from the queue
      optional<T> get();

    private:
      // Next circular position to position p
      int next_position(int p) const noexcept {
        return p + ((p+1>=size_)?(1-size_):1);
      }

      // Check if buffer is empty without locking
      bool is_empty() const noexcept {
        return (next_read_ == next_write_);
      }

      // Check if buffer is full without locking
      bool is_full() const noexcept {
        const int next = next_position(next_write_);
        return next == next_read_;
      }

    private:
      const int size_;
      const std::unique_ptr<optional<T>[]> buf_;
      int next_read_ = 0;
      int next_write_ = 0;

      mutable std::mutex mut_;
      std::condition_variable not_full_;
      std::condition_variable not_empty_;
    };

    template <typename T>
    void locked_buffer<T>::put(const optional<T> & x)
    {
      using namespace std;
      unique_lock<mutex> l{mut_};
      not_full_.wait(l, [this] { return !is_full(); });
      buf_[next_write_] = x;
      next_write_ = next_position(next_write_);
      not_empty_.notify_one();
    }

    template <typename T>
    optional<T> locked_buffer<T>::get()
    {
      using namespace std;
      unique_lock<mutex> l{mut_};
      not_empty_.wait(l, [this] { return !is_empty(); });
      auto res = buf_[next_read_];
      next_read_ = next_position(next_read_);
      not_full_.notify_one();
      return res;
    }

    #endif
```

答:
Let's go through it step by step.

Another StackOverflow answer says that mutable allows a const to be
  modified but I don’t see what that has to do with this project

This does somehow apply to your class.
You have this method.

```<code>bool empty() const noexcept {
    std::lock_guard<std::mutex> l{mut_};
    return is_empty();
}
</code>```

The lock guard expects a non const object reference as the lock_guardwill change the mutex.
But since your method is const you cannot access any member in a non const way. Here is where mutable comes into play.

What is the effect of removing “mutable” in this program? Does it disable the locks?

If you remove the mutable from your mutex you will get a compile error in the empty() and the full() method. So technically the locks are not disabled but your program is ill formed.

Furthering my lack of understanding of this, why is mutable not required for not_full and not_empty?

Well simply because they are used in non const methods.

So no need to make them mutable. If you would use any of them in a const method and you would like to use a non const method on the condition_variable then you would need to make them mutable.

Title: What can mutable do in C++?

Body:
I was given this code on sequential programming and lock programming. I have to analyze the difference, but I’m not sure what some of the code is doing. The code is below, and the parts I don’t understand are also mentioned in the bullets.

Effect of keyword: Mutable

Another StackOverflow answer says that mutable allows a const to be

modified but I don’t see what that has to do with this project

What is the effect of removing “mutable” in this program? Does it disable
the locks?

Mutable for not_full and not_empty

Furthering my lack of understanding of this, why is mutable not required for not_full and not_empty?

Thank you for reading, any help would be appreciated!

    #ifndef LOCKEDBUFFER_H
    #define LOCKEDBUFFER_H

    #include <memory>
    #include <mutex>
    #include <condition_variable>
    #include <atomic>

    #include "optional.h"

    template <typename T>
    class locked_buffer {
    public:
      // Creates buffer of size n
      locked_buffer(int n) :
        size_{n},
        buf_{new optional<T>[size_]}
      {
      }

      // Remove copy constructor
      locked_buffer(const locked_buffer &) = delete;

      // Destructor (default generated)
      ~locked_buffer() = default;

      // Gets buffer size
      int size() const noexcept {
        return size_;
      }

      // Checks if buffer is empty
      bool empty() const noexcept {
        std::lock_guard<std::mutex> l{mut_};
        return is_empty();
      }

      // Checks if buffer is full
      bool full() const noexcept {
        std::lock_guard<std::mutex> l{mut_};
        return is_full();
      }

      // Put an optional value in the queue
      void put(const optional<T> & x);

      // Get a value from the queue
      optional<T> get();

    private:
      // Next circular position to position p
      int next_position(int p) const noexcept {
        return p + ((p+1>=size_)?(1-size_):1);
      }

      // Check if buffer is empty without locking
      bool is_empty() const noexcept {
        return (next_read_ == next_write_);
      }

      // Check if buffer is full without locking
      bool is_full() const noexcept {
        const int next = next_position(next_write_);
        return next == next_read_;
      }

    private:
      const int size_;
      const std::unique_ptr<optional<T>[]> buf_;
      int next_read_ = 0;
      int next_write_ = 0;

      mutable std::mutex mut_;
      std::condition_variable not_full_;
      std::condition_variable not_empty_;
    };

    template <typename T>
    void locked_buffer<T>::put(const optional<T> & x)
    {
      using namespace std;
      unique_lock<mutex> l{mut_};
      not_full_.wait(l, [this] { return !is_full(); });
      buf_[next_write_] = x;
      next_write_ = next_position(next_write_);
      not_empty_.notify_one();
    }

    template <typename T>
    optional<T> locked_buffer<T>::get()
    {
      using namespace std;
      unique_lock<mutex> l{mut_};
      not_empty_.wait(l, [this] { return !is_empty(); });
      auto res = buf_[next_read_];
      next_read_ = next_position(next_read_);
      not_full_.notify_one();
      return res;
    }

    #endif

Body:
Let's go through it step by step.

Another StackOverflow answer says that mutable allows a const to be
  modified but I don’t see what that has to do with this project

This does somehow apply to your class.
You have this method.

bool empty() const noexcept {
    std::lock_guard<std::mutex> l{mut_};
    return is_empty();
}

The lock guard expects a non const object reference as the lock_guardwill change the mutex.
But since your method is const you cannot access any member in a non const way. Here is where mutable comes into play.

What is the effect of removing “mutable” in this program? Does it disable the locks?

If you remove the mutable from your mutex you will get a compile error in the empty() and the full() method. So technically the locks are not disabled but your program is ill formed.

Furthering my lack of understanding of this, why is mutable not required for not_full and not_empty?

Well simply because they are used in non const methods.

So no need to make them mutable. If you would use any of them in a const method and you would like to use a non const method on the condition_variable then you would need to make them mutable.


来源: stackexchange

问:
Making Variables Global in PHP?
Need to make $courseInfo and $row global so that they can be used for printing the row details in the header DIV.

Don't have a clue how to do this. Any help would be great.

```<code><?php

// Get Course ID From Link
$ID = mysql_real_escape_string($_REQUEST['ID']);

// Check the Course ID exists
$courseCheck = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");

if (mysql_num_rows($courseCheck) == 1) {

    $checkMember = mysql_query("SELECT * FROM CourseMembers WHERE CourseID = '".$ID."' AND UserID = '".$_SESSION['UserID']."'");

    if (mysql_num_rows($checkMember) == 1) {

        ?>
        <html>
        <head>
            <!-- Style Sheets -->
            <link rel="stylesheet" href="style/reset.css" type="text/css" media=screen />
            <link rel="stylesheet" href="style/style.css" type="text/css" media=screen />
        </head>
        <body>

        <?php
        if ($_SESSION['LoggedIn'] == 1){

            $courseInfo = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
            $row = mysql_fetch_assoc($courseInfo);

        ?>

            <div id="container">
                <div id="side">
                    <?php include("lib/sidebar.php"); ?>
                </div>
                <div id="main">
                    <div id="mainbox">
                        <div id="header"><b><?php echo $row['CourseName']; ?></b></div>
                        <p>Hello world, this is a test.</p>
                    </div>
                </div>
            </div>
            <div class="clear"></div>

            <?php
            }
        else {
            echo "Not logged in.";
        }

    }

    else {
        echo "You are not a member of this Course";
    }

}

else {
    echo "No Course Found";
}

?>
</body>
</code>```

答: I think they're already global. "PHP does not have a block-level scope."</p>

ContentLicense: CC BY-SA 2.5

Title: Making Variables Global in PHP?

Body:
Need to make $courseInfo and $row global so that they can be used for printing the row details in the header DIV.

Don't have a clue how to do this. Any help would be great.

<?php

// Get Course ID From Link
$ID = mysql_real_escape_string($_REQUEST['ID']);

// Check the Course ID exists
$courseCheck = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");

if (mysql_num_rows($courseCheck) == 1) {

    $checkMember = mysql_query("SELECT * FROM CourseMembers WHERE CourseID = '".$ID."' AND UserID = '".$_SESSION['UserID']."'");

    if (mysql_num_rows($checkMember) == 1) {

        ?>

            <link rel="stylesheet" href="style/reset.css" type="text/css" media=screen />
            <link rel="stylesheet" href="style/style.css" type="text/css" media=screen />

        <?php
        if ($_SESSION['LoggedIn'] == 1){

            $courseInfo = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
            $row = mysql_fetch_assoc($courseInfo);

        ?>

                    <?php include("lib/sidebar.php"); ?>

<?php echo $row['CourseName']; ?>

Hello world, this is a test.

            <?php
            }
        else {
            echo "Not logged in.";
        }

    }

    else {
        echo "You are not a member of this Course";
    }

}

else {
    echo "No Course Found";
}

?>


问:
Errors fetching records within a month
I am having issues trying to fetch records for dates within a month. The records usually stops at the penultimate day.  If for example, I try to select records between October 1 and 31, I only get records ending at October 30. Same thing applies to August, records stop at August 29.
This is a snippet</p>

```<code>SELECT * FROM transactions where date BETWEEN date(CONCAT('2017', '-', '08','-01')) AND date(CONCAT('2017', '-', '08','-30')
</code>```

答: Your date column likely has a time portion, which means that 2017-08-30 is being translated as midnight (00:00:00.000) of that day, so anything later in that day will be outside of the range. You're probably better off using date >= 2017-08-01 and date < 2017-09-01. Using BETWEEN with datetime values can be tricky.

ContentLicense: CC BY-SA 3.0

Title: Errors fetching records within a month

Body:
I am having issues trying to fetch records for dates within a month. The records usually stops at the penultimate day.  If for example, I try to select records between October 1 and 31, I only get records ending at October 30. Same thing applies to August, records stop at August 29.
This is a snippet

SELECT * FROM transactions where date BETWEEN date(CONCAT('2017', '-', '08','-01')) AND date(CONCAT('2017', '-', '08','-30')


问:
Gunicorn/flask API to expose an sklearn model not working
I can't seem to figure this out. I've got a model trained with scikit-learn, saved to a .pkl file, and I want to make an API that would make predictions based on it.

I already have the code that makes predictions and it runs fine from console/unit-tests. To speed up predictions I'm splitting the data (thousands of image patches) and spreading the load using joblib/multiprocessing.

I'm setting JOBLIB_START_METHOD=forkserver since scikit-learn hangs if used from within a multiprocessing process.

I've got an API done with flask which uses this code, and when run with flask's dev server it works just fine. Now I'm trying to host the flask app within gunicorn and it's not working at all.

If I use the default workers, then it just hangs with no errors when trying to predict, much like if I hadn't set the 'forkserver' multiprocessing. I'm running gunicorn like this:

JOBLIB_START_METHOD=forkserver gunicorn -w 2 -b 0.0.0.0:$PORT --timeout 3600 web.app:app

I also tried using the gevent backend. This actually does work but it's very slow, and it prints this:

Multiprocessing backed parallel loops cannot be nested below threads, setting n_jobs=1

So, any ideas on getting this to work in a way that there's multiple web workers running (I don't think that's the case with flask's dev server) and with a request being able to leverage joblib/multiprocessing? thanks

答:
Gevent won't work with joblib since it spawns thread(s) to handle requests concurrently (Refer this discussion) and that's what your warning actually says. Secondly, it's very slow because joblib converts your parallel calls into sequential calls and executes them (Refer to this discussion).

I did the face the same problem while performing parallelism using joblib. Although I didn't use sklearn, I think the following command should work for you as well:

```<code>gunicorn -b 0.0.0.0:$SERVICE_PORT --workers=2 -t $SERVICE_TIMEOUT rest_api:app
</code>```

If you want to have a look at the complete source code, you can follow it
here.

Body:
Gevent won't work with joblib since it spawns thread(s) to handle requests concurrently (Refer this discussion) and that's what your warning actually says. Secondly, it's very slow because joblib converts your parallel calls into sequential calls and executes them (Refer to this discussion).

I did the face the same problem while performing parallelism using joblib. Although I didn't use sklearn, I think the following command should work for you as well:

gunicorn -b 0.0.0.0:$SERVICE_PORT --workers=2 -t $SERVICE_TIMEOUT rest_api:app

If you want to have a look at the complete source code, you can follow it
here.


问:
ggplot in shiny app go to rstudio plot window
I have a shiny app that draw some ggplot2 plots in app. Now I’m making it into a package and export the plot drawing as a function. I found once I draw some ggplot in RStudio and start my shiny app, then all plots in my shiny app went to the RStudio plot pane.

I have tracked down the problem to very specific location and made a minimal working example.

This shiny app draw a ggplot, though it first save the ggplot into png with ggsave, then return the ggplot object to renderPlot so that it is shown in app.

```<code>library(shiny)
library(ggplot2)
SAVE_PLOT <- TRUE
ui <- fluidPage(fluidRow(column(12, plotOutput("plot"))))
server <- function(input, output){
  output$plot <- renderPlot({
    g <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
    if (SAVE_PLOT) {
      ggsave("plot.png", g)
    }
    g
  })
}
shinyApp(ui = ui, server = server)
</code>```

If I run this simple code in RStudio first

```<code>library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point()
</code>```

then run the app above, the plot in app is shown in RStudio plot window.

If I set SAVE_PLOT <- FALSE then the app will have plot shown correctly. This show the problem is caused by ggsave.

I didn’t try if plot first and save it later will not have this problem, because the plot in my real app is reactive, plot it first means I need to wrap every plot into a reactive instead of just write in renderPlot.

If I run dev.off after the ggplot in console, the plot will not go to rstudio. Though this is obviously not a solution either.

According to ggsave code,
it create a new device then turn off current device after saving. Is it possible that it actually messed up in this case and turned off the shiny plot device also?

It's also possible to be something with Shiny, or with RStudio.

UPDATE: the problem is not specific to RStudio, the R console have same problem.

答:
Enclosing the ggsave() function in pdf(NULL); ggsave(...); dev.off() seems to provide a workaround here, though sometimes the graphics device is in strange state when closing the app.

```<code>library(shiny)
library(ggplot2)
SAVE_PLOT <- TRUE
ui <- fluidPage(fluidRow(column(12, plotOutput("plot"))))
server <- function(input, output){
  output$plot <- renderPlot({
    g <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
    if (SAVE_PLOT) {
      pdf(NULL)
      ggsave("plot.png", g)
      dev.off()
    }
    g
  })
}
qplot(1:10, 1:10) # shows up in R Studio window
shinyApp(ui = ui, server = server) # shows up in shiny window
</code>```

Body:
I have a shiny app that draw some ggplot2 plots in app. Now I’m making it into a package and export the plot drawing as a function. I found once I draw some ggplot in RStudio and start my shiny app, then all plots in my shiny app went to the RStudio plot pane.

I have tracked down the problem to very specific location and made a minimal working example.

This shiny app draw a ggplot, though it first save the ggplot into png with ggsave, then return the ggplot object to renderPlot so that it is shown in app.

library(shiny)
library(ggplot2)
SAVE_PLOT <- TRUE
ui <- fluidPage(fluidRow(column(12, plotOutput("plot"))))
server <- function(input, output){
  output$plot <- renderPlot({
    g <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
    if (SAVE_PLOT) {
      ggsave("plot.png", g)
    }
    g
  })
}
shinyApp(ui = ui, server = server)

If I run this simple code in RStudio first

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point()

then run the app above, the plot in app is shown in RStudio plot window.

If I set SAVE_PLOT <- FALSE then the app will have plot shown correctly. This show the problem is caused by ggsave.

I didn’t try if plot first and save it later will not have this problem, because the plot in my real app is reactive, plot it first means I need to wrap every plot into a reactive instead of just write in renderPlot.

If I run dev.off after the ggplot in console, the plot will not go to rstudio. Though this is obviously not a solution either.

According to ggsave code,
it create a new device then turn off current device after saving. Is it possible that it actually messed up in this case and turned off the shiny plot device also?

It's also possible to be something with Shiny, or with RStudio.

UPDATE: the problem is not specific to RStudio, the R console have same problem.

Body:
Enclosing the ggsave() function in pdf(NULL); ggsave(...); dev.off() seems to provide a workaround here, though sometimes the graphics device is in strange state when closing the app.

library(shiny)
library(ggplot2)
SAVE_PLOT <- TRUE
ui <- fluidPage(fluidRow(column(12, plotOutput("plot"))))
server <- function(input, output){
  output$plot <- renderPlot({
    g <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
    if (SAVE_PLOT) {
      pdf(NULL)
      ggsave("plot.png", g)
      dev.off()
    }
    g
  })
}
qplot(1:10, 1:10) # shows up in R Studio window
shinyApp(ui = ui, server = server) # shows up in shiny window


问:
DataMapper delete works but only after restarting my app
I have two models, User and Snippet:

```<code>class User
  include DataMapper::Resource

  property :id,Serial
  ...
  has n,:snippets
end

class Snippet
  include DataMapper::Resource

  property :id,Serial
  ...
  belongs_to :user
end
</code>```

When I'm displaying the snippets, I'm using this:

```<code>snippets = user.snippets
</code>```

And when I'm deleting them I'm using this:

```<code>snippet = Snippet.first(:user_id => user.id,:id => snip_id)
if snippet
    destruction_res = snippet.destroy
    ...
end
</code>```

The thing is, destruction_res always returns true. I tried saving the user after I deleted the snippet. It returned true as well. The thing is, when I access the view that uses the code:

```<code>snippets = user.snippets
</code>```

it returns the complete list, including the snippet which should have been destroyed. If I restart the application however, I see the correct list. What am I doing wrong? Should I somehow force a commit to the database?

答:
It's possible that you're loading the snippets collection before destroying a snippet then you access that collection again and it still includes the deleted snippet. If that's the case, you can reject a destroyed snippet like that:

```<code>user.snippets.reject!(&:destroyed?)
</code>```

BTW - you can destroy a snippet like this:

```<code>user.snippets.get(snip_id).destroy
</code>```

A bit nicer :)

Body:
I have two models, User and Snippet:

class User
  include DataMapper::Resource

  property :id,Serial
  ...
  has n,:snippets
end

class Snippet
  include DataMapper::Resource

  property :id,Serial
  ...
  belongs_to :user
end

When I'm displaying the snippets, I'm using this:

snippets = user.snippets

And when I'm deleting them I'm using this:

snippet = Snippet.first(:user_id => user.id,:id => snip_id)
if snippet
    destruction_res = snippet.destroy
    ...
end

The thing is, destruction_res always returns true. I tried saving the user after I deleted the snippet. It returned true as well. The thing is, when I access the view that uses the code:

snippets = user.snippets

it returns the complete list, including the snippet which should have been destroyed. If I restart the application however, I see the correct list. What am I doing wrong? Should I somehow force a commit to the database?

Body:
It's possible that you're loading the snippets collection before destroying a snippet then you access that collection again and it still includes the deleted snippet. If that's the case, you can reject a destroyed snippet like that:

user.snippets.reject!(&:destroyed?)

BTW - you can destroy a snippet like this:

user.snippets.get(snip_id).destroy

A bit nicer :)


问:
php - LibreOffice stuck generating PDF file from DOCX at the same time
I have a problem where when I convert 2 docx files simultaneously by using LibreOffice (soffice.exe), the LibreOffice hangs. This doesn't happen when converting xslx (Excel) file simultaneously.

My code:

```<code>exec("C:/LibreOfficePortable/App/libreoffice/program/soffice.exe -headless -convert-to pdf:writer_pdf_Export -outdir C:\convertTest\ C:\convertTest\l06.docx");
</code>```

and

```<code>exec("C:/LibreOfficePortable/App/libreoffice/program/soffice.exe -headless -convert-to pdf:writer_pdf_Export -outdir C:\convertTest\ C:\convertTest\l07.docx");
</code>```

I have done some digging, and I think it is probably because the temp file generated by the LibreOffice has the same names when converting 2 docx files simultaneously so it haywires. This is just an assumption though.

I need either a fix or an alternative as good as LibreOffice.

Thanks.

答:
Do not convert two files simultaneously.

What I have done in the past is to make the PHP script place files in a polled directory.  Write a daemon (could be a simple shell script or something more complex such as Java) that polls that directory for incoming jobs, and when it sees jobs, it feeds them to LibreOffice one at a time, sending the results to an output directory.

The PHP script, meanwhile, waits for results in the output directory.

Another option is to use a file as a lock.  The PHP script would create a 0 bytes file before running the job.  If the file already exists, wait for it to go away before converting with LibreOffice, because another job may be running.  After converting, delete the file so that the next job can run.

According to the link:

PHP provides a file based locking as well as a Mutex class in the pthreads extension.

In my experience, using a lock file is a fragile setup, because if one job goes wrong, everything is stuck.  A Java daemon, however, can be programmed with threads so that if there is a problem, it can still keep going.

LibreOffice is primarily designed for user interaction.  I believe there are command-line based tools for doing such conversions, although I do not have experience with any.

Body:
I have a problem where when I convert 2 docx files simultaneously by using LibreOffice (soffice.exe), the LibreOffice hangs. This doesn't happen when converting xslx (Excel) file simultaneously.

My code:

exec("C:/LibreOfficePortable/App/libreoffice/program/soffice.exe -headless -convert-to pdf:writer_pdf_Export -outdir C:\convertTest\ C:\convertTest\l06.docx");

and

exec("C:/LibreOfficePortable/App/libreoffice/program/soffice.exe -headless -convert-to pdf:writer_pdf_Export -outdir C:\convertTest\ C:\convertTest\l07.docx");

I have done some digging, and I think it is probably because the temp file generated by the LibreOffice has the same names when converting 2 docx files simultaneously so it haywires. This is just an assumption though.

I need either a fix or an alternative as good as LibreOffice.

Thanks.


问:
Stretch div element over Y axis

I have fixed element that resides on bottom right corner. However its really small and i want to stretch it on Y axis to make it works as it should.

```<code>$(document).ready(function () {

    $('<div />');
    $('<div />', {
        id: 'firster',
        style: 'position: fixed; bottom: 0; right: 0; max-width: 500px;'
    }).appendTo('body');

    $('<iframe />'); // Create an iframe element
    $('<iframe />', {
        name: 'frame1',
        id: 'frame1',
        src: 'https://api.jquery.com/add/'
    }).appendTo('#firster');

});
</code>```

Here is a preview of how it looks so far. The pink lines represents the area that that div should cover.

Tried to set width: 600px; height: 100% on that div with firster id, but it did not work.

The results that i get when i do set width: 600px; height: 100% are basically moving that same size element left and right.

答:
When you set height: 100% on #firster, the browser actually does not know what 100% means: it has to be relative to a certain parent value. In this case, you are better off using top: 0 and bottom: 0 on the element. This will force it to stretch to the full height of the viewport. Alternatively you can also use top: 0 and height: 100vh (100vh meaning 100% of the viewport height), but this is less widely supported.

Then declare height: 100% on the nested  element. It will now have a proper reference/ruler to compute the 100% against, which is in this case, the full height of the viewport.

```<code>$(document).ready(function () {

    $('<div />', {
        id: 'firster',
        style: 'position: fixed; top: 0; bottom: 0; right: 0; max-width: 500px;'
    }).appendTo('body');

    $('<iframe />', {
        name: 'frame1',
        id: 'frame1',
        src: 'https://api.jquery.com/add/'
    })
    .css('height', '100%')
    .appendTo('#firster');

});
</code>```

Title: Stretch div element over Y axis

Body:
I have fixed element that resides on bottom right corner. However its really small and i want to stretch it on Y axis to make it works as it should.

$(document).ready(function () {

    $('
');
    $('
', {
        id: 'firster',
        style: 'position: fixed; bottom: 0; right: 0; max-width: 500px;'
    }).appendTo('body');

    $(''); // Create an iframe element
    $('', {
        name: 'frame1',
        id: 'frame1',
        src: 'https://api.jquery.com/add/'
    }).appendTo('#firster');

});

Here is a preview of how it looks so far. The pink lines represents the area that that div should cover.

Tried to set width: 600px; height: 100% on that div with firster id, but it did not work.

The results that i get when i do set width: 600px; height: 100% are basically moving that same size element left and right.

Body:
When you set height: 100% on #firster, the browser actually does not know what 100% means: it has to be relative to a certain parent value. In this case, you are better off using top: 0 and bottom: 0 on the element. This will force it to stretch to the full height of the viewport. Alternatively you can also use top: 0 and height: 100vh (100vh meaning 100% of the viewport height), but this is less widely supported.

Then declare height: 100% on the nested <iframe> element. It will now have a proper reference/ruler to compute the 100% against, which is in this case, the full height of the viewport.

$(document).ready(function () {

    $('<div />', {
        id: 'firster',
        style: 'position: fixed; top: 0; bottom: 0; right: 0; max-width: 500px;'
    }).appendTo('body');

    $('<iframe />', {
        name: 'frame1',
        id: 'frame1',
        src: 'https://api.jquery.com/add/'
    })
    .css('height', '100%')
    .appendTo('#firster');

});


问:
POST to asp.net web api with content type x-www-form-urlencoded raises error 415 unsupported media type
I have developed a web service which will be called by twilio' webHook, but i'm facing an issue that my server expects a Content-type of JSon and Twilio sends a Content-type of x-www-form-urlencoded.

any help would be appreciated.

```<code>[HttpPost]
    public async Task<string>ProcessSms([FromBody] clsTwilio twilio)
    {

        IncomingSms incomingSms = new IncomingSms();
        incomingSms.twilio = twilio;
        return await incomingSms.ProcessSmsAsync();

    }
</code>```

答:
After braking myself. I've changed to a GET and used the [FromQuery]  (i didn't use it before as I didn't know what the replacement for [FromUri] is. so I just figured it out)

Thanks for your assistance

Body:
I have developed a web service which will be called by twilio' webHook, but i'm facing an issue that my server expects a Content-type of JSon and Twilio sends a Content-type of x-www-form-urlencoded.

any help would be appreciated.

[HttpPost]
    public async Task<string>ProcessSms([FromBody] clsTwilio twilio)
    {

        IncomingSms incomingSms = new IncomingSms();
        incomingSms.twilio = twilio;
        return await incomingSms.ProcessSmsAsync();

    }


答:
What you're looking for has been done in Boost with MultiIndex.  Here's a good tutorial from Boost on how you can use it to solve what you're asking of your data collection and their selection of examples.

Of course, using this collection object will probably change how you store the information too.  You'll be placing it within a struct.  However, if you want to treat your information like a database with a unique order by specification this is the only way I know how that's clean.

The other option is to create your own ordering operator while placing the items in a std::map.  Hence:

```<code>struct Orders{
    int order_num;
    int id;
    int order_num_relation;
    int relation_id;

    bool operator<(const Orders& _rhs){
       if(order_num < _rhs.order_num) return true;
       if(order_num == _rhs.order_num){
           if( id < _rhs.id) return true;
           if( id == _rhs.id){
              //and so on, and so on
</code>```

Honestly this way is a pain and invites a very easily overlooked logic fault.  Using Boost, most of the "tricky" stuff is taken care of for you.

Title: Sorting map by size

Body:
I have similar map:

map<int, map<int, map<int, int> > > myMap;

order-num | id | order-num-of-relation | relation-id
-----------------------------------------------------
    0     | 1  | 0                     | 2
-----------------------------------------------------
    1     | 2  | 0                     | 1
-----------------------------------------------------
          |    | 1                     | 3
-----------------------------------------------------
    2     | 3  | 0                     | 2
-----------------------------------------------------

1(1), 2(2), 3(1)

and i need to sort (change the "order-num") this map by size of the last map (order-num-of-relation | relation-id).

I just need to do this:

order-num | id | order-num-of-relation | relation-id
-----------------------------------------------------
    0     | 1  | 0                     | 2
-----------------------------------------------------
    1     | 3  | 0                     | 2
-----------------------------------------------------
    2     | 2  | 0                     | 1
-----------------------------------------------------
          |    | 1                     | 3
-----------------------------------------------------

1(1), 3(1), 2(2)

can i use the "sort" function and pass here own sorting function (where i can checking size and returing true/false), or do i have to write explicite sorting algorithm?

Body:
What you're looking for has been done in Boost with MultiIndex.  Here's a good tutorial from Boost on how you can use it to solve what you're asking of your data collection and their selection of examples.

Of course, using this collection object will probably change how you store the information too.  You'll be placing it within a struct.  However, if you want to treat your information like a database with a unique order by specification this is the only way I know how that's clean.

The other option is to create your own ordering operator while placing the items in a std::map.  Hence:

struct Orders{
    int order_num;
    int id;
    int order_num_relation;
    int relation_id;

    bool operator<(const Orders& _rhs){
       if(order_num < _rhs.order_num) return true;
       if(order_num == _rhs.order_num){
           if( id < _rhs.id) return true;
           if( id == _rhs.id){
              //and so on, and so on

Honestly this way is a pain and invites a very easily overlooked logic fault.  Using Boost, most of the "tricky" stuff is taken care of for you.


问:
CSS - Fonts Render Differently in Firefox and Chrome
I'm using Google Fonts and CSS's @import method to include fonts onto my website.

Chrome displays the fonts beautifully; they have even weights and are crisp to view. Firefox does not replicate this rendering. See below:

On the left you can see Firefox. The font weight of the title is not consistent. You can see that the smaller descriptive text has some additional weight than the Chrome counterpart.

Chrome is on the right, and as you can see, the fonts are respectfully weighted.

I am using the following CSS in an attempt to fix this issue:

```<code>@import url('https://fonts.googleapis.com/css?family=Muli|Source+Code+Pro');

* {
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
</code>```

How can I resolve this issue and have Firefox displaying my fonts with proper weights?

Firefox Version: 57.0.1 (64 bit) [Most recent]

Chrome Version: 62.0.3202.94 (64 bit) [Most recent]

Many thanks.

答:
You're walking a bleak path. Right now, your best bet is to keep things as is and let the browser and OS makers fix their text rendering implementations.

Trust me, I've played with all these settings and none will produce a decent/consistent render, especially when you start testing across Windows, OS X, and Linux.

Overriding text-rendering and font-smoothing will eventually slow down your entire app (especially on instances where the DOM tree is large).

It will look bad no matter what if the end-user doesn't care about text rendering (perhaps he didn't set up ClearType on a Windows XP?).

Point being: do not try to force the text-rendering on all your elements. On headings where the font-rendering looks really off, try using geometricPrecision as that will try to keep the original shape precision of the font glyphs upon rendering.

Body:
I'm using Google Fonts and CSS's @import method to include fonts onto my website.

Chrome displays the fonts beautifully; they have even weights and are crisp to view. Firefox does not replicate this rendering. See below:

On the left you can see Firefox. The font weight of the title is not consistent. You can see that the smaller descriptive text has some additional weight than the Chrome counterpart.

Chrome is on the right, and as you can see, the fonts are respectfully weighted.

I am using the following CSS in an attempt to fix this issue:

@import url('https://fonts.googleapis.com/css?family=Muli|Source+Code+Pro');

* {
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

How can I resolve this issue and have Firefox displaying my fonts with proper weights?

Firefox Version: 57.0.1 (64 bit) [Most recent]

Chrome Version: 62.0.3202.94 (64 bit) [Most recent]

Many thanks.


问:
Chrome not reachable Selenium WebDriver error
I am facing this issue; I know this question is already present and I have tried the solutions mentioned hence asking this with my configurations and code.

Earlier the scripts were running but now they aren't So i tried making a basic open browser script.

Latest Version of Selenium WebDriver : http://selenium-release.storage.googleapis.com/3.5/selenium-java-3.5.0.zip

Latest Version on ChromeDriver : http://chromedriver.storage.googleapis.com/index.html?path=2.31/

Basic Open browser code:

```<code>package Trial;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Trial_Class {
    public static void main(String args[]){
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.youtube.com");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    }
}
</code>```

But still I am getting the below error:

```<code> Starting ChromeDriver 2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8) on port 43967
Only local connections are allowed.
Exception in thread "main" org.openqa.selenium.WebDriverException: chrome not reachable
  (Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 61.81 seconds
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'SWATI', ip: '192.168.0.5', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_121'
Driver info: driver.version: ChromeDriver
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
    at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$new$0(JsonWireProtocolResponse.java:53)
    at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$getResponseFunction$2(JsonWireProtocolResponse.java:91)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$24(ProtocolHandshake.java:360)
    at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
    at java.util.Spliterators$ArraySpliterator.tryAdvance(Unknown Source)
    at java.util.stream.ReferencePipeline.forEachWithCancel(Unknown Source)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(Unknown Source)
    at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.util.stream.FindOps$FindOp.evaluateSequential(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.ReferencePipeline.findFirst(Unknown Source)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:363)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:137)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:641)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:254)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:137)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:178)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:167)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:124)
    at Trial.Trial_Class.main(Trial_Class.java:11)
</code>```

Thanks in Advance.

答:
Your chromedriver is starting just fine:

"Starting ChromeDriver 2.31.488763
  (092de99f48a300323ecf8c2a4e2e7cab51de5ba8) on port 43967"

The problem is the browser itself is not responding. So I have two ideas:

1) Your browser is not installed in the default location; If this is the case, add this to your code:

```<code>ChromeOptions options = new ChromeOptions();
options.setBinary("/path/to/other/chrome/binary");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
WebDriver driver = new ChromeDriver(capabilities);
</code>```

2) Your browser is latest version, but your chromedriver isn't - current is 2.33

Body:
I am facing this issue; I know this question is already present and I have tried the solutions mentioned hence asking this with my configurations and code.

Earlier the scripts were running but now they aren't So i tried making a basic open browser script.

Latest Version of Selenium WebDriver : http://selenium-release.storage.googleapis.com/3.5/selenium-java-3.5.0.zip

Latest Version on ChromeDriver : http://chromedriver.storage.googleapis.com/index.html?path=2.31/

Basic Open browser code:

package Trial;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Trial_Class {
    public static void main(String args[]){
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.youtube.com");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    }
}

But still I am getting the below error:

 Starting ChromeDriver 2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8) on port 43967
Only local connections are allowed.
Exception in thread "main" org.openqa.selenium.WebDriverException: chrome not reachable
  (Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 61.81 seconds
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'SWATI', ip: '192.168.0.5', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_121'
Driver info: driver.version: ChromeDriver
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
    at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$new$0(JsonWireProtocolResponse.java:53)
    at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$getResponseFunction$2(JsonWireProtocolResponse.java:91)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$24(ProtocolHandshake.java:360)
    at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
    at java.util.Spliterators$ArraySpliterator.tryAdvance(Unknown Source)
    at java.util.stream.ReferencePipeline.forEachWithCancel(Unknown Source)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(Unknown Source)
    at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.util.stream.FindOps$FindOp.evaluateSequential(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.ReferencePipeline.findFirst(Unknown Source)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:363)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:137)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:641)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:254)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:137)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:178)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:167)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:124)
    at Trial.Trial_Class.main(Trial_Class.java:11)

Thanks in Advance.

Body:
Your chromedriver is starting just fine:

"Starting ChromeDriver 2.31.488763
  (092de99f48a300323ecf8c2a4e2e7cab51de5ba8) on port 43967"

The problem is the browser itself is not responding. So I have two ideas:

1) Your browser is not installed in the default location; If this is the case, add this to your code:

ChromeOptions options = new ChromeOptions();
options.setBinary("/path/to/other/chrome/binary");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
WebDriver driver = new ChromeDriver(capabilities);

2) Your browser is latest version, but your chromedriver isn't - current is 2.33


问:
Create a bar diagram with matplotlib with x-axis date and width is a time-delta
I have a simple dataset that I would like to display in a bar chart corresponding to a weight collected at different times. I want it cumulative with an error bar I have estimated before. Since the weight corresponds to an accumulation during a certain period of time, I want the bar to be the width of the time it represents.

The entry file is in the form:

```<code>Date    Weight  Deviation
2017-05-04  500 100
2017-05-08  7.4 0.3
2017-05-13  6.4 0.3
2017-05-21  8.7 0.27
2017-06-06  16.8    0.7
2017-06-07  14.4    0.6
2017-06-18  13.7    0.6
2017-06-25  16.3    0.7
2017-07-02  17  0
2017-07-09  17  0
2017-07-26  20  0
2017-08-11  19  0
2017-08-23  12  0
2017-09-03  27  0
2017-09-11  15  0
2017-09-16  60  0
</code>```

Here the code:

```<code>import os, sys, datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

DATA  = np.genfromtxt(Path_to_File, dtype=[('Date','datetime64[D]'),('Weight', 'float32'), ('Deviation', 'float32')], delimiter ='\t', skip_header = 1)
Days  = np.zeros(len(DATA)-1, dtype = 'datetime64[D]')
Duration = np.zeros(len(DATA)-1, dtype = 'timedelta64[D]')
for i in range(1, len(DATA)):
    DayOut = DATA[i][0]
    DayIn  = DATA[i-1][0]
    Duration[i-1] = DayOut - DayIn
    Days[i-1] = DayIn + Duration[i-1]/2

fig2 = plt.figure()
ax = fig2.add_subplot(111)
fig2.suptitle('FigureTitle', fontsize=16)
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
ax.bar(Days, DATA['Weight'].cumsum()[1:], width=Duration, yerr = DATA['Deviation'][1:])
ax.set_ylabel('Cumulative weight (kg)')
ax.set_xlabel('Date')
plt.show()
</code>```

I get this error message

```<code>Cannot cast ufunc less input from dtype('<m8[D]') to dtype('<m8') with casting rule 'same_kind'
</code>```

It is tricky because I think it gets annoyed between dates(datetime64), the Days array and duration for the width (timedelta64), the Duration array.
I am a bit stuck, I suppose I have to do a duration only axis? Any experience, or suggestions?
Thanks in advance

答:
Thanks to @ImportanceOfBeingErnest, I have managed to get the exact result I wanted and made the code a bit more 'pythonesque'. There were problems for consecutive dates with fraction of days, so I switched the duration format to hours and did some adjustments here and there. I also switched to a cumulative error it was more representative in my case.

```<code>DATA  = np.genfromtxt(WorkingDir+os.sep+File, dtype=[('Date','datetime64[D]'),('Weight', 'float32'), ('Deviation', 'float32')], delimiter ='\t', skip_header = 1)

Duration = np.diff(DATA['Date']).astype('timedelta64[h]')
Days = DATA['Date'][:-1] + Duration/2
### Trick: transform the np array 'datetime64[h]' to a list datetime.datetime
Days = [x.tolist() for x in Days]

fig2 = plt.figure()
ax = fig2.add_subplot(111)
fig2.suptitle('Cumulative weight', fontsize=16)
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
ax.bar(Days, DATA['Weight'].cumsum()[1:], width=Duration.astype(float)/24, yerr = DATA['Deviation'].cumsum()[1:], align="center", color= 'grey')
ax.set_ylabel('Cumulative weight (kg)')
ax.set_xlabel('Date')
fig2.autofmt_xdate()
plt.show()
</code>```

Thanks

Body:
I have a simple dataset that I would like to display in a bar chart corresponding to a weight collected at different times. I want it cumulative with an error bar I have estimated before. Since the weight corresponds to an accumulation during a certain period of time, I want the bar to be the width of the time it represents.

The entry file is in the form:

Date    Weight  Deviation
2017-05-04  500 100
2017-05-08  7.4 0.3
2017-05-13  6.4 0.3
2017-05-21  8.7 0.27
2017-06-06  16.8    0.7
2017-06-07  14.4    0.6
2017-06-18  13.7    0.6
2017-06-25  16.3    0.7
2017-07-02  17  0
2017-07-09  17  0
2017-07-26  20  0
2017-08-11  19  0
2017-08-23  12  0
2017-09-03  27  0
2017-09-11  15  0
2017-09-16  60  0

Here the code:

import os, sys, datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

DATA  = np.genfromtxt(Path_to_File, dtype=[('Date','datetime64[D]'),('Weight', 'float32'), ('Deviation', 'float32')], delimiter ='\t', skip_header = 1)
Days  = np.zeros(len(DATA)-1, dtype = 'datetime64[D]')
Duration = np.zeros(len(DATA)-1, dtype = 'timedelta64[D]')
for i in range(1, len(DATA)):
    DayOut = DATA[i][0]
    DayIn  = DATA[i-1][0]
    Duration[i-1] = DayOut - DayIn
    Days[i-1] = DayIn + Duration[i-1]/2

fig2 = plt.figure()
ax = fig2.add_subplot(111)
fig2.suptitle('FigureTitle', fontsize=16)
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
ax.bar(Days, DATA['Weight'].cumsum()[1:], width=Duration, yerr = DATA['Deviation'][1:])
ax.set_ylabel('Cumulative weight (kg)')
ax.set_xlabel('Date')
plt.show()

I get this error message

Cannot cast ufunc less input from dtype('<m8[D]') to dtype('<m8') with casting rule 'same_kind'

It is tricky because I think it gets annoyed between dates(datetime64), the Days array and duration for the width (timedelta64), the Duration array.
I am a bit stuck, I suppose I have to do a duration only axis? Any experience, or suggestions?
Thanks in advance

Body:
Thanks to @ImportanceOfBeingErnest, I have managed to get the exact result I wanted and made the code a bit more 'pythonesque'. There were problems for consecutive dates with fraction of days, so I switched the duration format to hours and did some adjustments here and there. I also switched to a cumulative error it was more representative in my case.

DATA  = np.genfromtxt(WorkingDir+os.sep+File, dtype=[('Date','datetime64[D]'),('Weight', 'float32'), ('Deviation', 'float32')], delimiter ='\t', skip_header = 1)

Duration = np.diff(DATA['Date']).astype('timedelta64[h]')
Days = DATA['Date'][:-1] + Duration/2
### Trick: transform the np array 'datetime64[h]' to a list datetime.datetime
Days = [x.tolist() for x in Days]

fig2 = plt.figure()
ax = fig2.add_subplot(111)
fig2.suptitle('Cumulative weight', fontsize=16)
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
ax.bar(Days, DATA['Weight'].cumsum()[1:], width=Duration.astype(float)/24, yerr = DATA['Deviation'].cumsum()[1:], align="center", color= 'grey')
ax.set_ylabel('Cumulative weight (kg)')
ax.set_xlabel('Date')
fig2.autofmt_xdate()
plt.show()

Thanks


问:
SQL: Getting All fields That Have a Corresponding Matching Field
I'm trying to get an answer that combines fields in 4 tables to show which fields have a specific relationship.

Here are the relevant tables & fields:

```<code>lowproducts
|productid|

highproducts
|productid|

orders
|productid|customerid|

inner join on productid
</code>```

orders has many duplicates for both customerid and productid fields; lowproducts and highproducts only have distinct productid fields.

What I need is code that does this:

For all orders.customerid:
Select only fields where all rows for a customerid have a productid in either highproducts or lowproducts

Sample table data

```<code>lowproducts
|productid|volume|price|
|1111|8|2.95
|2222|7|1.37

highproducts
|productid|weight|price|
|3333|25|9.99
|4444|22|8

orders
|productid|customerid|
|1111|abcd
|2222|abcd
|1111|efgh
|2222|efgh
|3333|efgh
|4444|efgh

inner join on productid

select customerid, productid
where (orders.productid = highproducts.productid) or (orders.productid = lowproducts.productid)
</code>```

That gets me all the matches. That's not hard for me. But how do I now refine it so that I only return the matches that represent all orders for a given customerid (which is to say, none of the orders for a customerid have productid that isn't in one of those two tables)?

The result I want would be efgh, and not abcd. I know how to get both abcd and efgh in a query, but not just efgh.

答:
You want to exclude records where orders in the other products table exist, so you can use WHERE NOT EXISTS. For example to get orders where the customer didn't order highproducts, exclude records where orders exist for that customer with products in the highproducts table Then do the same thing for lowproducts and Union them together:

```<code>SELECT *, 'only low' as type FROM orders o
WHERE NOT EXISTS
(SELECT * FROM orders p
JOIN highproducts on p.productid=highproducts.productid
WHERE o.customerid = p.customerid)
UNION
SELECT *, 'only high' FROM orders o
WHERE NOT EXISTS
(SELECT * FROM orders p
JOIN lowproducts on p.productid=lowproducts.productid
WHERE o.customerid = p.customerid)
</code>```

Body:
I'm trying to get an answer that combines fields in 4 tables to show which fields have a specific relationship.

Here are the relevant tables & fields:

lowproducts
|productid|

highproducts
|productid|

orders
|productid|customerid|

inner join on productid

orders has many duplicates for both customerid and productid fields; lowproducts and highproducts only have distinct productid fields.

What I need is code that does this:

For all orders.customerid:
Select only fields where all rows for a customerid have a productid in either highproducts or lowproducts

Sample table data

lowproducts
|productid|volume|price|
|1111|8|2.95
|2222|7|1.37

highproducts
|productid|weight|price|
|3333|25|9.99
|4444|22|8

orders
|productid|customerid|
|1111|abcd
|2222|abcd
|1111|efgh
|2222|efgh
|3333|efgh
|4444|efgh

inner join on productid

select customerid, productid
where (orders.productid = highproducts.productid) or (orders.productid = lowproducts.productid)

That gets me all the matches. That's not hard for me. But how do I now refine it so that I only return the matches that represent all orders for a given customerid (which is to say, none of the orders for a customerid have productid that isn't in one of those two tables)?

The result I want would be efgh, and not abcd. I know how to get both abcd and efgh in a query, but not just efgh.

Body:
You want to exclude records where orders in the other products table exist, so you can use WHERE NOT EXISTS. For example to get orders where the customer didn't order highproducts, exclude records where orders exist for that customer with products in the highproducts table Then do the same thing for lowproducts and Union them together:

SELECT *, 'only low' as type FROM orders o
WHERE NOT EXISTS
(SELECT * FROM orders p
JOIN highproducts on p.productid=highproducts.productid
WHERE o.customerid = p.customerid)
UNION
SELECT *, 'only high' FROM orders o
WHERE NOT EXISTS
(SELECT * FROM orders p
JOIN lowproducts on p.productid=lowproducts.productid
WHERE o.customerid = p.customerid)


问:
Handling database integrity
I'm introducing database integrity using innodb constraints in the next version of my application. Everything goes well, but some of my tables have records with deleted references (dead records) and because of them I can't add constraints to the table.

I am trying:

```<code>ALTER TABLE `article` ADD FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE;
</code>```

And I get:

```<code>#1452 - Cannot add or update a child row: a foreign key constraint fails (`books`.<result 2 when explaining filename '#sql-442_dc'>, CONSTRAINT `#sql-442_dc_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE)
</code>```

Running this query, I found out that over 500 records have no references (authors were deleted, but their articles remained):

```<code>SELECT `articles`.`id`
FROM `articles` LEFT JOIN `authors` ON `articles`.`author_id` = `authors`.`id`
WHERE ISNULL(`authors`.`id`);
</code>```

So, before I can add a constraint, I must deal with those. How do I delete all the records that I get using the query above?

I've tried:

```<code>DELETE FROM `articles` WHERE `id` IN (
  SELECT `articles`.`id`
  FROM `articles` LEFT JOIN `authors` ON `articles`.`author_id` = `authors`.`id`
  WHERE ISNULL(`authors`.`id`);
)
</code>```

But mysql responds:

```<code>You can't specify target table 'articles' for update in FROM clause
</code>```

Any help on this will be greatly appreciated.

答:
I'm not too familiar with mySql's many quirks, but this should also work, and perhaps mySql won't choke on it:

```<code>delete from articles
 where not exists (
           select id from authors
            where authors.id = articles.author_id
       )
</code>```

Um, of course we always have a backup of the table before we attempt set-based deletes :)

Title: Handling database integrity

Body:
I'm introducing database integrity using innodb constraints in the next version of my application. Everything goes well, but some of my tables have records with deleted references (dead records) and because of them I can't add constraints to the table.

I am trying:

ALTER TABLE `article` ADD FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE;

And I get:

#1452 - Cannot add or update a child row: a foreign key constraint fails (`books`.<result 2 when explaining filename '#sql-442_dc'>, CONSTRAINT `#sql-442_dc_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE)

Running this query, I found out that over 500 records have no references (authors were deleted, but their articles remained):

SELECT `articles`.`id`
FROM `articles` LEFT JOIN `authors` ON `articles`.`author_id` = `authors`.`id`
WHERE ISNULL(`authors`.`id`);

So, before I can add a constraint, I must deal with those. How do I delete all the records that I get using the query above?

I've tried:

DELETE FROM `articles` WHERE `id` IN (
  SELECT `articles`.`id`
  FROM `articles` LEFT JOIN `authors` ON `articles`.`author_id` = `authors`.`id`
  WHERE ISNULL(`authors`.`id`);
)

But mysql responds:

You can't specify target table 'articles' for update in FROM clause

Any help on this will be greatly appreciated.

Body:
I'm not too familiar with mySql's many quirks, but this should also work, and perhaps mySql won't choke on it:

delete from articles
 where not exists (
           select id from authors
            where authors.id = articles.author_id
       )

Um, of course we always have a backup of the table before we attempt set-based deletes :)


问:
Using Cuckoo sandbox platform for dynamically analyzing multiple file samples
I'm trying to run more than one sample at the same time in a single guest VM, for efficiency reasons, something that will be even more efficient than the distributed cuckoo solution, or using a few guest VMs.

For example, to submit a few URLs, so they will be opened in a few tabs(in IE or FF) in Cuckoo, so I won't need to run a clean VM for each URL.

Then, if any malicious activity is detected in any of the URLs, I'll find the malicious URL, and will make a deeper inspection of its activity using all other cuckoo plugins and modules, etc.

Can you think of a way to make it using cuckoo? or any workaround?

My use-case is that I have A LOT of samples, but only very few are malicious, so to run a VM for every one of them would be a waste of resources.

答: Cuckoo monitors malwares activity in system, record them and create report in a language like JSON. if you try several suspicious links probably malware in one VM, you cant track which part of JSON report (features) belong to which link (possibility malware). I believe you need to run different suspicious links/files in different VM. you can run few VM at the same time though.</p>


问:
Iterating over the elements of a structure in python
I have a class that is imitating a matlab like structure:

```<code>class params():
    maxresources = []
    functions = []
    terminals = []
    numvars = []
    initpoptype = []
</code>```

All elements are lists, and my objective is to iterate them, to see for example if all of them are empty.

I have tried to use a    def __iter__(self): but it did not work, and i have also tried to use a Enum but also didn't work.

This is done on Python3.

答:
Not sure why you want to do that or if using a class is the better way for your purpose but, to answer your question, you can read the class variables using:

```<code>params.__dict__.items()
</code>```

this gives you

```<code>dict_items([('__module__', '__main__'), ('maxresources', []), ('functions', []), ('terminals', []), ('numvars', []), ('initpoptype', []), ('__dict__', <attribute '__dict__' of 'params' objects>), ('__weakref__', <attribute '__weakref__' of 'params' objects>), ('__doc__', None)])
</code>```

and from here you can iterate with the different vatiables like:

```<code>params.__dict__['maxresources']
</code>```

or just iterate the tuples in dict_items

```<code>list(params.__dict__.items())
</code>```

gives:

```<code>[('__module__', '__main__'),
 ('maxresources', []),
 ('functions', []),
 ('terminals', []),
 ('numvars', []),
 ('initpoptype', []),
 ('__dict__', <attribute '__dict__' of 'params' objects>),
 ('__weakref__', <attribute '__weakref__' of 'params' objects>),
 ('__doc__', None)]
</code>```

so you can check the object (second member in each tuple) corresponding to the names without underscores

Body:
I have a class that is imitating a matlab like structure:

class params():
    maxresources = []
    functions = []
    terminals = []
    numvars = []
    initpoptype = []

All elements are lists, and my objective is to iterate them, to see for example if all of them are empty.

I have tried to use a    def __iter__(self): but it did not work, and i have also tried to use a Enum but also didn't work.

This is done on Python3.

Body:
Not sure why you want to do that or if using a class is the better way for your purpose but, to answer your question, you can read the class variables using:

params.__dict__.items()

this gives you

dict_items([('__module__', '__main__'), ('maxresources', []), ('functions', []), ('terminals', []), ('numvars', []), ('initpoptype', []), ('__dict__', <attribute '__dict__' of 'params' objects>), ('__weakref__', <attribute '__weakref__' of 'params' objects>), ('__doc__', None)])

and from here you can iterate with the different vatiables like:

params.__dict__['maxresources']

or just iterate the tuples in dict_items

list(params.__dict__.items())

gives:

[('__module__', '__main__'),
 ('maxresources', []),
 ('functions', []),
 ('terminals', []),
 ('numvars', []),
 ('initpoptype', []),
 ('__dict__', <attribute '__dict__' of 'params' objects>),
 ('__weakref__', <attribute '__weakref__' of 'params' objects>),
 ('__doc__', None)]

so you can check the object (second member in each tuple) corresponding to the names without underscores


问:
How to use $event.target to make changes to view
I know I should use binding. But I need some flexibility here.
Given a long list of records, I want to do something on each record by clicking a button of each record, when it finishes, I just want to change the record status.

On each record, I can "do(record, $event)". I can see I have $event.target which is the button of my click. It's great. Because after I'm done. I want to replace the button with a "Done".

How to achieve that?

答: You should check Renderer2 class, that's the preferred way to solve these kind of tasks. </p>


问:
How to make a millisecond chronometer in Javascript?
I found how to make a clock with milliseconds in javascript (Jquery)(see snippet) but I can't figure out how to make a chronometer in milliseconds only.
I tried to make a loop adding 1000 to the value of "milli" but my condition never works completely

// START CLOCK SCRIPT

Number.prototype.pad = function(n) {
  for (var r = this.toString(); r.length < n; r = 0 + r);
  return r;
};

function updateClock() {
  var now = new Date();
  var milli = now.getMilliseconds(),
    sec = now.getSeconds(),
    min = now.getMinutes(),
    hou = now.getHours(),
    mo = now.getMonth(),
    dy = now.getDate(),
    yr = now.getFullYear();
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var tags = ["mon", "d", "y", "h", "m", "s", "mi"],
    corr = [months[mo], dy, yr, hou.pad(2), min.pad(2), sec.pad(2), milli];
  for (var i = 0; i < tags.length; i++)
    document.getElementById(tags[i]).firstChild.nodeValue = corr[i];
}

function initClock() {
  updateClock();
  window.setInterval("updateClock()", 1);
}

// END CLOCK SCRIPT```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {background-color:#666;}

#timedate {
  font: small-caps bold 43px/150% Arial, Helvetica, sans-serif;
  text-align:left;
  width: 50%;
  margin: 20px auto;
  color:#333;
  border-left: 20px solid yellow;
  padding: 20px;
}</code>```

    January
    1,
    0

    12 :
    00:
    00:
    000

```

答:
You can use the getTime function in Date API, it returns milliseconds number after 1970/01/01.

```<code>function updateClock(initTime) {
  var now = new Date();
  var milli = now.getTime() - initTime;
  document.getElementById('timedate').innerHTML = milli;
}

function initClock() {
  var initTime = new Date().getTime();
  updateClock();
  window.setInterval(updateClock, 1, initTime);
}
</code>```

Body:
I found how to make a clock with milliseconds in javascript (Jquery)(see snippet) but I can't figure out how to make a chronometer in milliseconds only.
I tried to make a loop adding 1000 to the value of "milli" but my condition never works completely

// START CLOCK SCRIPT

Number.prototype.pad = function(n) {
  for (var r = this.toString(); r.length < n; r = 0 + r);
  return r;
};

function updateClock() {
  var now = new Date();
  var milli = now.getMilliseconds(),
    sec = now.getSeconds(),
    min = now.getMinutes(),
    hou = now.getHours(),
    mo = now.getMonth(),
    dy = now.getDate(),
    yr = now.getFullYear();
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var tags = ["mon", "d", "y", "h", "m", "s", "mi"],
    corr = [months[mo], dy, yr, hou.pad(2), min.pad(2), sec.pad(2), milli];
  for (var i = 0; i < tags.length; i++)
    document.getElementById(tags[i]).firstChild.nodeValue = corr[i];
}

function initClock() {
  updateClock();
  window.setInterval("updateClock()", 1);
}

// END CLOCK SCRIPT

body {background-color:#666;}

#timedate {
  font: small-caps bold 43px/150% Arial, Helvetica, sans-serif;
  text-align:left;
  width: 50%;
  margin: 20px auto;
  color:#333;
  border-left: 20px solid yellow;
  padding: 20px;
}

    January
    1,
    0

    12 :
    00:
    00:
    000

Body:
You can use the getTime function in Date API, it returns milliseconds number after 1970/01/01.

function updateClock(initTime) {
  var now = new Date();
  var milli = now.getTime() - initTime;
  document.getElementById('timedate').innerHTML = milli;
}

function initClock() {
  var initTime = new Date().getTime();
  updateClock();
  window.setInterval(updateClock, 1, initTime);
}


问:
How can I turn off optimistic concurrency in Entity Framework code first?
I am working with an Actian Pervasive (v12) database and Entity Framework 6 and trying to insert a new record.  When I do this, I receive a OptimisticConcurrencyException error. This behaviour does not happen when I use a MS SQL Server database, even though the tables are constructed the same and both have database generated identity fields.

In order to work around this problem I tried changing the [DatabaseGenerated] attribute on the Key field to all the different available values to see if it would behave better and not return the Exception (the Exception is invalid - I am the only user, and I am doing a single insert operation).  This didn't help.

As a result, I would like to TURN OFF optimistic concurrency in Entity Framework (i.e. I WANT any updates I do to overwrite whatever is currently in the database).  I do not want Entity Framework to raise this OptimisticConcurrencyException.  The problem is, I'm not sure how to do this.  My class definition does not currently have a TimeStamp field or any fields with the [ConcurrencyCheck] attribute, and yet it still raises this exception when I perform a simple insert.

Note: My application is developed using DevExpress XAF which is a framework on top of ASP.NET and Entity Framework, so the calls to retrieve data are automatically generated, and it is not easy to override these calls to catch and handle this exception, so I am trying to find a way to prevent Entity Framework from even raising this exception.

How can I turn off optimistic concurrency checks in Entity Framework (globally for my application)?

答:
I found the solution.

Something I failed to mention in my initial description of the problem is that I am getting this error on classes that have mapped Insert procedures.

The exception being raised by EF (OptimisticConcurrency) was somewhat misleading in that the problem was actually that the new ID of the item was not being returned by the stored procedure (Ivan's comment got me thinking about the return value of the sproc).

To fix the problem I had to return the new ID from the stored procedure as follows:

```<code>SELECT @@IDENTITY AS ID;
</code>```

Body:
I found the solution.

Something I failed to mention in my initial description of the problem is that I am getting this error on classes that have mapped Insert procedures.

The exception being raised by EF (OptimisticConcurrency) was somewhat misleading in that the problem was actually that the new ID of the item was not being returned by the stored procedure (Ivan's comment got me thinking about the return value of the sproc).

To fix the problem I had to return the new ID from the stored procedure as follows:

SELECT @@IDENTITY AS ID;


问:
PanGesture and some basic math
I'd like to calculate a percentage from 0-100 based on where the user "pans" the screen. If it's at the most bottom, 0%. If it's at the most top, 100%. I need this for an opacity sliding feature. A user can change the opacity of the screen by sliding, where the bottom most sets the screen to invisible while the top most sets it to brightest, 100%.

```<code>- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer{
    CGPoint translation = [recognizer translationInView:self.view];
    NSLog(@"Translation: %f", translation.x);
}
</code>```

I'm pretty sure I'm looking at converting translation.x to a percetange but it's confusing.

答:
Assuming your view covers the entire screen, I believe the percentage you're looking for is

```<code>CGPoint location = [recognizer locationInView:self.view];
CGFloat percentage = 1.0 - (location.y / self.view.bounds.size.height);
</code>```

locationInView gives you a point in the coordinate system of the view, which is defined by its bounds with (0,0) at the top left. You want the top to be 100%, hence the subtraction from 1 to flip it around (otherwise you'd get 100% at the bottom).

Title: PanGesture and some basic math

Body:
I'd like to calculate a percentage from 0-100 based on where the user "pans" the screen. If it's at the most bottom, 0%. If it's at the most top, 100%. I need this for an opacity sliding feature. A user can change the opacity of the screen by sliding, where the bottom most sets the screen to invisible while the top most sets it to brightest, 100%.

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer{
    CGPoint translation = [recognizer translationInView:self.view];
    NSLog(@"Translation: %f", translation.x);
}

I'm pretty sure I'm looking at converting translation.x to a percetange but it's confusing.

Body:
Assuming your view covers the entire screen, I believe the percentage you're looking for is

CGPoint location = [recognizer locationInView:self.view];
CGFloat percentage = 1.0 - (location.y / self.view.bounds.size.height);

locationInView gives you a point in the coordinate system of the view, which is defined by its bounds with (0,0) at the top left. You want the top to be 100%, hence the subtraction from 1 to flip it around (otherwise you'd get 100% at the bottom).


问:
Oracle ADF 12c deployment to Tomcat or Glassfish
Does anyone have experience successfully deploying an ADF 12c application to either Tomcat (7 or 8) or Glassfish 3.1?

I am having difficulty getting this accomplished and could use some help.

Thanks.

答:
You need to use ADF Essentials for deployment that are not on WebLogic.
Info here:
http://www.oracle.com/technetwork/developer-tools/adf/overview/adfessentials-1719844.html</p>


问:
Converting a date and and a char 'time' field to a single date
I am trying to concatenate two fields and load the data into a date field.

I have a table with hier_dt as DATE datatype and hier_tm as CHAR datatype, with data like:

```<code>hier_dt   | hier_tm
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
17-JAN-17 | 17:54
</code>```

I would like to concatenate both of these into a single DATE datatype field, to produce:

```<code>hier_dt_tm
----------------
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/17 17:54
</code>```

Is there a way I can accomplish this?

My current query is:

```<code>select to_date(concat(to_char(NVL(hier_DT,'01-JAN-1900'), 'yyyy/mm/dd'),
  concat(' ',NVL(hier_tm,'00:00'))), 'yyyy/mm/dd hh24:mi') as temp
from XXX1
</code>```

答:
Use this to convert it to DATE.

```<code>SELECT
   TO_DATE(  TO_CHAR(hier_dt,'DD-MON-YYYY') || hier_tm , 'DD-MON-YYYY HH24:MI' ) HIER_dt
 FROM Yourtable;
</code>```

Use this to display it in your desired format.

```<code> SELECT
  TO_CHAR (  TO_DATE(  TO_CHAR(hier_dt,'DD-MON-YYYY') || hier_tm , 'DD-MON-YYYY HH24:MI' ),
           'YYYY/MM/DD HH24:MI') hier_dt_tm
 FROM Yourtable;
</code>```

DEMO

Body:
I am trying to concatenate two fields and load the data into a date field.

I have a table with hier_dt as DATE datatype and hier_tm as CHAR datatype, with data like:

hier_dt   | hier_tm
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
17-JAN-17 | 17:54

I would like to concatenate both of these into a single DATE datatype field, to produce:

hier_dt_tm
----------------
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/17 17:54

Is there a way I can accomplish this?

My current query is:

select to_date(concat(to_char(NVL(hier_DT,'01-JAN-1900'), 'yyyy/mm/dd'),
  concat(' ',NVL(hier_tm,'00:00'))), 'yyyy/mm/dd hh24:mi') as temp
from XXX1

Body:
Use this to convert it to DATE.

SELECT
   TO_DATE(  TO_CHAR(hier_dt,'DD-MON-YYYY') || hier_tm , 'DD-MON-YYYY HH24:MI' ) HIER_dt
 FROM Yourtable;

Use this to display it in your desired format.

 SELECT
  TO_CHAR (  TO_DATE(  TO_CHAR(hier_dt,'DD-MON-YYYY') || hier_tm , 'DD-MON-YYYY HH24:MI' ),
           'YYYY/MM/DD HH24:MI') hier_dt_tm
 FROM Yourtable;

DEMO


问:
Node require absolute path
I have a directory that looks like this:

```<code>-- app/
   |- models/
      |- user.js
   |- config.json
</code>```

I want my user.js file to require config.json. Right now I'm using require('/config') but this is not working. What am I doing wrong? I'd like to avoid using require('../config').

答:
It seems like the module-loading functionality prepends node_modules/ to the argument. For example, place the following script into /tmp/t.js:

```<code>meow = require('meow/meow.js');
</code>```

create (mkdir) the /tmp/node_modules/ and try running it with BSD's ktrace (or Linux' strace, which provides comparable functionality). Node will attempt to open the following:

/tmp/node_modules/meow/meow.js

/tmp/node_modules/meow/meow.js.js

/tmp/node_modules/meow/meow.js.json

/tmp/node_modules/meow/meow.js.node

/tmp/node_modules/meow/meow.js/package.json

/tmp/node_modules/meow/meow.js/index.js

/tmp/node_modules/meow/meow.js/index.json

/tmp/node_modules/meow/meow.js/index.node

If you do not have the node_modules/ subdirectory next to your script, it will not lookup anywhere relative to your script at all.

Title: Node require absolute path

Body:
I have a directory that looks like this:

-- app/
   |- models/
      |- user.js
   |- config.json

I want my user.js file to require config.json. Right now I'm using require('/config') but this is not working. What am I doing wrong? I'd like to avoid using require('../config').

Body:
It seems like the module-loading functionality prepends node_modules/ to the argument. For example, place the following script into /tmp/t.js:

meow = require('meow/meow.js');

create (mkdir) the /tmp/node_modules/ and try running it with BSD's ktrace (or Linux' strace, which provides comparable functionality). Node will attempt to open the following:

/tmp/node_modules/meow/meow.js

/tmp/node_modules/meow/meow.js.js

/tmp/node_modules/meow/meow.js.json

/tmp/node_modules/meow/meow.js.node

/tmp/node_modules/meow/meow.js/package.json

/tmp/node_modules/meow/meow.js/index.js

/tmp/node_modules/meow/meow.js/index.json

/tmp/node_modules/meow/meow.js/index.node

If you do not have the node_modules/ subdirectory next to your script, it will not lookup anywhere relative to your script at all.


问:
Passing parameters to a window call in Windows
I'm new to programming against Windows calls, and I'm trying to figure out a way to pass a parameter to the lpfnWndProc function.  I have the following code:

```<code>HWND hwnd;
WNDCLASS wc1 = {0};

wc1.lpszClassName = TEXT( "sample" );
wc1.hInstance     = 0;
wc1.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
wc1.lpfnWndProc   = DepthWndProc;
</code>```

Note the line wc1.lpfnWndProc = DepthWndProc;  Am I able to pass DepthWndProc a parameter?  If so, what does the syntax look like?

Thanks!

答:
You are assigning a function pointer here, not making a call.  Thus no passing of arguments.

Having to store extra state with a HWND isn't unusual, a very common requirement for a C++ class wrapper around a window for example.  You should keep a map<> to help you retrieve the wrapper object from the window handle value.  Using SetWindowLongPtr() with GWLP_USERDATA is possible too but less ideal if you don't control the window creation.

Body:
I'm new to programming against Windows calls, and I'm trying to figure out a way to pass a parameter to the lpfnWndProc function.  I have the following code:

HWND hwnd;
WNDCLASS wc1 = {0};

wc1.lpszClassName = TEXT( "sample" );
wc1.hInstance     = 0;
wc1.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
wc1.lpfnWndProc   = DepthWndProc;

Note the line wc1.lpfnWndProc = DepthWndProc;  Am I able to pass DepthWndProc a parameter?  If so, what does the syntax look like?

Thanks!


问:
Boolean inputs to angular 2 component
I'm trying to write a component to be reused across my application, which will sometimes show a control button and sometimes not.

Ideally, I'd want to get this from the presence or absence of an attribute, so that using the component would look something like <generic-component hideControls></generic-component>, with a boolean variable in my component based on whether that attribute is present, but I can't see a way to do this.

Is there a way to do this?

I have tried with the slightly more messy version below (although ideally I would not need to set a value on showControls/hideControls);

generic.component.html

```<code><div>
  <div>Stuff</div>
  <div *ngIf="showControls">Controls</div>
</div>
</code>```

generic.component.ts

```<code>// imports etc.
@Component({
  selector: 'generic-selector',
  templateUrl: 'generic.component.html'
})
export class GenericComponent implements OnInit {
  @Input()
  public showControls: boolean = true;

  // other inputs and logic
}
</code>```

This fails, because the usage <generic-selector showControls="false"></generic-selector> sets showControls as the string "false", which is truthy, rather than as the boolean value. So I have to get round it by adding a lot of mess to the component to take in the input and convert to a boolean based on whether it is being given the string "false" or not. A non-messy way to sort this would be appreciated, but I'd prefer being able to do the other option above.

答:
You can use the Input decorator as you would normally do with other attributes. The only trick is that when the attribute is non-present, the value would be undefined, otherwise, the value would be an empty string.

Logic:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: '',
  templateUrl: './boolean-component.component.html'
})
export class AppBooleanComponent implements OnInit {

  @Input('boolean-attribute') booleanAttr: boolean;

  ngOnInit() {
    this.booleanAttr = this.booleanAttr !== undefined;
    console.log(`Boolean attribute is ${this.booleanAttr ? '' : 'non-'}present!`);
  }

}
</code>```

Template 1 (logs 'Boolean attribute is present!'):

```<code><app-boolean-component boolean-attribute></app-boolean-component>
</code>```

Template 2 (logs 'Boolean attribute is non-present!'):

```<code><app-boolean-component></app-boolean-component>
</code>```

Title: Boolean inputs to angular 2 component

Body:
I'm trying to write a component to be reused across my application, which will sometimes show a control button and sometimes not.

Ideally, I'd want to get this from the presence or absence of an attribute, so that using the component would look something like <generic-component hideControls></generic-component>, with a boolean variable in my component based on whether that attribute is present, but I can't see a way to do this.

Is there a way to do this?

I have tried with the slightly more messy version below (although ideally I would not need to set a value on showControls/hideControls);

generic.component.html

Stuff

Controls

generic.component.ts

// imports etc.
@Component({
  selector: 'generic-selector',
  templateUrl: 'generic.component.html'
})
export class GenericComponent implements OnInit {
  @Input()
  public showControls: boolean = true;

  // other inputs and logic
}

This fails, because the usage <generic-selector showControls="false"></generic-selector> sets showControls as the string "false", which is truthy, rather than as the boolean value. So I have to get round it by adding a lot of mess to the component to take in the input and convert to a boolean based on whether it is being given the string "false" or not. A non-messy way to sort this would be appreciated, but I'd prefer being able to do the other option above.

Body:
You can use the Input decorator as you would normally do with other attributes. The only trick is that when the attribute is non-present, the value would be undefined, otherwise, the value would be an empty string.

Logic:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: '',
  templateUrl: './boolean-component.component.html'
})
export class AppBooleanComponent implements OnInit {

  @Input('boolean-attribute') booleanAttr: boolean;

  ngOnInit() {
    this.booleanAttr = this.booleanAttr !== undefined;
    console.log(`Boolean attribute is ${this.booleanAttr ? '' : 'non-'}present!`);
  }

}

Template 1 (logs 'Boolean attribute is present!'):

<app-boolean-component boolean-attribute></app-boolean-component>

Template 2 (logs 'Boolean attribute is non-present!'):

<app-boolean-component></app-boolean-component>

ContentLicense: CC BY-SA 4.0


问:
How to download picture from Firebase storage on web?
I'm trying to download a picture from firebase storage and I'm coming across errors.enter image description here

i don't get it what's wrong in it. PLease help
This is a snapshot of my code

答: In your code, try changing storage.ref(...your path); to storage().ref().child(...your path);</p>


问:
Show all data from array in codeigniter
My code Is

```<code>$co = count($da);
print_r($co);
foreach($da as $abc) {
  $myarray = array(
    date("j", strtotime($abc - > date)) => ''
  );
}
</code>```

$da have four value but show only one record into calender I use

```<code>$data = $this->calendar->generate(2017,12, $myarray);
$this->load->view('calen',['va'=>$data]);
</code>```

Screen shot of output

Output

Into $da have four date store and pass this array into calender->generate but still show only one date highlight  that is last index date so how to solve this problem

Thanks in Advance

答:
You are overwriting the value of $myarray in every iteration of the loop

Change it to:

```<code>foreach($da as $abc) {
  $myarray[] = array(
        //^^ [] denotes new index in array
    date("j", strtotime($abc - > date)) => ''
  );
}
</code>```

Title: Show all data from array in codeigniter

Body:
My code Is

$co = count($da);
print_r($co);
foreach($da as $abc) {
  $myarray = array(
    date("j", strtotime($abc - > date)) => ''
  );
}

$da have four value but show only one record into calender I use

$data = $this->calendar->generate(2017,12, $myarray);
$this->load->view('calen',['va'=>$data]);

Screen shot of output

Output

Into $da have four date store and pass this array into calender->generate but still show only one date highlight  that is last index date so how to solve this problem

Thanks in Advance

Body:
You are overwriting the value of $myarray in every iteration of the loop

Change it to:

foreach($da as $abc) {
  $myarray[] = array(
        //^^ [] denotes new index in array
    date("j", strtotime($abc - > date)) => ''
  );
}


问:
Vertically Responsive background video
I have a simple html page in which i have added a background video clip and a div containing h1 and a p element.

Background video is fully responsive horizontally if browser window is resized but it is not responsive vertically. When browser window is resized, video shrinks vertically from the bottom of the screen. How can i make this video responsive vertically as well?

Here's a visual representation of my problem

as you can see, video shrinks vertically from the bottom when browser window is resized. Need help fixing this issue.

Here's my code

Relevant HTML code

```<code><body>

    <div class="video-container">
        <video src="Lamp%20-%2011186.mp4" autoplay loop muted></video>
    </div>

</body>
</code>```

Relevant CSS code

```<code>body{
    margin: 0;
    padding: 0;
}

.video-container{
    position: fixed;
    z-index: 1;
    width: 100%;
    height: 100%;
    padding: 0;
}

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

答:
Modify your CSS code to this and retry. It should work. The vh makes the video responsive with the browser viewport height and it will resize to 70% of the browser height when resized.</p>

```<code>body{
    margin: 0;
    padding: 0;
}

.video-container{
    position: fixed;
    z-index: 1;
    width: 100%;
    height: 100%;
    padding: 0;
}

video{
    width: 100%;
    height: 70vh;
}
</code>```

Title: Vertically Responsive background video

Body:
I have a simple html page in which i have added a background video clip and a div containing h1 and a p element.

Background video is fully responsive horizontally if browser window is resized but it is not responsive vertically. When browser window is resized, video shrinks vertically from the bottom of the screen. How can i make this video responsive vertically as well?

Here's a visual representation of my problem

as you can see, video shrinks vertically from the bottom when browser window is resized. Need help fixing this issue.

Here's my code

Relevant HTML code

        <video src="Lamp%20-%2011186.mp4" autoplay loop muted></video>

Relevant CSS code

body{
    margin: 0;
    padding: 0;
}

.video-container{
    position: fixed;
    z-index: 1;
    width: 100%;
    height: 100%;
    padding: 0;
}

video{
    width: 100%;
}

Body:
Modify your CSS code to this and retry. It should work. The vh makes the video responsive with the browser viewport height and it will resize to 70% of the browser height when resized.

body{
    margin: 0;
    padding: 0;
}

.video-container{
    position: fixed;
    z-index: 1;
    width: 100%;
    height: 100%;
    padding: 0;
}

video{
    width: 100%;
    height: 70vh;
}


问:
ProgressDialog cant stop
my app is loading some data from a web server.this time i would like to have a progress dialog in order to avoid a black screen to the app users.

```<code> Button ok = (Button) findViewById(R.id.ok);
        ok.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) {
                 MyDialog = ProgressDialog.show( yassou.this, " " , " Loading. Please wait ... ", true);
                    MyDialog.show();
               // myIntent.username.getText();
                  try {

                      Send();

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                  Status();
                  //MyDialog=null;
              }

          });
</code>```

this is the btn witch "onclick" is loading the data.Send(); is a method that sends some data that the user enters to my server,andStatus(); is a second method that directs me to a new page.unfortunately,as i press the ok button,the app first goes to the second page and secondly appears a non stop progress dialog.Where is my wrong please?

答:
You have to dismiss dialogs when you don't need them anymore. It appears after you are sent to the "second page" because all the onClick() code is executed before changes to the UI happen.

It's important that you do all the Send() and Status() work in an AsyncTask or in a thread (which, at the end, will dismiss the dialog), because while that code is being executed the UI will be locked, and won't be able to show the dialog. Moreover, if the job is too long you could get an Application Not Responding (ANR) message.

A good rule is that any method executed in UI thread should last less than 200ms, to guarantee responsiveness and not to result sluggish to the user.

Creating Dialogs (from Android Dev)

Title: ProgressDialog cant stop

Body:
my app is loading some data from a web server.this time i would like to have a progress dialog in order to avoid a black screen to the app users.

 Button ok = (Button) findViewById(R.id.ok);
        ok.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) {
                 MyDialog = ProgressDialog.show( yassou.this, " " , " Loading. Please wait ... ", true);
                    MyDialog.show();
               // myIntent.username.getText();
                  try {

                      Send();

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                  Status();
                  //MyDialog=null;
              }

          });

this is the btn witch "onclick" is loading the data.Send(); is a method that sends some data that the user enters to my server,andStatus(); is a second method that directs me to a new page.unfortunately,as i press the ok button,the app first goes to the second page and secondly appears a non stop progress dialog.Where is my wrong please?