问:
How to separate individual actions into separate functions
I'm new in PHP & Symfony. I've created same action who work.
Now I've not knowd how to separate individual actions into separate functions.
Run on Symfony 3 / PHP 7.1.

```<code><?php
// AppBundle/Controller/SuccessMYController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

use AppBundle\Entity\SuccessMY;
use AppBundle\Form\SuccessMYType;

/**
 * @Route("/success")
 *
 */
class SuccessMYController extends Controller
{
   /**
     *
     * @Route("/new/{idTask}",
     *     name = "MY_success_new")
     */
    public function newSuccessAction( Request $request, $idTask )
    {
        if ( !$this -> get( 'security.authorization_checker' ) -> isGranted( 'IS_AUTHENTICATED_FULLY' ) ) {
            throw $this -> createAccessDeniedException();
        }
        $user1 = $this -> get( 'security.token_storage' ) -> getToken() -> getUser() -> getId();

        // (1) load TASK data for a new Success
        $em = $this -> getDoctrine() -> getRepository( 'EinsteMYBundle:TaskMY' );
        $taskData = $em
            -> findOneBy( [ 'id' => $idTask ] );

        // (2) create fefault data
        $newSuccess = new SuccessMY();
        $newSuccess
            -> setUserID( $user1 )
            -> setEndTask( false );

        // (3) display form
        $form = $this -> createForm( SuccessMYType::class, $newSuccess );
        $form -> handleRequest( $request ) -> getData( $newSuccess );

        // **********************************************
        // (4) save after submit
        if ( $form -> isSubmitted() && $form->isValid() ) {

            // (4.5.1) The content of the confirmation message
            $messageFrom = $this -> get( 'translator' ) -> trans( 'success.created' );

            // Data update newSuccess
            // (4.5.2) Date assignment
            $successNewDate = new \DateTime();
            $newSuccess
                -> setDateSuccess( $successNewDate );
            $successNewDate = $newSuccess -> getDateSuccess() -> format( 'Y-m-d H:i:s' );

            // (4.6.1)  Increase the number
            $taskData
                -> setOwnCount( $taskData -> getOwnCount() + 1 );

            // (4.6.3)  TASK Setting status
            if ( $newSuccess -> getEndTask() == true ) {
                $taskData
                    -> setStatusTask( 8 );
                $messageTask = $this -> get( 'translator' ) -> trans( 'task.status.succeed' );
                $messageFrom = $messageFrom . ' ' . $messageTask;
            }

            // **** (4.8) Activities in the database *****
            // (4.8.1) Save newly created database success
            $em2 = $this -> getDoctrine() -> getManager();
            $em2 -> persist( $newSuccess );
            $em2 -> flush();

            // (4.8.2) Query updating overrides Task with newSuccess
            $sql
                = "UPDATE task_MY t
                    INNER JOIN zz_tech_parent e
                        on t.id = e.idParent
                    SET
                        t.success_count = t.success_count + 1
                    WHERE
                        e.idTask =  :parTaskId";
            $params = [
                'parTaskId'      => $idTask,
            ];

            $em4 = $this -> getDoctrine() -> getManager();
            $phrase = $em4 -> getConnection() -> prepare( $sql );
            $phrase -> execute( $params );

            // (4.9) Return to task list
            // And a message about the success of the operation
            $this -> get( 'session' ) -> getFlashBag() -> add( 'msg', $messageFrom );

            return
                $this -> redirect( $this -> generateUrl( 'MY_tasks_all' ) );
        }

        // (5) For bad data return to form
        return $this -> render( 'EinsteMYBundle:SuccessMY:newSuccess.html.twig',
                                [
                                    'form'     => $form -> createView(),
                                    'taskData' => $taskData,
                                ]
        );
    }

    // (...)
}
</code>```

Where can I find examples of how to send code to similar functions?
Which activities should (preferably) be separated so that coding is as transparent as possible when adding new activities?
Can anybody help me?

答:
Few ideas:

1) Move your form handling stuff to a separate method under your Controller. Pass in your entity (SuccessMY) and the Request objects as the arguments and return your $form->createView()

```<code>...

public function processForm(SuccessMY $successMy, request $request){

    $form = $this -> createForm( SuccessMYType::class, $newSuccess );
    $form -> handleRequest( $request ) -> getData( $newSuccess );

    ...

    return $form->createView();

}

...
</code>```

2) Typehint your $idTask and rename it to $task - it will make Symfony to load that entity for you if it exists.

```<code> public function newSuccessAction( Request $request, !YOUR_TASK_TYPE! $task )
</code>```

3) This kind of stuff clearly belongs to a Repository:

```<code>   $sql
            = "UPDATE task_MY t
                INNER JOIN zz_tech_parent e
                    on t.id = e.idParent
                SET
                    t.success_count = t.success_count + 1
                WHERE
                    e.idTask =  :parTaskId";
        $params = [
            'parTaskId'      => $idTask,
        ];
</code>```

Something like:

```<code>class GroupRepository extends NestedTreeRepository
{
    public function incrementSuccessCounterByTask(YOUR_TASK_TYPE $task){
       ....
    }
}
</code>```

4) You don't really need to have multiple entity managers within the same scope. So better have a single $em = $this->getDoctrine()->getManager() at the beginning of your Action and then just use it as needed. Get rid of those $em1, $em2 etc.

Also - this spot
$em = $this -> getDoctrine() -> getRepository( 'EinsteMYBundle:TaskMY' );

It really creates a Repository instance, not an EntityManager so you should rename the variable to something like $taskMyRepository = ...

Body:
I'm new in PHP & Symfony. I've created same action who work.
Now I've not knowd how to separate individual actions into separate functions.
Run on Symfony 3 / PHP 7.1.

<?php
// AppBundle/Controller/SuccessMYController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

use AppBundle\Entity\SuccessMY;
use AppBundle\Form\SuccessMYType;

/**
 * @Route("/success")
 *
 */
class SuccessMYController extends Controller
{
   /**
     *
     * @Route("/new/{idTask}",
     *     name = "MY_success_new")
     */
    public function newSuccessAction( Request $request, $idTask )
    {
        if ( !$this -> get( 'security.authorization_checker' ) -> isGranted( 'IS_AUTHENTICATED_FULLY' ) ) {
            throw $this -> createAccessDeniedException();
        }
        $user1 = $this -> get( 'security.token_storage' ) -> getToken() -> getUser() -> getId();

        // (1) load TASK data for a new Success
        $em = $this -> getDoctrine() -> getRepository( 'EinsteMYBundle:TaskMY' );
        $taskData = $em
            -> findOneBy( [ 'id' => $idTask ] );

        // (2) create fefault data
        $newSuccess = new SuccessMY();
        $newSuccess
            -> setUserID( $user1 )
            -> setEndTask( false );

        // (3) display form
        $form = $this -> createForm( SuccessMYType::class, $newSuccess );
        $form -> handleRequest( $request ) -> getData( $newSuccess );

        // **********************************************
        // (4) save after submit
        if ( $form -> isSubmitted() && $form->isValid() ) {

            // (4.5.1) The content of the confirmation message
            $messageFrom = $this -> get( 'translator' ) -> trans( 'success.created' );

            // Data update newSuccess
            // (4.5.2) Date assignment
            $successNewDate = new \DateTime();
            $newSuccess
                -> setDateSuccess( $successNewDate );
            $successNewDate = $newSuccess -> getDateSuccess() -> format( 'Y-m-d H:i:s' );

            // (4.6.1)  Increase the number
            $taskData
                -> setOwnCount( $taskData -> getOwnCount() + 1 );

            // (4.6.3)  TASK Setting status
            if ( $newSuccess -> getEndTask() == true ) {
                $taskData
                    -> setStatusTask( 8 );
                $messageTask = $this -> get( 'translator' ) -> trans( 'task.status.succeed' );
                $messageFrom = $messageFrom . ' ' . $messageTask;
            }

            // **** (4.8) Activities in the database *****
            // (4.8.1) Save newly created database success
            $em2 = $this -> getDoctrine() -> getManager();
            $em2 -> persist( $newSuccess );
            $em2 -> flush();

            // (4.8.2) Query updating overrides Task with newSuccess
            $sql
                = "UPDATE task_MY t
                    INNER JOIN zz_tech_parent e
                        on t.id = e.idParent
                    SET
                        t.success_count = t.success_count + 1
                    WHERE
                        e.idTask =  :parTaskId";
            $params = [
                'parTaskId'      => $idTask,
            ];

            $em4 = $this -> getDoctrine() -> getManager();
            $phrase = $em4 -> getConnection() -> prepare( $sql );
            $phrase -> execute( $params );

            // (4.9) Return to task list
            // And a message about the success of the operation
            $this -> get( 'session' ) -> getFlashBag() -> add( 'msg', $messageFrom );

            return
                $this -> redirect( $this -> generateUrl( 'MY_tasks_all' ) );
        }

        // (5) For bad data return to form
        return $this -> render( 'EinsteMYBundle:SuccessMY:newSuccess.html.twig',
                                [
                                    'form'     => $form -> createView(),
                                    'taskData' => $taskData,
                                ]
        );
    }

    // (...)
}

Where can I find examples of how to send code to similar functions?
Which activities should (preferably) be separated so that coding is as transparent as possible when adding new activities?
Can anybody help me?

Body:
Few ideas:

1) Move your form handling stuff to a separate method under your Controller. Pass in your entity (SuccessMY) and the Request objects as the arguments and return your $form->createView()

...

public function processForm(SuccessMY $successMy, request $request){

    $form = $this -> createForm( SuccessMYType::class, $newSuccess );
    $form -> handleRequest( $request ) -> getData( $newSuccess );

    ...

    return $form->createView();

}

...

2) Typehint your $idTask and rename it to $task - it will make Symfony to load that entity for you if it exists.

 public function newSuccessAction( Request $request, !YOUR_TASK_TYPE! $task )

3) This kind of stuff clearly belongs to a Repository:

   $sql
            = "UPDATE task_MY t
                INNER JOIN zz_tech_parent e
                    on t.id = e.idParent
                SET
                    t.success_count = t.success_count + 1
                WHERE
                    e.idTask =  :parTaskId";
        $params = [
            'parTaskId'      => $idTask,
        ];

Something like:

class GroupRepository extends NestedTreeRepository
{
    public function incrementSuccessCounterByTask(YOUR_TASK_TYPE $task){
       ....
    }
}

4) You don't really need to have multiple entity managers within the same scope. So better have a single $em = $this->getDoctrine()->getManager() at the beginning of your Action and then just use it as needed. Get rid of those $em1, $em2 etc.

Also - this spot
$em = $this -> getDoctrine() -> getRepository( 'EinsteMYBundle:TaskMY' );

It really creates a Repository instance, not an EntityManager so you should rename the variable to something like $taskMyRepository = ...


来源: stackexchange

问:
django fuzzy string translation not showing up

Why sometimes I get a fuzzy item in django.po language file. Actually, I have checked in my project the fuzzy string item is totally unique.

```<code>#: .\users\views.py:81 .\users\views.py:101
#, fuzzy
msgid "username or email"
msgstr "9988"
</code>```

It is ok to be fuzzy but my translation of fuzzy item not showing up on the page, only English version shows up. It is totally odd.

答:
I also had these problems and I solved them all by using a 'po editor' (like poedit) which highlights fuzzy and untranslated entries and makes the translation process much faster.

You can also use Django Rosetta to have the translating process integrated in your Django environment.

ContentLicense: CC BY-SA 3.0

Body:
Why sometimes I get a fuzzy item in django.po language file. Actually, I have checked in my project the fuzzy string item is totally unique.

#: .\users\views.py:81 .\users\views.py:101
#, fuzzy
msgid "username or email"
msgstr "9988"

It is ok to be fuzzy but my translation of fuzzy item not showing up on the page, only English version shows up. It is totally odd.


问:
how to export ssl key , crt and CA from httpd.conf apache to use it into nginx for all users
use custom setup that use nginx as web engine  with cpanel
need command to export ssl files to use it into nginx

cpanel now use AutoSSL powered by Comodo that give it free and will renew it automatic when any users domains ssl expire

example httpd.conf

```<code><VirtualHost 4xx30:4433>
  ServerName xnxxsch.com
  <IfModule ssl_module>
 SSLCertificateFile /var/cpanel/ssl/installed/certs/xnh_com_d98c5_67ca3_150707$
    SSLCertificateKeyFile /var/cpanel/ssl/installed/keys/d98c5_67ca3_76c14a301e0260891bbe91504$
    SSLCACertificateFile /var/cpanel/ssl/installed/cabundles/cPanel_Inc__681917bfb43af6b642178$
  </IfModule>
</VirtualHost>

<VirtualHost 46.xx30:4433>
  ServerName xxxh.com
  <IfModule ssl_module>
 SSLCertificateFile /var/cpanel/ssl/installed/certs/xnah_com_d98c5_67ca3_150707$
    SSLCertificateKeyFile /var/cpanel/ssl/installed/keys/d98c5_67ca3_76c14a301e0260891bbe91504$
    SSLCACertificateFile /var/cpanel/ssl/installed/cabundles/cPanel_Inc__681917bfb43af6b642178$
  </IfModule>
</VirtualHost>
</code>```

need to export every domains  (ServerName)

as two files

SSLCertificateKeyFile as ServerName.key

and

SSLCertificateFile+ SSLCACertificateFile  as ServerName.crt

from ssh

with

```<code>grep 'ServerName' /etc/apache2/conf/httpd.conf
</code>```

i export all need to use at loop

to get SSLCertificateKeyFile under it

and copy it with name servername.crt  to /etc/nginx/ssl/

答:
I'm sure some efficiency nuts will choke on this, but it should work:</p>

```<code>#!/bin/bash
# Look for ServerName, and extract the value.  Loop over results.
for server in $( grep ServerName httpd.conf | sed 's/.*ServerName\s*//' ); do
    echo $server
    # Pull out the block of XML for that server
    block=$( grep -A5 "$server" httpd.conf)

    # Extract file names from the XML block
    SSLCertificateFile=$( echo "$block" | sed -n 's/.*SSLCertificateFile\s*//p')
    SSLCertificateKeyFile=$( echo "$block" | sed -n 's/.*SSLCertificateKeyFile\s*//p')
    SSLCACertificateFile=$( echo "$block" | sed -n 's/.*SSLCACertificateFile\s*//p')

    # Create files
    cp "$SSLCertificateKeyFile" "${server}.key"
    cat "$SSLCertificateFile" "$SSLCACertificateFile" > "${server}.crt"
done
# end of loop
</code>```

Body:
use custom setup that use nginx as web engine  with cpanel
need command to export ssl files to use it into nginx

cpanel now use AutoSSL powered by Comodo that give it free and will renew it automatic when any users domains ssl expire

example httpd.conf

<VirtualHost 4xx30:4433>
  ServerName xnxxsch.com
  <IfModule ssl_module>
 SSLCertificateFile /var/cpanel/ssl/installed/certs/xnh_com_d98c5_67ca3_150707$
    SSLCertificateKeyFile /var/cpanel/ssl/installed/keys/d98c5_67ca3_76c14a301e0260891bbe91504$
    SSLCACertificateFile /var/cpanel/ssl/installed/cabundles/cPanel_Inc__681917bfb43af6b642178$
  </IfModule>
</VirtualHost>

<VirtualHost 46.xx30:4433>
  ServerName xxxh.com
  <IfModule ssl_module>
 SSLCertificateFile /var/cpanel/ssl/installed/certs/xnah_com_d98c5_67ca3_150707$
    SSLCertificateKeyFile /var/cpanel/ssl/installed/keys/d98c5_67ca3_76c14a301e0260891bbe91504$
    SSLCACertificateFile /var/cpanel/ssl/installed/cabundles/cPanel_Inc__681917bfb43af6b642178$
  </IfModule>
</VirtualHost>

need to export every domains  (ServerName)

as two files

SSLCertificateKeyFile as ServerName.key

and

SSLCertificateFile+ SSLCACertificateFile  as ServerName.crt

from ssh

with

grep 'ServerName' /etc/apache2/conf/httpd.conf

i export all need to use at loop

to get SSLCertificateKeyFile under it

and copy it with name servername.crt  to /etc/nginx/ssl/

Body:
I'm sure some efficiency nuts will choke on this, but it should work:

#!/bin/bash
# Look for ServerName, and extract the value.  Loop over results.
for server in $( grep ServerName httpd.conf | sed 's/.*ServerName\s*//' ); do
    echo $server
    # Pull out the block of XML for that server
    block=$( grep -A5 "$server" httpd.conf)

    # Extract file names from the XML block
    SSLCertificateFile=$( echo "$block" | sed -n 's/.*SSLCertificateFile\s*//p')
    SSLCertificateKeyFile=$( echo "$block" | sed -n 's/.*SSLCertificateKeyFile\s*//p')
    SSLCACertificateFile=$( echo "$block" | sed -n 's/.*SSLCACertificateFile\s*//p')

    # Create files
    cp "$SSLCertificateKeyFile" "${server}.key"
    cat "$SSLCertificateFile" "$SSLCACertificateFile" > "${server}.crt"
done
# end of loop


问:
How Can I Rewrite Without Stod()
How can I rewrite my readDetails function without using stod() or strtod() in C++?
The compiler I will be using doesn't have c++11 enabled and I get

'stod' was not declared in this scope error

```<code>int readDetails(SmallRestaurant sr[])
{
//Declaration
ifstream inf;

//Open file
inf.open("pop_density.txt");

//Check condition
if (!inf)
{
    //Display
    cout << "Input file is not found!" << endl;

    //Pause
    system("pause");

    //Exit on failure
    exit(EXIT_FAILURE);
}

//Declarations and initializations
string fLine;
int counter = 0;
int loc = -1;

//Read
getline(inf, fLine);

//Loop
while (inf)
{
    //File read
    loc = fLine.find('|');
    sr[counter].nameInFile = fLine.substr(0, loc);
    fLine = fLine.substr(loc + 1);
    loc = fLine.find('|');
    sr[counter].areaInFile = stod(fLine.substr(0, loc));  //line using stod
    fLine = fLine.substr(loc + 1);
    loc = fLine.find('|');
    sr[counter].popInFile = stoi(fLine.substr(0, loc));
    fLine = fLine.substr(loc + 1);
    sr[counter].densityInFile = stod(fLine);   //line using stod
    counter++;
    getline(inf, fLine);
}

//Return
return counter;
}
</code>```

Below is the text I am trying to read:

Census Tract 201, Autauga County, Alabama|9.84473419420788|1808|183.651479494869
Census Tract 202, Autauga County, Alabama|3.34583234555866|2355|703.860730836106
Census Tract 203, Autauga County, Alabama|5.35750339330735|3057|570.60159846447

答:
Use std::istringstream.

```<code>std::string number_as_text("123");
int value;
std::istringstream number_stream(number_as_text);
number_stream >> value;
</code>```

Edit 2:  For those pedantic people:

The example below reads a double.  Very similar pattern to the above reading of an integer.

```<code>std::string number_as_text("3.14159");
double pi;
std::istringstream number_stream(number_as_text);
number_stream >> pi;
</code>```

You could also use a variant of sprintf.

Edit 1: Another parsing method

You could try:

```<code>std::string tract;
std::string county;
std::string state;
double value1;
char separator;

//...
std::ifstream input("myfile.txt");
//...
std::getline(input, tract, ',');
std::getline(input, county, ',');
std::getline(input, state, '|');
input >> value1;
input >> separator;
//...
input.ignore(100000, '\n'); // Ignore any remaining characters on the line
</code>```

The above doesn't require separate string to number conversion.

Title: How Can I Rewrite Without Stod()

Body:
How can I rewrite my readDetails function without using stod() or strtod() in C++?
The compiler I will be using doesn't have c++11 enabled and I get

'stod' was not declared in this scope error

int readDetails(SmallRestaurant sr[])
{
//Declaration
ifstream inf;

//Open file
inf.open("pop_density.txt");

//Check condition
if (!inf)
{
    //Display
    cout << "Input file is not found!" << endl;

    //Pause
    system("pause");

    //Exit on failure
    exit(EXIT_FAILURE);
}

//Declarations and initializations
string fLine;
int counter = 0;
int loc = -1;

//Read
getline(inf, fLine);

//Loop
while (inf)
{
    //File read
    loc = fLine.find('|');
    sr[counter].nameInFile = fLine.substr(0, loc);
    fLine = fLine.substr(loc + 1);
    loc = fLine.find('|');
    sr[counter].areaInFile = stod(fLine.substr(0, loc));  //line using stod
    fLine = fLine.substr(loc + 1);
    loc = fLine.find('|');
    sr[counter].popInFile = stoi(fLine.substr(0, loc));
    fLine = fLine.substr(loc + 1);
    sr[counter].densityInFile = stod(fLine);   //line using stod
    counter++;
    getline(inf, fLine);
}

//Return
return counter;
}

Below is the text I am trying to read:

Census Tract 201, Autauga County, Alabama|9.84473419420788|1808|183.651479494869
Census Tract 202, Autauga County, Alabama|3.34583234555866|2355|703.860730836106
Census Tract 203, Autauga County, Alabama|5.35750339330735|3057|570.60159846447

Body:
Use std::istringstream.

std::string number_as_text("123");
int value;
std::istringstream number_stream(number_as_text);
number_stream >> value;

Edit 2:  For those pedantic people:

The example below reads a double.  Very similar pattern to the above reading of an integer.

std::string number_as_text("3.14159");
double pi;
std::istringstream number_stream(number_as_text);
number_stream >> pi;

You could also use a variant of sprintf.

Edit 1: Another parsing method

You could try:

std::string tract;
std::string county;
std::string state;
double value1;
char separator;

//...
std::ifstream input("myfile.txt");
//...
std::getline(input, tract, ',');
std::getline(input, county, ',');
std::getline(input, state, '|');
input >> value1;
input >> separator;
//...
input.ignore(100000, '\n'); // Ignore any remaining characters on the line

The above doesn't require separate string to number conversion.


问:
Documentation of Spring Validation Errors
Spring, als always, provides very useful defaults to handle Validation errors. But sometimes it looks difficult to customize those. In my case I have a custom validation that uses a javascript function to validate a field in a domain object. The default validation error produces 4 message codes that use the object name, the field name, the field type and the validation type. So far so good. But I would like to add an additional code that contains the name of the js-function as a component. How could I do that?

Or more general my question is: where do I find a documentation of the way Spring builds the default error messages, and how they can be manipulated.

In my case I get an output like:

```<code>{
  "timestamp": 1457092927829,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "codes": [
        "JSValidated.order.validFrom",
        "JSValidated.validFrom",
        "JSValidated.java.time.ZonedDateTime",
        "JSValidated"
      ],
      "arguments": [
        {
          "codes": [
            "order.validFrom",
            "validFrom"
          ],
          "arguments": null,
          "defaultMessage": "validFrom",
          "code": "validFrom"
        },
        "checkOrder",
        "static/OrderValidator.js"
      ],
      "defaultMessage": "validation checkValidFrom failed",
      "objectName": "order",
      "field": "validFrom",
      "rejectedValue": 1196586930,
      "bindingFailure": false,
      "code": "JSValidated"
    },
    {
      "codes": [
        "NotEmpty.order.id",
        "NotEmpty.id",
        "NotEmpty.java.lang.String",
        "NotEmpty"
      ],
      "arguments": [
        {
          "codes": [
            "order.id",
            "id"
          ],
          "arguments": null,
          "defaultMessage": "id",
          "code": "id"
        }
      ],
      "defaultMessage": "may not be empty",
      "objectName": "order",
      "field": "id",
      "rejectedValue": null,
      "bindingFailure": false,
      "code": "NotEmpty"
    }
  ],
  "message": "Validation failed for object='order'. Error count: 2",
  "path": "/order"
}
</code>```

How can I add or change the codes? How can I add or change the list of arguments? Where is all the stuff documented?

答:
This is a json serialization of the result of method getErrorAttributes(RequestAttributes requestAttributes,
                                             boolean includeStackTrace) of class
 org.springframework.boot.autoconfigure.web.DefaultErrorAttributes.

This class can be extended to add additional properties.

Codes and messages are added by validators, do if you'd like to change them you need to customize validators used.

Body:
Spring, als always, provides very useful defaults to handle Validation errors. But sometimes it looks difficult to customize those. In my case I have a custom validation that uses a javascript function to validate a field in a domain object. The default validation error produces 4 message codes that use the object name, the field name, the field type and the validation type. So far so good. But I would like to add an additional code that contains the name of the js-function as a component. How could I do that?

Or more general my question is: where do I find a documentation of the way Spring builds the default error messages, and how they can be manipulated.

In my case I get an output like:

{
  "timestamp": 1457092927829,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "codes": [
        "JSValidated.order.validFrom",
        "JSValidated.validFrom",
        "JSValidated.java.time.ZonedDateTime",
        "JSValidated"
      ],
      "arguments": [
        {
          "codes": [
            "order.validFrom",
            "validFrom"
          ],
          "arguments": null,
          "defaultMessage": "validFrom",
          "code": "validFrom"
        },
        "checkOrder",
        "static/OrderValidator.js"
      ],
      "defaultMessage": "validation checkValidFrom failed",
      "objectName": "order",
      "field": "validFrom",
      "rejectedValue": 1196586930,
      "bindingFailure": false,
      "code": "JSValidated"
    },
    {
      "codes": [
        "NotEmpty.order.id",
        "NotEmpty.id",
        "NotEmpty.java.lang.String",
        "NotEmpty"
      ],
      "arguments": [
        {
          "codes": [
            "order.id",
            "id"
          ],
          "arguments": null,
          "defaultMessage": "id",
          "code": "id"
        }
      ],
      "defaultMessage": "may not be empty",
      "objectName": "order",
      "field": "id",
      "rejectedValue": null,
      "bindingFailure": false,
      "code": "NotEmpty"
    }
  ],
  "message": "Validation failed for object='order'. Error count: 2",
  "path": "/order"
}

How can I add or change the codes? How can I add or change the list of arguments? Where is all the stuff documented?


问:
Comma initialization and Constructors C++ and Eigen
I'm using Eigen library in C++ and I'm trying to find the determinant of a matrix. I'm getting different results depending on how I initialize the matrices.

Method I:

```<code>MatrixXd a(3, 3);
for (int n = 0; n < 3; n++)
    for (int m = 0; m < 3; m++)
        a(n,m) = (double) (n + m*m + 2.5)/3;

cout << "Matrix a: " << endl;
cout << a << endl;
cout << "Determinat of matrix a is: " << a.determinant() << endl;
</code>```

This part of the code prints

```<code>Matrix a:
0.8333333  1.166667  2.166667
1.166667       1.5       2.5
1.5  1.833333  2.833333
Determinat of matrix a is: -7.401487e-17
</code>```

Method II:

```<code>MatrixXd b(3, 3);
b << 0.8333333, 1.166667, 2.166667,
    1.166667, 1.5, 2.5,
    1.5, 1.833333, 2.833333;

cout << b;
cout << endl << "Determinant of matrix b is: " << b.determinant();
</code>```

which prints

```<code>0.8333333  1.166667  2.166667
1.166667       1.5       2.5
1.5  1.833333  2.833333
Determinant of matrix b is: 2.333331e-07
</code>```

Method I produces the wrong result while Method II gives the right answer. What's going wrong in the first case? (I'm using Visual Studio.) Thanks in advance!

答:
What you are observing here are rounding errors in your calculations. Let me explain it like this:

For a computer, everything is based on the binary number system, i.e. instead of base 10 like we mostly use in our everyday lives, computers calculate with base 2, i.e. only the digits 0 and 1.

This not only applies to integers, but also to real numbers like 0.83333...
But just like it is impossible to write all digits of 0.83333..., your computer cannot store every last digit of the binary representation of this number - thus it has to round the result somehow.

Depending on how you initialize it (either by computing (n + m*m + 2.5)/3 or by reading the value from your comma-initialization), the result might be slightly different in one of the last digits, thus leading to different results.

You can try this out by comparing 0.8333333 with 2.5/3, which will probably return false. If you print the numbers, you get the same result, but the internal representation differs ever so slightly.

However you should note that the absolute error itself is quite small (smaller than 0.000001), so you don't need to worry about it at the moment.
If you want exact results, it might be helpful to switch to a rational number type which can represent these values exactly.

Body:
I'm using Eigen library in C++ and I'm trying to find the determinant of a matrix. I'm getting different results depending on how I initialize the matrices.

Method I:

MatrixXd a(3, 3);
for (int n = 0; n < 3; n++)
    for (int m = 0; m < 3; m++)
        a(n,m) = (double) (n + m*m + 2.5)/3;

cout << "Matrix a: " << endl;
cout << a << endl;
cout << "Determinat of matrix a is: " << a.determinant() << endl;

This part of the code prints

Matrix a:
0.8333333  1.166667  2.166667
1.166667       1.5       2.5
1.5  1.833333  2.833333
Determinat of matrix a is: -7.401487e-17

Method II:

MatrixXd b(3, 3);
b << 0.8333333, 1.166667, 2.166667,
    1.166667, 1.5, 2.5,
    1.5, 1.833333, 2.833333;

cout << b;
cout << endl << "Determinant of matrix b is: " << b.determinant();

which prints

0.8333333  1.166667  2.166667
1.166667       1.5       2.5
1.5  1.833333  2.833333
Determinant of matrix b is: 2.333331e-07

Method I produces the wrong result while Method II gives the right answer. What's going wrong in the first case? (I'm using Visual Studio.) Thanks in advance!


问:
How do I put Bookdown chapters in a subdirectory?
I can't figure put how to make a book with Rmd files in a subdirectory.

Here's my current directory structure:

myProject.Rproj

index.RMD

_bookdown.yml

chapters/

chapt1.RMD

chapt2.RMD

extraThatShouldNotBeIncluded.RMD

What should go in _bookdown.yml and in index.RMD to make this work?

答:
It turns out that you just have to specify the directory of each RMD in _bookdown.yml:

```<code>rmd_files: ["index.Rmd", "chapters/chapt1.RMD", "chapters/chapt2.RMD"]
</code>```

Body:
It turns out that you just have to specify the directory of each RMD in _bookdown.yml:

rmd_files: ["index.Rmd", "chapters/chapt1.RMD", "chapters/chapt2.RMD"]


问:
Count the number of set bits in a 32-bit integer
8 bits representing the number 7 look like this:

```<code>00000111
</code>```

Three bits are set.

What are the algorithms to determine the number of set bits in a 32-bit integer?

答:
I have not seen this approach anywhere:

```<code>int nbits(unsigned char v) {
    return ((((v - ((v >> 1) & 0x55)) * 0x1010101) & 0x30c00c03) * 0x10040041) >> 0x1c;
}
</code>```

It works per byte, so it would have to be called four times for a 32-bit integer. It is derived from the sideways addition, but it uses two 32-bit multiplications to reduce the number of instructions to only seven.

Most current C compilers will optimize this function using SIMD (SSE2) instructions when it is clear that the number of requests is a multiple of 4, and it becomes quite competitive.  It is portable, can be defined as a macro or inline function and does not need data tables.

This approach can be extended to work on 16 bits at a time, using 64-bit multiplications. However, it fails when all 16 bits are set, returning zero, so it can be used only when the 0xFFFF input value is not present.  It is also slower due to the 64-bit operations and does not optimize well.

OwnerDisplayName: Matt Howells

ContentLicense: CC BY-SA 4.0

Body:
8 bits representing the number 7 look like this:

00000111

Three bits are set.

What are the algorithms to determine the number of set bits in a 32-bit integer?

LastEditorDisplayName: Nils

Body:
I have not seen this approach anywhere:

int nbits(unsigned char v) {
    return ((((v - ((v >> 1) & 0x55)) * 0x1010101) & 0x30c00c03) * 0x10040041) >> 0x1c;
}

It works per byte, so it would have to be called four times for a 32-bit integer. It is derived from the sideways addition, but it uses two 32-bit multiplications to reduce the number of instructions to only seven.

Most current C compilers will optimize this function using SIMD (SSE2) instructions when it is clear that the number of requests is a multiple of 4, and it becomes quite competitive.  It is portable, can be defined as a macro or inline function and does not need data tables.

This approach can be extended to work on 16 bits at a time, using 64-bit multiplications. However, it fails when all 16 bits are set, returning zero, so it can be used only when the 0xFFFF input value is not present.  It is also slower due to the 64-bit operations and does not optimize well.


问:
Creating an anonymous object that implements an interface with overloaded functions
I have a TypeScript interface that has a single function called "send" that is overloaded with two allowed signatures.

```<code>export interface ConnectionContext {
    send(data: ConnectionData): void;
    send(data: ConnectionData, timeout: number): Promise<ConnectionData>;
}
</code>```

I'm trying to create an anonymous object that implements this interface:

```<code>const context: ConnectionContext = {
    send: (data: ConnectionData, timeout?: number): void | Promise<ConnectionData> => {
        //
    }
};
</code>```

However, TypeScript 2.4.1 is producing the following errors:

Error:(58, 15) TS2322:Type '{ send: (data: ConnectionData, timeout?: number | undefined) => void | Promise<ConnectionData>; }' is not assignable to type 'ConnectionContext'.

Types of property 'send' are incompatible.

Type '(data: ConnectionData, timeout?: number | undefined) => void | Promise<ConnectionData>' is not assignable to type '{ (data: ConnectionData): void; (data: ConnectionData, timeout: number): Promise<ConnectionData>; }'.

Type 'void | Promise<ConnectionData>' is not assignable to type 'Promise<ConnectionData>'.

Type 'void' is not assignable to type 'Promise<ConnectionData>'.

I know I can do this with a class but I'd rather not create an entire class if there is some way to do this without one.

答:
Figured it out - if a function has overload signatures, type the base function as any. This is counterintuitive, but is how TypeScript currently works.

Fixed code:

```<code>export interface ConnectionContext {
  send(data: ConnectionData): void;
  send(data: ConnectionData, timeout: number): Promise<ConnectionData>;
}

const context: ConnectionContext = {
  send: (data: ConnectionData, timeout?: number): any => {}
};

let a = context.send(1)     // void
let b = context.send(1, 2)  // Promise<ConnectionData>
</code>```

TypeScript playground link

See the very last paragraph from the TypeScript Handbook's functions section:

Note that the function pickCard(x): any piece is not part of the overload list, so it only has two overloads: one that takes an object and one that takes a number. Calling pickCard with any other parameter types would cause an error.

Body:
I have a TypeScript interface that has a single function called "send" that is overloaded with two allowed signatures.

export interface ConnectionContext {
    send(data: ConnectionData): void;
    send(data: ConnectionData, timeout: number): Promise<ConnectionData>;
}

I'm trying to create an anonymous object that implements this interface:

const context: ConnectionContext = {
    send: (data: ConnectionData, timeout?: number): void | Promise<ConnectionData> => {
        //
    }
};

However, TypeScript 2.4.1 is producing the following errors:

Error:(58, 15) TS2322:Type '{ send: (data: ConnectionData, timeout?: number | undefined) => void | Promise<ConnectionData>; }' is not assignable to type 'ConnectionContext'.

Types of property 'send' are incompatible.

Type '(data: ConnectionData, timeout?: number | undefined) => void | Promise<ConnectionData>' is not assignable to type '{ (data: ConnectionData): void; (data: ConnectionData, timeout: number): Promise<ConnectionData>; }'.

Type 'void | Promise<ConnectionData>' is not assignable to type 'Promise<ConnectionData>'.

Type 'void' is not assignable to type 'Promise<ConnectionData>'.

I know I can do this with a class but I'd rather not create an entire class if there is some way to do this without one.

Body:
Figured it out - if a function has overload signatures, type the base function as any. This is counterintuitive, but is how TypeScript currently works.

Fixed code:

export interface ConnectionContext {
  send(data: ConnectionData): void;
  send(data: ConnectionData, timeout: number): Promise<ConnectionData>;
}

const context: ConnectionContext = {
  send: (data: ConnectionData, timeout?: number): any => {}
};

let a = context.send(1)     // void
let b = context.send(1, 2)  // Promise<ConnectionData>

<a href="http://www.typescriptlang.org/play/index.html#src=type%20ConnectionData%20%3D%20number%20%2F%2F%20mock%0D%0A%0D%0Aexport%20interface%20ConnectionContext%20%7B%0D%0A%20%20%20%20send(data%3A%20ConnectionData)%3A%20void%3B%0D%0A%20%20%20%20send(data%3A%20ConnectionData%2C%20timeout%3A%20number)%3A%20Promise%3CConnectionData%3E%3B%0D%0A%7D%0D%0A%0D%0Aconst%20context%3A%20ConnectionContext%20%3D%20%7B%0D%0A%20%20%20%20send%3A%20(data%3A%20ConnectionData%2C%20timeout%3F%3A%20number)%3A%20any%20%3D%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20%2F%2F%20%0D%0A%20%20%20%20%7D%0D%0A%7D%3B%0D%0A%0D%0Alet%20a%20%3D%20context.send(1)%20%20%20%20%20%2F%2F%20void%0D%0Alet%20b%20%3D%20context.send(1%2C%202)%20%20%2F%2F%20Promise%3CConnectionData%3E" rel="nofollow noreferrer">TypeScript playground link

See the very last paragraph from the TypeScript Handbook's functions section:

Note that the function pickCard(x): any piece is not part of the overload list, so it only has two overloads: one that takes an object and one that takes a number. Calling pickCard with any other parameter types would cause an error.


问:
Asp.Net Core 2.0 on Azure results in a 502.5
I have a small web app developed with Asp.Net Core 1.1 deployed on Azure and it works well. I just migrated the project to use Asp.Net Core 2.0 and tried to deploy it on Azure. The deployment went fine but when I open the site, I get a 502.5 error. When I check my Azure log stream, I get the following error:

This error occurs when a CGI application does not return a valid set
  of HTTP headers, or when a proxy or gateway was unable to send the
  request to a parent gateway. You may need to get a network trace or
  contact the proxy server administrator, if it is not a CGI problem.

Useless to say that it works well on my development machine with the same code. Note that I'm also using Entity Framework Core 2.0 although I deactivated the database creation on Azure (to check if it was not the cause).

For information, the way I migrated from 1.1 to 2.0 is by changing the target framework settings to "netcoreapp2.0" and by using the NuGet package "Microsoft.AspNetCore.All". Just to be sure, I also deleted my publish profile and recreate one.

Is it possible that Asp.Net Core 2.0 is not yet available on Azure ? I'm fairly new to Asp.Net Core, so I don't know when new releases are made available on Azure.

EDIT

When I try to run my app with dot net CLI via the debug console as proposed by natemcmaster, I got the following issue:

Unhandled Exception: System.IO.FileLoadException: Could not load file
  or assembly 'Microsoft.AspNetCore.Hosting.Abstractions,
  Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
  The located assembly's manifest definition does not match the assembly
  reference. (Exception from HRESULT: 0x80131040)

I downloaded the DLL on my desktop and check the version with Dot Net Peak and indeed, the DLL is 1.1.2, although I created the project with Visual Studio and directly publish it, so is it an issue with Visual Studio ? Or Nuget ?

答:
the issue was actually coming from the fact that, at first, my web app was using .net core 1.1, which deploys all the DLL in the "wwwroot" folder of the web application. However, with asp.net core 2.0, it does not do that anymore as the DLL are picked up from a global store. However, as Visual Studio does not clean the destination folder before a publish, I ended up with a situation where the 1.1 DLL were in my wwwroot, so the web site was picking up these ones instead of the 2.0 ones in the store folder.

This is explained in more details here: https://github.com/Azure/app-service-announcements-discussions/issues/2#issuecomment-313816550


问:
How to check whether the Redis server is running
How to check whether the Redis server is running?

If it's not running, I want to fallback to using the database.

I'm using the FuelPHP framework, so I'm open to a solution based on this, or just standard PHP.

答:
You can use command line to determine if redis is running:

```<code>redis-cli ping
</code>```

you should get back

```<code>PONG
</code>```

that indicates redis is up and running.

Body:
You can use command line to determine if redis is running:

redis-cli ping

you should get back

PONG

that indicates redis is up and running.


问:
Can recursion be used to guarantee an object gets saved to the DB in Ruby?
I am making payouts to my sub-merchants and wanted to know if I could use recursion to guarantee that when a payout is made to them, we save that data to our DB.

Example:

```<code>def make_payout
  result = object.process_payout_through_gateway
  if result.success?
    payout = Payout.new
    payout[:paid] = true
    save_payout(payout)
  end
end

def save_payout(payout)
  begin
    payout.save!
  rescue e
    save_payout(payout)
  end
end
</code>```

答:
Thanks guys, all great answers. I personally went with:

```<code>def save_payout(payout)
  begin
    payout.save!
  rescue e
    puts "Payment to User-ID: #{current_user.id} FAILED TO SAVE! #{e}"
    UserMailer.send_payout_failure_email(current_user.id).deliver_now
  end
end
</code>```

I won't mark a "right" answer and just let everyone up-vote their favorite route.

Body:
I am making payouts to my sub-merchants and wanted to know if I could use recursion to guarantee that when a payout is made to them, we save that data to our DB.

Example:

def make_payout
  result = object.process_payout_through_gateway
  if result.success?
    payout = Payout.new
    payout[:paid] = true
    save_payout(payout)
  end
end

def save_payout(payout)
  begin
    payout.save!
  rescue e
    save_payout(payout)
  end
end

Body:
Thanks guys, all great answers. I personally went with:

def save_payout(payout)
  begin
    payout.save!
  rescue e
    puts "Payment to User-ID: #{current_user.id} FAILED TO SAVE! #{e}"
    UserMailer.send_payout_failure_email(current_user.id).deliver_now
  end
end

I won't mark a "right" answer and just let everyone up-vote their favorite route.


问:
sending mail but no message-id
I am getting interesting rejections from my clients mail server when sending a mail with indy-10's tidMessage component saying:

550 Rejected: Message does not contain a Message-ID

I get this even when using indy's own demo app

http://www.indyproject.org/DemoDownloads/Indy_10_MailClient.zip

what do I do to fix this. thanks!

答:
TIdMessage in Indy 10 intentionally omits the 'Message-Id' header when encoding an email to a socket or TStream.  You will have to use the TIdMessage.ExtraHeaders property, eg:

```<code>IdMessage1.MsgId := '...';
IdMessage1.ExtraHeaders.Values['Message-Id'] := IdMessage1.MsgId;
</code>```

EDIT:

As a followup for this - TIdMessage has now been updated with logic changes in how it handles the "Message-ID" and "In-Reply-To" headers:

https://www.indyproject.org/2016/09/12/logic-changes-in-tidmessage-regarding-message-id-and-in-reply-to-headers/

The TIdMessage.MsgId property now generates a "Message-ID" header regardless of whether the email is being saved, streamed, or transmitted.  So you do not need to use the ExtraHeaders property anymore.

ContentLicense: CC BY-SA 2.5

Title: sending mail but no message-id

Body:
TIdMessage in Indy 10 intentionally omits the 'Message-Id' header when encoding an email to a socket or TStream.  You will have to use the TIdMessage.ExtraHeaders property, eg:

IdMessage1.MsgId := '...';
IdMessage1.ExtraHeaders.Values['Message-Id'] := IdMessage1.MsgId;

EDIT:

As a followup for this - TIdMessage has now been updated with logic changes in how it handles the "Message-ID" and "In-Reply-To" headers:

https://www.indyproject.org/2016/09/12/logic-changes-in-tidmessage-regarding-message-id-and-in-reply-to-headers/

The TIdMessage.MsgId property now generates a "Message-ID" header regardless of whether the email is being saved, streamed, or transmitted.  So you do not need to use the ExtraHeaders property anymore.


问:
D3 v4 force graph with images as nodes
Having problems using images as nodes in a force-directed graph. Everything I've looked at so far seems to be v3 code and I haven't been able to get any images at all so far, whether using xlink:href or svg:image or both.

What's the right way to use an img as a node with v4?

Here's what I'm trying, and a jsfiddle.

As you can see in the CSS, I'm trying to get images from a spritesheet for each node.

```<code>var defs = d3.append("svg:defs");

defs.append("svg:pattern")
      .attr("width", 48)
      .attr("height", 48)
      //.attr("patternUnits", "userSpaceOnUse")
      .append("svg:image")
      .attr("xlink:href", "http://placekitten.com/g/48/48")
      .attr("width", 48)
      .attr("height", 48)
      .attr("x", 0)
      .attr("y", 0);

var nodesDrawn = svg
.selectAll("node")
.data(nodesData)
.enter()
.append("g")
//.append("xhtml:i")
.append('circle')
.attr('r', 10);
</code>```

答:
The problems so far:

There is no d3.append in D3. You probably meant svg.append.

Set the width and the height of the <pattern> to 1.

Set an ID to the <pattern> and use that to fill the circles.

Here are the code with that changes (I'm increasing the circles' radii, so you can better see the image): https://jsfiddle.net/ppk23hnz/

By the way, none of those changes are related to D3 version: they are the same in v3.x and v4.x.

PS: Don't mix jQuery and D3. you don't need that (and it's quite disturbing).

Title: D3 v4 force graph with images as nodes

Body:
Having problems using images as nodes in a force-directed graph. Everything I've looked at so far seems to be v3 code and I haven't been able to get any images at all so far, whether using xlink:href or svg:image or both.

What's the right way to use an img as a node with v4?

Here's what I'm trying, and a jsfiddle.

As you can see in the CSS, I'm trying to get images from a spritesheet for each node.

var defs = d3.append("svg:defs");

defs.append("svg:pattern")
      .attr("width", 48)
      .attr("height", 48)
      //.attr("patternUnits", "userSpaceOnUse")
      .append("svg:image")
      .attr("xlink:href", "http://placekitten.com/g/48/48")
      .attr("width", 48)
      .attr("height", 48)
      .attr("x", 0)
      .attr("y", 0);

var nodesDrawn = svg
.selectAll("node")
.data(nodesData)
.enter()
.append("g")
//.append("xhtml:i")
.append('circle')
.attr('r', 10);


问:
Uploading multiple pictures from the same form in CakePHP 1.2
I have a one-to-many relationship where one House can have many Pictures. The models that I have are "House" and "Picture". I am using CakePHP 1.2 and I can upload one picture successfully by using this:

```<code>echo $form->input('Picture.filename', array('type' => 'file', 'label' => __l('Image')));
</code>```

In my houses_controller.php file, I have this code to save the picture and corresponding association with its house:

```<code>$this->House->Picture->save($this->data['Picture']);
</code>```

But I need to save several pictures now. I read the documentation at https://book.cakephp.org/1.2/en/The-Manual/Core-Helpers/Form.html and based on that information, I am trying to use this:

```<code>echo $form->input('Picture.0.filename', array('type' => 'file', 'label' => __l('Image 1'));
echo $form->input('Picture.1.filename', array('type' => 'file', 'label' => __l('Image 2'));
</code>```

Then my houses_controller.php file has this:

```<code>$this->House->Picture->saveAll($this->data['Picture']);
</code>```

I see that one new record is saved in my pictures table, but I was expecting to see two new entries in my table because I should have added two pictures, not only one. Any ideas about why this may not be saving two pictures for me? Thank you.

答:
Solution:

```<code>$this->Deal->Picture->save($this->data['Picture'][0]);
$this->Deal->Picture->save($this->data['Picture'][1]);
</code>```

Using $this->data['Picture'] was not sufficient because the array was returning multiple elements, so I had to reference each with the corresponding index such as $this->data['Picture'][0] for the first element, $this->data['Picture'][1] for the second one, etc.

NOTE: It was not saving two records for me, even thought I was using save() twice. But that was another issue. You can read the answers at Save multiple times in Cakephp for the corresponding solution. Basically you need to use create() before you use save().

Body:
I have a one-to-many relationship where one House can have many Pictures. The models that I have are "House" and "Picture". I am using CakePHP 1.2 and I can upload one picture successfully by using this:

echo $form->input('Picture.filename', array('type' => 'file', 'label' => __l('Image')));

In my houses_controller.php file, I have this code to save the picture and corresponding association with its house:

$this->House->Picture->save($this->data['Picture']);

But I need to save several pictures now. I read the documentation at https://book.cakephp.org/1.2/en/The-Manual/Core-Helpers/Form.html and based on that information, I am trying to use this:

echo $form->input('Picture.0.filename', array('type' => 'file', 'label' => __l('Image 1'));
echo $form->input('Picture.1.filename', array('type' => 'file', 'label' => __l('Image 2'));

Then my houses_controller.php file has this:

$this->House->Picture->saveAll($this->data['Picture']);

I see that one new record is saved in my pictures table, but I was expecting to see two new entries in my table because I should have added two pictures, not only one. Any ideas about why this may not be saving two pictures for me? Thank you.

Body:
Solution:

$this->Deal->Picture->save($this->data['Picture'][0]);
$this->Deal->Picture->save($this->data['Picture'][1]);

Using $this->data['Picture'] was not sufficient because the array was returning multiple elements, so I had to reference each with the corresponding index such as $this->data['Picture'][0] for the first element, $this->data['Picture'][1] for the second one, etc.

NOTE: It was not saving two records for me, even thought I was using save() twice. But that was another issue. You can read the answers at Save multiple times in Cakephp for the corresponding solution. Basically you need to use create() before you use save().


问:
libcurl async integration with kevent on macOS Sierra
I'm integrating curl into an asynchronous I/O event loop based on kqueue.

libcurl has an excellent API for integrating into the applications event loop.

You provide libcurl with two callbacks, one to set a timer (used to limit request/connect times), and the other to register a libcurl's file descriptors for read/write/error events.

The documentation for the callback used to perform FD registration is here: CURLMOPT_SOCKETFUNCTION

The argument that informs the callback of what events libcurl is interested in, has four enum values:

```<code>CURL_POLL_IN

Wait for incoming data. For the socket to become readable.

CURL_POLL_OUT

Wait for outgoing data. For the socket to become writable.

CURL_POLL_INOUT

Wait for incoming and outgoing data. For the socket to become readable or writable.

CURL_POLL_REMOVE

The specified socket/file descriptor is no longer used by libcurl.
</code>```

Although not explicitly documented, libcurl expects, that on subsequent calls to the callback, that the filter state of the event loop, be updated to match what it passed. i.e. If on the first call it passed CURL_POLL_IN (EVFILT_READ) and on a subsequent call it passed CURL_POLL_OUT (EVFILT_WRITE), then the original EVFILT_READ filter would be removed.

I updated the FD registration code to handle this.

```<code>int fr_event_fd_insert(fr_event_list_t *el, int fd,
               fr_event_fd_handler_t read,
               fr_event_fd_handler_t write,
               fr_event_fd_handler_t error,
               void *ctx)
{
    int       filter = 0;
    struct kevent evset[2];
    struct kevent *ev_p = evset;
    fr_event_fd_t *ef, find;

    if (!el) {
        fr_strerror_printf("Invalid argument: NULL event list");
        return -1;
    }

    if (!read && !write) {
        fr_strerror_printf("Invalid arguments: NULL read and write callbacks");
        return -1;
    }

    if (fd < 0) {
        fr_strerror_printf("Invalid arguments: Bad FD %i", fd);
        return -1;
    }

    if (el->exit) {
        fr_strerror_printf("Event loop exiting");
        return -1;
    }

    memset(&find, 0, sizeof(find));

    /*
     *  Get the existing fr_event_fd_t if it exists.
     */
    find.fd = fd;
    ef = rbtree_finddata(el->fds, &find);
    if (!ef) {
        ef = talloc_zero(el, fr_event_fd_t);
        if (!ef) {
            fr_strerror_printf("Out of memory");
            return -1;
        }
        talloc_set_destructor(ef, _fr_event_fd_free);
        el->num_fds++;
        ef->fd = fd;
        rbtree_insert(el->fds, ef);
    /*
     *  Existing filters will be overwritten if there's
     *  a new filter which takes their place.  If there
     *  is no new filter however, we need to delete the
     *  existing one.
     */
    } else {
        if (ef->read && !read) filter |= EVFILT_READ;
        if (ef->write && !write) filter |= EVFILT_WRITE;

        if (filter) {
            EV_SET(ev_p++, ef->fd, filter, EV_DELETE, 0, 0, 0);
            filter = 0;
        }

        /*
         *  I/O handler may delete an event, then
         *  re-add it.  To avoid deleting modified
         *  events we unset the do_delete flag.
         */
        ef->do_delete = false;
    }

    ef->ctx = ctx;

    if (read) {
        ef->read = read;
        filter |= EVFILT_READ;
    }

    if (write) {
        ef->write = write;
        filter |= EVFILT_WRITE;
    }
    ef->error = error;

    EV_SET(ev_p++, fd, filter, EV_ADD | EV_ENABLE, 0, 0, ef);
    if (kevent(el->kq, evset, ev_p - evset, NULL, 0, NULL) < 0) {
        fr_strerror_printf("Failed inserting event for FD %i: %s", fd, fr_syserror(errno));
        talloc_free(ef);
        return -1;
    }
    ef->is_registered = true;

    return 0;
 }
</code>```

Unfortunately, it doesn't work.  kevent does not appear to remove the old filters (we continue to receive notifications from them).

What's weirder is if I apply the two operations in two separate calls, it works perfectly.

```<code>if (filter) {
    EV_SET(&evset, ef->fd, filter, EV_DELETE, 0, 0, 0);
    kevent(el->kq, evset, ev_p - evset, NULL, 0, NULL);
    filter = 0;
}
</code>```

Is this a bug in Sierra's kevent implementation, or did I misunderstand how kevent should work?

答:
The problem here, is that you can't 'or' together the EVFILT_READ and EVFILT_WRITE flags.

When enabling or disabling multiple filters you need to call EV_SET() multiple times, on multiple evset structures.

The non-functional code in the example above:

```<code>struct kevent evset[2];
struct kevent *ev_p = evset;

if (read) {
    ef->read = read;
    filter |= EVFILT_READ;
}

if (write) {
    ef->write = write;
    filter |= EVFILT_WRITE;
}
ef->error = error;

EV_SET(ev_p++, fd, filter, EV_ADD | EV_ENABLE, 0, 0, ef);
event(el->kq, evset, ev_p - evset, NULL, 0, NULL)
</code>```

becomes:

```<code>int count = 0;
struct ev_set[2];

if (read) {
    ef->read = read;
    EV_SET(ev_set[count++], fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, ef);
}

if (write) {
    ef->write = write;
    EV_SET(ev_set[count++], fd, EVFILT_WRITE, EV_ADD | EV_ENABLE, 0, 0, ef);
}
ef->error = error;
kevent(el->kq, ev_set, count, NULL, 0, NULL)
</code>```

After making this change everything worked as expected.

Body:
I'm integrating curl into an asynchronous I/O event loop based on kqueue.

libcurl has an excellent API for integrating into the applications event loop.

You provide libcurl with two callbacks, one to set a timer (used to limit request/connect times), and the other to register a libcurl's file descriptors for read/write/error events.

The documentation for the callback used to perform FD registration is here: CURLMOPT_SOCKETFUNCTION

The argument that informs the callback of what events libcurl is interested in, has four enum values:

CURL_POLL_IN

Wait for incoming data. For the socket to become readable.

CURL_POLL_OUT

Wait for outgoing data. For the socket to become writable.

CURL_POLL_INOUT

Wait for incoming and outgoing data. For the socket to become readable or writable.

CURL_POLL_REMOVE

The specified socket/file descriptor is no longer used by libcurl.

Although not explicitly documented, libcurl expects, that on subsequent calls to the callback, that the filter state of the event loop, be updated to match what it passed. i.e. If on the first call it passed CURL_POLL_IN (EVFILT_READ) and on a subsequent call it passed CURL_POLL_OUT (EVFILT_WRITE), then the original EVFILT_READ filter would be removed.

I updated the FD registration code to handle this.

int fr_event_fd_insert(fr_event_list_t *el, int fd,
               fr_event_fd_handler_t read,
               fr_event_fd_handler_t write,
               fr_event_fd_handler_t error,
               void *ctx)
{
    int       filter = 0;
    struct kevent evset[2];
    struct kevent *ev_p = evset;
    fr_event_fd_t *ef, find;

    if (!el) {
        fr_strerror_printf("Invalid argument: NULL event list");
        return -1;
    }

    if (!read && !write) {
        fr_strerror_printf("Invalid arguments: NULL read and write callbacks");
        return -1;
    }

    if (fd < 0) {
        fr_strerror_printf("Invalid arguments: Bad FD %i", fd);
        return -1;
    }

    if (el->exit) {
        fr_strerror_printf("Event loop exiting");
        return -1;
    }

    memset(&find, 0, sizeof(find));

    /*
     *  Get the existing fr_event_fd_t if it exists.
     */
    find.fd = fd;
    ef = rbtree_finddata(el->fds, &find);
    if (!ef) {
        ef = talloc_zero(el, fr_event_fd_t);
        if (!ef) {
            fr_strerror_printf("Out of memory");
            return -1;
        }
        talloc_set_destructor(ef, _fr_event_fd_free);
        el->num_fds++;
        ef->fd = fd;
        rbtree_insert(el->fds, ef);
    /*
     *  Existing filters will be overwritten if there's
     *  a new filter which takes their place.  If there
     *  is no new filter however, we need to delete the
     *  existing one.
     */
    } else {
        if (ef->read && !read) filter |= EVFILT_READ;
        if (ef->write && !write) filter |= EVFILT_WRITE;

        if (filter) {
            EV_SET(ev_p++, ef->fd, filter, EV_DELETE, 0, 0, 0);
            filter = 0;
        }

        /*
         *  I/O handler may delete an event, then
         *  re-add it.  To avoid deleting modified
         *  events we unset the do_delete flag.
         */
        ef->do_delete = false;
    }

    ef->ctx = ctx;

    if (read) {
        ef->read = read;
        filter |= EVFILT_READ;
    }

    if (write) {
        ef->write = write;
        filter |= EVFILT_WRITE;
    }
    ef->error = error;

    EV_SET(ev_p++, fd, filter, EV_ADD | EV_ENABLE, 0, 0, ef);
    if (kevent(el->kq, evset, ev_p - evset, NULL, 0, NULL) < 0) {
        fr_strerror_printf("Failed inserting event for FD %i: %s", fd, fr_syserror(errno));
        talloc_free(ef);
        return -1;
    }
    ef->is_registered = true;

    return 0;
 }

Unfortunately, it doesn't work.  kevent does not appear to remove the old filters (we continue to receive notifications from them).

What's weirder is if I apply the two operations in two separate calls, it works perfectly.

if (filter) {
    EV_SET(&evset, ef->fd, filter, EV_DELETE, 0, 0, 0);
    kevent(el->kq, evset, ev_p - evset, NULL, 0, NULL);
    filter = 0;
}

Is this a bug in Sierra's kevent implementation, or did I misunderstand how kevent should work?

Body:
The problem here, is that you can't 'or' together the EVFILT_READ and EVFILT_WRITE flags.

When enabling or disabling multiple filters you need to call EV_SET() multiple times, on multiple evset structures.

The non-functional code in the example above:

struct kevent evset[2];
struct kevent *ev_p = evset;

if (read) {
    ef->read = read;
    filter |= EVFILT_READ;
}

if (write) {
    ef->write = write;
    filter |= EVFILT_WRITE;
}
ef->error = error;

EV_SET(ev_p++, fd, filter, EV_ADD | EV_ENABLE, 0, 0, ef);
event(el->kq, evset, ev_p - evset, NULL, 0, NULL)

becomes:

int count = 0;
struct ev_set[2];

if (read) {
    ef->read = read;
    EV_SET(ev_set[count++], fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, ef);
}

if (write) {
    ef->write = write;
    EV_SET(ev_set[count++], fd, EVFILT_WRITE, EV_ADD | EV_ENABLE, 0, 0, ef);
}
ef->error = error;
kevent(el->kq, ev_set, count, NULL, 0, NULL)

After making this change everything worked as expected.


问:
Prolog Duplicate a word in list
I have a Prolog code that duplicates whole list but what I want is duplicate only a single word(for example 'a'). For example;

```<code>dups([],[]).
dups([H|T],[H,H|Y]) :-
    dups(T,Y).
</code>```

My code duplicates list [a,b] like => [a, a ,b ,b].

But what i want is, duplicate list [a, b] like => [a, a, b].

答:
Since you are describing lists you can opt to use DCGs. Consider the following rules:

```<code>x_dup(_X,[]) -->       % if the input list is empty
   [].                 % the output list is empty
x_dup(X,[X|Ys]) -->    % if X and the head of the list are equal
   [X,X],              % X is twice in the output list
   x_dup(X,Ys).        % the same holds for X and the tail
x_dup(X,[Y|Ys]) -->    % if X and the head of the input list
   {dif(X,Y)},         % are different
   [Y],                % the head is once in the output list
   x_dup(X,Ys).        % the same holds for X and the tail
</code>```

If you are only interested in duplicating the head of the list, you can define the calling predicate like so:

```<code>dups([],[]).                    % <- only for empty list
dups([X|Xs],L) :-
   phrase(x_dup(X,[X|Xs]),L).
</code>```

The first rule is only for dealing with the empty list. If you don't intend your predicate to cover that case just omit the first rule. Querying this with your example yields the desired result:

```<code>   ?- dups([a,b,a,a,c,c,c],L).
L = [a,a,b,a,a,a,a,c,c,c] ? ;
no
</code>```

Alternatively, you can define the calling predicate such that you can duplicate an arbitrary element. In that case you need an additional argument to specify the element to be duplicated:

```<code>dups(X,L1,L2) :-
   phrase(x_dup(X,L1),L2).
</code>```

Some example queries:

```<code>   ?- dups(a,[a,b,a,a,c,c,c],L).
L = [a,a,b,a,a,a,a,c,c,c] ? ;
no
   ?- dups(b,[a,b,a,a,c,c,c],L).
L = [a,b,b,a,a,c,c,c] ? ;
no
   ?- dups(c,[a,b,a,a,c,c,c],L).
L = [a,b,a,a,c,c,c,c,c,c] ? ;
no
   ?- dups(d,[a,b,a,a,c,c,c],L).
L = [a,b,a,a,c,c,c]
</code>```

Title: Prolog Duplicate a word in list

Body:
I have a Prolog code that duplicates whole list but what I want is duplicate only a single word(for example 'a'). For example;

dups([],[]).
dups([H|T],[H,H|Y]) :-
    dups(T,Y).

My code duplicates list [a,b] like => [a, a ,b ,b].

But what i want is, duplicate list [a, b] like => [a, a, b].

Body:
Since you are describing lists you can opt to use DCGs. Consider the following rules:

x_dup(_X,[]) -->       % if the input list is empty
   [].                 % the output list is empty
x_dup(X,[X|Ys]) -->    % if X and the head of the list are equal
   [X,X],              % X is twice in the output list
   x_dup(X,Ys).        % the same holds for X and the tail
x_dup(X,[Y|Ys]) -->    % if X and the head of the input list
   {dif(X,Y)},         % are different
   [Y],                % the head is once in the output list
   x_dup(X,Ys).        % the same holds for X and the tail

If you are only interested in duplicating the head of the list, you can define the calling predicate like so:

dups([],[]).                    % <- only for empty list
dups([X|Xs],L) :-
   phrase(x_dup(X,[X|Xs]),L).

The first rule is only for dealing with the empty list. If you don't intend your predicate to cover that case just omit the first rule. Querying this with your example yields the desired result:

   ?- dups([a,b,a,a,c,c,c],L).
L = [a,a,b,a,a,a,a,c,c,c] ? ;
no

Alternatively, you can define the calling predicate such that you can duplicate an arbitrary element. In that case you need an additional argument to specify the element to be duplicated:

dups(X,L1,L2) :-
   phrase(x_dup(X,L1),L2).

Some example queries:

   ?- dups(a,[a,b,a,a,c,c,c],L).
L = [a,a,b,a,a,a,a,c,c,c] ? ;
no
   ?- dups(b,[a,b,a,a,c,c,c],L).
L = [a,b,b,a,a,c,c,c] ? ;
no
   ?- dups(c,[a,b,a,a,c,c,c],L).
L = [a,b,a,a,c,c,c,c,c,c] ? ;
no
   ?- dups(d,[a,b,a,a,c,c,c],L).
L = [a,b,a,a,c,c,c]


问:
DataStudio : BigQuery & Standard SQL
How to use standard SQL queries on Google Data Studio using a BigQuery Data Source ?
Thanks</p>

答:
Google Data Studio supports #standardSQL now!

Just check the appropriate box when inserting your query.

Title: DataStudio : BigQuery & Standard SQL


问:
Will an inner transaction scope roll back if the outer transaction scope doesn't complete?
I have two transaction scopes, one within another. I would love to know if the inner transaction scope will be rolled back after it has been committed and the outer one does not complete.</p>

答:
It depends on the scope option you start the nested transaction scope with.

If you use the default option TransactionScopeOption.Required then the nested scope will enlist in the same transaction as the outer scope and as such when the outer scope rolls back the inner scope will also be rolled back even if it has called Complete.

If, however, you use TransactionScopeOption.RequiresNew then the nested scope will begin its own transaction and complete it separately from the outer scope, so it will not roll back even if the outer scope rolls back.

If you use TransactionScopeOption.Suppress then the nested scope will not take part in the outer transaction and will complete non-transactionally, thus does not form part of the work that would be rolled back if the outer transaction rolls back.


问:
Using apply() with a custom function and a second data frame
I'm trying to generate predicted values from a large number of model simulations and I'm having a hard time doing it simply. I suspect I need something from the apply() family, but I can't figure out the syntax.  Maybe my knowledge of apply() is weak. Or maybe my function is wrong.  Any suggestions?

Suppose I've got following coefficients resulting from six model simulations...

```<code>coef <- data.frame(intercept=c(2,3,5,7,2,1),
                   b1 = c(.2,.5,.6,.7,.9,.4),
                   b2 = c(10,11,12,11,9,10))
</code>```

I want to compute (predicted values or) the linear combination of each row above and each row of the following data frame...

```<code>df <- data.frame(age = c(50,20,19, 42),
                 height = c(60,72,79, 66))
</code>```

...Using the following model equation:

```<code>coef$intercept + coef$b1*df$age + coef$b2*df$height
</code>```

Done right, I should get the following 24 data values:

```<code>612.0   726.0   795.8   670.4
688.0   805.0   881.5   750
755.0   881.0   964.4   822.2
702.0   813.0   889.3   762.4
587.0   668.0   730.1   633.8
621.0   729.0   798.6   677.8
</code>```

To get the above, I've tried the following function and use of apply()...

```<code>equation <-  function(...) coef$intercept + coef$b1*df$age + coef$b2*df$height
result <- apply(df, 1, equation)
</code>```

...but I don't get the correct answer. The "result" data frame just repeats the correct diagonals. I also get the message:

```<code>> Warning messages: 1: In coef$b1 * df$age :   longer object length is
> not a multiple of shorter object length
</code>```

Yes I can get the correct answer through simple matrix multiplication:

```<code>df$ones <- 1
df <- df[,c(3, 1, 2)]
result <- as.matrix(coef) %*% t(as.matrix(df))
</code>```

But it seems to me one ought to be able to do this more generally using apply() and a custom function. Use of apply() is more compact and puts me less at risk of having my matrix columns in the wrong order.  Any suggestions?

Body:
I'm trying to generate predicted values from a large number of model simulations and I'm having a hard time doing it simply. I suspect I need something from the apply() family, but I can't figure out the syntax.  Maybe my knowledge of apply() is weak. Or maybe my function is wrong.  Any suggestions?

Suppose I've got following coefficients resulting from six model simulations...

coef <- data.frame(intercept=c(2,3,5,7,2,1),
                   b1 = c(.2,.5,.6,.7,.9,.4),
                   b2 = c(10,11,12,11,9,10))

I want to compute (predicted values or) the linear combination of each row above and each row of the following data frame...

df <- data.frame(age = c(50,20,19, 42),
                 height = c(60,72,79, 66))

...Using the following model equation:

coef$intercept + coef$b1*df$age + coef$b2*df$height

Done right, I should get the following 24 data values:

612.0   726.0   795.8   670.4
688.0   805.0   881.5   750
755.0   881.0   964.4   822.2
702.0   813.0   889.3   762.4
587.0   668.0   730.1   633.8
621.0   729.0   798.6   677.8

To get the above, I've tried the following function and use of apply()...

equation <-  function(...) coef$intercept + coef$b1*df$age + coef$b2*df$height
result <- apply(df, 1, equation)

...but I don't get the correct answer. The "result" data frame just repeats the correct diagonals. I also get the message:

> Warning messages: 1: In coef$b1 * df$age :   longer object length is
> not a multiple of shorter object length

Yes I can get the correct answer through simple matrix multiplication:

df$ones <- 1
df <- df[,c(3, 1, 2)]
result <- as.matrix(coef) %*% t(as.matrix(df))

But it seems to me one ought to be able to do this more generally using apply() and a custom function. Use of apply() is more compact and puts me less at risk of having my matrix columns in the wrong order.  Any suggestions?

Body:
Here is what I'd do:

sapply(seq_along(1:nrow(coef)), function(x){

  sapply(seq_along(1:nrow(df)), function(y) {
    coef$intercept[[x]] + coef$b1[[x]]*df$age[[y]] + coef$b2[[x]]*df$height[[y]]
  })

})

Result:

     [,1]  [,2]  [,3]  [,4]  [,5]  [,6]
[1,] 612.0 688.0 755.0 702.0 587.0 621.0
[2,] 726.0 805.0 881.0 813.0 668.0 729.0
[3,] 795.8 881.5 964.4 889.3 730.1 798.6
[4,] 670.4 750.0 822.2 762.4 633.8 677.8

Use two sapplys. One for each object (df and coef).


问:
More efficient way to multiply each column of a 2-d matrix by each slice of a 3-d matrix
I have an 8x8x25000 array W and an 8 x 25000 array r. I want to multiple each 8x8 slice of W by each column (8x1) of r and save the result in Wres, which will end up being an 8x25000 matrix.

I am accomplishing this using a for loop as such:

```<code>for i in range(0,25000):
    Wres[:,i] = np.matmul(W[:,:,i],res[:,i])
</code>```

But this is slow and I am hoping there is a quicker way to accomplish this.

Any ideas?

答:
An alternative to using np.matmul is np.einsum, which can be accomplished in 1 shorter and arguably more palatable line of code with no method chaining.

Example arrays:

```<code>np.random.seed(123)
w = np.random.rand(8,8,25000)
r = np.random.rand(8,25000)
wres = np.einsum('ijk,jk->ik',w,r)

# a quick check on result equivalency to your loop
print(np.allclose(np.matmul(w[:, :, 1], r[:, 1]), wres[:, 1]))
True
</code>```

Timing is equivalent to @Imanol's solution so take your pick of the two.  Both are 30x faster than looping.  Here, einsum will be competitive because of the size of the arrays.  With arrays larger than these, it would likely win out, and lose for smaller arrays.  See this discussion for more.

```<code>def solution1():
    return np.einsum('ijk,jk->ik',w,r)

def solution2():
    return np.squeeze(np.matmul(w.transpose(2, 0, 1), r.T[..., None])).T

def solution3():
    Wres = np.empty((8, 25000))
    for i in range(0,25000):
        Wres[:,i] = np.matmul(w[:,:,i],r[:,i])
    return Wres

%timeit solution1()
100 loops, best of 3: 2.51 ms per loop

%timeit solution2()
100 loops, best of 3: 2.52 ms per loop

%timeit solution3()
10 loops, best of 3: 64.2 ms per loop
</code>```

Credit to: @Divakar

Body:
I have an 8x8x25000 array W and an 8 x 25000 array r. I want to multiple each 8x8 slice of W by each column (8x1) of r and save the result in Wres, which will end up being an 8x25000 matrix.

I am accomplishing this using a for loop as such:

for i in range(0,25000):
    Wres[:,i] = np.matmul(W[:,:,i],res[:,i])

But this is slow and I am hoping there is a quicker way to accomplish this.

Any ideas?

Body:
An alternative to using np.matmul is np.einsum, which can be accomplished in 1 shorter and arguably more palatable line of code with no method chaining.

Example arrays:

np.random.seed(123)
w = np.random.rand(8,8,25000)
r = np.random.rand(8,25000)
wres = np.einsum('ijk,jk->ik',w,r)

# a quick check on result equivalency to your loop
print(np.allclose(np.matmul(w[:, :, 1], r[:, 1]), wres[:, 1]))
True

Timing is equivalent to @Imanol's solution so take your pick of the two.  Both are 30x faster than looping.  Here, einsum will be competitive because of the size of the arrays.  With arrays larger than these, it would likely win out, and lose for smaller arrays.  See this discussion for more.

def solution1():
    return np.einsum('ijk,jk->ik',w,r)

def solution2():
    return np.squeeze(np.matmul(w.transpose(2, 0, 1), r.T[..., None])).T

def solution3():
    Wres = np.empty((8, 25000))
    for i in range(0,25000):
        Wres[:,i] = np.matmul(w[:,:,i],r[:,i])
    return Wres

%timeit solution1()
100 loops, best of 3: 2.51 ms per loop

%timeit solution2()
100 loops, best of 3: 2.52 ms per loop

%timeit solution3()
10 loops, best of 3: 64.2 ms per loop

Credit to: @Divakar


问:
issue with forms in bootstrap and html
I have a bit of a problem and i need some help. I am learning new things and trying to get some skills with the time spend on learning.

I want to make this picture and forms look the same as the picture. I am posting my code
enter image description here

index.html

```<code><div class="jumbotron">
<div class="row">

   <div class="col-md-6 col-sm-6">
    <img class="img-responsive" src="img/lqvopodravnenasnimka.jpg" alt="smiley face">
    </div>  <!--col-md-5-->

    <div class="col-md-6 col-sm-6">
    <h3>Send Request</h3>
        <p id="mainparagraph">Заповядайте в нашия нов хотел Grand Hotel Gergana. Ние Ви предлагаме отлични условия, където можете да прекарате своите ценни свободни дни.</p>
        <form name="myForm" action="#" onsubmit="return validateForm()" method="post">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group form-group-sm" style="margin-top:20px;">
                        <label for="firstname" class="control-label">Name</label> <!--name-->
                        <br>
                        <input type="text" class="form-control" id="firstname" style="width:100%;" name="fname">
                    </div><!-- form-group-->
                </div><!--col-md-5-->

                 <div class="col-md-6">
                    <div class="form-group form-group-sm" style="margin-top:20px;">
                        <label for="surname" class="control-label">Surname</label>  <!--surname -->
                        <br>
                        <input type="text" class="form-control" id="surname" style="width:100%;" name="sname">
                    </div><!-- form-group-->
                </div><!--col-md-5-->
            </div><!--row-->

            <div class="row">
                <div class="col-md-12">
                    <div class="form-group form-group-sm" style="margin-top:20px;">
                        <label for="email" class="control-label">Email</label>
                        <br>
                        <input type="text" class="form-control" id="email" style="width:100%;" name="mail">
                    </div>
                </div>
            </div><!--row-->

            <div class="row">
                <div class="col-sm-12">
                    <div class="form-group form-group-sm" style="margin-top:20px;">
                        <label for="phone" class="control-label">Mobile phone</label>
                        <!--<span class="glyphicon glyphicon-arrow-right"><p style="color:gray; font-style:italic; font-size:0.7em;">Sample: +352XXXXXXXXX</p> -->
                        <br>
                        <input type="phone" class="form-control" id="phone" style="width:100%;" name="mphone">
                    </div>
                </div>
            </div><!--row-->

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group form-group-sm" style="margin-top:20px;">
                        <label for="date" class="control-label">Date of birth</label>
                        <br>
                        <input type="number" class="form-control" id="number" Placeholder="DD" style="width:55px;" name="day">
                        <input type="number" class="form-control" id="number" Placeholder="MM" style="width:55px;" name="month">
                        <input type="number" class="form-control" id="number" Placeholder="YYYY" style="width:90px;" name="year">
                    </div>
                </div><!--col-md-6-->

                <div class="col-md-6">
                    <div class="form-group form-group-sm" >
                        <label for="text" class="control-label" style="margin-top:20px;">Nationality</label>
                        <br>
                        <select class="options" name="cars" style="width:100%;">
                            <option value="България">България</option>
                            <option value="Румъния">Румъния</option>
                            <option value="Гърция">Гърция</option>
                            <option value="Сърбия">Сърбия</option>
                        </select>

                    </div><!--form-group-->
                </div>

                <div class="col-md-12">
                    <input type="submit" value="SAMPLE BUTTON">
                </div>
            </div><!--row-->

        </form>
    </div><!--col-md-7-->
</code>```

答:
Its quite a simple fix. You were really close! Firstly with Bootstrap you need to have a container, so that's a class that would be on your main div that holds everything so for this instance it would be your jumbotron div.

```<code><div class="jumbotron container">
</code>```

This will format 90% of what you are trying to achieve into a neat box where all the cols work in harmony with each other.

As for the input boxes, I see you were having difficulty with your date inputs. This too is an easy fix. Simply add the following code to your css:

```<code>#number {
   float: left;
}
</code>```

This will push them close together as seen in your picture.

Working example here - https://codepen.io/anon/pen/MoqRMK

I am sure you are experienced enough to make any other required changes.

Title: issue with forms in bootstrap and html

Body:
I have a bit of a problem and i need some help. I am learning new things and trying to get some skills with the time spend on learning.

I want to make this picture and forms look the same as the picture. I am posting my code
enter image description here

index.html

Send Request

Заповядайте в нашия нов хотел Grand Hotel Gergana. Ние Ви предлагаме отлични условия, където можете да прекарате своите ценни свободни дни.

        <form name="myForm" action="#" onsubmit="return validateForm()" method="post">

                        Name

                        <input type="text" class="form-control" id="firstname" style="width:100%;" name="fname">

                        Surname

                        <input type="text" class="form-control" id="surname" style="width:100%;" name="sname">

                        Email

                        <input type="text" class="form-control" id="email" style="width:100%;" name="mail">

                        Mobile phone

                        <input type="phone" class="form-control" id="phone" style="width:100%;" name="mphone">

                        Date of birth

                        <input type="number" class="form-control" id="number" Placeholder="DD" style="width:55px;" name="day">
                        <input type="number" class="form-control" id="number" Placeholder="MM" style="width:55px;" name="month">
                        <input type="number" class="form-control" id="number" Placeholder="YYYY" style="width:90px;" name="year">

                        Nationality

                        <select class="options" name="cars" style="width:100%;">
                            <option value="България">България</option>
                            <option value="Румъния">Румъния</option>
                            <option value="Гърция">Гърция</option>
                            <option value="Сърбия">Сърбия</option>
                        </select>

                    <input type="submit" value="SAMPLE BUTTON">

        </form>

Body:
Its quite a simple fix. You were really close! Firstly with Bootstrap you need to have a container, so that's a class that would be on your main div that holds everything so for this instance it would be your jumbotron div.

<div class="jumbotron container">

This will format 90% of what you are trying to achieve into a neat box where all the cols work in harmony with each other.

As for the input boxes, I see you were having difficulty with your date inputs. This too is an easy fix. Simply add the following code to your css:

#number {
   float: left;
}

This will push them close together as seen in your picture.

Working example here - https://codepen.io/anon/pen/MoqRMK

I am sure you are experienced enough to make any other required changes.


问:
pandas join two dataframe based on Index
I am trying to join two dataframes based on Index values of dataframes however, my result produces NaN and followed by values with index values repeated.

```<code>print st
</code>```

results in (stored in data frame series and with only index as follows)

```<code>index
1499054400000
1499140800000
1499227200000
1499313600000
1499400000000
</code>```

Another dataframe is as follows

```<code>print dtest2
</code>```

This results in (same index as above)

```<code>                1
index
1499227200000   33.48
1499400000000   35.71
</code>```

I am trying to get the following when i merge two dataframes

Result desired

```<code>index            1
1499054400000    0.0
1499140800000    0.0
1499227200000    33.48
1499313600000    0.0
1499400000000    35.71
</code>```

However when i concatenate as follows

```<code>pd.concat([st,dtest2],ignore_index=False)
</code>```

I get the following

```<code>                1
index
1499054400000   NaN
1499140800000   NaN
1499227200000   NaN
1499313600000   NaN
1499400000000   NaN
1499227200000   33.48
1499400000000   35.71
</code>```

答:
IIUC... use pd.DataFrame.reindex

```<code>dtest2.reindex(st.index, fill_value=0)

                   1
index
1499054400000   0.00
1499140800000   0.00
1499227200000  33.48
1499313600000   0.00
1499400000000  35.71
</code>```

However, you may have a hidden problem in that the types are not the same.  You can ensure that all indices are the same by using astype to cast them.

```<code>dtest2.index = dtest2.index.astype(str)
st.index = st.index.astype(str)

dtest2.reindex(st.index, fill_value=0)

                   1
index
1499054400000   0.00
1499140800000   0.00
1499227200000  33.48
1499313600000   0.00
1499400000000  35.71
</code>```

Or

```<code>dtest2.index = dtest2.index.astype(int)
st.index = st.index.astype(int)

dtest2.reindex(st.index, fill_value=0)

                   1
index
1499054400000   0.00
1499140800000   0.00
1499227200000  33.48
1499313600000   0.00
1499400000000  35.71
</code>```

Body:
I am trying to join two dataframes based on Index values of dataframes however, my result produces NaN and followed by values with index values repeated.

print st

results in (stored in data frame series and with only index as follows)

index
1499054400000
1499140800000
1499227200000
1499313600000
1499400000000

Another dataframe is as follows

print dtest2

This results in (same index as above)

                1
index
1499227200000   33.48
1499400000000   35.71

I am trying to get the following when i merge two dataframes

Result desired

index            1
1499054400000    0.0
1499140800000    0.0
1499227200000    33.48
1499313600000    0.0
1499400000000    35.71

However when i concatenate as follows

pd.concat([st,dtest2],ignore_index=False)

I get the following

                1
index
1499054400000   NaN
1499140800000   NaN
1499227200000   NaN
1499313600000   NaN
1499400000000   NaN
1499227200000   33.48
1499400000000   35.71

Body:
IIUC... use pd.DataFrame.reindex

dtest2.reindex(st.index, fill_value=0)

                   1
index
1499054400000   0.00
1499140800000   0.00
1499227200000  33.48
1499313600000   0.00
1499400000000  35.71

However, you may have a hidden problem in that the types are not the same.  You can ensure that all indices are the same by using astype to cast them.

dtest2.index = dtest2.index.astype(str)
st.index = st.index.astype(str)

dtest2.reindex(st.index, fill_value=0)

                   1
index
1499054400000   0.00
1499140800000   0.00
1499227200000  33.48
1499313600000   0.00
1499400000000  35.71

Or

dtest2.index = dtest2.index.astype(int)
st.index = st.index.astype(int)

dtest2.reindex(st.index, fill_value=0)

                   1
index
1499054400000   0.00
1499140800000   0.00
1499227200000  33.48
1499313600000   0.00
1499400000000  35.71


问:
To do searching in an array with some keyword
I have an array which is like

```<code>books={'java 350','Photoshop 225','php 210','JavaScript 80','python 180','jquery 250'}
</code>```

my input for search as be like "ph2" it retrieve both Photoshop 225,php 210 in drop-down menu what is the exact string function to do this task or any set codes available to do this task.

I'm using some build in function like

```<code>if (array.Any(keyword.Contains))
</code>```

and

```<code>if (array.Contains(keyword))
</code>```

it's doesn't help what exactly i want any one pls help me to solve this thanks in advance.....

答:
More flexible approach:</p>

```<code>using Microsoft.VisualBasic; // add reference
using Microsoft.VisualBasic.CompilerServices;
using System.Linq;

namespace ConsoleApplication
{
    class Program
    {
        static void Main (string[] args)
        {
            string[] books = { "java 350", "Photoshop 225", "php 210", "JavaScript 80", "python 180", "jquery 250" };

            string input = "*" + string.Join ("*", "ph2".ToArray ()) + "*"; // will be *p*h*2*

            var matches = books.Where (x => LikeOperator.LikeString (x, input, CompareMethod.Text));
        }
    }
}
</code>```

Body:
I have an array which is like

books={'java 350','Photoshop 225','php 210','JavaScript 80','python 180','jquery 250'}

my input for search as be like "ph2" it retrieve both Photoshop 225,php 210 in drop-down menu what is the exact string function to do this task or any set codes available to do this task.

I'm using some build in function like

if (array.Any(keyword.Contains))

and

if (array.Contains(keyword))

it's doesn't help what exactly i want any one pls help me to solve this thanks in advance.....

Body:
More flexible approach:

using Microsoft.VisualBasic; // add reference
using Microsoft.VisualBasic.CompilerServices;
using System.Linq;

namespace ConsoleApplication
{
    class Program
    {
        static void Main (string[] args)
        {
            string[] books = { "java 350", "Photoshop 225", "php 210", "JavaScript 80", "python 180", "jquery 250" };

            string input = "*" + string.Join ("*", "ph2".ToArray ()) + "*"; // will be *p*h*2*

            var matches = books.Where (x => LikeOperator.LikeString (x, input, CompareMethod.Text));
        }
    }
}


问:
"Attribute provided with no value" when runing a simple HTTP request script with Google Apps Script
I'm trying to run a simple HTTP request with the following script :

```<code>function myFunction() {
  var USERNAME = PropertiesService.getScriptProperties().getProperty('XXXXXX');
  var PASSWORD = PropertiesService.getScriptProperties().getProperty('XXXXXXX');

  var url = PropertiesService.getScriptProperties().getProperty('https://myurlapi');

    var headers = {
    "Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
  };

  var params = {
    "method":"GET",
    "headers":headers,
  };
var response = UrlFetchApp.fetch(url, params);
}
</code>```

When running the script I have the following error Attribute provided with no value: url (line 16, file "Code")

Line 16 is var response = UrlFetchApp.fetch(url, params);

I've positively tested the API with https://www.hurl.it/ and It's working. so what's wrong with my script ?

答:
Ok, It's working with the following script :

```<code>function myFunction() {
  var USERNAME = 'XXXXXXX';
  var PASSWORD = 'XXXXXXX';

  var url = 'myurlpi';

    var headers = {
    "Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD),
    "Accept" : "*/*",
  };

  var params = {
    "method":"GET",
    "headers":headers,
    "validateHttpsCertificates" :false
  };
var response = UrlFetchApp.fetch(url, params);
  Logger.log(response);
}
</code>```

I basically get rid of of the PropertiesService.getScriptProperties().getProperty.

Would love to understand why ? :)

Body:
I'm trying to run a simple HTTP request with the following script :

function myFunction() {
  var USERNAME = PropertiesService.getScriptProperties().getProperty('XXXXXX');
  var PASSWORD = PropertiesService.getScriptProperties().getProperty('XXXXXXX');

  var url = PropertiesService.getScriptProperties().getProperty('https://myurlapi');

    var headers = {
    "Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
  };

  var params = {
    "method":"GET",
    "headers":headers,
  };
var response = UrlFetchApp.fetch(url, params);
}

When running the script I have the following error Attribute provided with no value: url (line 16, file "Code")

Line 16 is var response = UrlFetchApp.fetch(url, params);

I've positively tested the API with https://www.hurl.it/ and It's working. so what's wrong with my script ?

Body:
Ok, It's working with the following script :

function myFunction() {
  var USERNAME = 'XXXXXXX';
  var PASSWORD = 'XXXXXXX';

  var url = 'myurlpi';

    var headers = {
    "Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD),
    "Accept" : "*/*",
  };

  var params = {
    "method":"GET",
    "headers":headers,
    "validateHttpsCertificates" :false
  };
var response = UrlFetchApp.fetch(url, params);
  Logger.log(response);
}

I basically get rid of of the PropertiesService.getScriptProperties().getProperty.

Would love to understand why ? :)


问:
IIS Virtual Directory map to network drive (with drive letter) but fail to create file
I am using C#/ASP.NET, IIS6 on Windows Server 2003.

Map the data server shared folder to the WebServer with driver letter V:\

On the WebServer, IIS created a virtual directory and pointed to 'local location' with V:\ . Since there is no 'Connect As', not sure which USER will be used

In my WebMethod, I want to create file on the shared folder with FileStream.Write().

I got IO Exception on the action, any hint?

P.S. I have added ASPNET/NETWORK SERVICE on the data server shared folder.

thanks!
Gavin

答:
Mapped network drives are specific to the user account that created them:

Using Mapped Drives with IIS - MS KB257174

The preferred method of accessing content for the Web server that exists on a remote computer is to use shares that follow the universal naming convention (UNC).

It's very likely that NETWORK SERVICE (or if you're running ASP.NET under impersonation, the site anonymous account) hasn't got this mapping.

To change the location where the virtual directory points to, browse to your site in IIS manager, right click on the virtual directory and select properties. You can then select "A share located on another computer":


问:
error copy file that was created in C#
I have this problem when I try to copy a file that was created in C#:

"System.IO.IOException: 'The process can not access the file' d:\las.txt 'because it is being used in another process.'"

my code:

```
using System;

namespace modulo1
{
    class Program
    {
        static void Main(string[] args)
        {
           string folderName = @"c:\lasss";

           System.IO.Directory.CreateDirectory(folderName);

           string archivo = @"d:\las.txt";

           System.IO.File.Create(archivo);

            string dest = @"d:\soft";

           //here is the problem
            System.IO.File.Copy(archivo, dest, true);
        }
    }
}
```

How can i solve this problem???

答:
The File.Create() method creates a file and returns a FileStream object to the file (see the documentation here). So, if you're not going to use that file stream, then you need to close it before you can access the file:

```<code>System.IO.File.Create(archivo).Close();
</code>```

Or, since FileStream implements IDisposable, you can put it in a using block, which will close and dispose of it for you:

```<code>using (var fileStream = System.IO.File.Create(archive))
{
    // do something with the file stream here if you need to
}
</code>```

Title: error copy file that was created in C#

Body:
I have this problem when I try to copy a file that was created in C#:

"System.IO.IOException: 'The process can not access the file' d:\las.txt 'because it is being used in another process.'"

my code:

using System;

namespace modulo1
{
    class Program
    {
        static void Main(string[] args)
        {
           string folderName = @"c:\lasss";

           System.IO.Directory.CreateDirectory(folderName);

           string archivo = @"d:\las.txt";

           System.IO.File.Create(archivo);

            string dest = @"d:\soft";

           //here is the problem
            System.IO.File.Copy(archivo, dest, true);
        }
    }
}

How can i solve this problem???

Body:
The File.Create() method creates a file and returns a FileStream object to the file (see the documentation here). So, if you're not going to use that file stream, then you need to close it before you can access the file:

System.IO.File.Create(archivo).Close();

Or, since FileStream implements IDisposable, you can put it in a using block, which will close and dispose of it for you:

using (var fileStream = System.IO.File.Create(archive))
{
    // do something with the file stream here if you need to
}