问:
How to show custom server errors in UI using Plupload and Symfony3

INTRODUCTION

In order to upload multiple files to the server I am using:

Symfony v3.2.6

OneUpUploaderBundle

OneUpFlysystemBundle

Plupload file uploading library

NOTE

Please note that: this configuration works without a hitch for single and multiple file uploads. It just does not show custom server errors in the clients browser.

TARGET

I would like to show file exists error in UI

PROBLEM

I am using validator to restrict some uploadable files.

At the moment files that validator restricts are not uploaded (ValidationException is beeing trown).

I do not know how to make Plupload to show file already exist errors.

CODE

My template with relevant javascript code

```<code>{% extends 'base.html.twig' %}

{% block stylesheets %}
    {{ parent() }}
    <link type="text/css" rel="stylesheet" href="{{ asset('js/plupload/jquery-ui-1.12.1/jquery-ui.css') }}" />
    <link type="text/css" rel="stylesheet" href="{{ asset('js/plupload/jquery.ui.plupload/css/jquery.ui.plupload.css') }}" media="screen" />
{% endblock %}

{% block content %}
    <div id="box-upload">
        <div id="uploader">
            <p>Your browser doesn't have HTML5 support.</p>
        </div>
    </div>
{% endblock %}

{% block javascripts %}
    <script type="text/javascript" src="{{ asset('js/browserplus/browserplus.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/plupload/plupload.full.min.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/jquery-2.2.4.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/plupload/jquery-ui-1.12.1/jquery-ui.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/plupload/jquery.ui.plupload/jquery.ui.plupload.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/plupload/i18n/lv.js') }}"></script>
    <script type="text/javascript">
        'use strict';

        $(function()
        {
            var uploader;

            uploader = $("#uploader");

            uploader.plupload(
            {
                // General settings
                runtimes: 'html5',
                url: "{{ oneup_uploader_endpoint('gallery') }}",
                multi_selection: true,

                // Maximum file size
                max_file_size: '5mb',

                chunk_size: '5mb',

                // Specify what files to browse for
                filters: [
                    {title: "Image files", extensions: "jpg,jpeg,png,gif"},
                    {title: "Zip files", extensions: "zip,7z"},
                    {title: "Pdf files", extensions: "pdf"},
                    {title: "Binary files", extensions: "bin"},
                    {title: "Text files", extensions: "txt"},
                    {title: "Media files", extensions: "avi"}
                ],

                // Rename files by clicking on their titles
                rename: true,

                // Sort files
                sortable: true,

                // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
                dragdrop: true,

                // Views to activate
                views: {
                    list: true,
                    thumbs: false, // Show thumbs
                    active: 'list'
                }
            });

            var $uploader = uploader.plupload('getUploader');

            // Add Clear Button
            var $button = $("<button>"+ plupload.translate("Clear list") + "</button>").button({icons: {primary: "ui-icon-trash"}}).button("disable").appendTo('.plupload_buttons');

            // Clear Button Action
            $button.click(function()
            {
                removeErrorMessages();
                $uploader.splice();
                $(".plupload_filelist_content").html('');
                $button.button("disable");
                return true;
            });

            // Clear Button Toggle Enabled
            $uploader.bind('QueueChanged', function ()
            {
                if ($uploader.files.length > 0)
                {
                    $button.button("enable");
                }
                else
                {
                    $button.button("disable");
                }
            });

            // Clear Button Toggle Hidden
            $uploader.bind('StateChanged', function ()
            {
                if ($uploader.state == plupload.STARTED)
                {
                    $button.hide();
                }
                else
                {
                    $button.show();
                }
            });

            // Clear Button Toggle Hidden
            $uploader.bind('Browse', function ()
            {
                removeErrorMessages();
                $uploader.splice();

            });

            $uploader.bind('Error', function(uploader, error)
            {
                console.error(error.message);
                console.log(error.message);
            });

            function removeErrorMessages()
            {
                $(".ui-state-error").remove();
            }
        });
    </script>
{% endblock %}
</code>```

My validator

```<code><?php

namespace AppBundle\EventListener;

use Oneup\UploaderBundle\Event\ValidationEvent;
use Oneup\UploaderBundle\Uploader\Exception\ValidationException;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;

class AllowedMimeTypeValidationListener
{
    /**
     * @var Container
     */
    private $container;

    private $file_extension_array = [];
    private $file_type_array = [];
    private $banned_files = [];

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function onValidate(ValidationEvent $event)
    {
        $ultra_helpers = $this->container->get('app.ultra_helpers');
        $ultra_text = $this->container->get('app.ultra_text');

        array_push($this->file_extension_array, '.gif');
        array_push($this->file_extension_array, '.jpg');
        array_push($this->file_extension_array, '.jpeg');
        array_push($this->file_extension_array, '.png');
        array_push($this->file_extension_array, '.zip');
        array_push($this->file_extension_array, '.7z');
        array_push($this->file_extension_array, '.pdf');
        array_push($this->file_extension_array, '.bin');
        array_push($this->file_extension_array, '.txt');

        array_push($this->file_type_array, 'image/gif');
        array_push($this->file_type_array, 'image/jpg');
        array_push($this->file_type_array, 'image/jpeg');
        array_push($this->file_type_array, 'image/png');
        array_push($this->file_type_array, 'application/zip');
        array_push($this->file_type_array, 'application/x-7z-compressed');
        array_push($this->file_type_array, 'application/pdf');
        array_push($this->file_type_array, 'application/octet-stream');
        array_push($this->file_type_array, 'text/plain');

        array_push($this->banned_files, 'do_not_allow_me_1.txt');
        array_push($this->banned_files, 'do_not_allow_me_3.txt');
        array_push($this->banned_files, 'do_not_allow_me_2.txt');

        $file = $event->getFile();
        $file_extension = '.'. $file->getExtension();
        $file_mime_type = $file->getMimeType();

        $file_info = $ultra_helpers->filterFileInfoFromFilename($file->getClientOriginalName());
        $transliterated_file_name = $ultra_text->transliterateText($file_info['name']);
        $full_file_name = $transliterated_file_name .'.'. $file_info['extension'];

        if (in_array($full_file_name, $this->banned_files))
        {
            throw new ValidationException('error.file_exists');
        }

        // Is file mime type the same as extension mime type
        $mime_type_position = array_search($file_extension, $this->file_extension_array);
        if ($mime_type_position !== false)
        {
            $mime_type_by_extension = $this->file_type_array[$mime_type_position];

            if ($mime_type_by_extension !== $file_mime_type)
            {
                throw new ValidationException('error.mime_type_mismatch');
            }
        }

        // Is file type not in activated file type array
        if (!in_array($file_mime_type, $this->file_type_array))
        {
            throw new ValidationException('error.forbidden_mime_type');
        }
    }
}
</code>```

FINALLY

What am I missing?

CONCLUSION

Please advise.

Thank You for your time and knowledge.

答:
To show error in UI one has to listen to FileUploaded event and manually trigger an error (like in code example below).

```<code>$uploader.bind('FileUploaded', function(up, file, info)
{
    var response;
    response = jQuery.parseJSON(info.response);

    // trigger error manually
    up.trigger("error", {message: "Test error message", code: 12345, details: "Testing errors"});

    // add some CSS class to the corresponding file in UI
    $("#"+ file.id).addClass("highlight-file");
});
</code>```

Body:
INTRODUCTION

In order to upload multiple files to the server I am using:

Symfony v3.2.6

OneUpUploaderBundle

OneUpFlysystemBundle

Plupload file uploading library

NOTE

Please note that: this configuration works without a hitch for single and multiple file uploads. It just does not show custom server errors in the clients browser.

TARGET

I would like to show file exists error in UI

PROBLEM

I am using validator to restrict some uploadable files.

At the moment files that validator restricts are not uploaded (ValidationException is beeing trown).

I do not know how to make Plupload to show file already exist errors.

CODE

My template with relevant javascript code

{% extends 'base.html.twig' %}

{% block stylesheets %}
    {{ parent() }}
    <link type="text/css" rel="stylesheet" href="{{ asset('js/plupload/jquery-ui-1.12.1/jquery-ui.css') }}" />
    <link type="text/css" rel="stylesheet" href="{{ asset('js/plupload/jquery.ui.plupload/css/jquery.ui.plupload.css') }}" media="screen" />
{% endblock %}

{% block content %}

Your browser doesn't have HTML5 support.

{% endblock %}

{% block javascripts %}

{% endblock %}

My validator

<?php

namespace AppBundle\EventListener;

use Oneup\UploaderBundle\Event\ValidationEvent;
use Oneup\UploaderBundle\Uploader\Exception\ValidationException;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;

class AllowedMimeTypeValidationListener
{
    /**
     * @var Container
     */
    private $container;

    private $file_extension_array = [];
    private $file_type_array = [];
    private $banned_files = [];

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function onValidate(ValidationEvent $event)
    {
        $ultra_helpers = $this->container->get('app.ultra_helpers');
        $ultra_text = $this->container->get('app.ultra_text');

        array_push($this->file_extension_array, '.gif');
        array_push($this->file_extension_array, '.jpg');
        array_push($this->file_extension_array, '.jpeg');
        array_push($this->file_extension_array, '.png');
        array_push($this->file_extension_array, '.zip');
        array_push($this->file_extension_array, '.7z');
        array_push($this->file_extension_array, '.pdf');
        array_push($this->file_extension_array, '.bin');
        array_push($this->file_extension_array, '.txt');

        array_push($this->file_type_array, 'image/gif');
        array_push($this->file_type_array, 'image/jpg');
        array_push($this->file_type_array, 'image/jpeg');
        array_push($this->file_type_array, 'image/png');
        array_push($this->file_type_array, 'application/zip');
        array_push($this->file_type_array, 'application/x-7z-compressed');
        array_push($this->file_type_array, 'application/pdf');
        array_push($this->file_type_array, 'application/octet-stream');
        array_push($this->file_type_array, 'text/plain');

        array_push($this->banned_files, 'do_not_allow_me_1.txt');
        array_push($this->banned_files, 'do_not_allow_me_3.txt');
        array_push($this->banned_files, 'do_not_allow_me_2.txt');

        $file = $event->getFile();
        $file_extension = '.'. $file->getExtension();
        $file_mime_type = $file->getMimeType();

        $file_info = $ultra_helpers->filterFileInfoFromFilename($file->getClientOriginalName());
        $transliterated_file_name = $ultra_text->transliterateText($file_info['name']);
        $full_file_name = $transliterated_file_name .'.'. $file_info['extension'];

        if (in_array($full_file_name, $this->banned_files))
        {
            throw new ValidationException('error.file_exists');
        }

        // Is file mime type the same as extension mime type
        $mime_type_position = array_search($file_extension, $this->file_extension_array);
        if ($mime_type_position !== false)
        {
            $mime_type_by_extension = $this->file_type_array[$mime_type_position];

            if ($mime_type_by_extension !== $file_mime_type)
            {
                throw new ValidationException('error.mime_type_mismatch');
            }
        }

        // Is file type not in activated file type array
        if (!in_array($file_mime_type, $this->file_type_array))
        {
            throw new ValidationException('error.forbidden_mime_type');
        }
    }
}

FINALLY

What am I missing?

CONCLUSION

Please advise.

Thank You for your time and knowledge.

Body:
To show error in UI one has to listen to FileUploaded event and manually trigger an error (like in code example below).

$uploader.bind('FileUploaded', function(up, file, info)
{
    var response;
    response = jQuery.parseJSON(info.response);

    // trigger error manually
    up.trigger("error", {message: "Test error message", code: 12345, details: "Testing errors"});

    // add some CSS class to the corresponding file in UI
    $("#"+ file.id).addClass("highlight-file");
});


来源: stackexchange

问:
Calling JSF ManageBean after PageLoad using f:event postAddToView
I am writing an app using JSF 2.0.

For one of the page, there is a section of the page that takes a long time to display.

To improve the  user experience, I am thinking to load the page first and then automatically do an Ajax call back to the JSF manage bean object once the page is loaded successfully after 1st load.

I am thinking to use f:event with type postAddView.

```<code><h:outputText id="dummyId">
    <f:event type="postAddToView" listener="#{mngBean.doSomething}" />
</h:outputText>
</code>```

However it seems like f:event postAddToView is still being processed before the page is displayed for the first time.

The other options that I have explore is to create a hidden button and get javascript to trigger it. It works however I am just wondering if there is a nice JSF component/event that can do this instead of using java script.

Thanks for your help.

```<code><h:commandButton id="dmyButton"
</code>```

value="#{mngBean.getSomething}"
 actionListener="#{mngBean.doSomething}"
 style="display: none"
 type="submit">

Java Script

```<code><script language="JavaScript">
 $(document).ready(function() {
  if (document.getElementById('form:dmyButton').value == 'true') {
   document.getElementById('form:dmyButton').click();
  }

 });
</script>
</code>```

Thanks for all your help in advance

答:
I think the PreRenderViewEvent is what you want.

http://javaserverfaces.java.net/nonav/docs/2.0/javadocs/javax/faces/event/PreRenderViewEvent.html

Though the docs don't show it, the preRenderViewEvent does work with f:event.  I'll fix the docs presently.

ContentLicense: CC BY-SA 2.5

Body:
I am writing an app using JSF 2.0.

For one of the page, there is a section of the page that takes a long time to display.

To improve the  user experience, I am thinking to load the page first and then automatically do an Ajax call back to the JSF manage bean object once the page is loaded successfully after 1st load.

I am thinking to use f:event with type postAddView.

<h:outputText id="dummyId">
    <f:event type="postAddToView" listener="#{mngBean.doSomething}" />
</h:outputText>

However it seems like f:event postAddToView is still being processed before the page is displayed for the first time.

The other options that I have explore is to create a hidden button and get javascript to trigger it. It works however I am just wondering if there is a nice JSF component/event that can do this instead of using java script.

Thanks for your help.

<h:commandButton id="dmyButton"

value="#{mngBean.getSomething}"
 actionListener="#{mngBean.doSomething}"
 style="display: none"
 type="submit">

Java Script

Thanks for all your help in advance

ContentLicense: CC BY-SA 3.0


问:
Apply `class` to a list column of a data table
Consider this data table:

```<code>library(data.table)
DT <- data.table(A = c("a", "b", "c"),
                 B = list(1, "x", "y"),
                 key = "A")
str(DT)
## Classes 'data.table' and 'data.frame':   3 obs. of  2 variables:
##  $ A: chr  "a" "b" "c"
##  $ B:List of 3
##   ..$ : num 1
##   ..$ : chr "x"
##   ..$ : chr "y"
##  - attr(*, "sorted")= chr "A"
##  - attr(*, ".internal.selfref")=<externalptr>
</code>```

Can someone explain why the second action below always returns numeric? (I expected numeric character character).

```<code>DT[, `:=`(C=class(B))]
DT # ok
##    A B    C
## 1: a 1 list
## 2: b x list
## 3: c y list
DT[, `:=`(C=class(B[[1]]))]
DT # why ??
##    A B       C
## 1: a 1 numeric
## 2: b x numeric
## 3: c y numeric
DT[, `:=`(C=sapply(B, class))]
DT # ok
##    A B         C
## 1: a 1   numeric
## 2: b x character
## 3: c y character
</code>```

答:
Here is another way to get the same output as with sapply

```<code>DT[, C := unlist(lapply(B, class))]
</code>```

The reason for second case to output all numeric class is because we are finding the class of the first list element which is numeric and assigning (:=) it to the whole column.

Body:
Consider this data table:

library(data.table)
DT <- data.table(A = c("a", "b", "c"),
                 B = list(1, "x", "y"),
                 key = "A")
str(DT)
## Classes 'data.table' and 'data.frame':   3 obs. of  2 variables:
##  $ A: chr  "a" "b" "c"
##  $ B:List of 3
##   ..$ : num 1
##   ..$ : chr "x"
##   ..$ : chr "y"
##  - attr(*, "sorted")= chr "A"
##  - attr(*, ".internal.selfref")=<externalptr>

Can someone explain why the second action below always returns numeric? (I expected numeric character character).

DT[, `:=`(C=class(B))]
DT # ok
##    A B    C
## 1: a 1 list
## 2: b x list
## 3: c y list
DT[, `:=`(C=class(B[[1]]))]
DT # why ??
##    A B       C
## 1: a 1 numeric
## 2: b x numeric
## 3: c y numeric
DT[, `:=`(C=sapply(B, class))]
DT # ok
##    A B         C
## 1: a 1   numeric
## 2: b x character
## 3: c y character

Body:
Here is another way to get the same output as with sapply

DT[, C := unlist(lapply(B, class))]

The reason for second case to output all numeric class is because we are finding the class of the first list element which is numeric and assigning (:=) it to the whole column.


问:
Can't vertically center text in a table cell
I'm creating a website for a school project using HTML and CSS. In the header there is a table and I need a text (which is inside a cell) to be aligned on the vertical center and on the horizontal right.

This is the HTML code

```<code><table id="intestazione">
........
    <tr>
        <td class="centerV"><h1>Text</h1></td>
        <td><img src="Logo.jpg"></td>
    </tr>
</table>
</code>```

and this is the CSS code

```<code>h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;
    text-align:right;
}
.centerV
{
    display:table-cell;
    vertical-align:middle;
}
</code>```

but it doesn't work as I want, so I changed the CSS code into

```<code>h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;

    display:table-cell;
    vertical-align:middle;
    text-align:right;
}
</code>```

and the text is vertically centered, but not on the right (it is on the left). I've read that I can use line-height or a padding on the top, but in my opinion it is more clean and elegant to use vertical-align (tell me if I am wrong).

I tried also other code from suggestions on the web but I don't write it otherwise the question will be too long.

答:
you can use :
 position : relative;
 right : value%;
 (or left:value%)
as you like ..

check this

```<code><table id="intestazione" border="1">
<tr>
    <td class="centerV"><h1>Text</h1></td>
    <td><img src="http://www.sec4ever.com/home/images/misc/noavatar.gif"></td>

</tr>
</code>```

```<code>h1{
font-family:Arial;
font-size:50px;
color:#009ED9;
display:table-cell;
padding:100px;
vertical-align:middle;
position:relative;
right:30%; }
</code>```

Body:
I'm creating a website for a school project using HTML and CSS. In the header there is a table and I need a text (which is inside a cell) to be aligned on the vertical center and on the horizontal right.

This is the HTML code

........

Text

and this is the CSS code

h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;
    text-align:right;
}
.centerV
{
    display:table-cell;
    vertical-align:middle;
}

but it doesn't work as I want, so I changed the CSS code into

h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;

    display:table-cell;
    vertical-align:middle;
    text-align:right;
}

and the text is vertically centered, but not on the right (it is on the left). I've read that I can use line-height or a padding on the top, but in my opinion it is more clean and elegant to use vertical-align (tell me if I am wrong).

I tried also other code from suggestions on the web but I don't write it otherwise the question will be too long.

Body:
you can use :
 position : relative;
 right : value%;
 (or left:value%)
as you like ..

check this

<table id="intestazione" border="1">
<tr>
    <td class="centerV"><h1>Text</h1></td>
    <td><img src="http://www.sec4ever.com/home/images/misc/noavatar.gif"></td>

</tr>

h1{
font-family:Arial;
font-size:50px;
color:#009ED9;
display:table-cell;
padding:100px;
vertical-align:middle;
position:relative;
right:30%; }


问:
Can anyone provide me Magento2 Documents that from where i can learn to develop modules for Magento2
I am new to Magento2 but have experience in Magento. But found that structure of Magento2 is completly different. So can anyone provide me magento2 document that how to create module in Magento2.

Thank you

答:
At the very basic, a new Magento2 module requires three files.

```<code> /etc/module.xml
 composer.json
 registration.php
</code>```

I have always created my modules in the /app/code folder, in which case you would create a Vendor folder (using a name of your choosing) and then within that a Module folder (again, with a name of your choosing). For example, the full path would be /app/code/VendorName/ModuleName.

Within the module folder, add one additional folder called /etc.

With the folder structure created, you simply need to add the contents of the three files, replacing VendorName and ModuleName with the names you set above.

/app/code/VendorName/ModuleName/etc/module.xml

```<code><?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="VendorName_ModuleName" setup_version="0.1.0" />
</config>
</code>```

/app/code/VendorName/ModuleName/composer.json

```<code>{
    "name": "vendorname/module-modulename",
    "description": "",
    "type": "magento2-module",
    "version": "0.1.0",
    "license": [],
    "require": {
        "php": "~5.6.0",
        "magento/magento-composer-installer": "*"
    },
    "extra": {
        "map": [
            [
                "*",
                "VendorName/ModuleName"
            ]
        ]
    }
}
</code>```

/app/code/VendorName/ModuleName/registration.php

```<code><?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'VendorName_ModuleName',
    __DIR__
);
</code>```

With those three files in place, the final step is to register the module with Magento by running bin/magento setup:upgrade on the command line in the root of your Magento installation.

After that, you should see your module listed in bin/magento module:status or "Stores > Configuration > Advanced > Advanced" on the backend.

From there you can start adding Controllers, Models, Observers, Plugins, etc. A quick web search should surface a bunch of tutorials for creating more useful modules, but you should certainly visit the official Magento2 documentation as a start.

Body:
At the very basic, a new Magento2 module requires three files.

 /etc/module.xml
 composer.json
 registration.php

I have always created my modules in the /app/code folder, in which case you would create a Vendor folder (using a name of your choosing) and then within that a Module folder (again, with a name of your choosing). For example, the full path would be /app/code/VendorName/ModuleName.

Within the module folder, add one additional folder called /etc.

With the folder structure created, you simply need to add the contents of the three files, replacing VendorName and ModuleName with the names you set above.

/app/code/VendorName/ModuleName/etc/module.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="VendorName_ModuleName" setup_version="0.1.0" />
</config>

/app/code/VendorName/ModuleName/composer.json

{
    "name": "vendorname/module-modulename",
    "description": "",
    "type": "magento2-module",
    "version": "0.1.0",
    "license": [],
    "require": {
        "php": "~5.6.0",
        "magento/magento-composer-installer": "*"
    },
    "extra": {
        "map": [
            [
                "*",
                "VendorName/ModuleName"
            ]
        ]
    }
}

/app/code/VendorName/ModuleName/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'VendorName_ModuleName',
    __DIR__
);

With those three files in place, the final step is to register the module with Magento by running bin/magento setup:upgrade on the command line in the root of your Magento installation.

After that, you should see your module listed in bin/magento module:status or "Stores > Configuration > Advanced > Advanced" on the backend.

From there you can start adding Controllers, Models, Observers, Plugins, etc. A quick web search should surface a bunch of tutorials for creating more useful modules, but you should certainly visit the official Magento2 documentation as a start.


问:
How to plot a legend on matplotlib?
I have plotted a graph on matplotlib and am trying to create a legend. How do i get matplotlib to create its own legend using the colour markers it has used to differentiate my types of data?

My data is read from a csv file that contains the labels for each type of shape.

My code looks like this:

```<code>data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv")
    X1 = np.array(data_df[features2].values)
    y1 = np.array(data_df[features3].values)

    plt.scatter(X1[:, 0],y1, c=y, cmap=plt.cm.Paired)
    plt.axis([0, 17, 0, 200])
    plt.ylabel("Maximum Angle (Degrees)")
    plt.xlabel("Number Of Sides")
    plt.title('Original 450 Test Shapes')

    plt.legend()
    plt.show()
</code>```

I have tried this:

```<code>handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)
</code>```

But I keep getting this error:

```<code>    handles, labels = ax.get_legend_handles_labels()
UnboundLocalError: local variable 'ax' referenced before assignment
</code>```

EDIT:

I tried this:

```<code>features_of_labels = ["Circle", "Equilateral Triangle", "Right Angle Triangle",
                     "Obtuse Triangle", "Acute Triangle", "Square", "Rectangle",
                     "Parallelogram", "Seal"]

data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv")
X1 = np.array(data_df[features2].values)
y1 = np.array(data_df[features3].values)
l = np.array(data_df[features_of_labels].values)
</code>```

But i get the following error:
    KeyError: "['Circle' 'Equilateral Triangle' 'Right Angle Triangle' 'Obtuse Triangle'\n 'Acute Triangle' 'Square' 'Rectangle' 'Parallelogram' 'Seal'] not in index"

However if i change features_of_labels to header and header = ["Label"] it works but prints out every label like shown in the next picture.

答:
Here is an example:

```<code>import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

# data for example
y1 = [i for i in range(10)]
y2 = [i for i in range(10)]
colors = ['m','b','g','m','b','g','m','b','g','g']
lables = ['m','b','g','m','b','g','m','b','g','g']

plt.scatter(y1, y2,c=colors, cmap=plt.cm.Paired)

# Match colors and labels，remove duplicates
colors_lables = zip(colors, lables)
colors_lables = list(set(colors_lables))
lables = [lable for color,lable in colors_lables]

# create some patchs of colors
lables_patchs = []
for item in c_l:
    add_patch = mpatches.Patch(color=item[0], label=item[1])
    lables_patchs.append(add_patch)

plt.legend(lables_patchs, lables)

plt.show()
</code>```

And the picture we get:

You can match your colors and lables,remove duplicates,and create some patchs of colors for your legend.

Further more,you can make some dot of colors for your legend

```<code>lables_patchs = []
for item in c_l:
    # here, use scatter()
    add_patch = plt.scatter([],[],color=item[0], label=item[1])
    lables_patchs.append(add_patch)
</code>```

And you will get :

Title: How to plot a legend on matplotlib?

Body:
I have plotted a graph on matplotlib and am trying to create a legend. How do i get matplotlib to create its own legend using the colour markers it has used to differentiate my types of data?

My data is read from a csv file that contains the labels for each type of shape.

My code looks like this:

data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv")
    X1 = np.array(data_df[features2].values)
    y1 = np.array(data_df[features3].values)

    plt.scatter(X1[:, 0],y1, c=y, cmap=plt.cm.Paired)
    plt.axis([0, 17, 0, 200])
    plt.ylabel("Maximum Angle (Degrees)")
    plt.xlabel("Number Of Sides")
    plt.title('Original 450 Test Shapes')

    plt.legend()
    plt.show()

I have tried this:

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)

But I keep getting this error:

    handles, labels = ax.get_legend_handles_labels()
UnboundLocalError: local variable 'ax' referenced before assignment

EDIT:

I tried this:

features_of_labels = ["Circle", "Equilateral Triangle", "Right Angle Triangle",
                     "Obtuse Triangle", "Acute Triangle", "Square", "Rectangle",
                     "Parallelogram", "Seal"]

data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv")
X1 = np.array(data_df[features2].values)
y1 = np.array(data_df[features3].values)
l = np.array(data_df[features_of_labels].values)

But i get the following error:
    KeyError: "['Circle' 'Equilateral Triangle' 'Right Angle Triangle' 'Obtuse Triangle'\n 'Acute Triangle' 'Square' 'Rectangle' 'Parallelogram' 'Seal'] not in index"

However if i change features_of_labels to header and header = ["Label"] it works but prints out every label like shown in the next picture.

Body:
Here is an example:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

# data for example
y1 = [i for i in range(10)]
y2 = [i for i in range(10)]
colors = ['m','b','g','m','b','g','m','b','g','g']
lables = ['m','b','g','m','b','g','m','b','g','g']

plt.scatter(y1, y2,c=colors, cmap=plt.cm.Paired)

# Match colors and labels，remove duplicates
colors_lables = zip(colors, lables)
colors_lables = list(set(colors_lables))
lables = [lable for color,lable in colors_lables]

# create some patchs of colors
lables_patchs = []
for item in c_l:
    add_patch = mpatches.Patch(color=item[0], label=item[1])
    lables_patchs.append(add_patch)

plt.legend(lables_patchs, lables)

plt.show()

And the picture we get:

You can match your colors and lables,remove duplicates,and create some patchs of colors for your legend.

Further more,you can make some dot of colors for your legend

lables_patchs = []
for item in c_l:
    # here, use scatter()
    add_patch = plt.scatter([],[],color=item[0], label=item[1])
    lables_patchs.append(add_patch)

And you will get :


问:
Animating a div with CSS animations with a slight delay between two
What I am trying to do is basically a notification bar which I want to show and hide with CSS animation. The problem is I am not being able to make a good amount of delay between the occurring of two animations.

HTML

```<code><div id="notification" class="alert" role="alert"></div>
</code>```

JS

```<code>$('#notification').html('This place is already occupied!').addClass('alert-warning animated bounceInDown').show().delay(5000).addClass('bounceOutUp');
</code>```

CSS

```<code>#notification {
    position: fixed;
    top: 5px;
    border-radius: 0;
    width: 100%;
    display: none;
    z-index: 1200 !important;
}
.animated {
    -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
}
@-webkit-keyframes bounceInDown {
    from, 60%, 75%, 90%, to {
        -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
        animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    }
    0% {
        opacity: 0;
        -webkit-transform: translate3d(0, -3000px, 0);
        transform: translate3d(0, -3000px, 0);
    }
    60% {
        opacity: 1;
        -webkit-transform: translate3d(0, 25px, 0);
        transform: translate3d(0, 25px, 0);
    }
    75% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    90% {
        -webkit-transform: translate3d(0, 5px, 0);
        transform: translate3d(0, 5px, 0);
    }
    to {
        -webkit-transform: none;
        transform: none;
    }
}
@keyframes bounceInDown {
    from, 60%, 75%, 90%, to {
        -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
        animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    }
    0% {
        opacity: 0;
        -webkit-transform: translate3d(0, -3000px, 0);
        transform: translate3d(0, -3000px, 0);
    }
    60% {
        opacity: 1;
        -webkit-transform: translate3d(0, 25px, 0);
        transform: translate3d(0, 25px, 0);
    }
    75% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    90% {
        -webkit-transform: translate3d(0, 5px, 0);
        transform: translate3d(0, 5px, 0);
    }
    to {
        -webkit-transform: none;
        transform: none;
    }
}
.bounceInDown {
    -webkit-animation-name: bounceInDown;
    animation-name: bounceInDown;
}
@-webkit-keyframes bounceOutUp {
    20% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    40%, 45% {
        opacity: 1;
        -webkit-transform: translate3d(0, 20px, 0);
        transform: translate3d(0, 20px, 0);
    }
    to {
        opacity: 0;
        -webkit-transform: translate3d(0, -2000px, 0);
        transform: translate3d(0, -2000px, 0);
    }
}
@keyframes bounceOutUp {
    20% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    40%, 45% {
        opacity: 1;
        -webkit-transform: translate3d(0, 20px, 0);
        transform: translate3d(0, 20px, 0);
    }
    to {
        opacity: 0;
        -webkit-transform: translate3d(0, -2000px, 0);
        transform: translate3d(0, -2000px, 0);
    }
}
.bounceOutUp {
    -webkit-animation-name: bounceOutUp;
    animation-name: bounceOutUp;
}
</code>```

答:
Dont know if i understand you correctly, but you can make delay with css:</p>

```<code>div {
    -webkit-animation-delay: 2s; /* Safari 4.0 - 8.0 */
    animation-delay: 2s;
}
</code>```

Body:
What I am trying to do is basically a notification bar which I want to show and hide with CSS animation. The problem is I am not being able to make a good amount of delay between the occurring of two animations.

HTML

JS

$('#notification').html('This place is already occupied!').addClass('alert-warning animated bounceInDown').show().delay(5000).addClass('bounceOutUp');

CSS

#notification {
    position: fixed;
    top: 5px;
    border-radius: 0;
    width: 100%;
    display: none;
    z-index: 1200 !important;
}
.animated {
    -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
}
@-webkit-keyframes bounceInDown {
    from, 60%, 75%, 90%, to {
        -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
        animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    }
    0% {
        opacity: 0;
        -webkit-transform: translate3d(0, -3000px, 0);
        transform: translate3d(0, -3000px, 0);
    }
    60% {
        opacity: 1;
        -webkit-transform: translate3d(0, 25px, 0);
        transform: translate3d(0, 25px, 0);
    }
    75% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    90% {
        -webkit-transform: translate3d(0, 5px, 0);
        transform: translate3d(0, 5px, 0);
    }
    to {
        -webkit-transform: none;
        transform: none;
    }
}
@keyframes bounceInDown {
    from, 60%, 75%, 90%, to {
        -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
        animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    }
    0% {
        opacity: 0;
        -webkit-transform: translate3d(0, -3000px, 0);
        transform: translate3d(0, -3000px, 0);
    }
    60% {
        opacity: 1;
        -webkit-transform: translate3d(0, 25px, 0);
        transform: translate3d(0, 25px, 0);
    }
    75% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    90% {
        -webkit-transform: translate3d(0, 5px, 0);
        transform: translate3d(0, 5px, 0);
    }
    to {
        -webkit-transform: none;
        transform: none;
    }
}
.bounceInDown {
    -webkit-animation-name: bounceInDown;
    animation-name: bounceInDown;
}
@-webkit-keyframes bounceOutUp {
    20% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    40%, 45% {
        opacity: 1;
        -webkit-transform: translate3d(0, 20px, 0);
        transform: translate3d(0, 20px, 0);
    }
    to {
        opacity: 0;
        -webkit-transform: translate3d(0, -2000px, 0);
        transform: translate3d(0, -2000px, 0);
    }
}
@keyframes bounceOutUp {
    20% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    40%, 45% {
        opacity: 1;
        -webkit-transform: translate3d(0, 20px, 0);
        transform: translate3d(0, 20px, 0);
    }
    to {
        opacity: 0;
        -webkit-transform: translate3d(0, -2000px, 0);
        transform: translate3d(0, -2000px, 0);
    }
}
.bounceOutUp {
    -webkit-animation-name: bounceOutUp;
    animation-name: bounceOutUp;
}

Body:
Dont know if i understand you correctly, but you can make delay with css:

div {
    -webkit-animation-delay: 2s; /* Safari 4.0 - 8.0 */
    animation-delay: 2s;
}


问:
How to check java-script,which is in JSP function output in java servlet file or scriptlets
Here my aim is to submit this form to servlet, which will built process DB query. I have validated the mail using javascript. Normally when i click submit it will validate email and prompt user for false format of mail and simultaneously  pass to servlet all information which make query and insert into DB. But the validation of mail gives false mail.
So how can i pass javascript function value to servlet to to validate first and then built query and insert into database?
We can use Scriptlet also.

Javascript:

```<code><script>
    function ValidateEmail(inputText)
    {
        var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if(inputText.value.match(mailformat))
        {
            document.text1.focus();
            return true;
        }
        else
        {
            alert("You have entered an invalid email address!");
            document.text1.focus();
            return false;
        }
    }
</script>
</code>```

jsp:

```<code><input type="text" placeholder="Enter Email" name="email" required/><br/>
<button type="submit" name="xyz" onclick=ValidateEmail(email) class="signupbtn">Sign Up</button>
</code>```

Provide code snippet for solution.

答:
First declare an input type hidden field within form tag and give it id and name attribute like

```<code><input type="hidden" id="demo" name="valid">
</code>```

Next store value true or false in a js variable and put that variable value in hidden field that we earlier declared like

```<code><script>
function ValidateEmail(inputText)
{
var val;
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
document.text1.focus();
val=true;

}
else
{
alert("You have entered an invalid email address!");
document.text1.focus();
val=false;

}
document.getElementById("demo").value=val;
}
</code>```

After this in servlet declare a variable and get value from jsp of hidden field by its name attribute like

```<code>String value=request.getParameter("valid");
</code>```

Body:
Here my aim is to submit this form to servlet, which will built process DB query. I have validated the mail using javascript. Normally when i click submit it will validate email and prompt user for false format of mail and simultaneously  pass to servlet all information which make query and insert into DB. But the validation of mail gives false mail.
So how can i pass javascript function value to servlet to to validate first and then built query and insert into database?
We can use Scriptlet also.

Javascript:

jsp:

<input type="text" placeholder="Enter Email" name="email" required/>

<button type="submit" name="xyz" onclick=ValidateEmail(email) class="signupbtn">Sign Up</button>

Provide code snippet for solution.

Body:
First declare an input type hidden field within form tag and give it id and name attribute like

<input type="hidden" id="demo" name="valid">

Next store value true or false in a js variable and put that variable value in hidden field that we earlier declared like

<script>
function ValidateEmail(inputText)
{
var val;
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
document.text1.focus();
val=true;

}
else
{
alert("You have entered an invalid email address!");
document.text1.focus();
val=false;

}
document.getElementById("demo").value=val;
}

After this in servlet declare a variable and get value from jsp of hidden field by its name attribute like

String value=request.getParameter("valid");


问:
How to config Wildfly Server on OpenShift V3.x
So the problem I'm facing now is that I cannot find anyway to config WildFly server on OpenShift v3.x, because when the end of deploy processing it auto deploy welcome-content to the path "/", and it override to my "/" path.

I couldn't find anyway to get the standalone.xml of that server to modify. Any idea to fix it?

答:
The easiest way is source-to-image. Here can you found example images for wildfly. https://github.com/openshift-s2i/s2i-wildfly

You only have to add your standlone.xml under contrib/wfcfg/ in your git repo. Than deploy the s2i-wildfly with your git repo.

Here is a example for the first try. https://github.com/openshift/openshift-jee-sample


问:
Could not exec java with Spring+Maven exit code 1
I am new to Spring/Maven, and am following this tutorial:
Serving Web Content with Spring MVC.

Everytime I run mvn spring-boot:run, I get this error:

Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.2.RELEASE:run (default-cli) on project gs-serving-web-content: Could not exec java: Application finished with exit code: 1 ->

I tried to add classpath, tried to run mvn install clean spring-boot:run, did a lot of other things that people suggested on stackoverflow in similar situations, spent on this more than 8 hours - no use.

Here is my main class Application.java:

```<code>package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception{
        SpringApplication.run(Application.class, args);
    }
}
</code>```

Here is my GreeetingController.java class:

```<code>package hello;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }

}
</code>```

Here is my pom.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-serving-web-content</artifactId>
    <version>0.1.0</version>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- Exclusions to allow SpringBoot execute on HCP -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.tomcat.embed</groupId>
                    <artifactId>tomcat-embed-el</artifactId>
                </exclusion>
                <exclusion>
                    <artifactId>logback-classic</artifactId>
                    <groupId>ch.qos.logback</groupId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

    <properties>
        <java.version>1.8</java.version>
        <!-- The main class to start by executing java -jar -->

    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                                    <mainClass>hello.Application</mainClass>

        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
            </manifest>
        </archive>
    </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Here is my HTML template:

```<code><!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
</code>```

The structure of a project is

```<code>src/main/java/hello/pom.xml
src/main/java/hello/Application.java
src/main/java/hello/GreetingController.java
src/main/resources/templates/greeting.html
</code>```

答:
I made the following changes to make mvn clean spring-boot:run work:

Move pom.xml to the root directory, which makes the directory hierarchy to be:

Directory hierarchy:

```<code>.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── hello
        │       ├── Application.java
        │       └── GreetingController.java
        └── resources
            └── templates
                └── greeting.html
</code>```

Commented out the exclusions in the following part:

Commented out part:

```<code><dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <!-- Exclusions to allow SpringBoot execute on HCP -->
        <!--<exclusions>-->
            <!--<exclusion>-->
                <!--<groupId>org.springframework.boot</groupId>-->
                <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
            <!--</exclusion>-->
            <!--<exclusion>-->
                <!--<groupId>org.apache.tomcat.embed</groupId>-->
                <!--<artifactId>tomcat-embed-el</artifactId>-->
            <!--</exclusion>-->
            <!--<exclusion>-->
                <!--<artifactId>logback-classic</artifactId>-->
                <!--<groupId>ch.qos.logback</groupId>-->
            <!--</exclusion>-->
        <!--</exclusions>-->
    </dependency>
</code>```

It seems you meant to exclude those dependencies. mvn clean spring-boot:run will just exit successfully if the embed tomcat is excluded, but I think this is the correct behave because there's no container to deploy the application. Anyway, you can try it out and make changes according your requirements.

Body:
I am new to Spring/Maven, and am following this tutorial:
Serving Web Content with Spring MVC.

Everytime I run mvn spring-boot:run, I get this error:

Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.2.RELEASE:run (default-cli) on project gs-serving-web-content: Could not exec java: Application finished with exit code: 1 ->

I tried to add classpath, tried to run mvn install clean spring-boot:run, did a lot of other things that people suggested on stackoverflow in similar situations, spent on this more than 8 hours - no use.

Here is my main class Application.java:

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception{
        SpringApplication.run(Application.class, args);
    }
}

Here is my GreeetingController.java class:

package hello;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }

}

Here is my pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-serving-web-content</artifactId>
    <version>0.1.0</version>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>

            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.tomcat.embed</groupId>
                    <artifactId>tomcat-embed-el</artifactId>
                </exclusion>
                <exclusion>
                    <artifactId>logback-classic</artifactId>
                    <groupId>ch.qos.logback</groupId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

    <properties>
        <java.version>1.8</java.version>

    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                                    <mainClass>hello.Application</mainClass>

        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
            </manifest>
        </archive>
    </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Here is my HTML template:

<!DOCTYPE HTML>

    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

The structure of a project is

src/main/java/hello/pom.xml
src/main/java/hello/Application.java
src/main/java/hello/GreetingController.java
src/main/resources/templates/greeting.html

Body:
I made the following changes to make mvn clean spring-boot:run work:

Move pom.xml to the root directory, which makes the directory hierarchy to be:

Directory hierarchy:

.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── hello
        │       ├── Application.java
        │       └── GreetingController.java
        └── resources
            └── templates
                └── greeting.html

Commented out the exclusions in the following part:

Commented out part:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <!-- Exclusions to allow SpringBoot execute on HCP -->
        <!--<exclusions>-->
            <!--<exclusion>-->
                <!--<groupId>org.springframework.boot</groupId>-->
                <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
            <!--</exclusion>-->
            <!--<exclusion>-->
                <!--<groupId>org.apache.tomcat.embed</groupId>-->
                <!--<artifactId>tomcat-embed-el</artifactId>-->
            <!--</exclusion>-->
            <!--<exclusion>-->
                <!--<artifactId>logback-classic</artifactId>-->
                <!--<groupId>ch.qos.logback</groupId>-->
            <!--</exclusion>-->
        <!--</exclusions>-->
    </dependency>

It seems you meant to exclude those dependencies. mvn clean spring-boot:run will just exit successfully if the embed tomcat is excluded, but I think this is the correct behave because there's no container to deploy the application. Anyway, you can try it out and make changes according your requirements.

ContentLicense: CC BY-SA 4.0


问:
Autoclick an onclick event every often
I wanted to make a script to click automatically on that onclick element "training.start_training(50)", but couldn't figure it out how to.

This is the code from the page I want the autoclick:

```<code><td style="text-align:center"><img src="/y/training/train.png" onclick="training.start_training(50)" style="cursor:pointer" /></td>
</code>```

And this comes before it, but I don't know if it's actually useful to do this:

form id="trainform" action="" method="post"
input id="trainid" name="trainid" type="hidden" value="0" />

Thanks for the answers. Buuut, I don't know how to write a script, I tried several Frankenstein scripts on greasemonkey (joined several things, kept changing to see if it worked), but got nothing. I don't know how to make an autoclick that clicks on that specified onclick (element?) "training.start_training(50)".

答:
You can give an id to that image tag or use javascript to get the element by tag name and trigger a click.   </p>

```<code> var img= document.getElementsByTagName("IMG")[0];
setInterval(function(){  img.click(); }, 1000);
</code>```

Title: Autoclick an onclick event every often

Body:
I wanted to make a script to click automatically on that onclick element "training.start_training(50)", but couldn't figure it out how to.

This is the code from the page I want the autoclick:

And this comes before it, but I don't know if it's actually useful to do this:

form id="trainform" action="" method="post"
input id="trainid" name="trainid" type="hidden" value="0" />

Thanks for the answers. Buuut, I don't know how to write a script, I tried several Frankenstein scripts on greasemonkey (joined several things, kept changing to see if it worked), but got nothing. I don't know how to make an autoclick that clicks on that specified onclick (element?) "training.start_training(50)".

Body:
You can give an id to that image tag or use javascript to get the element by tag name and trigger a click.

 var img= document.getElementsByTagName("IMG")[0];
setInterval(function(){  img.click(); }, 1000);


问:
Authenticating new users through mail?
so I have a table of users in my database in phpmyadmin for a website. This users table has an auto-incremented id, mail, firstname, lastname, hash(for password) and authentication_state. I want to be able to send a mail to new users that includes a link and that link makes authentication_state go from 0(the default value) to 1 wherein he is authenticated. How would I go about doing this?

Thanks in advance.

答:
Suggestion:

A better design would be to create a temporary users table lets call it temp_users. Whenever a user registers in your website the data will go to this table instead of your actual users table. Once the user clicks the link sent to the email address you can move the data from the temp_users table to users table. You can run a scheduler once every 24 hours or so and remove the accounts that were registered 48 hours ago but have not been verified yet. I personally feel this is a better implementation.

Now coming to your actual question:

Add one more column to the users table. Lets call it as hash_code. Whenever a new user registered compute a random series of digits or letter. MD5 encryption on timestamp is one example you can use. Along with the actual user data insert the computed hash to the table. Then send an email to the user's email, something like

```<code> www.example.com/verify.php?hashcode=<The computed hash code here>&email=<email registered>
</code>```

When the user clicks on the link he lands in the verify.php page.

In verify.php using $_GET to get the hashcode value and email value from the URL. Now fire an sql on your database for example,

```<code>SELECT COUNT(1) FROM users WHERE email=<VALUE FROM $_GET['email']> AND hash_code=<Value from $_GET['hashcode'];
</code>```

If the SQL returns 1 then you can fire an update on the table to turn verified flag to true. If you are using a temporary table like I talked about in the beginning, You will do a select on the temporary table and insert those values to the permanent one.

Title: Authenticating new users through mail?

Body:
Suggestion:

A better design would be to create a temporary users table lets call it temp_users. Whenever a user registers in your website the data will go to this table instead of your actual users table. Once the user clicks the link sent to the email address you can move the data from the temp_users table to users table. You can run a scheduler once every 24 hours or so and remove the accounts that were registered 48 hours ago but have not been verified yet. I personally feel this is a better implementation.

Now coming to your actual question:

Add one more column to the users table. Lets call it as hash_code. Whenever a new user registered compute a random series of digits or letter. MD5 encryption on timestamp is one example you can use. Along with the actual user data insert the computed hash to the table. Then send an email to the user's email, something like

 www.example.com/verify.php?hashcode=<The computed hash code here>&email=<email registered>

When the user clicks on the link he lands in the verify.php page.

In verify.php using $_GET to get the hashcode value and email value from the URL. Now fire an sql on your database for example,

SELECT COUNT(1) FROM users WHERE email=<VALUE FROM $_GET['email']> AND hash_code=<Value from $_GET['hashcode'];

If the SQL returns 1 then you can fire an update on the table to turn verified flag to true. If you are using a temporary table like I talked about in the beginning, You will do a select on the temporary table and insert those values to the permanent one.


问:
Installing magento 2 with magento-vagrant failing
I am trying to install magento 2 on my PC running Windows 7 , with the help of magento-vagrant ( https://github.com/paliarush/magento2-vagrant-for-developers )

At the step where is says to enter 'bash init_project.sh' I get the following errors:

[2017-04-01 16:06:14] STATUS: Checking requirements [/w/projets/shoptest.dev/vagrant-magento/scripts/host/check_requirements.sh]]
  [2017-04-01 16:06:14] STATUS: Installing missing vagrant plugins [init_project.sh]]
  [2017-04-01 16:06:16] STATUS: Generating random IP address, and host name to prevent collisions (if no custom values specified) [init_project.sh]]
  [2017-04-01 16:06:17] STATUS: Configuring git for Windows host [init_project.sh]]
  [2017-04-01 16:06:18] STATUS: Checking out CE repository [init_project.sh]]
  [2017-04-01 16:06:20] ERROR: Permission denied (publickey).
  fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository
  exists. [Unknown source file]] error: Permission denied (publickey).
  fatal: Could not read from remote repository.
  Please make sure you have the correct access rights and the repository
  exists.

I have checked that my C:/users/username/.ssh folder has the public keys : correct

I have checked that when I run "ssh-add -l" I have an output of various numbers and letters mexed together. Correct.

I have added the SSH key to the ssh agentby running "ssh-add ~/.ssh/id_rsa" Correct, done.

I have copied the key to paste it in my "settings > ssh and pgp keys " category, in the SSH key field, on GitHub.com. Done.

The key icon inside my githubt account turned green and the message:

"Last used within the last day"

appeared after doing bash init_project.sh

What should I do ? I'm lost and don't know much about github and ssh in general. Just followed the steps in the tutorials.

答:
It sounds like you haven't finished your git set-up, you have to configure the git client with your git username, and email:

```<code>    $ git config --global user.name "John Doe"
    $ git config --global user.email johndoe@example.com
</code>```

More details and additional git info at:
https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

Body:
It sounds like you haven't finished your git set-up, you have to configure the git client with your git username, and email:

    $ git config --global user.name "John Doe"
    $ git config --global user.email johndoe@example.com

More details and additional git info at:
https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration


问:
Generic async Retry with Timeout function in C#
I have hundreds of calls to various external API's that I want to wrap in a generic async function that is capable of doing retries and handling timeouts.

Basically, I think I need to implement something like this function call:

```<code>await Retry(()=>someFunctionAsync(doWorkParams, new CancellationToken()), retryCount, timeout);
</code>```

How do I define such Retry function?  Also, how do I call this function from Sync code, as a ton of my calls are housed in the sync methods?

答:
If you are still curious about how to do it without Policy it would be something like this:</p>

```<code>/// Untested code
static class Retry
{
    public static async Task<T> Run<T>(Func<CancellationToken, Task<T>> function, int retries, TimeSpan timeout)
    {
        Exception error = null;
        do
        {
            try
            {
                var cancellation = new CancellationTokenSource(timeout);
                return await function(cancellation.Token).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                error = ex;
            }

            retries--;
        }
        while (retries > 0);

        throw error;
    }

    public static async Task<T> Run<T>(Func<Task<T>> function, int retries, TimeSpan timeout)
    {
        Exception error = null;
        do
        {
            try
            {
                var timeoutTask = Task.Delay(timeout);
                var resultTask = function();

                await Task.WhenAny(resultTask, timeoutTask).ConfigureAwait(false);

                if (resultTask.Status == TaskStatus.RanToCompletion)
                    return resultTask.Result;
                else
                    error = new TimeoutException();
            }
            catch (Exception ex)
            {
                error = ex;
            }

            retries--;
        }
        while (retries > 0);

        throw error;
    }
}
</code>```

Body:
I have hundreds of calls to various external API's that I want to wrap in a generic async function that is capable of doing retries and handling timeouts.

Basically, I think I need to implement something like this function call:

await Retry(()=>someFunctionAsync(doWorkParams, new CancellationToken()), retryCount, timeout);

How do I define such Retry function?  Also, how do I call this function from Sync code, as a ton of my calls are housed in the sync methods?

Body:
If you are still curious about how to do it without Policy it would be something like this:

/// Untested code
static class Retry
{
    public static async Task<T> Run<T>(Func<CancellationToken, Task<T>> function, int retries, TimeSpan timeout)
    {
        Exception error = null;
        do
        {
            try
            {
                var cancellation = new CancellationTokenSource(timeout);
                return await function(cancellation.Token).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                error = ex;
            }

            retries--;
        }
        while (retries > 0);

        throw error;
    }

    public static async Task<T> Run<T>(Func<Task<T>> function, int retries, TimeSpan timeout)
    {
        Exception error = null;
        do
        {
            try
            {
                var timeoutTask = Task.Delay(timeout);
                var resultTask = function();

                await Task.WhenAny(resultTask, timeoutTask).ConfigureAwait(false);

                if (resultTask.Status == TaskStatus.RanToCompletion)
                    return resultTask.Result;
                else
                    error = new TimeoutException();
            }
            catch (Exception ex)
            {
                error = ex;
            }

            retries--;
        }
        while (retries > 0);

        throw error;
    }
}


问:
How to know if a point belongs more or less to a circle?
I know the formula to know if a point is inside, outside and on a circle : https://math.stackexchange.com/q/198769 This quote explains that we must compare d to r (please read the quote, it's only 5 lines).

But I just want to know if a point is ON a circle. Moreover, and that's the real problem : if a point is a bit inside/outside a circle, I want to consider it as ON the circle.

How could I do that ? I tried to delimit d-r (ie. : the comparison) in a range. Example :

if(d-r > -100 && d-r < 100) { point is on the circle }

It works, with -100 and 100, for circles with a little radius (ie. : ALL the points that are a bit outside/inside the circle are considered as being on the circle).

But for circles for a big radius, only SOME points are considered as being on the circle (ie. : only some of the points that are a bit outside/inside the circle are considered as being on the circle)...

So I would want that ALL the points that are a bit outside/inside the circle are considered as being on the circle, independently of the circle's radius. How ?

答:
Your comparison for absolute difference might be written shorter as

```<code>if Abs(d - r) < delta (i.e. 100) ...
</code>```

But seems you need relative difference depending on circle radius like this:

```<code>if Abs(d - r) / r  < reldelta (i.e. 0.001) ...
</code>```

Body:
Your comparison for absolute difference might be written shorter as

if Abs(d - r) < delta (i.e. 100) ...

But seems you need relative difference depending on circle radius like this:

if Abs(d - r) / r  < reldelta (i.e. 0.001) ...


问:
Why does .sort() actually change the variable?
I am learning Python and I came across the sort method and I want to understand why running sort.() actually changes the list and I don't have to reassign it? </p>

```<code>>>> list = [88,1,4,56,9,7,8,9]
>>> list
[88, 1, 4, 56, 9, 7, 8, 9]
>>> list.sort()
>>> list
[1, 4, 7, 8, 9, 9, 56, 88]
</code>```

答: .sort() is a method of the list class. which means when it is called is directly changes the list stored inside of the class.</p>

Body:
I am learning Python and I came across the sort method and I want to understand why running sort.() actually changes the list and I don't have to reassign it?

>>> list = [88,1,4,56,9,7,8,9]
>>> list
[88, 1, 4, 56, 9, 7, 8, 9]
>>> list.sort()
>>> list
[1, 4, 7, 8, 9, 9, 56, 88]


问:
jQuery - Issues with combining selectors in a single event handler
This is regarding Patrick DW's comment on my answer to this question.

Multiple selectors: identify the triggering one?

My Answer:

Using $(this) will get you the element that was clicked..  and using is() can help you determine what was clicked.

```<code>$('a.button, span.xyz, a.another').click(function(e) {
   if ($(this).is("a.button")) {
     alert("a.button was clicked");
   } else if ($(this).is("span.xyz")) {
     alert("span.xyz was clicked");
   } else if($(this).is("a.another")) {
     alert("a.another was clicked);
   }
});
</code>```

Patrick's Comments

Trouble with this is that it is effectively combining the inefficiency that .delegate() suffers (testing against a selector) with the inefficiency of assigning multiple redundant handlers. So you get the worst of both worlds.

@John - Yes, it would make more sense to break them up into separate handlers, and place any common functionality they share into a named function that can be called from within the handlers. This eliminates the need to run the .is() tests at every event occurrence, which can be costly. It can sometimes be beneficial to test for the element that was clicked. This is what .delegate() does. You suffer the expense of the test, but gain from the reduced number of handlers being assigned

Could someone explain (in detail) the inefficiencies that Patrick is talking about? Why is .is() costly in this scenario? Can you give an example as well using .delegate()

答:
Per my comment above...   (this can be simpler etc.)

```<code><!-- using unique IDs or attributes to solve the issue -->
<p><span id="elementA">elementA</span></p>
<div id="elementB">elementB</div>
<script type="text/javascript">
$(document).ready(function(){
     $('div, p span').click(function(){
        var id = $(this).attr('id');
        alert('You clicked ' + $('#' + id).text());
     });
});
</script>
</code>```

OR let the tag type handle things for you if that's appropriate for your case

```<code><p><span>elementA</span></p>
<div>elementB</div>

<script type="text/javascript">
 $(document).ready(function() {
    $('div, p span').click(function() {
        var tagName = $(this)[0].tagName;
        alert(tagName);
    });
});
</script>
</code>```

Body:
This is regarding Patrick DW's comment on my answer to this question.

Multiple selectors: identify the triggering one?

My Answer:

Using $(this) will get you the element that was clicked..  and using is() can help you determine what was clicked.

$('a.button, span.xyz, a.another').click(function(e) {
   if ($(this).is("a.button")) {
     alert("a.button was clicked");
   } else if ($(this).is("span.xyz")) {
     alert("span.xyz was clicked");
   } else if($(this).is("a.another")) {
     alert("a.another was clicked);
   }
});

Patrick's Comments

Trouble with this is that it is effectively combining the inefficiency that .delegate() suffers (testing against a selector) with the inefficiency of assigning multiple redundant handlers. So you get the worst of both worlds.

@John - Yes, it would make more sense to break them up into separate handlers, and place any common functionality they share into a named function that can be called from within the handlers. This eliminates the need to run the .is() tests at every event occurrence, which can be costly. It can sometimes be beneficial to test for the element that was clicked. This is what .delegate() does. You suffer the expense of the test, but gain from the reduced number of handlers being assigned

Could someone explain (in detail) the inefficiencies that Patrick is talking about? Why is .is() costly in this scenario? Can you give an example as well using .delegate()

Body:
Per my comment above...   (this can be simpler etc.)

<!-- using unique IDs or attributes to solve the issue -->
<p><span id="elementA">elementA</span></p>
<div id="elementB">elementB</div>
<script type="text/javascript">
$(document).ready(function(){
     $('div, p span').click(function(){
        var id = $(this).attr('id');
        alert('You clicked ' + $('#' + id).text());
     });
});
</script>

OR let the tag type handle things for you if that's appropriate for your case

<p><span>elementA</span></p>
<div>elementB</div>

<script type="text/javascript">
 $(document).ready(function() {
    $('div, p span').click(function() {
        var tagName = $(this)[0].tagName;
        alert(tagName);
    });
});
</script>


问:
Authentication without email and password.
I am trying to have an authentication system for apis. But unlike traditional way, this will be without email and password

The front end is an android app. Initially the app will have empty auth_token in the local storage, now the app requests for
an auth token from the server, by sending the mobile_number, device_id and gcm_id.

Now the server generates a 16 securerandom hex, and sends it as auth token to the front end.

Now the front end has to call all the apis using this auth token.

The server user table will be like this

id || mobile_number || device_id || gcm_id || auth_token

Question 1:

Should I generate my auth token based on the mobile_number, device id or can it be independently generated?

Question 2:

Should the auth token be changed? or can I use the same auth token permanently for the user. If it has to be changed .. can you please guide me in pointing out which strategy to use

Question 3:

What are the pitfalls for this kind of authentication. I don't want the user to type the email and password, but at the same time want to identify the user for personalization calculations.

答:
Authentication tokens are passwords. They should generally be designed to be handled by the client and server automatically with periodic rotation, to mitigate the risks of potential brute force attacks or credential leakage such as through a compromised user device or another server bug like Heartbleed. Make your tokens expire every so often, maybe 2 weeks or a month, and have the client app either require re-authentication when a token expires, or automatically make a request to refresh the token before it happens.

The user authentication scheme you're describing is for a device, not a user. You won't be able to identify one user from another reliably using those details, but that's not to say email+password is any better, it just comes with different usage expectations. You're identifying a mobile device by its device_id and adding some confidence that its owner hasn't changed by verifying the phone number. I'm not familiar with GCM so I'm not sure what property that adds. To add another factor of device authentication that is not so straightforward for another party to spoof, I suggest having your client app generate its own "something you know" password to use for requesting an initial token. That device-internal password can be its secret for authenticating with the service for purposes of automatic token issuance, and can be rotated more infrequently than the regular per-request auth token.

For both your client secret and your auth tokens, just like passwords you should aim to make them long and random. If the auth token is auto-rotating, you can allow for it to be much shorter without introducing realistic risks, to a degree. I'd say at least 16 random bytes even for a short-lived token should be the minimum, as 12 characters are within the realm of practical offline hash brute-forcing, and it's good to have a sizeable window of safety between what's plausible today and tomorrow's improvements in cracking capabilities.

It's important to remember that what you're describing will not authenticate a person, but simply an individual device. It sounds like that's what you intend to do for your project but it's important to understand the distinction and what it implies.


问:
What is the difference between private and protected members of C++ classes?
What is the difference between private and protected members in C++ classes?

I understand from best practice conventions that variables and functions which are not called outside the class should be made private—but looking at my MFC project, MFC seems to favor protected.

What's the difference and which should I use?

答:
private = accessible by the mothership (base class) only
(ie only my parent can go into my parent's bedroom)

protected = accessible by mothership (base class), and her daughters
(ie only my parent can go into my parent's bedroom, but gave son/daughter permission to walk into parent's bedroom)

public = accessible by mothership (base class), daughter, and everyone else
(ie only my parent can go into my parent's bedroom, but it's a house party - mi casa su casa)

OwnerDisplayName: Whyamistilltyping

LastEditorDisplayName: Don Kirkby


问:
Capturing a screenshot using window.scroll with high DPI settings
I'm using CefSharp 55.0.0 WinForms.

In order to take screenshots in CefSharp, I scroll the webpage using window.scroll within JavaScript and take an image of the current viewport. Once that has completed, it is then stitched back together again. This works fine for monitors that have their DPI setting set to 100%. However, when the monitor has a DPI greater than 100% screenshots do not work as expected and miss content.

Image 1 - 100%

Image 2 - 150%

Compare Image 1 to Image 2. While they both (practically) have the same width and height, Image 2 is missing a large portion of the content, compared to a perfect Image 1.

When DPI settings are above 100%, how can I correctly scroll and capture a screenshot that ensures I obtain everything it would if settings were at 100%?

Other details

The application has the correct DPI aware settings in theapp.manifest file and Cef.EnableHighDPISupport(); has been called in the Main method within Program.cs.

Screenshot Code (abridged)

```<code>int scrollHeight = GetDocHeight(); //some javascript that calcs the height of the document
int viewportHeight = ClientRectangle.Size.Height;
int viewportWidth = ClientRectangle.Size.Width;
int count = 0;
int pageLeft = scrollHeight;
bool atBottom = false;

while (!atBottom)
{
    if (pageLeft > viewportHeight)
    {
        await GetBrowser().MainFrame.EvaluateScriptAsync("(function() { window.scroll(0," + (count * viewportHeight) + "); })();"); //I think the issue lies here
        count++;
        await PutTaskDelay();
        using (Bitmap image = GetCurrentViewScreenshot())
        {
            //just a class that saves the partial images to a disk cache
            cache.AddImage(count, image);
        }
    }
    else
    {

        await GetBrowser().MainFrame.EvaluateScriptAsync("(function() { window.scrollBy(0," + pageLeft + "); })();");

        atBottom = true;
        count++;

        await PutTaskDelay();
        Rectangle cropRect = new Rectangle(new Point(0, viewportHeight - pageLeft), new Size(viewportWidth, pageLeft));

        using (Bitmap src = GetCurrentViewScreenshot())
        using (Bitmap target = new Bitmap(cropRect.Width, cropRect.Height))
        using (Graphics g = Graphics.FromImage(target))
        {
            g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel);
            cache.AddImage(count, target);
        }

    }
    pageLeft = pageLeft - viewportHeight;
}
</code>```

Current View Screenshot Method

```<code>private Bitmap GetCurrentViewScreenshot()
{
    int width, height;
    width = ClientRectangle.Width;
    height = ClientRectangle.Height;

    using (Bitmap image = new Bitmap(width, height))
    {
        using (Graphics graphics = Graphics.FromImage(image))
        {
            Point p, upperLeftDestination;
            Point upperLeftSource = new Point(0, 0);
            p = new Point(0, 0);
            upperLeftSource = PointToScreen(p);
            upperLeftDestination = new Point(0, 0);
            Size blockRegionSize = ClientRectangle.Size;
            graphics.CopyFromScreen(upperLeftSource, upperLeftDestination, blockRegionSize);

        }
        return new Bitmap(image);
    }
}
</code>```

答:
While not a perfect solution, I found a workaround that involves setting the force-device-scale-factor flag to 1 in CefSettings. It's not perfect because the browser isn't scaled on high DPI displays, potentially making text hard to read for users. However, it does fix my more pressing issue of missing data in screenshots.

```<code>CefSettings settings = new CefSettings();
settings.CefCommandLineArgs.Add("force-device-scale-factor", "1");
Cef.Initialize(settings);
</code>```

This question is still open for better suggestions, if there are any. :-)

Body:
I'm using CefSharp 55.0.0 WinForms.

In order to take screenshots in CefSharp, I scroll the webpage using window.scroll within JavaScript and take an image of the current viewport. Once that has completed, it is then stitched back together again. This works fine for monitors that have their DPI setting set to 100%. However, when the monitor has a DPI greater than 100% screenshots do not work as expected and miss content.

Image 1 - 100%

Image 2 - 150%

Compare Image 1 to Image 2. While they both (practically) have the same width and height, Image 2 is missing a large portion of the content, compared to a perfect Image 1.

When DPI settings are above 100%, how can I correctly scroll and capture a screenshot that ensures I obtain everything it would if settings were at 100%?

Other details

The application has the correct DPI aware settings in theapp.manifest file and Cef.EnableHighDPISupport(); has been called in the Main method within Program.cs.

Screenshot Code (abridged)

int scrollHeight = GetDocHeight(); //some javascript that calcs the height of the document
int viewportHeight = ClientRectangle.Size.Height;
int viewportWidth = ClientRectangle.Size.Width;
int count = 0;
int pageLeft = scrollHeight;
bool atBottom = false;

while (!atBottom)
{
    if (pageLeft > viewportHeight)
    {
        await GetBrowser().MainFrame.EvaluateScriptAsync("(function() { window.scroll(0," + (count * viewportHeight) + "); })();"); //I think the issue lies here
        count++;
        await PutTaskDelay();
        using (Bitmap image = GetCurrentViewScreenshot())
        {
            //just a class that saves the partial images to a disk cache
            cache.AddImage(count, image);
        }
    }
    else
    {

        await GetBrowser().MainFrame.EvaluateScriptAsync("(function() { window.scrollBy(0," + pageLeft + "); })();");

        atBottom = true;
        count++;

        await PutTaskDelay();
        Rectangle cropRect = new Rectangle(new Point(0, viewportHeight - pageLeft), new Size(viewportWidth, pageLeft));

        using (Bitmap src = GetCurrentViewScreenshot())
        using (Bitmap target = new Bitmap(cropRect.Width, cropRect.Height))
        using (Graphics g = Graphics.FromImage(target))
        {
            g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel);
            cache.AddImage(count, target);
        }

    }
    pageLeft = pageLeft - viewportHeight;
}

Current View Screenshot Method

private Bitmap GetCurrentViewScreenshot()
{
    int width, height;
    width = ClientRectangle.Width;
    height = ClientRectangle.Height;

    using (Bitmap image = new Bitmap(width, height))
    {
        using (Graphics graphics = Graphics.FromImage(image))
        {
            Point p, upperLeftDestination;
            Point upperLeftSource = new Point(0, 0);
            p = new Point(0, 0);
            upperLeftSource = PointToScreen(p);
            upperLeftDestination = new Point(0, 0);
            Size blockRegionSize = ClientRectangle.Size;
            graphics.CopyFromScreen(upperLeftSource, upperLeftDestination, blockRegionSize);

        }
        return new Bitmap(image);
    }
}

Body:
While not a perfect solution, I found a workaround that involves setting the force-device-scale-factor flag to 1 in CefSettings. It's not perfect because the browser isn't scaled on high DPI displays, potentially making text hard to read for users. However, it does fix my more pressing issue of missing data in screenshots.

CefSettings settings = new CefSettings();
settings.CefCommandLineArgs.Add("force-device-scale-factor", "1");
Cef.Initialize(settings);

This question is still open for better suggestions, if there are any. :-)


问:
what is the best way to upload file with javaee maven
im trying to upload file with fileUpload , i added the jar library ( commons-io-1.4.jar commons-fileupload-1.2.jar ) and configure web.xml by adding filter :

```<code>    <filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filterclass>org.primefaces.webapp.filter.FileUploadFilter</filterclass>
    <init-param>
        <param-name>thresholdSize</param-name>
        <param-value>2097152</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
</code>```

but i get a build failure , am i doin it right or im missing something else

答:
I think you code is suffering with  dependency error. You need to add version dependency </p>

```<code><dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-io</artifactId>
         <version>2.4</version>
</dependency>
<dependency>
       <groupId>commons-fileupload</groupId>
       <artifactId>commons-fileupload</artifactId>
       <version>1.3.1</version>
 </dependency>
</code>```

Body:
im trying to upload file with fileUpload , i added the jar library ( commons-io-1.4.jar commons-fileupload-1.2.jar ) and configure web.xml by adding filter :

    <filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filterclass>org.primefaces.webapp.filter.FileUploadFilter</filterclass>
    <init-param>
        <param-name>thresholdSize</param-name>
        <param-value>2097152</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>

but i get a build failure , am i doin it right or im missing something else

Body:
I think you code is suffering with  dependency error. You need to add version dependency

<dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-io</artifactId>
         <version>2.4</version>
</dependency>
<dependency>
       <groupId>commons-fileupload</groupId>
       <artifactId>commons-fileupload</artifactId>
       <version>1.3.1</version>
 </dependency>


问:
Sorting string date array in JavaScript
I was having some problem when trying to sort the string date array in JavaScript.

```<code>function drawLineChart(crisislist){
    crisislist.sort(function(a,b) {
        a = a.split('-').reverse().join('');
        b = b.split('-').reverse().join('');
        return a > b ? 1 : a < b ? -1 : 0;
    });
    for(var i = 0; i < crisislist.length; i++){
        console.log(crisislist[i].date);
    }
}
</code>```

Basically my crisislist got other stuffs other than date:

```<code> crisislist.push({category: marker[2], month: marker[13], date: marker[14]});
</code>```

When I tried to sort it, it gave me an error message:

```<code>a.split is not a function
</code>```

I wonder is there any way to sort it directly in the crisislist rather than create another string date array which only has the date field?

Thanks in advance!

The console.log without the chunk of sorting code gave me these dates:

答: You seem to be looking for a.date.split(…). You don't have an array of date strings, but an array of objects containing the strings.

Title: Sorting string date array in JavaScript

Body:
I was having some problem when trying to sort the string date array in JavaScript.

function drawLineChart(crisislist){
    crisislist.sort(function(a,b) {
        a = a.split('-').reverse().join('');
        b = b.split('-').reverse().join('');
        return a > b ? 1 : a < b ? -1 : 0;
    });
    for(var i = 0; i < crisislist.length; i++){
        console.log(crisislist[i].date);
    }
}

Basically my crisislist got other stuffs other than date:

 crisislist.push({category: marker[2], month: marker[13], date: marker[14]});

When I tried to sort it, it gave me an error message:

a.split is not a function

I wonder is there any way to sort it directly in the crisislist rather than create another string date array which only has the date field?

Thanks in advance!

The console.log without the chunk of sorting code gave me these dates:


问:
SQL query, join on a manipulated column
I have database table with the following column structure and data (1 column example only)

```<code>[ProductRaw] [nvarchar](255) NULL
One Kind of Product (CatA)
Another Product (CatB)
Yet Another Product (CatC)
</code>```

I cannot change this column due to other requirements but I also need to do a 'join' on a clean version of this column. The clean version would look like this

```<code>[ProductClean] [nvarchar](255) NULL
One Kind of Product
Another Product
Yet Another Product
</code>```

What would the best way to do this in SQL server be? I know it can be done using  the following

```<code>DECLARE @Sql varchar(50) = 'One Kind of Product (CatA)'

SELECT
    PARSENAME(REPLACE(@sql,' (','.'),2)
</code>```

Is there a better way to do this (eg such as calculated column)?

答:
My recommendation is to create a separate index view with all the columns of existing table and an additional column naming ProductClean.

```<code>CREATE VIEW [P_RawWithClean] WITH SCHEMABINDING
AS

      SELECT *
           , RTRIM(SUBSTRING([ProductRaw], 1, CHARINDEX('(', [ProductRaw] + '(') - 1)) AS [ProductClean]
       FROM [YourTableName]

CREATE UNIQUE CLUSTERED INDEX idx_RawWithClean ON P_RawWithClean(ProductClean)
</code>```

Now, you can use this view for any JOIN with ProductClean or ProductRaw. The index view will give you better performance. Moreover, you can create non clustered index on any columns if needed.

Title: SQL query, join on a manipulated column

Body:
I have database table with the following column structure and data (1 column example only)

[ProductRaw] [nvarchar](255) NULL
One Kind of Product (CatA)
Another Product (CatB)
Yet Another Product (CatC)

I cannot change this column due to other requirements but I also need to do a 'join' on a clean version of this column. The clean version would look like this

[ProductClean] [nvarchar](255) NULL
One Kind of Product
Another Product
Yet Another Product

What would the best way to do this in SQL server be? I know it can be done using  the following

DECLARE @Sql varchar(50) = 'One Kind of Product (CatA)'

SELECT
    PARSENAME(REPLACE(@sql,' (','.'),2)

Is there a better way to do this (eg such as calculated column)?

Body:
My recommendation is to create a separate index view with all the columns of existing table and an additional column naming ProductClean.

CREATE VIEW [P_RawWithClean] WITH SCHEMABINDING
AS

      SELECT *
           , RTRIM(SUBSTRING([ProductRaw], 1, CHARINDEX('(', [ProductRaw] + '(') - 1)) AS [ProductClean]
       FROM [YourTableName]

CREATE UNIQUE CLUSTERED INDEX idx_RawWithClean ON P_RawWithClean(ProductClean)

Now, you can use this view for any JOIN with ProductClean or ProductRaw. The index view will give you better performance. Moreover, you can create non clustered index on any columns if needed.


问:
Tight border on current matlab figure
I know

imshow('myimage.png','border','tight');

will give a tight border around the image. But what if I already have an image open? Is there a way to make it have a tight border?

答:
```<code>imshow('coins.png')
set(gca, 'Units', 'normalized', 'Position', [0 0 1 1])
</code>```

Title: Tight border on current matlab figure


问:
How to invoke a character in java?
How to do it without char c = scanner.next().charAt(0)
as I didn't learn how to use 'At' and read function invokes only one character while I want it to read the entire line.</p>

答:
One of the approaches can be: read the line using nextLine() and store it in a String and then use charAt() something like:

```<code>String line = reader.nextLine();
char c = line.charAt(0);
</code>```

Title: How to invoke a character in java?

Body:
One of the approaches can be: read the line using nextLine() and store it in a String and then use charAt() something like:

String line = reader.nextLine();
char c = line.charAt(0);


问:
Are homography matrices commutative?
I have 3 sets of points A, B and C. The homography matrices H0 and H1 are such that H0(A) = B and H1(B) = C. So, H1(B) = H1(H0(A)) = C.

My question:

Is H0(H1(A)) = C? Or, what are the conditions under which H0(H1(A)) = H1(H0(A))?

Thanks very much for any help!!

答:
A homography is by definition an invertible mapping from one plane P to another plane Q with the condition that points lying on a line in P are mapped to points on a line in Q. Since this property is transitive there is a homography from point set A to point set C.
When H0, H1 are the matrix representations of the respective homographies, then H2 = H1 * H0 maps A to C.
The only restriction on the matrices H0 and H1 is nonsingularity wherefore - as with matrix multiplication in general - it is in general not a commutative mapping. </p>

Title: Are homography matrices commutative?


问:
Equivlent to SUM(CASE WHEN...) in WHERE
POSTGRES 9.4: I need to put an "if" function on WHERE but the only way I know is to SUM a CASE WHEN function. Since you can't use aggregate functions on WHERE, it doesn't work. Does anyone know a way to do so? (The query below has been edited due to the answers given me, but still is taking forever to execute. Can anyone help me?)

My query:

```<code>SELECT companies.id
  , avg(char_length(field_answers.comment))
  , count(distinct(field_answers.id))
  , count(distinct(surveys.id))

FROM contracts
JOIN companies on contracts.company_id = companies.id
JOIN surveys on companies.id = surveys.company_id
JOIN fields on surveys.id = fields.owner_id
JOIN field_answers on fields.id = field_answers.field_id
JOIN participants on surveys.id = participants.survey_id

WHERE fields.owner_type = 'Survey'
AND surveys.stage in ('finished', 'closed', 'active')

GROUP BY companies.id

HAVING sum(case when participants.finished = 'true' then 1 else 0 end) > 0.9 * count(participants.id)
</code>```

答:
You use windows functions for processing like this.

You forgot to tell us what the grouping for the sum and count is, but let's assume that you want to aggregate by the attribute team.

Then you'd do it somewhat like this:

```<code>SELECT id, name
FROM (SELECT id,
             name,
             sum(finished::integer) OVER (PARTITION BY team) finished_per_team,
             count(1) OVER (PARTITION BY team) team_size
      FROM participants
     ) part_with_stats
WHERE finished_per_team > 0.9 * team_size;
</code>```

Title: Equivlent to SUM(CASE WHEN...) in WHERE

Body:
POSTGRES 9.4: I need to put an "if" function on WHERE but the only way I know is to SUM a CASE WHEN function. Since you can't use aggregate functions on WHERE, it doesn't work. Does anyone know a way to do so? (The query below has been edited due to the answers given me, but still is taking forever to execute. Can anyone help me?)

My query:

SELECT companies.id
  , avg(char_length(field_answers.comment))
  , count(distinct(field_answers.id))
  , count(distinct(surveys.id))

FROM contracts
JOIN companies on contracts.company_id = companies.id
JOIN surveys on companies.id = surveys.company_id
JOIN fields on surveys.id = fields.owner_id
JOIN field_answers on fields.id = field_answers.field_id
JOIN participants on surveys.id = participants.survey_id

WHERE fields.owner_type = 'Survey'
AND surveys.stage in ('finished', 'closed', 'active')

GROUP BY companies.id

HAVING sum(case when participants.finished = 'true' then 1 else 0 end) > 0.9 * count(participants.id)

Body:
You use windows functions for processing like this.

You forgot to tell us what the grouping for the sum and count is, but let's assume that you want to aggregate by the attribute team.

Then you'd do it somewhat like this:

SELECT id, name
FROM (SELECT id,
             name,
             sum(finished::integer) OVER (PARTITION BY team) finished_per_team,
             count(1) OVER (PARTITION BY team) team_size
      FROM participants
     ) part_with_stats
WHERE finished_per_team > 0.9 * team_size;